gitea源码

api_token_test.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package integration
  4. import (
  5. "fmt"
  6. "net/http"
  7. "testing"
  8. auth_model "code.gitea.io/gitea/models/auth"
  9. "code.gitea.io/gitea/models/unittest"
  10. user_model "code.gitea.io/gitea/models/user"
  11. "code.gitea.io/gitea/modules/log"
  12. api "code.gitea.io/gitea/modules/structs"
  13. "code.gitea.io/gitea/tests"
  14. "github.com/stretchr/testify/assert"
  15. )
  16. // TestAPICreateAndDeleteToken tests that token that was just created can be deleted
  17. func TestAPICreateAndDeleteToken(t *testing.T) {
  18. defer tests.PrepareTestEnv(t)()
  19. user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
  20. newAccessToken := createAPIAccessTokenWithoutCleanUp(t, "test-key-1", user, []auth_model.AccessTokenScope{auth_model.AccessTokenScopeAll})
  21. deleteAPIAccessToken(t, newAccessToken, user)
  22. newAccessToken = createAPIAccessTokenWithoutCleanUp(t, "test-key-2", user, []auth_model.AccessTokenScope{auth_model.AccessTokenScopeAll})
  23. deleteAPIAccessToken(t, newAccessToken, user)
  24. }
  25. // TestAPIDeleteMissingToken ensures that error is thrown when token not found
  26. func TestAPIDeleteMissingToken(t *testing.T) {
  27. defer tests.PrepareTestEnv(t)()
  28. user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
  29. req := NewRequestf(t, "DELETE", "/api/v1/users/user1/tokens/%d", unittest.NonexistentID).
  30. AddBasicAuth(user.Name)
  31. MakeRequest(t, req, http.StatusNotFound)
  32. }
  33. // TestAPIGetTokensPermission ensures that only the admin can get tokens from other users
  34. func TestAPIGetTokensPermission(t *testing.T) {
  35. defer tests.PrepareTestEnv(t)()
  36. // admin can get tokens for other users
  37. user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
  38. req := NewRequest(t, "GET", "/api/v1/users/user2/tokens").
  39. AddBasicAuth(user.Name)
  40. MakeRequest(t, req, http.StatusOK)
  41. // non-admin can get tokens for himself
  42. user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
  43. req = NewRequest(t, "GET", "/api/v1/users/user2/tokens").
  44. AddBasicAuth(user.Name)
  45. MakeRequest(t, req, http.StatusOK)
  46. // non-admin can't get tokens for other users
  47. user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4})
  48. req = NewRequest(t, "GET", "/api/v1/users/user2/tokens").
  49. AddBasicAuth(user.Name)
  50. MakeRequest(t, req, http.StatusForbidden)
  51. }
  52. // TestAPIDeleteTokensPermission ensures that only the admin can delete tokens from other users
  53. func TestAPIDeleteTokensPermission(t *testing.T) {
  54. defer tests.PrepareTestEnv(t)()
  55. admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
  56. user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
  57. user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4})
  58. // admin can delete tokens for other users
  59. createAPIAccessTokenWithoutCleanUp(t, "test-key-1", user2, []auth_model.AccessTokenScope{auth_model.AccessTokenScopeAll})
  60. req := NewRequest(t, "DELETE", "/api/v1/users/"+user2.LoginName+"/tokens/test-key-1").
  61. AddBasicAuth(admin.Name)
  62. MakeRequest(t, req, http.StatusNoContent)
  63. // non-admin can delete tokens for himself
  64. createAPIAccessTokenWithoutCleanUp(t, "test-key-2", user2, []auth_model.AccessTokenScope{auth_model.AccessTokenScopeAll})
  65. req = NewRequest(t, "DELETE", "/api/v1/users/"+user2.LoginName+"/tokens/test-key-2").
  66. AddBasicAuth(user2.Name)
  67. MakeRequest(t, req, http.StatusNoContent)
  68. // non-admin can't delete tokens for other users
  69. createAPIAccessTokenWithoutCleanUp(t, "test-key-3", user2, []auth_model.AccessTokenScope{auth_model.AccessTokenScopeAll})
  70. req = NewRequest(t, "DELETE", "/api/v1/users/"+user2.LoginName+"/tokens/test-key-3").
  71. AddBasicAuth(user4.Name)
  72. MakeRequest(t, req, http.StatusForbidden)
  73. }
  74. type permission struct {
  75. category auth_model.AccessTokenScopeCategory
  76. level auth_model.AccessTokenScopeLevel
  77. }
  78. type requiredScopeTestCase struct {
  79. url string
  80. method string
  81. requiredPermissions []permission
  82. }
  83. func (c *requiredScopeTestCase) Name() string {
  84. return fmt.Sprintf("%v %v", c.method, c.url)
  85. }
  86. // TestAPIDeniesPermissionBasedOnTokenScope tests that API routes forbid access
  87. // when the correct token scope is not included.
  88. func TestAPIDeniesPermissionBasedOnTokenScope(t *testing.T) {
  89. defer tests.PrepareTestEnv(t)()
  90. // We'll assert that each endpoint, when fetched with a token with all
  91. // scopes *except* the ones specified, a forbidden status code is returned.
  92. //
  93. // This is to protect against endpoints having their access check copied
  94. // from other endpoints and not updated.
  95. //
  96. // Test cases are in alphabetical order by URL.
  97. testCases := []requiredScopeTestCase{
  98. {
  99. "/api/v1/admin/emails",
  100. "GET",
  101. []permission{
  102. {
  103. auth_model.AccessTokenScopeCategoryAdmin,
  104. auth_model.Read,
  105. },
  106. },
  107. },
  108. {
  109. "/api/v1/admin/users",
  110. "GET",
  111. []permission{
  112. {
  113. auth_model.AccessTokenScopeCategoryAdmin,
  114. auth_model.Read,
  115. },
  116. },
  117. },
  118. {
  119. "/api/v1/admin/users",
  120. "POST",
  121. []permission{
  122. {
  123. auth_model.AccessTokenScopeCategoryAdmin,
  124. auth_model.Write,
  125. },
  126. },
  127. },
  128. {
  129. "/api/v1/admin/users/user2",
  130. "PATCH",
  131. []permission{
  132. {
  133. auth_model.AccessTokenScopeCategoryAdmin,
  134. auth_model.Write,
  135. },
  136. },
  137. },
  138. {
  139. "/api/v1/admin/users/user2/orgs",
  140. "GET",
  141. []permission{
  142. {
  143. auth_model.AccessTokenScopeCategoryAdmin,
  144. auth_model.Read,
  145. },
  146. },
  147. },
  148. {
  149. "/api/v1/admin/users/user2/orgs",
  150. "POST",
  151. []permission{
  152. {
  153. auth_model.AccessTokenScopeCategoryAdmin,
  154. auth_model.Write,
  155. },
  156. },
  157. },
  158. {
  159. "/api/v1/admin/orgs",
  160. "GET",
  161. []permission{
  162. {
  163. auth_model.AccessTokenScopeCategoryAdmin,
  164. auth_model.Read,
  165. },
  166. },
  167. },
  168. {
  169. "/api/v1/notifications",
  170. "GET",
  171. []permission{
  172. {
  173. auth_model.AccessTokenScopeCategoryNotification,
  174. auth_model.Read,
  175. },
  176. },
  177. },
  178. {
  179. "/api/v1/notifications",
  180. "PUT",
  181. []permission{
  182. {
  183. auth_model.AccessTokenScopeCategoryNotification,
  184. auth_model.Write,
  185. },
  186. },
  187. },
  188. {
  189. "/api/v1/org/org1/repos",
  190. "POST",
  191. []permission{
  192. {
  193. auth_model.AccessTokenScopeCategoryOrganization,
  194. auth_model.Write,
  195. },
  196. {
  197. auth_model.AccessTokenScopeCategoryRepository,
  198. auth_model.Write,
  199. },
  200. },
  201. },
  202. {
  203. "/api/v1/packages/user1/type/name/1",
  204. "GET",
  205. []permission{
  206. {
  207. auth_model.AccessTokenScopeCategoryPackage,
  208. auth_model.Read,
  209. },
  210. },
  211. },
  212. {
  213. "/api/v1/packages/user1/type/name/1",
  214. "DELETE",
  215. []permission{
  216. {
  217. auth_model.AccessTokenScopeCategoryPackage,
  218. auth_model.Write,
  219. },
  220. },
  221. },
  222. {
  223. "/api/v1/repos/user1/repo1",
  224. "GET",
  225. []permission{
  226. {
  227. auth_model.AccessTokenScopeCategoryRepository,
  228. auth_model.Read,
  229. },
  230. },
  231. },
  232. {
  233. "/api/v1/repos/user1/repo1",
  234. "PATCH",
  235. []permission{
  236. {
  237. auth_model.AccessTokenScopeCategoryRepository,
  238. auth_model.Write,
  239. },
  240. },
  241. },
  242. {
  243. "/api/v1/repos/user1/repo1",
  244. "DELETE",
  245. []permission{
  246. {
  247. auth_model.AccessTokenScopeCategoryRepository,
  248. auth_model.Write,
  249. },
  250. },
  251. },
  252. {
  253. "/api/v1/repos/user1/repo1/branches",
  254. "GET",
  255. []permission{
  256. {
  257. auth_model.AccessTokenScopeCategoryRepository,
  258. auth_model.Read,
  259. },
  260. },
  261. },
  262. {
  263. "/api/v1/repos/user1/repo1/archive/foo",
  264. "GET",
  265. []permission{
  266. {
  267. auth_model.AccessTokenScopeCategoryRepository,
  268. auth_model.Read,
  269. },
  270. },
  271. },
  272. {
  273. "/api/v1/repos/user1/repo1/issues",
  274. "GET",
  275. []permission{
  276. {
  277. auth_model.AccessTokenScopeCategoryIssue,
  278. auth_model.Read,
  279. },
  280. },
  281. },
  282. {
  283. "/api/v1/repos/user1/repo1/media/foo",
  284. "GET",
  285. []permission{
  286. {
  287. auth_model.AccessTokenScopeCategoryRepository,
  288. auth_model.Read,
  289. },
  290. },
  291. },
  292. {
  293. "/api/v1/repos/user1/repo1/raw/foo",
  294. "GET",
  295. []permission{
  296. {
  297. auth_model.AccessTokenScopeCategoryRepository,
  298. auth_model.Read,
  299. },
  300. },
  301. },
  302. {
  303. "/api/v1/repos/user1/repo1/teams",
  304. "GET",
  305. []permission{
  306. {
  307. auth_model.AccessTokenScopeCategoryRepository,
  308. auth_model.Read,
  309. },
  310. },
  311. },
  312. {
  313. "/api/v1/repos/user1/repo1/teams/team1",
  314. "PUT",
  315. []permission{
  316. {
  317. auth_model.AccessTokenScopeCategoryRepository,
  318. auth_model.Write,
  319. },
  320. },
  321. },
  322. {
  323. "/api/v1/repos/user1/repo1/transfer",
  324. "POST",
  325. []permission{
  326. {
  327. auth_model.AccessTokenScopeCategoryRepository,
  328. auth_model.Write,
  329. },
  330. },
  331. },
  332. // Private repo
  333. {
  334. "/api/v1/repos/user2/repo2",
  335. "GET",
  336. []permission{
  337. {
  338. auth_model.AccessTokenScopeCategoryRepository,
  339. auth_model.Read,
  340. },
  341. },
  342. },
  343. // Private repo
  344. {
  345. "/api/v1/repos/user2/repo2",
  346. "GET",
  347. []permission{
  348. {
  349. auth_model.AccessTokenScopeCategoryRepository,
  350. auth_model.Read,
  351. },
  352. },
  353. },
  354. {
  355. "/api/v1/user",
  356. "GET",
  357. []permission{
  358. {
  359. auth_model.AccessTokenScopeCategoryUser,
  360. auth_model.Read,
  361. },
  362. },
  363. },
  364. {
  365. "/api/v1/user/emails",
  366. "GET",
  367. []permission{
  368. {
  369. auth_model.AccessTokenScopeCategoryUser,
  370. auth_model.Read,
  371. },
  372. },
  373. },
  374. {
  375. "/api/v1/user/emails",
  376. "POST",
  377. []permission{
  378. {
  379. auth_model.AccessTokenScopeCategoryUser,
  380. auth_model.Write,
  381. },
  382. },
  383. },
  384. {
  385. "/api/v1/user/emails",
  386. "DELETE",
  387. []permission{
  388. {
  389. auth_model.AccessTokenScopeCategoryUser,
  390. auth_model.Write,
  391. },
  392. },
  393. },
  394. {
  395. "/api/v1/user/applications/oauth2",
  396. "GET",
  397. []permission{
  398. {
  399. auth_model.AccessTokenScopeCategoryUser,
  400. auth_model.Read,
  401. },
  402. },
  403. },
  404. {
  405. "/api/v1/user/applications/oauth2",
  406. "POST",
  407. []permission{
  408. {
  409. auth_model.AccessTokenScopeCategoryUser,
  410. auth_model.Write,
  411. },
  412. },
  413. },
  414. {
  415. "/api/v1/users/search",
  416. "GET",
  417. []permission{
  418. {
  419. auth_model.AccessTokenScopeCategoryUser,
  420. auth_model.Read,
  421. },
  422. },
  423. },
  424. // Private user
  425. {
  426. "/api/v1/users/user31",
  427. "GET",
  428. []permission{
  429. {
  430. auth_model.AccessTokenScopeCategoryUser,
  431. auth_model.Read,
  432. },
  433. },
  434. },
  435. // Private user
  436. {
  437. "/api/v1/users/user31/gpg_keys",
  438. "GET",
  439. []permission{
  440. {
  441. auth_model.AccessTokenScopeCategoryUser,
  442. auth_model.Read,
  443. },
  444. },
  445. },
  446. }
  447. // User needs to be admin so that we can verify that tokens without admin
  448. // scopes correctly deny access.
  449. user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
  450. assert.True(t, user.IsAdmin, "User needs to be admin")
  451. for _, testCase := range testCases {
  452. runTestCase(t, &testCase, user)
  453. }
  454. }
  455. // runTestCase Helper function to run a single test case.
  456. func runTestCase(t *testing.T, testCase *requiredScopeTestCase, user *user_model.User) {
  457. t.Run(testCase.Name(), func(t *testing.T) {
  458. defer tests.PrintCurrentTest(t)()
  459. // Create a token with all scopes NOT required by the endpoint.
  460. var unauthorizedScopes []auth_model.AccessTokenScope
  461. for _, category := range auth_model.AllAccessTokenScopeCategories {
  462. // For permissions, Write > Read > NoAccess. So we need to
  463. // find the minimum required, and only grant permission up to but
  464. // not including the minimum required.
  465. minRequiredLevel := auth_model.Write
  466. categoryIsRequired := false
  467. for _, requiredPermission := range testCase.requiredPermissions {
  468. if requiredPermission.category != category {
  469. continue
  470. }
  471. categoryIsRequired = true
  472. if requiredPermission.level < minRequiredLevel {
  473. minRequiredLevel = requiredPermission.level
  474. }
  475. }
  476. unauthorizedLevel := auth_model.Write
  477. if categoryIsRequired {
  478. if minRequiredLevel == auth_model.Read {
  479. unauthorizedLevel = auth_model.NoAccess
  480. } else if minRequiredLevel == auth_model.Write {
  481. unauthorizedLevel = auth_model.Read
  482. } else {
  483. assert.FailNow(t, "Invalid test case", "Unknown access token scope level: %v", minRequiredLevel)
  484. }
  485. }
  486. if unauthorizedLevel == auth_model.NoAccess {
  487. continue
  488. }
  489. cateogoryUnauthorizedScopes := auth_model.GetRequiredScopes(
  490. unauthorizedLevel,
  491. category)
  492. unauthorizedScopes = append(unauthorizedScopes, cateogoryUnauthorizedScopes...)
  493. }
  494. accessToken := createAPIAccessTokenWithoutCleanUp(t, "test-token", user, unauthorizedScopes)
  495. defer deleteAPIAccessToken(t, accessToken, user)
  496. // Request the endpoint. Verify that permission is denied.
  497. req := NewRequest(t, testCase.method, testCase.url).
  498. AddTokenAuth(accessToken.Token)
  499. MakeRequest(t, req, http.StatusForbidden)
  500. })
  501. }
  502. // createAPIAccessTokenWithoutCleanUp Create an API access token and assert that
  503. // creation succeeded. The caller is responsible for deleting the token.
  504. func createAPIAccessTokenWithoutCleanUp(t *testing.T, tokenName string, user *user_model.User, scopes []auth_model.AccessTokenScope) api.AccessToken {
  505. payload := map[string]any{
  506. "name": tokenName,
  507. "scopes": scopes,
  508. }
  509. log.Debug("Requesting creation of token with scopes: %v", scopes)
  510. req := NewRequestWithJSON(t, "POST", "/api/v1/users/"+user.LoginName+"/tokens", payload).
  511. AddBasicAuth(user.Name)
  512. resp := MakeRequest(t, req, http.StatusCreated)
  513. var newAccessToken api.AccessToken
  514. DecodeJSON(t, resp, &newAccessToken)
  515. unittest.AssertExistsAndLoadBean(t, &auth_model.AccessToken{
  516. ID: newAccessToken.ID,
  517. Name: newAccessToken.Name,
  518. Token: newAccessToken.Token,
  519. UID: user.ID,
  520. })
  521. return newAccessToken
  522. }
  523. // deleteAPIAccessToken deletes an API access token and assert that deletion succeeded.
  524. func deleteAPIAccessToken(t *testing.T, accessToken api.AccessToken, user *user_model.User) {
  525. req := NewRequestf(t, "DELETE", "/api/v1/users/"+user.LoginName+"/tokens/%d", accessToken.ID).
  526. AddBasicAuth(user.Name)
  527. MakeRequest(t, req, http.StatusNoContent)
  528. unittest.AssertNotExistsBean(t, &auth_model.AccessToken{ID: accessToken.ID})
  529. }