You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo_commits_test.go 7.3KB

Redesign Scoped Access Tokens (#24767) ## Changes - Adds the following high level access scopes, each with `read` and `write` levels: - `activitypub` - `admin` (hidden if user is not a site admin) - `misc` - `notification` - `organization` - `package` - `issue` - `repository` - `user` - Adds new middleware function `tokenRequiresScopes()` in addition to `reqToken()` - `tokenRequiresScopes()` is used for each high-level api section - _if_ a scoped token is present, checks that the required scope is included based on the section and HTTP method - `reqToken()` is used for individual routes - checks that required authentication is present (but does not check scope levels as this will already have been handled by `tokenRequiresScopes()` - Adds migration to convert old scoped access tokens to the new set of scopes - Updates the user interface for scope selection ### User interface example <img width="903" alt="Screen Shot 2023-05-31 at 1 56 55 PM" src="https://github.com/go-gitea/gitea/assets/23248839/654766ec-2143-4f59-9037-3b51600e32f3"> <img width="917" alt="Screen Shot 2023-05-31 at 1 56 43 PM" src="https://github.com/go-gitea/gitea/assets/23248839/1ad64081-012c-4a73-b393-66b30352654c"> ## tokenRequiresScopes Design Decision - `tokenRequiresScopes()` was added to more reliably cover api routes. For an incoming request, this function uses the given scope category (say `AccessTokenScopeCategoryOrganization`) and the HTTP method (say `DELETE`) and verifies that any scoped tokens in use include `delete:organization`. - `reqToken()` is used to enforce auth for individual routes that require it. If a scoped token is not present for a request, `tokenRequiresScopes()` will not return an error ## TODO - [x] Alphabetize scope categories - [x] Change 'public repos only' to a radio button (private vs public). Also expand this to organizations - [X] Disable token creation if no scopes selected. Alternatively, show warning - [x] `reqToken()` is missing from many `POST/DELETE` routes in the api. `tokenRequiresScopes()` only checks that a given token has the correct scope, `reqToken()` must be used to check that a token (or some other auth) is present. - _This should be addressed in this PR_ - [x] The migration should be reviewed very carefully in order to minimize access changes to existing user tokens. - _This should be addressed in this PR_ - [x] Link to api to swagger documentation, clarify what read/write/delete levels correspond to - [x] Review cases where more than one scope is needed as this directly deviates from the api definition. - _This should be addressed in this PR_ - For example: ```go m.Group("/users/{username}/orgs", func() { m.Get("", reqToken(), org.ListUserOrgs) m.Get("/{org}/permissions", reqToken(), org.GetUserOrgsPermissions) }, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryUser, auth_model.AccessTokenScopeCategoryOrganization), context_service.UserAssignmentAPI()) ``` ## Future improvements - [ ] Add required scopes to swagger documentation - [ ] Redesign `reqToken()` to be opt-out rather than opt-in - [ ] Subdivide scopes like `repository` - [ ] Once a token is created, if it has no scopes, we should display text instead of an empty bullet point - [ ] If the 'public repos only' option is selected, should read categories be selected by default Closes #24501 Closes #24799 Co-authored-by: Jonathan Tran <jon@allspice.io> Co-authored-by: Kyle D <kdumontnu@gmail.com> Co-authored-by: silverwind <me@silverwind.io>
1 year ago
Redesign Scoped Access Tokens (#24767) ## Changes - Adds the following high level access scopes, each with `read` and `write` levels: - `activitypub` - `admin` (hidden if user is not a site admin) - `misc` - `notification` - `organization` - `package` - `issue` - `repository` - `user` - Adds new middleware function `tokenRequiresScopes()` in addition to `reqToken()` - `tokenRequiresScopes()` is used for each high-level api section - _if_ a scoped token is present, checks that the required scope is included based on the section and HTTP method - `reqToken()` is used for individual routes - checks that required authentication is present (but does not check scope levels as this will already have been handled by `tokenRequiresScopes()` - Adds migration to convert old scoped access tokens to the new set of scopes - Updates the user interface for scope selection ### User interface example <img width="903" alt="Screen Shot 2023-05-31 at 1 56 55 PM" src="https://github.com/go-gitea/gitea/assets/23248839/654766ec-2143-4f59-9037-3b51600e32f3"> <img width="917" alt="Screen Shot 2023-05-31 at 1 56 43 PM" src="https://github.com/go-gitea/gitea/assets/23248839/1ad64081-012c-4a73-b393-66b30352654c"> ## tokenRequiresScopes Design Decision - `tokenRequiresScopes()` was added to more reliably cover api routes. For an incoming request, this function uses the given scope category (say `AccessTokenScopeCategoryOrganization`) and the HTTP method (say `DELETE`) and verifies that any scoped tokens in use include `delete:organization`. - `reqToken()` is used to enforce auth for individual routes that require it. If a scoped token is not present for a request, `tokenRequiresScopes()` will not return an error ## TODO - [x] Alphabetize scope categories - [x] Change 'public repos only' to a radio button (private vs public). Also expand this to organizations - [X] Disable token creation if no scopes selected. Alternatively, show warning - [x] `reqToken()` is missing from many `POST/DELETE` routes in the api. `tokenRequiresScopes()` only checks that a given token has the correct scope, `reqToken()` must be used to check that a token (or some other auth) is present. - _This should be addressed in this PR_ - [x] The migration should be reviewed very carefully in order to minimize access changes to existing user tokens. - _This should be addressed in this PR_ - [x] Link to api to swagger documentation, clarify what read/write/delete levels correspond to - [x] Review cases where more than one scope is needed as this directly deviates from the api definition. - _This should be addressed in this PR_ - For example: ```go m.Group("/users/{username}/orgs", func() { m.Get("", reqToken(), org.ListUserOrgs) m.Get("/{org}/permissions", reqToken(), org.GetUserOrgsPermissions) }, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryUser, auth_model.AccessTokenScopeCategoryOrganization), context_service.UserAssignmentAPI()) ``` ## Future improvements - [ ] Add required scopes to swagger documentation - [ ] Redesign `reqToken()` to be opt-out rather than opt-in - [ ] Subdivide scopes like `repository` - [ ] Once a token is created, if it has no scopes, we should display text instead of an empty bullet point - [ ] If the 'public repos only' option is selected, should read categories be selected by default Closes #24501 Closes #24799 Co-authored-by: Jonathan Tran <jon@allspice.io> Co-authored-by: Kyle D <kdumontnu@gmail.com> Co-authored-by: silverwind <me@silverwind.io>
1 year ago
Redesign Scoped Access Tokens (#24767) ## Changes - Adds the following high level access scopes, each with `read` and `write` levels: - `activitypub` - `admin` (hidden if user is not a site admin) - `misc` - `notification` - `organization` - `package` - `issue` - `repository` - `user` - Adds new middleware function `tokenRequiresScopes()` in addition to `reqToken()` - `tokenRequiresScopes()` is used for each high-level api section - _if_ a scoped token is present, checks that the required scope is included based on the section and HTTP method - `reqToken()` is used for individual routes - checks that required authentication is present (but does not check scope levels as this will already have been handled by `tokenRequiresScopes()` - Adds migration to convert old scoped access tokens to the new set of scopes - Updates the user interface for scope selection ### User interface example <img width="903" alt="Screen Shot 2023-05-31 at 1 56 55 PM" src="https://github.com/go-gitea/gitea/assets/23248839/654766ec-2143-4f59-9037-3b51600e32f3"> <img width="917" alt="Screen Shot 2023-05-31 at 1 56 43 PM" src="https://github.com/go-gitea/gitea/assets/23248839/1ad64081-012c-4a73-b393-66b30352654c"> ## tokenRequiresScopes Design Decision - `tokenRequiresScopes()` was added to more reliably cover api routes. For an incoming request, this function uses the given scope category (say `AccessTokenScopeCategoryOrganization`) and the HTTP method (say `DELETE`) and verifies that any scoped tokens in use include `delete:organization`. - `reqToken()` is used to enforce auth for individual routes that require it. If a scoped token is not present for a request, `tokenRequiresScopes()` will not return an error ## TODO - [x] Alphabetize scope categories - [x] Change 'public repos only' to a radio button (private vs public). Also expand this to organizations - [X] Disable token creation if no scopes selected. Alternatively, show warning - [x] `reqToken()` is missing from many `POST/DELETE` routes in the api. `tokenRequiresScopes()` only checks that a given token has the correct scope, `reqToken()` must be used to check that a token (or some other auth) is present. - _This should be addressed in this PR_ - [x] The migration should be reviewed very carefully in order to minimize access changes to existing user tokens. - _This should be addressed in this PR_ - [x] Link to api to swagger documentation, clarify what read/write/delete levels correspond to - [x] Review cases where more than one scope is needed as this directly deviates from the api definition. - _This should be addressed in this PR_ - For example: ```go m.Group("/users/{username}/orgs", func() { m.Get("", reqToken(), org.ListUserOrgs) m.Get("/{org}/permissions", reqToken(), org.GetUserOrgsPermissions) }, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryUser, auth_model.AccessTokenScopeCategoryOrganization), context_service.UserAssignmentAPI()) ``` ## Future improvements - [ ] Add required scopes to swagger documentation - [ ] Redesign `reqToken()` to be opt-out rather than opt-in - [ ] Subdivide scopes like `repository` - [ ] Once a token is created, if it has no scopes, we should display text instead of an empty bullet point - [ ] If the 'public repos only' option is selected, should read categories be selected by default Closes #24501 Closes #24799 Co-authored-by: Jonathan Tran <jon@allspice.io> Co-authored-by: Kyle D <kdumontnu@gmail.com> Co-authored-by: silverwind <me@silverwind.io>
1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package integration
  4. import (
  5. "fmt"
  6. "net/http"
  7. "net/http/httptest"
  8. "path"
  9. "sync"
  10. "testing"
  11. auth_model "code.gitea.io/gitea/models/auth"
  12. "code.gitea.io/gitea/modules/json"
  13. "code.gitea.io/gitea/modules/setting"
  14. api "code.gitea.io/gitea/modules/structs"
  15. "code.gitea.io/gitea/tests"
  16. "github.com/stretchr/testify/assert"
  17. )
  18. func TestRepoCommits(t *testing.T) {
  19. defer tests.PrepareTestEnv(t)()
  20. session := loginUser(t, "user2")
  21. // Request repository commits page
  22. req := NewRequest(t, "GET", "/user2/repo1/commits/branch/master")
  23. resp := session.MakeRequest(t, req, http.StatusOK)
  24. doc := NewHTMLParser(t, resp.Body)
  25. commitURL, exists := doc.doc.Find("#commits-table tbody tr td.sha a").Attr("href")
  26. assert.True(t, exists)
  27. assert.NotEmpty(t, commitURL)
  28. }
  29. func doTestRepoCommitWithStatus(t *testing.T, state string, classes ...string) {
  30. defer tests.PrepareTestEnv(t)()
  31. session := loginUser(t, "user2")
  32. // Request repository commits page
  33. req := NewRequest(t, "GET", "/user2/repo1/commits/branch/master")
  34. resp := session.MakeRequest(t, req, http.StatusOK)
  35. doc := NewHTMLParser(t, resp.Body)
  36. // Get first commit URL
  37. commitURL, exists := doc.doc.Find("#commits-table tbody tr td.sha a").Attr("href")
  38. assert.True(t, exists)
  39. assert.NotEmpty(t, commitURL)
  40. // Call API to add status for commit
  41. ctx := NewAPITestContext(t, "user2", "repo1", auth_model.AccessTokenScopeWriteRepository)
  42. t.Run("CreateStatus", doAPICreateCommitStatus(ctx, path.Base(commitURL), api.CreateStatusOption{
  43. State: api.CommitStatusState(state),
  44. TargetURL: "http://test.ci/",
  45. Description: "",
  46. Context: "testci",
  47. }))
  48. req = NewRequest(t, "GET", "/user2/repo1/commits/branch/master")
  49. resp = session.MakeRequest(t, req, http.StatusOK)
  50. doc = NewHTMLParser(t, resp.Body)
  51. // Check if commit status is displayed in message column (.tippy-target to ignore the tippy trigger)
  52. sel := doc.doc.Find("#commits-table tbody tr td.message .tippy-target .commit-status")
  53. assert.Equal(t, 1, sel.Length())
  54. for _, class := range classes {
  55. assert.True(t, sel.HasClass(class))
  56. }
  57. // By SHA
  58. req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/"+path.Base(commitURL)+"/statuses")
  59. reqOne := NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/"+path.Base(commitURL)+"/status")
  60. testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), session.MakeRequest(t, reqOne, http.StatusOK), state)
  61. // By short SHA
  62. req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/"+path.Base(commitURL)[:10]+"/statuses")
  63. reqOne = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/"+path.Base(commitURL)[:10]+"/status")
  64. testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), session.MakeRequest(t, reqOne, http.StatusOK), state)
  65. // By Ref
  66. req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/master/statuses")
  67. reqOne = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/master/status")
  68. testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), session.MakeRequest(t, reqOne, http.StatusOK), state)
  69. req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/v1.1/statuses")
  70. reqOne = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/v1.1/status")
  71. testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), session.MakeRequest(t, reqOne, http.StatusOK), state)
  72. }
  73. func testRepoCommitsWithStatus(t *testing.T, resp, respOne *httptest.ResponseRecorder, state string) {
  74. var statuses []*api.CommitStatus
  75. assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), &statuses))
  76. var status api.CombinedStatus
  77. assert.NoError(t, json.Unmarshal(respOne.Body.Bytes(), &status))
  78. assert.NotNil(t, status)
  79. if assert.Len(t, statuses, 1) {
  80. assert.Equal(t, api.CommitStatusState(state), statuses[0].State)
  81. assert.Equal(t, setting.AppURL+"api/v1/repos/user2/repo1/statuses/65f1bf27bc3bf70f64657658635e66094edbcb4d", statuses[0].URL)
  82. assert.Equal(t, "http://test.ci/", statuses[0].TargetURL)
  83. assert.Equal(t, "", statuses[0].Description)
  84. assert.Equal(t, "testci", statuses[0].Context)
  85. assert.Len(t, status.Statuses, 1)
  86. assert.Equal(t, statuses[0], status.Statuses[0])
  87. assert.Equal(t, "65f1bf27bc3bf70f64657658635e66094edbcb4d", status.SHA)
  88. }
  89. }
  90. func TestRepoCommitsWithStatusPending(t *testing.T) {
  91. doTestRepoCommitWithStatus(t, "pending", "octicon-dot-fill", "yellow")
  92. }
  93. func TestRepoCommitsWithStatusSuccess(t *testing.T) {
  94. doTestRepoCommitWithStatus(t, "success", "octicon-check", "green")
  95. }
  96. func TestRepoCommitsWithStatusError(t *testing.T) {
  97. doTestRepoCommitWithStatus(t, "error", "gitea-exclamation", "red")
  98. }
  99. func TestRepoCommitsWithStatusFailure(t *testing.T) {
  100. doTestRepoCommitWithStatus(t, "failure", "octicon-x", "red")
  101. }
  102. func TestRepoCommitsWithStatusWarning(t *testing.T) {
  103. doTestRepoCommitWithStatus(t, "warning", "gitea-exclamation", "yellow")
  104. }
  105. func TestRepoCommitsStatusParallel(t *testing.T) {
  106. defer tests.PrepareTestEnv(t)()
  107. session := loginUser(t, "user2")
  108. // Request repository commits page
  109. req := NewRequest(t, "GET", "/user2/repo1/commits/branch/master")
  110. resp := session.MakeRequest(t, req, http.StatusOK)
  111. doc := NewHTMLParser(t, resp.Body)
  112. // Get first commit URL
  113. commitURL, exists := doc.doc.Find("#commits-table tbody tr td.sha a").Attr("href")
  114. assert.True(t, exists)
  115. assert.NotEmpty(t, commitURL)
  116. var wg sync.WaitGroup
  117. for i := 0; i < 10; i++ {
  118. wg.Add(1)
  119. go func(parentT *testing.T, i int) {
  120. parentT.Run(fmt.Sprintf("ParallelCreateStatus_%d", i), func(t *testing.T) {
  121. ctx := NewAPITestContext(t, "user2", "repo1", auth_model.AccessTokenScopeWriteRepository)
  122. runBody := doAPICreateCommitStatus(ctx, path.Base(commitURL), api.CreateStatusOption{
  123. State: api.CommitStatusPending,
  124. TargetURL: "http://test.ci/",
  125. Description: "",
  126. Context: "testci",
  127. })
  128. runBody(t)
  129. wg.Done()
  130. })
  131. }(t, i)
  132. }
  133. wg.Wait()
  134. }
  135. func TestRepoCommitsStatusMultiple(t *testing.T) {
  136. defer tests.PrepareTestEnv(t)()
  137. session := loginUser(t, "user2")
  138. // Request repository commits page
  139. req := NewRequest(t, "GET", "/user2/repo1/commits/branch/master")
  140. resp := session.MakeRequest(t, req, http.StatusOK)
  141. doc := NewHTMLParser(t, resp.Body)
  142. // Get first commit URL
  143. commitURL, exists := doc.doc.Find("#commits-table tbody tr td.sha a").Attr("href")
  144. assert.True(t, exists)
  145. assert.NotEmpty(t, commitURL)
  146. // Call API to add status for commit
  147. ctx := NewAPITestContext(t, "user2", "repo1", auth_model.AccessTokenScopeWriteRepository)
  148. t.Run("CreateStatus", doAPICreateCommitStatus(ctx, path.Base(commitURL), api.CreateStatusOption{
  149. State: api.CommitStatusSuccess,
  150. TargetURL: "http://test.ci/",
  151. Description: "",
  152. Context: "testci",
  153. }))
  154. t.Run("CreateStatus", doAPICreateCommitStatus(ctx, path.Base(commitURL), api.CreateStatusOption{
  155. State: api.CommitStatusSuccess,
  156. TargetURL: "http://test.ci/",
  157. Description: "",
  158. Context: "other_context",
  159. }))
  160. req = NewRequest(t, "GET", "/user2/repo1/commits/branch/master")
  161. resp = session.MakeRequest(t, req, http.StatusOK)
  162. doc = NewHTMLParser(t, resp.Body)
  163. // Check that the data-tippy="commit-statuses" (for trigger) and commit-status (svg) are present
  164. sel := doc.doc.Find("#commits-table tbody tr td.message [data-tippy=\"commit-statuses\"] .commit-status")
  165. assert.Equal(t, 1, sel.Length())
  166. }