From 90e3b585ff5010833d5068563f9a542b718edb36 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Mon, 22 Aug 2022 02:24:30 -0400 Subject: [PATCH 001/118] Add scope field to access token --- models/auth/token.go | 1 + 1 file changed, 1 insertion(+) diff --git a/models/auth/token.go b/models/auth/token.go index 01654f29017bf..86e3830d71017 100644 --- a/models/auth/token.go +++ b/models/auth/token.go @@ -59,6 +59,7 @@ type AccessToken struct { TokenHash string `xorm:"UNIQUE"` // sha256 of token TokenSalt string TokenLastEight string `xorm:"token_last_eight"` + Scope string CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` From 89d1140aad553665398fc478b7745b85dc6c0558 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Fri, 26 Aug 2022 14:09:18 -0400 Subject: [PATCH 002/118] Add token scope helper functions --- models/auth/token.go | 2 +- models/token_scope.go | 148 +++++++++++++++++++++++++++++++++++++ models/token_scope_test.go | 27 +++++++ 3 files changed, 176 insertions(+), 1 deletion(-) create mode 100644 models/token_scope.go create mode 100644 models/token_scope_test.go diff --git a/models/auth/token.go b/models/auth/token.go index 86e3830d71017..0401175ae8b40 100644 --- a/models/auth/token.go +++ b/models/auth/token.go @@ -59,7 +59,7 @@ type AccessToken struct { TokenHash string `xorm:"UNIQUE"` // sha256 of token TokenSalt string TokenLastEight string `xorm:"token_last_eight"` - Scope string + Scope AccessTokenScope CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` diff --git a/models/token_scope.go b/models/token_scope.go new file mode 100644 index 0000000000000..565c52d83d0bd --- /dev/null +++ b/models/token_scope.go @@ -0,0 +1,148 @@ +package models + +import ( + "fmt" + "strings" +) + +type AccessTokenScope string + +const ( + AccessTokenScopeRepo = "repo" + AccessTokenScopeRepoStatus = "repo:status" + AccessTokenScopePublicRepo = "public_repo" + + AccessTokenScopeAdminOrg = "admin:org" + AccessTokenScopeWriteOrg = "write:org" + AccessTokenScopeReadOrg = "read:org" + + AccessTokenScopeAdminPublicKey = "admin:public_key" + AccessTokenScopeWritePublicKey = "write:public_key" + AccessTokenScopeReadPublicKey = "read:public_key" + + AccessTokenScopeAdminRepoHook = "admin:repo_hook" + AccessTokenScopeWriteRepoHook = "write:repo_hook" + AccessTokenScopeReadRepoHook = "read:repo_hook" + + AccessTokenScopeAdminOrgHook = "admin:org_hook" + + AccessTokenScopeNotification = "notification" + + AccessTokenScopeUser = "user" + AccessTokenScopeReadUser = "read:user" + AccessTokenScopeUserEmail = "user:email" + AccessTokenScopeUserFollow = "user:follow" + + AccessTokenScopeDeleteRepo = "delete_repo" + + AccessTokenScopePackage = "package" + AccessTokenScopeWritePackage = "write:package" + AccessTokenScopeReadPackage = "read:package" + AccessTokenScopeDeletePackage = "delete:package" + + AccessTokenScopeAdminGPGKey = "admin:gpg_key" + AccessTokenScopeWriteGPGKey = "write:gpg_key" + AccessTokenScopeReadGPGKey = "read:gpg_key" +) + +// AllAccessTokenScopes contains all access token scopes. +// The order is important: parent scope must precedes child scopes. +var AllAccessTokenScopes = []string{ + AccessTokenScopeRepo, AccessTokenScopeRepoStatus, AccessTokenScopePublicRepo, + AccessTokenScopeAdminOrg, AccessTokenScopeWriteOrg, AccessTokenScopeReadOrg, + AccessTokenScopeAdminPublicKey, AccessTokenScopeWritePublicKey, AccessTokenScopeReadPublicKey, + AccessTokenScopeAdminRepoHook, AccessTokenScopeWriteRepoHook, AccessTokenScopeReadRepoHook, + AccessTokenScopeAdminOrgHook, + AccessTokenScopeNotification, + AccessTokenScopeUser, AccessTokenScopeReadUser, AccessTokenScopeUserEmail, AccessTokenScopeUserFollow, + AccessTokenScopeDeleteRepo, + AccessTokenScopePackage, AccessTokenScopeWritePackage, AccessTokenScopeReadPackage, AccessTokenScopeDeletePackage, + AccessTokenScopeAdminGPGKey, AccessTokenScopeWriteGPGKey, AccessTokenScopeReadGPGKey, +} + +func (s AccessTokenScope) Parse() (AccessTokenScopeBitmap, error) { + list := strings.Split(string(s), ",") + + var bitmap AccessTokenScopeBitmap + for _, v := range list { + if v == "" { + continue + } + + idx := sliceIndex(AllAccessTokenScopes, v) + if idx < 0 { + return 0, fmt.Errorf("invalid access token scope: %s", v) + } + bitmap |= 1 << uint(idx) + } + return bitmap, nil +} + +func (s AccessTokenScope) Normalize() (AccessTokenScope, error) { + bitmap, err := s.Parse() + if err != nil { + return "", err + } + + return bitmap.ToScope(), nil +} + +type AccessTokenScopeBitmap uint64 + +func (bitmap AccessTokenScopeBitmap) ToScope() AccessTokenScope { + var scopes []string + + groupedScope := make(map[string]struct{}) + for i, v := range AllAccessTokenScopes { + if bitmap&(1< Date: Tue, 6 Sep 2022 04:43:35 -0400 Subject: [PATCH 003/118] Add comments --- models/token_scope.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/models/token_scope.go b/models/token_scope.go index 565c52d83d0bd..9092ff66f08c6 100644 --- a/models/token_scope.go +++ b/models/token_scope.go @@ -5,6 +5,7 @@ import ( "strings" ) +// AccessTokenScope represents the scope for an access token. type AccessTokenScope string const ( @@ -60,6 +61,7 @@ var AllAccessTokenScopes = []string{ AccessTokenScopeAdminGPGKey, AccessTokenScopeWriteGPGKey, AccessTokenScopeReadGPGKey, } +// Parse parses the scope string into a bitmap, thus removing possible duplicates. func (s AccessTokenScope) Parse() (AccessTokenScopeBitmap, error) { list := strings.Split(string(s), ",") @@ -78,6 +80,7 @@ func (s AccessTokenScope) Parse() (AccessTokenScopeBitmap, error) { return bitmap, nil } +// Normalize returns a normalized scope string without any duplicates. func (s AccessTokenScope) Normalize() (AccessTokenScope, error) { bitmap, err := s.Parse() if err != nil { @@ -87,8 +90,10 @@ func (s AccessTokenScope) Normalize() (AccessTokenScope, error) { return bitmap.ToScope(), nil } +// AccessTokenScopeBitmap represents a bitmap of access token scopes. type AccessTokenScopeBitmap uint64 +// ToScope returns a normalized scope string without any duplicates. func (bitmap AccessTokenScopeBitmap) ToScope() AccessTokenScope { var scopes []string From 948cd14a34f233fc17fd4feaff3db70f4a89958e Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 6 Sep 2022 04:45:11 -0400 Subject: [PATCH 004/118] Move token_scope file to models/auth --- models/{ => auth}/token_scope.go | 2 +- models/{ => auth}/token_scope_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename models/{ => auth}/token_scope.go (99%) rename models/{ => auth}/token_scope_test.go (96%) diff --git a/models/token_scope.go b/models/auth/token_scope.go similarity index 99% rename from models/token_scope.go rename to models/auth/token_scope.go index 9092ff66f08c6..9e83c31621fe9 100644 --- a/models/token_scope.go +++ b/models/auth/token_scope.go @@ -1,4 +1,4 @@ -package models +package auth import ( "fmt" diff --git a/models/token_scope_test.go b/models/auth/token_scope_test.go similarity index 96% rename from models/token_scope_test.go rename to models/auth/token_scope_test.go index 25ecb0a5cad33..20923842860cc 100644 --- a/models/token_scope_test.go +++ b/models/auth/token_scope_test.go @@ -1,4 +1,4 @@ -package models +package auth import ( "testing" From fd6e8213436993bfdcbd5f0b86b79b312d2ca713 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 6 Sep 2022 04:54:28 -0400 Subject: [PATCH 005/118] Include copyright --- models/auth/token_scope.go | 4 ++++ models/auth/token_scope_test.go | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/models/auth/token_scope.go b/models/auth/token_scope.go index 9e83c31621fe9..cf99c5f9cfb69 100644 --- a/models/auth/token_scope.go +++ b/models/auth/token_scope.go @@ -1,3 +1,7 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + package auth import ( diff --git a/models/auth/token_scope_test.go b/models/auth/token_scope_test.go index 20923842860cc..0d5a67540ef8f 100644 --- a/models/auth/token_scope_test.go +++ b/models/auth/token_scope_test.go @@ -1,3 +1,7 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + package auth import ( From b013747a984e66be7ea53d038f24b48ea16f6dc6 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 6 Sep 2022 05:05:52 -0400 Subject: [PATCH 006/118] Add more unit tests --- models/auth/token_scope_test.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/models/auth/token_scope_test.go b/models/auth/token_scope_test.go index 0d5a67540ef8f..cd8a26887ee92 100644 --- a/models/auth/token_scope_test.go +++ b/models/auth/token_scope_test.go @@ -17,8 +17,23 @@ func TestAccessTokenScope_Normalize(t *testing.T) { err error }{ {"", "", nil}, + {"repo", "repo", nil}, + {"repo,repo:status", "repo", nil}, + {"repo,public_repo", "repo", nil}, + {"admin:public_key,write:public_key", "admin:public_key", nil}, + {"admin:public_key,read:public_key", "admin:public_key", nil}, + {"admin:repo_hook,write:repo_hook", "admin:repo_hook", nil}, + {"admin:repo_hook,read:repo_hook", "admin:repo_hook", nil}, {"user", "user", nil}, {"user,read:user", "user", nil}, + {"user,admin:org,write:org", "admin:org,user", nil}, + {"admin:org,write:org,user", "admin:org,user", nil}, + {"package", "package", nil}, + {"package,write:package", "package", nil}, + {"package,write:package,delete:package", "package", nil}, + {"admin:gpg_key", "admin:gpg_key", nil}, + {"admin:gpg_key,write:gpg_key", "admin:gpg_key", nil}, + {"admin:gpg_key,write:gpg_key,user", "admin:gpg_key,user", nil}, } for _, test := range tests { From 794484a4ce6d64b534fba7daf8bab334cd92b53f Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 6 Sep 2022 05:44:15 -0400 Subject: [PATCH 007/118] Support 'all' scope --- models/auth/token_scope.go | 20 ++++++++++++++++---- models/auth/token_scope_test.go | 4 +++- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/models/auth/token_scope.go b/models/auth/token_scope.go index cf99c5f9cfb69..790b10d1e3474 100644 --- a/models/auth/token_scope.go +++ b/models/auth/token_scope.go @@ -13,6 +13,8 @@ import ( type AccessTokenScope string const ( + AccessTokenScopeAll = "all" + AccessTokenScopeRepo = "repo" AccessTokenScopeRepoStatus = "repo:status" AccessTokenScopePublicRepo = "public_repo" @@ -65,6 +67,12 @@ var AllAccessTokenScopes = []string{ AccessTokenScopeAdminGPGKey, AccessTokenScopeWriteGPGKey, AccessTokenScopeReadGPGKey, } +// AccessTokenScopeBitmap represents a bitmap of access token scopes. +type AccessTokenScopeBitmap uint64 + +// AccessTokenScopeAllBitmap is the bitmap of all access token scopes. +var AccessTokenScopeAllBitmap AccessTokenScopeBitmap = 1< Date: Tue, 6 Sep 2022 06:03:28 -0400 Subject: [PATCH 008/118] Support checking scope access --- models/auth/token_scope.go | 43 +++++++++++++++++++++++++++++++++ models/auth/token_scope_test.go | 30 +++++++++++++++++++++++ 2 files changed, 73 insertions(+) diff --git a/models/auth/token_scope.go b/models/auth/token_scope.go index 790b10d1e3474..ef939cba43877 100644 --- a/models/auth/token_scope.go +++ b/models/auth/token_scope.go @@ -91,6 +91,33 @@ func (s AccessTokenScope) Parse() (AccessTokenScopeBitmap, error) { return 0, fmt.Errorf("invalid access token scope: %s", v) } bitmap |= 1 << uint(idx) + + // take care of child scopes + switch v { + case AccessTokenScopeRepo: + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeRepoStatus)) + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopePublicRepo)) + case AccessTokenScopeAdminOrg: + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeWriteOrg)) + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeReadOrg)) + case AccessTokenScopeAdminPublicKey: + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeWritePublicKey)) + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeReadPublicKey)) + case AccessTokenScopeAdminRepoHook: + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeWriteRepoHook)) + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeReadRepoHook)) + case AccessTokenScopeUser: + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeReadUser)) + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeUserEmail)) + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeUserFollow)) + case AccessTokenScopePackage: + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeWritePackage)) + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeReadPackage)) + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeDeletePackage)) + case AccessTokenScopeAdminGPGKey: + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeWriteGPGKey)) + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeReadGPGKey)) + } } return bitmap, nil } @@ -105,6 +132,21 @@ func (s AccessTokenScope) Normalize() (AccessTokenScope, error) { return bitmap.ToScope(), nil } +// HasScope returns true if the string has the given scope +func (s AccessTokenScope) HasScope(scope string) (bool, error) { + index := sliceIndex(AllAccessTokenScopes, scope) + if index == -1 { + return false, fmt.Errorf("invalid access token scope: %s", scope) + } + + bitmap, err := s.Parse() + if err != nil { + return false, err + } + + return bitmap&(1< Date: Tue, 6 Sep 2022 16:27:04 -0400 Subject: [PATCH 009/118] Restrict scope for some APIs --- routers/api/v1/api.go | 237 ++++++++++++++++++++------------------ services/auth/basic.go | 2 + services/auth/httpsign.go | 2 + services/auth/oauth2.go | 4 + 4 files changed, 134 insertions(+), 111 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 6a98121b73a51..cacca8409670c 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -71,6 +71,7 @@ import ( "reflect" "strings" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/perm" access_model "code.gitea.io/gitea/models/perm/access" @@ -208,9 +209,22 @@ func reqPackageAccess(accessMode perm.AccessMode) func(ctx *context.APIContext) } // Contexter middleware already checks token for user sign in process. -func reqToken() func(ctx *context.APIContext) { +func reqToken(requiredScope string) func(ctx *context.APIContext) { return func(ctx *context.APIContext) { if true == ctx.Data["IsApiToken"] { + if requiredScope == "" { + return + } + scope := ctx.Data["ApiTokenScope"].(auth_model.AccessTokenScope) + allow, err := scope.HasScope(requiredScope) + if err != nil { + ctx.Error(http.StatusUnauthorized, "reqToken", "parsing token failed") + return + } + if !allow { + ctx.Error(http.StatusUnauthorized, "reqToken", "token does not have required scope") + return + } return } if ctx.Context.IsBasicAuth { @@ -662,7 +676,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/repository", settings.GetGeneralRepoSettings) }) - // Notifications + // Notifications (requires 'notification' scope) m.Group("/notifications", func() { m.Combo(""). Get(notify.ListNotifications). @@ -671,9 +685,9 @@ func Routes(ctx gocontext.Context) *web.Route { m.Combo("/threads/{id}"). Get(notify.GetThread). Patch(notify.ReadThread) - }, reqToken()) + }, reqToken(auth_model.AccessTokenScopeNotification)) - // Users + // Users (public information, no scope required) m.Group("/users", func() { m.Get("/search", reqExploreSignIn(), user.Search) @@ -689,10 +703,11 @@ func Routes(ctx gocontext.Context) *web.Route { m.Combo("").Get(user.ListAccessTokens). Post(bind(api.CreateAccessTokenOption{}), user.CreateAccessToken) m.Combo("/{id}").Delete(user.DeleteAccessToken) - }, reqBasicOrRevProxyAuth()) + }, reqBasicOrRevProxyAuth()) // basic auth or reverse proxy auth required }, context_service.UserAssignmentAPI()) }) + // (public information, no scope required) m.Group("/users", func() { m.Group("/{username}", func() { m.Get("/keys", user.ListPublicKeys) @@ -708,25 +723,25 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/subscriptions", user.GetWatchedRepos) }, context_service.UserAssignmentAPI()) - }, reqToken()) + }, reqToken("")) m.Group("/user", func() { m.Get("", user.GetAuthenticatedUser) m.Group("/settings", func() { - m.Get("", user.GetUserSettings) - m.Patch("", bind(api.UserSettingsOptions{}), user.UpdateUserSettings) - }, reqToken()) - m.Combo("/emails").Get(user.ListEmails). - Post(bind(api.CreateEmailOption{}), user.AddEmail). - Delete(bind(api.DeleteEmailOption{}), user.DeleteEmail) + m.Get("", reqToken(auth_model.AccessTokenScopeReadUser), user.GetUserSettings) // requires 'read:user' scope + m.Patch("", reqToken(auth_model.AccessTokenScopeReadUser), bind(api.UserSettingsOptions{}), user.UpdateUserSettings) // requires 'read:user' scope + }, reqToken("")) + m.Combo("/emails").Get(reqToken(auth_model.AccessTokenScopeReadUser), user.ListEmails). // requires 'read:user' scope + Post(reqToken(auth_model.AccessTokenScopeUser), bind(api.CreateEmailOption{}), user.AddEmail). // requires 'user' scope + Delete(reqToken(auth_model.AccessTokenScopeUser), bind(api.DeleteEmailOption{}), user.DeleteEmail) // requires 'user' scope m.Get("/followers", user.ListMyFollowers) m.Group("/following", func() { m.Get("", user.ListMyFollowing) m.Group("/{username}", func() { m.Get("", user.CheckMyFollowing) - m.Put("", user.Follow) - m.Delete("", user.Unfollow) + m.Put("", reqToken(auth_model.AccessTokenScopeUserFollow), user.Follow) // requires 'user:follow' scope + m.Delete("", reqToken(auth_model.AccessTokenScopeUserFollow), user.Unfollow) // requires 'user:follow' scope }, context_service.UserAssignmentAPI()) }) @@ -744,7 +759,7 @@ func Routes(ctx gocontext.Context) *web.Route { Delete(user.DeleteOauth2Application). Patch(bind(api.CreateOAuth2ApplicationOptions{}), user.UpdateOauth2Application). Get(user.GetOauth2Application) - }, reqToken()) + }, reqToken("")) m.Group("/gpg_keys", func() { m.Combo("").Get(user.ListMyGPGKeys). @@ -774,31 +789,31 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/subscriptions", user.GetMyWatchedRepos) m.Get("/teams", org.ListUserTeams) - }, reqToken()) + }, reqToken("")) // Repositories - m.Post("/org/{org}/repos", reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepoDeprecated) + m.Post("/org/{org}/repos", reqToken(""), bind(api.CreateRepoOption{}), repo.CreateOrgRepoDeprecated) - m.Combo("/repositories/{id}", reqToken()).Get(repo.GetByID) + m.Combo("/repositories/{id}", reqToken("")).Get(repo.GetByID) m.Group("/repos", func() { m.Get("/search", repo.Search) m.Get("/issues/search", repo.SearchIssues) - m.Post("/migrate", reqToken(), bind(api.MigrateRepoOptions{}), repo.Migrate) + m.Post("/migrate", reqToken(""), bind(api.MigrateRepoOptions{}), repo.Migrate) m.Group("/{username}/{reponame}", func() { m.Combo("").Get(reqAnyRepoReader(), repo.Get). - Delete(reqToken(), reqOwner(), repo.Delete). - Patch(reqToken(), reqAdmin(), bind(api.EditRepoOption{}), repo.Edit) - m.Post("/generate", reqToken(), reqRepoReader(unit.TypeCode), bind(api.GenerateRepoOption{}), repo.Generate) + Delete(reqToken(auth_model.AccessTokenScopeDeleteRepo), reqOwner(), repo.Delete). + Patch(reqToken(auth_model.AccessTokenScopeRepo), reqAdmin(), bind(api.EditRepoOption{}), repo.Edit) + m.Post("/generate", reqToken(""), reqRepoReader(unit.TypeCode), bind(api.GenerateRepoOption{}), repo.Generate) m.Post("/transfer", reqOwner(), bind(api.TransferRepoOption{}), repo.Transfer) - m.Post("/transfer/accept", reqToken(), repo.AcceptTransfer) - m.Post("/transfer/reject", reqToken(), repo.RejectTransfer) - m.Combo("/notifications"). - Get(reqToken(), notify.ListRepoNotifications). - Put(reqToken(), notify.ReadRepoNotifications) + m.Post("/transfer/accept", reqToken(""), repo.AcceptTransfer) + m.Post("/transfer/reject", reqToken(""), repo.RejectTransfer) + m.Combo("/notifications", reqToken(auth_model.AccessTokenScopeNotification)). + Get(reqToken(""), notify.ListRepoNotifications). + Put(reqToken(""), notify.ReadRepoNotifications) m.Group("/hooks/git", func() { m.Combo("").Get(repo.ListGitHooks) m.Group("/{id}", func() { @@ -806,7 +821,7 @@ func Routes(ctx gocontext.Context) *web.Route { Patch(bind(api.EditGitHookOption{}), repo.EditGitHook). Delete(repo.DeleteGitHook) }) - }, reqToken(), reqAdmin(), reqGitHook(), context.ReferencesGitRepo(true)) + }, reqToken(""), reqAdmin(), reqGitHook(), context.ReferencesGitRepo(true)) m.Group("/hooks", func() { m.Combo("").Get(repo.ListHooks). Post(bind(api.CreateHookOption{}), repo.CreateHook) @@ -816,7 +831,7 @@ func Routes(ctx gocontext.Context) *web.Route { Delete(repo.DeleteHook) m.Post("/tests", context.ReferencesGitRepo(), context.RepoRefForAPI, repo.TestHook) }) - }, reqToken(), reqAdmin(), reqWebhooksEnabled()) + }, reqToken(""), reqAdmin(), reqWebhooksEnabled()) m.Group("/collaborators", func() { m.Get("", reqAnyRepoReader(), repo.ListCollaborators) m.Group("/{collaborator}", func() { @@ -824,21 +839,21 @@ func Routes(ctx gocontext.Context) *web.Route { Put(reqAdmin(), bind(api.AddCollaboratorOption{}), repo.AddCollaborator). Delete(reqAdmin(), repo.DeleteCollaborator) m.Get("/permission", repo.GetRepoPermissions) - }, reqToken()) - }, reqToken()) - m.Get("/assignees", reqToken(), reqAnyRepoReader(), repo.GetAssignees) - m.Get("/reviewers", reqToken(), reqAnyRepoReader(), repo.GetReviewers) + }, reqToken("")) + }, reqToken("")) + m.Get("/assignees", reqToken(""), reqAnyRepoReader(), repo.GetAssignees) + m.Get("/reviewers", reqToken(""), reqAnyRepoReader(), repo.GetReviewers) m.Group("/teams", func() { m.Get("", reqAnyRepoReader(), repo.ListTeams) m.Combo("/{team}").Get(reqAnyRepoReader(), repo.IsTeam). Put(reqAdmin(), repo.AddTeam). Delete(reqAdmin(), repo.DeleteTeam) - }, reqToken()) + }, reqToken("")) m.Get("/raw/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFile) m.Get("/media/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFileOrLFS) m.Get("/archive/*", reqRepoReader(unit.TypeCode), repo.GetArchive) m.Combo("/forks").Get(repo.ListForks). - Post(reqToken(), reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork) + Post(reqToken(""), reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork) m.Group("/branches", func() { m.Get("", repo.ListBranches) m.Get("/*", repo.GetBranch) @@ -853,7 +868,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Patch("", bind(api.EditBranchProtectionOption{}), repo.EditBranchProtection) m.Delete("", repo.DeleteBranchProtection) }) - }, reqToken(), reqAdmin()) + }, reqToken(""), reqAdmin()) m.Group("/tags", func() { m.Get("", repo.ListTags) m.Get("/*", repo.GetTag) @@ -865,11 +880,11 @@ func Routes(ctx gocontext.Context) *web.Route { Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey) m.Combo("/{id}").Get(repo.GetDeployKey). Delete(repo.DeleteDeploykey) - }, reqToken(), reqAdmin()) + }, reqToken(""), reqAdmin()) m.Group("/times", func() { m.Combo("").Get(repo.ListTrackedTimesByRepository) m.Combo("/{timetrackingusername}").Get(repo.ListTrackedTimesByUser) - }, mustEnableIssues, reqToken()) + }, mustEnableIssues, reqToken("")) m.Group("/wiki", func() { m.Combo("/page/{pageName}"). Get(repo.GetWikiPage). @@ -881,37 +896,37 @@ func Routes(ctx gocontext.Context) *web.Route { }, mustEnableWiki) m.Group("/issues", func() { m.Combo("").Get(repo.ListIssues). - Post(reqToken(), mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue) + Post(reqToken(""), mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue) m.Group("/comments", func() { m.Get("", repo.ListRepoIssueComments) m.Group("/{id}", func() { m.Combo(""). Get(repo.GetIssueComment). - Patch(mustNotBeArchived, reqToken(), bind(api.EditIssueCommentOption{}), repo.EditIssueComment). - Delete(reqToken(), repo.DeleteIssueComment) + Patch(mustNotBeArchived, reqToken(""), bind(api.EditIssueCommentOption{}), repo.EditIssueComment). + Delete(reqToken(""), repo.DeleteIssueComment) m.Combo("/reactions"). Get(repo.GetIssueCommentReactions). - Post(reqToken(), bind(api.EditReactionOption{}), repo.PostIssueCommentReaction). - Delete(reqToken(), bind(api.EditReactionOption{}), repo.DeleteIssueCommentReaction) + Post(reqToken(""), bind(api.EditReactionOption{}), repo.PostIssueCommentReaction). + Delete(reqToken(""), bind(api.EditReactionOption{}), repo.DeleteIssueCommentReaction) }) }) m.Group("/{index}", func() { m.Combo("").Get(repo.GetIssue). - Patch(reqToken(), bind(api.EditIssueOption{}), repo.EditIssue). - Delete(reqToken(), reqAdmin(), repo.DeleteIssue) + Patch(reqToken(""), bind(api.EditIssueOption{}), repo.EditIssue). + Delete(reqToken(""), reqAdmin(), repo.DeleteIssue) m.Group("/comments", func() { m.Combo("").Get(repo.ListIssueComments). - Post(reqToken(), mustNotBeArchived, bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment) - m.Combo("/{id}", reqToken()).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueCommentDeprecated). + Post(reqToken(""), mustNotBeArchived, bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment) + m.Combo("/{id}", reqToken("")).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueCommentDeprecated). Delete(repo.DeleteIssueCommentDeprecated) }) m.Get("/timeline", repo.ListIssueCommentsAndTimeline) m.Group("/labels", func() { m.Combo("").Get(repo.ListIssueLabels). - Post(reqToken(), bind(api.IssueLabelsOption{}), repo.AddIssueLabels). - Put(reqToken(), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels). - Delete(reqToken(), repo.ClearIssueLabels) - m.Delete("/{id}", reqToken(), repo.DeleteIssueLabel) + Post(reqToken(""), bind(api.IssueLabelsOption{}), repo.AddIssueLabels). + Put(reqToken(""), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels). + Delete(reqToken(""), repo.ClearIssueLabels) + m.Delete("/{id}", reqToken(""), repo.DeleteIssueLabel) }) m.Group("/times", func() { m.Combo(""). @@ -919,70 +934,70 @@ func Routes(ctx gocontext.Context) *web.Route { Post(bind(api.AddTimeOption{}), repo.AddTime). Delete(repo.ResetIssueTime) m.Delete("/{id}", repo.DeleteTime) - }, reqToken()) - m.Combo("/deadline").Post(reqToken(), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline) + }, reqToken("")) + m.Combo("/deadline").Post(reqToken(""), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline) m.Group("/stopwatch", func() { - m.Post("/start", reqToken(), repo.StartIssueStopwatch) - m.Post("/stop", reqToken(), repo.StopIssueStopwatch) - m.Delete("/delete", reqToken(), repo.DeleteIssueStopwatch) + m.Post("/start", reqToken(""), repo.StartIssueStopwatch) + m.Post("/stop", reqToken(""), repo.StopIssueStopwatch) + m.Delete("/delete", reqToken(""), repo.DeleteIssueStopwatch) }) m.Group("/subscriptions", func() { m.Get("", repo.GetIssueSubscribers) - m.Get("/check", reqToken(), repo.CheckIssueSubscription) - m.Put("/{user}", reqToken(), repo.AddIssueSubscription) - m.Delete("/{user}", reqToken(), repo.DelIssueSubscription) + m.Get("/check", reqToken(""), repo.CheckIssueSubscription) + m.Put("/{user}", reqToken(""), repo.AddIssueSubscription) + m.Delete("/{user}", reqToken(""), repo.DelIssueSubscription) }) m.Combo("/reactions"). Get(repo.GetIssueReactions). - Post(reqToken(), bind(api.EditReactionOption{}), repo.PostIssueReaction). - Delete(reqToken(), bind(api.EditReactionOption{}), repo.DeleteIssueReaction) + Post(reqToken(""), bind(api.EditReactionOption{}), repo.PostIssueReaction). + Delete(reqToken(""), bind(api.EditReactionOption{}), repo.DeleteIssueReaction) }) }, mustEnableIssuesOrPulls) m.Group("/labels", func() { m.Combo("").Get(repo.ListLabels). - Post(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateLabelOption{}), repo.CreateLabel) + Post(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateLabelOption{}), repo.CreateLabel) m.Combo("/{id}").Get(repo.GetLabel). - Patch(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditLabelOption{}), repo.EditLabel). - Delete(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteLabel) + Patch(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditLabelOption{}), repo.EditLabel). + Delete(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteLabel) }) m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown) m.Post("/markdown/raw", misc.MarkdownRaw) m.Group("/milestones", func() { m.Combo("").Get(repo.ListMilestones). - Post(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateMilestoneOption{}), repo.CreateMilestone) + Post(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateMilestoneOption{}), repo.CreateMilestone) m.Combo("/{id}").Get(repo.GetMilestone). - Patch(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditMilestoneOption{}), repo.EditMilestone). - Delete(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteMilestone) + Patch(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditMilestoneOption{}), repo.EditMilestone). + Delete(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteMilestone) }) m.Get("/stargazers", repo.ListStargazers) m.Get("/subscribers", repo.ListSubscribers) m.Group("/subscription", func() { m.Get("", user.IsWatching) - m.Put("", reqToken(), user.Watch) - m.Delete("", reqToken(), user.Unwatch) + m.Put("", reqToken(""), user.Watch) + m.Delete("", reqToken(""), user.Unwatch) }) m.Group("/releases", func() { m.Combo("").Get(repo.ListReleases). - Post(reqToken(), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.CreateReleaseOption{}), repo.CreateRelease) + Post(reqToken(""), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.CreateReleaseOption{}), repo.CreateRelease) m.Group("/{id}", func() { m.Combo("").Get(repo.GetRelease). - Patch(reqToken(), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.EditReleaseOption{}), repo.EditRelease). - Delete(reqToken(), reqRepoWriter(unit.TypeReleases), repo.DeleteRelease) + Patch(reqToken(""), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.EditReleaseOption{}), repo.EditRelease). + Delete(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.DeleteRelease) m.Group("/assets", func() { m.Combo("").Get(repo.ListReleaseAttachments). - Post(reqToken(), reqRepoWriter(unit.TypeReleases), repo.CreateReleaseAttachment) + Post(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.CreateReleaseAttachment) m.Combo("/{asset}").Get(repo.GetReleaseAttachment). - Patch(reqToken(), reqRepoWriter(unit.TypeReleases), bind(api.EditAttachmentOptions{}), repo.EditReleaseAttachment). - Delete(reqToken(), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseAttachment) + Patch(reqToken(""), reqRepoWriter(unit.TypeReleases), bind(api.EditAttachmentOptions{}), repo.EditReleaseAttachment). + Delete(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseAttachment) }) }) m.Group("/tags", func() { m.Combo("/{tag}"). Get(repo.GetReleaseByTag). - Delete(reqToken(), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseByTag) + Delete(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseByTag) }) }, reqRepoReader(unit.TypeReleases)) - m.Post("/mirror-sync", reqToken(), reqRepoWriter(unit.TypeCode), repo.MirrorSync) + m.Post("/mirror-sync", reqToken(""), reqRepoWriter(unit.TypeCode), repo.MirrorSync) m.Post("/push_mirrors-sync", reqAdmin(), repo.PushMirrorSync) m.Group("/push_mirrors", func() { m.Combo("").Get(repo.ListPushMirrors). @@ -995,39 +1010,39 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/editorconfig/{filename}", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetEditorconfig) m.Group("/pulls", func() { m.Combo("").Get(repo.ListPullRequests). - Post(reqToken(), mustNotBeArchived, bind(api.CreatePullRequestOption{}), repo.CreatePullRequest) + Post(reqToken(""), mustNotBeArchived, bind(api.CreatePullRequestOption{}), repo.CreatePullRequest) m.Group("/{index}", func() { m.Combo("").Get(repo.GetPullRequest). - Patch(reqToken(), bind(api.EditPullRequestOption{}), repo.EditPullRequest) + Patch(reqToken(""), bind(api.EditPullRequestOption{}), repo.EditPullRequest) m.Get(".{diffType:diff|patch}", repo.DownloadPullDiffOrPatch) - m.Post("/update", reqToken(), repo.UpdatePullRequest) + m.Post("/update", reqToken(""), repo.UpdatePullRequest) m.Get("/commits", repo.GetPullRequestCommits) m.Combo("/merge").Get(repo.IsPullRequestMerged). - Post(reqToken(), mustNotBeArchived, bind(forms.MergePullRequestForm{}), repo.MergePullRequest). - Delete(reqToken(), mustNotBeArchived, repo.CancelScheduledAutoMerge) + Post(reqToken(""), mustNotBeArchived, bind(forms.MergePullRequestForm{}), repo.MergePullRequest). + Delete(reqToken(""), mustNotBeArchived, repo.CancelScheduledAutoMerge) m.Group("/reviews", func() { m.Combo(""). Get(repo.ListPullReviews). - Post(reqToken(), bind(api.CreatePullReviewOptions{}), repo.CreatePullReview) + Post(reqToken(""), bind(api.CreatePullReviewOptions{}), repo.CreatePullReview) m.Group("/{id}", func() { m.Combo(""). Get(repo.GetPullReview). - Delete(reqToken(), repo.DeletePullReview). - Post(reqToken(), bind(api.SubmitPullReviewOptions{}), repo.SubmitPullReview) + Delete(reqToken(""), repo.DeletePullReview). + Post(reqToken(""), bind(api.SubmitPullReviewOptions{}), repo.SubmitPullReview) m.Combo("/comments"). Get(repo.GetPullReviewComments) - m.Post("/dismissals", reqToken(), bind(api.DismissPullReviewOptions{}), repo.DismissPullReview) - m.Post("/undismissals", reqToken(), repo.UnDismissPullReview) + m.Post("/dismissals", reqToken(""), bind(api.DismissPullReviewOptions{}), repo.DismissPullReview) + m.Post("/undismissals", reqToken(""), repo.UnDismissPullReview) }) }) m.Combo("/requested_reviewers"). - Delete(reqToken(), bind(api.PullReviewRequestOptions{}), repo.DeleteReviewRequests). - Post(reqToken(), bind(api.PullReviewRequestOptions{}), repo.CreateReviewRequests) + Delete(reqToken(""), bind(api.PullReviewRequestOptions{}), repo.DeleteReviewRequests). + Post(reqToken(""), bind(api.PullReviewRequestOptions{}), repo.CreateReviewRequests) }) }, mustAllowPulls, reqRepoReader(unit.TypeCode), context.ReferencesGitRepo()) m.Group("/statuses", func() { m.Combo("/{sha}").Get(repo.GetCommitStatuses). - Post(reqToken(), reqRepoWriter(unit.TypeCode), bind(api.CreateStatusOption{}), repo.NewCommitStatus) + Post(reqToken(""), reqRepoWriter(unit.TypeCode), bind(api.CreateStatusOption{}), repo.NewCommitStatus) }, reqRepoReader(unit.TypeCode)) m.Group("/commits", func() { m.Get("", context.ReferencesGitRepo(), repo.GetAllCommits) @@ -1048,7 +1063,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/tags/{sha}", repo.GetAnnotatedTag) m.Get("/notes/{sha}", repo.GetNote) }, context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode)) - m.Post("/diffpatch", reqRepoWriter(unit.TypeCode), reqToken(), bind(api.ApplyDiffPatchFileOptions{}), repo.ApplyDiffPatch) + m.Post("/diffpatch", reqRepoWriter(unit.TypeCode), reqToken(""), bind(api.ApplyDiffPatchFileOptions{}), repo.ApplyDiffPatch) m.Group("/contents", func() { m.Get("", repo.GetContentsList) m.Get("/*", repo.GetContents) @@ -1056,15 +1071,15 @@ func Routes(ctx gocontext.Context) *web.Route { m.Post("", bind(api.CreateFileOptions{}), reqRepoBranchWriter, repo.CreateFile) m.Put("", bind(api.UpdateFileOptions{}), reqRepoBranchWriter, repo.UpdateFile) m.Delete("", bind(api.DeleteFileOptions{}), reqRepoBranchWriter, repo.DeleteFile) - }, reqToken()) + }, reqToken("")) }, reqRepoReader(unit.TypeCode)) m.Get("/signing-key.gpg", misc.SigningKey) m.Group("/topics", func() { m.Combo("").Get(repo.ListTopics). - Put(reqToken(), reqAdmin(), bind(api.RepoTopicOptions{}), repo.UpdateTopics) + Put(reqToken(""), reqAdmin(), bind(api.RepoTopicOptions{}), repo.UpdateTopics) m.Group("/{topic}", func() { - m.Combo("").Put(reqToken(), repo.AddTopic). - Delete(reqToken(), repo.DeleteTopic) + m.Combo("").Put(reqToken(""), repo.AddTopic). + Delete(reqToken(""), repo.DeleteTopic) }, reqAdmin()) }, reqAnyRepoReader()) m.Get("/issue_templates", context.ReferencesGitRepo(), repo.GetIssueTemplates) @@ -1082,41 +1097,41 @@ func Routes(ctx gocontext.Context) *web.Route { }, context_service.UserAssignmentAPI(), context.PackageAssignmentAPI(), reqPackageAccess(perm.AccessModeRead)) // Organizations - m.Get("/user/orgs", reqToken(), org.ListMyOrgs) + m.Get("/user/orgs", reqToken(""), org.ListMyOrgs) m.Group("/users/{username}/orgs", func() { m.Get("", org.ListUserOrgs) - m.Get("/{org}/permissions", reqToken(), org.GetUserOrgsPermissions) + m.Get("/{org}/permissions", reqToken(""), org.GetUserOrgsPermissions) }, context_service.UserAssignmentAPI()) - m.Post("/orgs", reqToken(), bind(api.CreateOrgOption{}), org.Create) + m.Post("/orgs", reqToken(""), bind(api.CreateOrgOption{}), org.Create) m.Get("/orgs", org.GetAll) m.Group("/orgs/{org}", func() { m.Combo("").Get(org.Get). - Patch(reqToken(), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit). - Delete(reqToken(), reqOrgOwnership(), org.Delete) + Patch(reqToken(""), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit). + Delete(reqToken(""), reqOrgOwnership(), org.Delete) m.Combo("/repos").Get(user.ListOrgRepos). - Post(reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepo) + Post(reqToken(""), bind(api.CreateRepoOption{}), repo.CreateOrgRepo) m.Group("/members", func() { m.Get("", org.ListMembers) m.Combo("/{username}").Get(org.IsMember). - Delete(reqToken(), reqOrgOwnership(), org.DeleteMember) + Delete(reqToken(""), reqOrgOwnership(), org.DeleteMember) }) m.Group("/public_members", func() { m.Get("", org.ListPublicMembers) m.Combo("/{username}").Get(org.IsPublicMember). - Put(reqToken(), reqOrgMembership(), org.PublicizeMember). - Delete(reqToken(), reqOrgMembership(), org.ConcealMember) + Put(reqToken(""), reqOrgMembership(), org.PublicizeMember). + Delete(reqToken(""), reqOrgMembership(), org.ConcealMember) }) m.Group("/teams", func() { m.Get("", org.ListTeams) m.Post("", reqOrgOwnership(), bind(api.CreateTeamOption{}), org.CreateTeam) m.Get("/search", org.SearchTeam) - }, reqToken(), reqOrgMembership()) + }, reqToken(""), reqOrgMembership()) m.Group("/labels", func() { m.Get("", org.ListLabels) - m.Post("", reqToken(), reqOrgOwnership(), bind(api.CreateLabelOption{}), org.CreateLabel) + m.Post("", reqToken(""), reqOrgOwnership(), bind(api.CreateLabelOption{}), org.CreateLabel) m.Combo("/{id}").Get(org.GetLabel). - Patch(reqToken(), reqOrgOwnership(), bind(api.EditLabelOption{}), org.EditLabel). - Delete(reqToken(), reqOrgOwnership(), org.DeleteLabel) + Patch(reqToken(""), reqOrgOwnership(), bind(api.EditLabelOption{}), org.EditLabel). + Delete(reqToken(""), reqOrgOwnership(), org.DeleteLabel) }) m.Group("/hooks", func() { m.Combo("").Get(org.ListHooks). @@ -1124,7 +1139,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Combo("/{id}").Get(org.GetHook). Patch(bind(api.EditHookOption{}), org.EditHook). Delete(org.DeleteHook) - }, reqToken(), reqOrgOwnership(), reqWebhooksEnabled()) + }, reqToken(""), reqOrgOwnership(), reqWebhooksEnabled()) }, orgAssignment(true)) m.Group("/teams/{teamid}", func() { m.Combo("").Get(org.GetTeam). @@ -1144,7 +1159,7 @@ func Routes(ctx gocontext.Context) *web.Route { Delete(org.RemoveTeamRepository). Get(org.GetTeamRepo) }) - }, orgAssignment(false, true), reqToken(), reqTeamMembership()) + }, orgAssignment(false, true), reqToken(""), reqTeamMembership()) m.Group("/admin", func() { m.Group("/cron", func() { @@ -1172,7 +1187,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Post("/{username}/{reponame}", admin.AdoptRepository) m.Delete("/{username}/{reponame}", admin.DeleteUnadoptedRepository) }) - }, reqToken(), reqSiteAdmin()) + }, reqToken(""), reqSiteAdmin()) m.Group("/topics", func() { m.Get("/search", repo.TopicSearch) diff --git a/services/auth/basic.go b/services/auth/basic.go index 9b32ad29af8bd..2e873daac7bb6 100644 --- a/services/auth/basic.go +++ b/services/auth/basic.go @@ -82,6 +82,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore } store.GetData()["IsApiToken"] = true + store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScopeAll return u } @@ -100,6 +101,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore } store.GetData()["IsApiToken"] = true + store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScopeAll return u } else if !auth_model.IsErrAccessTokenNotExist(err) && !auth_model.IsErrAccessTokenEmpty(err) { log.Error("GetAccessTokenBySha: %v", err) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index 67053d2b77730..98226906d0aa4 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -13,6 +13,7 @@ import ( "strings" asymkey_model "code.gitea.io/gitea/models/asymkey" + auth_model "code.gitea.io/gitea/models/auth" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -80,6 +81,7 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt } store.GetData()["IsApiToken"] = true + store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScopeAll log.Trace("HTTP Sign: Logged in user %-v", u) diff --git a/services/auth/oauth2.go b/services/auth/oauth2.go index 8f038d6104181..f3dc1e401376a 100644 --- a/services/auth/oauth2.go +++ b/services/auth/oauth2.go @@ -60,6 +60,8 @@ func (o *OAuth2) Name() string { } // userIDFromToken returns the user id corresponding to the OAuth token. +// It will set 'IsApiToken' to true if the token is an API token and +// set 'ApiTokenScope' to the scope of the access token func (o *OAuth2) userIDFromToken(req *http.Request, store DataStore) int64 { _ = req.ParseForm() @@ -87,6 +89,7 @@ func (o *OAuth2) userIDFromToken(req *http.Request, store DataStore) int64 { uid := CheckOAuthAccessToken(tokenSHA) if uid != 0 { store.GetData()["IsApiToken"] = true + store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScopeAll // fallback to all } return uid } @@ -102,6 +105,7 @@ func (o *OAuth2) userIDFromToken(req *http.Request, store DataStore) int64 { log.Error("UpdateAccessToken: %v", err) } store.GetData()["IsApiToken"] = true + store.GetData()["ApiTokenScope"] = t.Scope return t.UID } From cd1385014beb32302e3a85518dcad9dcb6e08cf3 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 6 Sep 2022 17:19:12 -0400 Subject: [PATCH 010/118] Let repo scope to cover admin:repo_hook --- models/auth/token_scope.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/models/auth/token_scope.go b/models/auth/token_scope.go index ef939cba43877..2a6090c66360f 100644 --- a/models/auth/token_scope.go +++ b/models/auth/token_scope.go @@ -97,6 +97,10 @@ func (s AccessTokenScope) Parse() (AccessTokenScopeBitmap, error) { case AccessTokenScopeRepo: bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeRepoStatus)) bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopePublicRepo)) + // admin:repo_hook, write:repo_hook, read:repo_hook + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeAdminRepoHook)) + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeWriteRepoHook)) + bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeReadRepoHook)) case AccessTokenScopeAdminOrg: bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeWriteOrg)) bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeReadOrg)) From 745ec98600432b47ae5558767b6ba44a497a2a1a Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 6 Sep 2022 19:46:36 -0400 Subject: [PATCH 011/118] Add sudo scope --- models/auth/token_scope.go | 26 ++++++++++++++++++++------ models/auth/token_scope_test.go | 5 ++++- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/models/auth/token_scope.go b/models/auth/token_scope.go index 2a6090c66360f..f41ba618a167a 100644 --- a/models/auth/token_scope.go +++ b/models/auth/token_scope.go @@ -50,6 +50,8 @@ const ( AccessTokenScopeAdminGPGKey = "admin:gpg_key" AccessTokenScopeWriteGPGKey = "write:gpg_key" AccessTokenScopeReadGPGKey = "read:gpg_key" + + AccessTokenScopeSudo = "sudo" ) // AllAccessTokenScopes contains all access token scopes. @@ -65,13 +67,14 @@ var AllAccessTokenScopes = []string{ AccessTokenScopeDeleteRepo, AccessTokenScopePackage, AccessTokenScopeWritePackage, AccessTokenScopeReadPackage, AccessTokenScopeDeletePackage, AccessTokenScopeAdminGPGKey, AccessTokenScopeWriteGPGKey, AccessTokenScopeReadGPGKey, + AccessTokenScopeSudo, } // AccessTokenScopeBitmap represents a bitmap of access token scopes. type AccessTokenScopeBitmap uint64 // AccessTokenScopeAllBitmap is the bitmap of all access token scopes. -var AccessTokenScopeAllBitmap AccessTokenScopeBitmap = 1< Date: Tue, 6 Sep 2022 19:50:10 -0400 Subject: [PATCH 012/118] Add more scope requirements --- routers/api/v1/api.go | 264 ++++++++++++++++++++++-------------------- 1 file changed, 136 insertions(+), 128 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index cacca8409670c..3a1c9fadb7748 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -650,7 +650,7 @@ func Routes(ctx gocontext.Context) *web.Route { })) m.Group("", func() { - // Miscellaneous + // Miscellaneous (no scope required) if setting.API.EnableSwagger { m.Get("/swagger", func(ctx *context.APIContext) { ctx.Redirect(setting.AppSubURL + "/api/swagger") @@ -687,7 +687,7 @@ func Routes(ctx gocontext.Context) *web.Route { Patch(notify.ReadThread) }, reqToken(auth_model.AccessTokenScopeNotification)) - // Users (public information, no scope required) + // Users (no scope required) m.Group("/users", func() { m.Get("/search", reqExploreSignIn(), user.Search) @@ -707,7 +707,7 @@ func Routes(ctx gocontext.Context) *web.Route { }, context_service.UserAssignmentAPI()) }) - // (public information, no scope required) + // (no scope required) m.Group("/users", func() { m.Group("/{username}", func() { m.Get("/keys", user.ListPublicKeys) @@ -728,12 +728,12 @@ func Routes(ctx gocontext.Context) *web.Route { m.Group("/user", func() { m.Get("", user.GetAuthenticatedUser) m.Group("/settings", func() { - m.Get("", reqToken(auth_model.AccessTokenScopeReadUser), user.GetUserSettings) // requires 'read:user' scope - m.Patch("", reqToken(auth_model.AccessTokenScopeReadUser), bind(api.UserSettingsOptions{}), user.UpdateUserSettings) // requires 'read:user' scope + m.Get("", reqToken(auth_model.AccessTokenScopeReadUser), user.GetUserSettings) + m.Patch("", reqToken(auth_model.AccessTokenScopeUser), bind(api.UserSettingsOptions{}), user.UpdateUserSettings) }, reqToken("")) - m.Combo("/emails").Get(reqToken(auth_model.AccessTokenScopeReadUser), user.ListEmails). // requires 'read:user' scope - Post(reqToken(auth_model.AccessTokenScopeUser), bind(api.CreateEmailOption{}), user.AddEmail). // requires 'user' scope - Delete(reqToken(auth_model.AccessTokenScopeUser), bind(api.DeleteEmailOption{}), user.DeleteEmail) // requires 'user' scope + m.Combo("/emails").Get(reqToken(auth_model.AccessTokenScopeReadUser), user.ListEmails). + Post(reqToken(auth_model.AccessTokenScopeUser), bind(api.CreateEmailOption{}), user.AddEmail). + Delete(reqToken(auth_model.AccessTokenScopeUser), bind(api.DeleteEmailOption{}), user.DeleteEmail) m.Get("/followers", user.ListMyFollowers) m.Group("/following", func() { @@ -745,12 +745,15 @@ func Routes(ctx gocontext.Context) *web.Route { }, context_service.UserAssignmentAPI()) }) + // (admin:public_key scope) m.Group("/keys", func() { - m.Combo("").Get(user.ListMyPublicKeys). - Post(bind(api.CreateKeyOption{}), user.CreatePublicKey) - m.Combo("/{id}").Get(user.GetPublicKey). - Delete(user.DeletePublicKey) + m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadPublicKey), user.ListMyPublicKeys). + Post(reqToken(auth_model.AccessTokenScopeWritePublicKey), bind(api.CreateKeyOption{}), user.CreatePublicKey) + m.Combo("/{id}").Get(reqToken(auth_model.AccessTokenScopeReadPublicKey), user.GetPublicKey). + Delete(reqToken(auth_model.AccessTokenScopeWritePublicKey), user.DeletePublicKey) }) + + // (repo scope) m.Group("/applications", func() { m.Combo("/oauth2"). Get(user.ListOauth2Applications). @@ -759,21 +762,25 @@ func Routes(ctx gocontext.Context) *web.Route { Delete(user.DeleteOauth2Application). Patch(bind(api.CreateOAuth2ApplicationOptions{}), user.UpdateOauth2Application). Get(user.GetOauth2Application) - }, reqToken("")) + }, reqToken(auth_model.AccessTokenScopeRepo)) + // (admin:gpg_key scope) m.Group("/gpg_keys", func() { - m.Combo("").Get(user.ListMyGPGKeys). - Post(bind(api.CreateGPGKeyOption{}), user.CreateGPGKey) - m.Combo("/{id}").Get(user.GetGPGKey). - Delete(user.DeleteGPGKey) + m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadGPGKey), user.ListMyGPGKeys). + Post(reqToken(auth_model.AccessTokenScopeWriteGPGKey), bind(api.CreateGPGKeyOption{}), user.CreateGPGKey) + m.Combo("/{id}").Get(reqToken(auth_model.AccessTokenScopeReadGPGKey), user.GetGPGKey). + Delete(reqToken(auth_model.AccessTokenScopeWriteGPGKey), user.DeleteGPGKey) }) - m.Get("/gpg_key_token", user.GetVerificationToken) - m.Post("/gpg_key_verify", bind(api.VerifyGPGKeyOption{}), user.VerifyUserGPGKey) + // (read:gpg_key scope) + m.Get("/gpg_key_token", reqToken(auth_model.AccessTokenScopeReadGPGKey), user.GetVerificationToken) + m.Post("/gpg_key_verify", reqToken(auth_model.AccessTokenScopeReadGPGKey), bind(api.VerifyGPGKeyOption{}), user.VerifyUserGPGKey) - m.Combo("/repos").Get(user.ListMyRepos). + // (repo scope) + m.Combo("/repos", reqToken(auth_model.AccessTokenScopeRepo)).Get(user.ListMyRepos). Post(bind(api.CreateRepoOption{}), repo.Create) + // (repo scope) m.Group("/starred", func() { m.Get("", user.GetMyStarredRepos) m.Group("/{username}/{reponame}", func() { @@ -781,57 +788,58 @@ func Routes(ctx gocontext.Context) *web.Route { m.Put("", user.Star) m.Delete("", user.Unstar) }, repoAssignment()) - }) - m.Get("/times", repo.ListMyTrackedTimes) - - m.Get("/stopwatches", repo.GetStopwatches) - - m.Get("/subscriptions", user.GetMyWatchedRepos) - - m.Get("/teams", org.ListUserTeams) + }, reqToken(auth_model.AccessTokenScopeRepo)) + m.Get("/times", reqToken(auth_model.AccessTokenScopeRepo), repo.ListMyTrackedTimes) + m.Get("/stopwatches", reqToken(auth_model.AccessTokenScopeRepo), repo.GetStopwatches) + m.Get("/subscriptions", reqToken(auth_model.AccessTokenScopeRepo), user.GetMyWatchedRepos) + m.Get("/teams", reqToken(auth_model.AccessTokenScopeRepo), org.ListUserTeams) }, reqToken("")) - // Repositories - m.Post("/org/{org}/repos", reqToken(""), bind(api.CreateRepoOption{}), repo.CreateOrgRepoDeprecated) + // Repositories (admin:org scope) + m.Post("/org/{org}/repos", reqToken(auth_model.AccessTokenScopeAdminOrg), bind(api.CreateRepoOption{}), repo.CreateOrgRepoDeprecated) - m.Combo("/repositories/{id}", reqToken("")).Get(repo.GetByID) + // (repo scope) + m.Combo("/repositories/{id}", reqToken(auth_model.AccessTokenScopeRepo)).Get(repo.GetByID) m.Group("/repos", func() { m.Get("/search", repo.Search) m.Get("/issues/search", repo.SearchIssues) - m.Post("/migrate", reqToken(""), bind(api.MigrateRepoOptions{}), repo.Migrate) + // (repo scope) + m.Post("/migrate", reqToken(auth_model.AccessTokenScopeRepo), bind(api.MigrateRepoOptions{}), repo.Migrate) m.Group("/{username}/{reponame}", func() { m.Combo("").Get(reqAnyRepoReader(), repo.Get). Delete(reqToken(auth_model.AccessTokenScopeDeleteRepo), reqOwner(), repo.Delete). Patch(reqToken(auth_model.AccessTokenScopeRepo), reqAdmin(), bind(api.EditRepoOption{}), repo.Edit) - m.Post("/generate", reqToken(""), reqRepoReader(unit.TypeCode), bind(api.GenerateRepoOption{}), repo.Generate) - m.Post("/transfer", reqOwner(), bind(api.TransferRepoOption{}), repo.Transfer) - m.Post("/transfer/accept", reqToken(""), repo.AcceptTransfer) - m.Post("/transfer/reject", reqToken(""), repo.RejectTransfer) + m.Post("/generate", reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode), bind(api.GenerateRepoOption{}), repo.Generate) + m.Group("/transfer", func() { + m.Post("", reqOwner(), bind(api.TransferRepoOption{}), repo.Transfer) + m.Post("/accept", repo.AcceptTransfer) + m.Post("/reject", repo.RejectTransfer) + }, reqToken(auth_model.AccessTokenScopeRepo)) m.Combo("/notifications", reqToken(auth_model.AccessTokenScopeNotification)). - Get(reqToken(""), notify.ListRepoNotifications). - Put(reqToken(""), notify.ReadRepoNotifications) + Get(notify.ListRepoNotifications). + Put(notify.ReadRepoNotifications) m.Group("/hooks/git", func() { - m.Combo("").Get(repo.ListGitHooks) + m.Get("", reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.ListGitHooks) m.Group("/{id}", func() { - m.Combo("").Get(repo.GetGitHook). - Patch(bind(api.EditGitHookOption{}), repo.EditGitHook). - Delete(repo.DeleteGitHook) + m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.GetGitHook). + Patch(reqToken(auth_model.AccessTokenScopeWriteRepoHook), bind(api.EditGitHookOption{}), repo.EditGitHook). + Delete(reqToken(auth_model.AccessTokenScopeWriteRepoHook), repo.DeleteGitHook) }) - }, reqToken(""), reqAdmin(), reqGitHook(), context.ReferencesGitRepo(true)) + }, reqAdmin(), reqGitHook(), context.ReferencesGitRepo(true)) m.Group("/hooks", func() { - m.Combo("").Get(repo.ListHooks). - Post(bind(api.CreateHookOption{}), repo.CreateHook) + m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.ListHooks). + Post(reqToken(auth_model.AccessTokenScopeWriteRepoHook), bind(api.CreateHookOption{}), repo.CreateHook) m.Group("/{id}", func() { - m.Combo("").Get(repo.GetHook). - Patch(bind(api.EditHookOption{}), repo.EditHook). - Delete(repo.DeleteHook) - m.Post("/tests", context.ReferencesGitRepo(), context.RepoRefForAPI, repo.TestHook) + m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.GetHook). + Patch(reqToken(auth_model.AccessTokenScopeWriteRepoHook), bind(api.EditHookOption{}), repo.EditHook). + Delete(reqToken(auth_model.AccessTokenScopeWriteRepoHook), repo.DeleteHook) + m.Post("/tests", reqToken(auth_model.AccessTokenScopeReadRepoHook), context.ReferencesGitRepo(), context.RepoRefForAPI, repo.TestHook) }) - }, reqToken(""), reqAdmin(), reqWebhooksEnabled()) + }, reqAdmin(), reqWebhooksEnabled()) m.Group("/collaborators", func() { m.Get("", reqAnyRepoReader(), repo.ListCollaborators) m.Group("/{collaborator}", func() { @@ -840,26 +848,26 @@ func Routes(ctx gocontext.Context) *web.Route { Delete(reqAdmin(), repo.DeleteCollaborator) m.Get("/permission", repo.GetRepoPermissions) }, reqToken("")) - }, reqToken("")) - m.Get("/assignees", reqToken(""), reqAnyRepoReader(), repo.GetAssignees) - m.Get("/reviewers", reqToken(""), reqAnyRepoReader(), repo.GetReviewers) + }, reqToken(auth_model.AccessTokenScopeRepo)) + m.Get("/assignees", reqToken(auth_model.AccessTokenScopeRepo), reqAnyRepoReader(), repo.GetAssignees) + m.Get("/reviewers", reqToken(auth_model.AccessTokenScopeRepo), reqAnyRepoReader(), repo.GetReviewers) m.Group("/teams", func() { m.Get("", reqAnyRepoReader(), repo.ListTeams) m.Combo("/{team}").Get(reqAnyRepoReader(), repo.IsTeam). Put(reqAdmin(), repo.AddTeam). Delete(reqAdmin(), repo.DeleteTeam) - }, reqToken("")) - m.Get("/raw/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFile) - m.Get("/media/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFileOrLFS) - m.Get("/archive/*", reqRepoReader(unit.TypeCode), repo.GetArchive) - m.Combo("/forks").Get(repo.ListForks). + }, reqToken(auth_model.AccessTokenScopeRepo)) + m.Get("/raw/*", reqToken(auth_model.AccessTokenScopeRepo), context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFile) + m.Get("/media/*", reqToken(auth_model.AccessTokenScopeRepo), context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFileOrLFS) + m.Get("/archive/*", reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode), repo.GetArchive) + m.Combo("/forks", reqToken(auth_model.AccessTokenScopeRepo)).Get(repo.ListForks). Post(reqToken(""), reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork) m.Group("/branches", func() { m.Get("", repo.ListBranches) m.Get("/*", repo.GetBranch) m.Delete("/*", reqRepoWriter(unit.TypeCode), repo.DeleteBranch) m.Post("", reqRepoWriter(unit.TypeCode), bind(api.CreateBranchRepoOption{}), repo.CreateBranch) - }, context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode)) + }, reqToken(auth_model.AccessTokenScopeRepo), context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode)) m.Group("/branch_protections", func() { m.Get("", repo.ListBranchProtections) m.Post("", bind(api.CreateBranchProtectionOption{}), repo.CreateBranchProtection) @@ -868,23 +876,23 @@ func Routes(ctx gocontext.Context) *web.Route { m.Patch("", bind(api.EditBranchProtectionOption{}), repo.EditBranchProtection) m.Delete("", repo.DeleteBranchProtection) }) - }, reqToken(""), reqAdmin()) + }, reqToken(auth_model.AccessTokenScopeRepo), reqAdmin()) m.Group("/tags", func() { m.Get("", repo.ListTags) m.Get("/*", repo.GetTag) m.Post("", reqRepoWriter(unit.TypeCode), bind(api.CreateTagOption{}), repo.CreateTag) m.Delete("/*", repo.DeleteTag) - }, reqRepoReader(unit.TypeCode), context.ReferencesGitRepo(true)) + }, reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode), context.ReferencesGitRepo(true)) m.Group("/keys", func() { m.Combo("").Get(repo.ListDeployKeys). Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey) m.Combo("/{id}").Get(repo.GetDeployKey). Delete(repo.DeleteDeploykey) - }, reqToken(""), reqAdmin()) + }, reqToken(auth_model.AccessTokenScopeRepo), reqAdmin()) m.Group("/times", func() { m.Combo("").Get(repo.ListTrackedTimesByRepository) m.Combo("/{timetrackingusername}").Get(repo.ListTrackedTimesByUser) - }, mustEnableIssues, reqToken("")) + }, reqToken(auth_model.AccessTokenScopeRepo), mustEnableIssues, reqToken("")) m.Group("/wiki", func() { m.Combo("/page/{pageName}"). Get(repo.GetWikiPage). @@ -893,7 +901,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/revisions/{pageName}", repo.ListPageRevisions) m.Post("/new", mustNotBeArchived, reqRepoWriter(unit.TypeWiki), bind(api.CreateWikiPageOptions{}), repo.NewWikiPage) m.Get("/pages", repo.ListWikiPages) - }, mustEnableWiki) + }, reqToken(auth_model.AccessTokenScopeRepo), mustEnableWiki) m.Group("/issues", func() { m.Combo("").Get(repo.ListIssues). Post(reqToken(""), mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue) @@ -952,30 +960,30 @@ func Routes(ctx gocontext.Context) *web.Route { Post(reqToken(""), bind(api.EditReactionOption{}), repo.PostIssueReaction). Delete(reqToken(""), bind(api.EditReactionOption{}), repo.DeleteIssueReaction) }) - }, mustEnableIssuesOrPulls) + }, reqToken(auth_model.AccessTokenScopeRepo), mustEnableIssuesOrPulls) m.Group("/labels", func() { m.Combo("").Get(repo.ListLabels). Post(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateLabelOption{}), repo.CreateLabel) m.Combo("/{id}").Get(repo.GetLabel). Patch(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditLabelOption{}), repo.EditLabel). Delete(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteLabel) - }) - m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown) - m.Post("/markdown/raw", misc.MarkdownRaw) + }, reqToken(auth_model.AccessTokenScopeRepo)) + m.Post("/markdown", reqToken(auth_model.AccessTokenScopeRepo), bind(api.MarkdownOption{}), misc.Markdown) + m.Post("/markdown/raw", reqToken(auth_model.AccessTokenScopeRepo), misc.MarkdownRaw) m.Group("/milestones", func() { m.Combo("").Get(repo.ListMilestones). Post(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateMilestoneOption{}), repo.CreateMilestone) m.Combo("/{id}").Get(repo.GetMilestone). Patch(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditMilestoneOption{}), repo.EditMilestone). Delete(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteMilestone) - }) - m.Get("/stargazers", repo.ListStargazers) - m.Get("/subscribers", repo.ListSubscribers) + }, reqToken(auth_model.AccessTokenScopeRepo)) + m.Get("/stargazers", reqToken(auth_model.AccessTokenScopeRepo), repo.ListStargazers) + m.Get("/subscribers", reqToken(auth_model.AccessTokenScopeRepo), repo.ListSubscribers) m.Group("/subscription", func() { m.Get("", user.IsWatching) m.Put("", reqToken(""), user.Watch) m.Delete("", reqToken(""), user.Unwatch) - }) + }, reqToken(auth_model.AccessTokenScopeRepo)) m.Group("/releases", func() { m.Combo("").Get(repo.ListReleases). Post(reqToken(""), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.CreateReleaseOption{}), repo.CreateRelease) @@ -990,24 +998,24 @@ func Routes(ctx gocontext.Context) *web.Route { Patch(reqToken(""), reqRepoWriter(unit.TypeReleases), bind(api.EditAttachmentOptions{}), repo.EditReleaseAttachment). Delete(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseAttachment) }) - }) + }, reqToken(auth_model.AccessTokenScopeRepo)) m.Group("/tags", func() { m.Combo("/{tag}"). Get(repo.GetReleaseByTag). Delete(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseByTag) - }) + }, reqToken(auth_model.AccessTokenScopeRepo)) }, reqRepoReader(unit.TypeReleases)) - m.Post("/mirror-sync", reqToken(""), reqRepoWriter(unit.TypeCode), repo.MirrorSync) - m.Post("/push_mirrors-sync", reqAdmin(), repo.PushMirrorSync) + m.Post("/mirror-sync", reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeCode), repo.MirrorSync) + m.Post("/push_mirrors-sync", reqToken(auth_model.AccessTokenScopeRepo), reqAdmin(), repo.PushMirrorSync) m.Group("/push_mirrors", func() { m.Combo("").Get(repo.ListPushMirrors). Post(bind(api.CreatePushMirrorOption{}), repo.AddPushMirror) m.Combo("/{name}"). Delete(repo.DeletePushMirrorByRemoteName). Get(repo.GetPushMirrorByName) - }, reqAdmin()) + }, reqToken(auth_model.AccessTokenScopeRepo), reqAdmin()) - m.Get("/editorconfig/{filename}", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetEditorconfig) + m.Get("/editorconfig/{filename}", reqToken(auth_model.AccessTokenScopeRepo), context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetEditorconfig) m.Group("/pulls", func() { m.Combo("").Get(repo.ListPullRequests). Post(reqToken(""), mustNotBeArchived, bind(api.CreatePullRequestOption{}), repo.CreatePullRequest) @@ -1039,18 +1047,18 @@ func Routes(ctx gocontext.Context) *web.Route { Delete(reqToken(""), bind(api.PullReviewRequestOptions{}), repo.DeleteReviewRequests). Post(reqToken(""), bind(api.PullReviewRequestOptions{}), repo.CreateReviewRequests) }) - }, mustAllowPulls, reqRepoReader(unit.TypeCode), context.ReferencesGitRepo()) + }, reqToken(auth_model.AccessTokenScopeRepo), mustAllowPulls, reqRepoReader(unit.TypeCode), context.ReferencesGitRepo()) m.Group("/statuses", func() { m.Combo("/{sha}").Get(repo.GetCommitStatuses). Post(reqToken(""), reqRepoWriter(unit.TypeCode), bind(api.CreateStatusOption{}), repo.NewCommitStatus) - }, reqRepoReader(unit.TypeCode)) + }, reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode)) m.Group("/commits", func() { m.Get("", context.ReferencesGitRepo(), repo.GetAllCommits) m.Group("/{ref}", func() { m.Get("/status", repo.GetCombinedCommitStatusByRef) m.Get("/statuses", repo.GetCommitStatusesByRef) }, context.ReferencesGitRepo()) - }, reqRepoReader(unit.TypeCode)) + }, reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode)) m.Group("/git", func() { m.Group("/commits", func() { m.Get("/{sha}", repo.GetSingleCommit) @@ -1062,8 +1070,8 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/blobs/{sha}", repo.GetBlob) m.Get("/tags/{sha}", repo.GetAnnotatedTag) m.Get("/notes/{sha}", repo.GetNote) - }, context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode)) - m.Post("/diffpatch", reqRepoWriter(unit.TypeCode), reqToken(""), bind(api.ApplyDiffPatchFileOptions{}), repo.ApplyDiffPatch) + }, reqToken(auth_model.AccessTokenScopeRepo), context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode)) + m.Post("/diffpatch", reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeCode), bind(api.ApplyDiffPatchFileOptions{}), repo.ApplyDiffPatch) m.Group("/contents", func() { m.Get("", repo.GetContentsList) m.Get("/*", repo.GetContents) @@ -1071,7 +1079,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Post("", bind(api.CreateFileOptions{}), reqRepoBranchWriter, repo.CreateFile) m.Put("", bind(api.UpdateFileOptions{}), reqRepoBranchWriter, repo.UpdateFile) m.Delete("", bind(api.DeleteFileOptions{}), reqRepoBranchWriter, repo.DeleteFile) - }, reqToken("")) + }, reqToken(auth_model.AccessTokenScopeRepo)) }, reqRepoReader(unit.TypeCode)) m.Get("/signing-key.gpg", misc.SigningKey) m.Group("/topics", func() { @@ -1081,7 +1089,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Combo("").Put(reqToken(""), repo.AddTopic). Delete(reqToken(""), repo.DeleteTopic) }, reqAdmin()) - }, reqAnyRepoReader()) + }, reqToken(auth_model.AccessTokenScopeRepo), reqAnyRepoReader()) m.Get("/issue_templates", context.ReferencesGitRepo(), repo.GetIssueTemplates) m.Get("/languages", reqRepoReader(unit.TypeCode), repo.GetLanguages) }, repoAssignment()) @@ -1089,49 +1097,49 @@ func Routes(ctx gocontext.Context) *web.Route { m.Group("/packages/{username}", func() { m.Group("/{type}/{name}/{version}", func() { - m.Get("", packages.GetPackage) - m.Delete("", reqPackageAccess(perm.AccessModeWrite), packages.DeletePackage) - m.Get("/files", packages.ListPackageFiles) + m.Get("", reqToken(auth_model.AccessTokenScopeReadPackage), packages.GetPackage) + m.Delete("", reqToken(auth_model.AccessTokenScopeDeletePackage), reqPackageAccess(perm.AccessModeWrite), packages.DeletePackage) + m.Get("/files", reqToken(auth_model.AccessTokenScopeReadPackage), packages.ListPackageFiles) }) - m.Get("/", packages.ListPackages) + m.Get("/", reqToken(auth_model.AccessTokenScopeReadPackage), packages.ListPackages) }, context_service.UserAssignmentAPI(), context.PackageAssignmentAPI(), reqPackageAccess(perm.AccessModeRead)) // Organizations - m.Get("/user/orgs", reqToken(""), org.ListMyOrgs) + m.Get("/user/orgs", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListMyOrgs) m.Group("/users/{username}/orgs", func() { - m.Get("", org.ListUserOrgs) - m.Get("/{org}/permissions", reqToken(""), org.GetUserOrgsPermissions) + m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListUserOrgs) + m.Get("/{org}/permissions", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetUserOrgsPermissions) }, context_service.UserAssignmentAPI()) - m.Post("/orgs", reqToken(""), bind(api.CreateOrgOption{}), org.Create) - m.Get("/orgs", org.GetAll) + m.Post("/orgs", reqToken(auth_model.AccessTokenScopeWriteOrg), bind(api.CreateOrgOption{}), org.Create) + m.Get("/orgs", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetAll) m.Group("/orgs/{org}", func() { - m.Combo("").Get(org.Get). - Patch(reqToken(""), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit). - Delete(reqToken(""), reqOrgOwnership(), org.Delete) - m.Combo("/repos").Get(user.ListOrgRepos). - Post(reqToken(""), bind(api.CreateRepoOption{}), repo.CreateOrgRepo) + m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.Get). + Patch(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit). + Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.Delete) + m.Combo("/repos").Get(reqToken(auth_model.AccessTokenScopeReadOrg), user.ListOrgRepos). + Post(reqToken(auth_model.AccessTokenScopeWriteOrg), bind(api.CreateRepoOption{}), repo.CreateOrgRepo) m.Group("/members", func() { - m.Get("", org.ListMembers) + m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListMembers) m.Combo("/{username}").Get(org.IsMember). - Delete(reqToken(""), reqOrgOwnership(), org.DeleteMember) + Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.DeleteMember) }) m.Group("/public_members", func() { - m.Get("", org.ListPublicMembers) - m.Combo("/{username}").Get(org.IsPublicMember). - Put(reqToken(""), reqOrgMembership(), org.PublicizeMember). - Delete(reqToken(""), reqOrgMembership(), org.ConcealMember) + m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListPublicMembers) + m.Combo("/{username}").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.IsPublicMember). + Put(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgMembership(), org.PublicizeMember). + Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgMembership(), org.ConcealMember) }) m.Group("/teams", func() { - m.Get("", org.ListTeams) - m.Post("", reqOrgOwnership(), bind(api.CreateTeamOption{}), org.CreateTeam) - m.Get("/search", org.SearchTeam) - }, reqToken(""), reqOrgMembership()) + m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListTeams) + m.Post("", reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.CreateTeamOption{}), org.CreateTeam) + m.Get("/search", reqToken(auth_model.AccessTokenScopeReadOrg), org.SearchTeam) + }, reqOrgMembership()) m.Group("/labels", func() { - m.Get("", org.ListLabels) - m.Post("", reqToken(""), reqOrgOwnership(), bind(api.CreateLabelOption{}), org.CreateLabel) - m.Combo("/{id}").Get(org.GetLabel). - Patch(reqToken(""), reqOrgOwnership(), bind(api.EditLabelOption{}), org.EditLabel). - Delete(reqToken(""), reqOrgOwnership(), org.DeleteLabel) + m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListLabels) + m.Post("", reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.CreateLabelOption{}), org.CreateLabel) + m.Combo("/{id}").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetLabel). + Patch(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.EditLabelOption{}), org.EditLabel). + Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.DeleteLabel) }) m.Group("/hooks", func() { m.Combo("").Get(org.ListHooks). @@ -1139,27 +1147,27 @@ func Routes(ctx gocontext.Context) *web.Route { m.Combo("/{id}").Get(org.GetHook). Patch(bind(api.EditHookOption{}), org.EditHook). Delete(org.DeleteHook) - }, reqToken(""), reqOrgOwnership(), reqWebhooksEnabled()) + }, reqToken(auth_model.AccessTokenScopeAdminOrgHook), reqOrgOwnership(), reqWebhooksEnabled()) }, orgAssignment(true)) m.Group("/teams/{teamid}", func() { - m.Combo("").Get(org.GetTeam). - Patch(reqOrgOwnership(), bind(api.EditTeamOption{}), org.EditTeam). - Delete(reqOrgOwnership(), org.DeleteTeam) + m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeam). + Patch(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.EditTeamOption{}), org.EditTeam). + Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.DeleteTeam) m.Group("/members", func() { - m.Get("", org.GetTeamMembers) + m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamMembers) m.Combo("/{username}"). - Get(org.GetTeamMember). - Put(reqOrgOwnership(), org.AddTeamMember). - Delete(reqOrgOwnership(), org.RemoveTeamMember) + Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamMember). + Put(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.AddTeamMember). + Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.RemoveTeamMember) }) m.Group("/repos", func() { - m.Get("", org.GetTeamRepos) + m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamRepos) m.Combo("/{org}/{reponame}"). - Put(org.AddTeamRepository). - Delete(org.RemoveTeamRepository). - Get(org.GetTeamRepo) + Put(reqToken(auth_model.AccessTokenScopeWriteOrg), org.AddTeamRepository). + Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), org.RemoveTeamRepository). + Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamRepo) }) - }, orgAssignment(false, true), reqToken(""), reqTeamMembership()) + }, orgAssignment(false, true), reqTeamMembership()) m.Group("/admin", func() { m.Group("/cron", func() { @@ -1187,7 +1195,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Post("/{username}/{reponame}", admin.AdoptRepository) m.Delete("/{username}/{reponame}", admin.DeleteUnadoptedRepository) }) - }, reqToken(""), reqSiteAdmin()) + }, reqToken(auth_model.AccessTokenScopeSudo), reqSiteAdmin()) m.Group("/topics", func() { m.Get("/search", repo.TopicSearch) From 6f4eed091245dabbc84aa65641c6c2291ce15ec2 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 6 Sep 2022 23:18:33 -0400 Subject: [PATCH 013/118] Add token selection UI --- options/locale/locale_en-US.ini | 1 + templates/user/settings/applications.tmpl | 183 +++++++++++++++++++++- 2 files changed, 183 insertions(+), 1 deletion(-) diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index 6845680ccfbdf..780b26e73fd1b 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -723,6 +723,7 @@ access_token_deletion_cancel_action = Cancel access_token_deletion_confirm_action = Delete access_token_deletion_desc = Deleting a token will revoke access to your account for applications using it. This cannot be undone. Continue? delete_token_success = The token has been deleted. Applications using it no longer have access to your account. +select_scopes = Select scopes manage_oauth2_applications = Manage OAuth2 Applications edit_oauth2_application = Edit OAuth2 Application diff --git a/templates/user/settings/applications.tmpl b/templates/user/settings/applications.tmpl index 9125f4bd00f6a..ed54f409e6095 100644 --- a/templates/user/settings/applications.tmpl +++ b/templates/user/settings/applications.tmpl @@ -41,6 +41,187 @@ +
+ + {{.locale.Tr "settings.select_scopes"}} + +
+
+ + +
+
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+
+ + +
+
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+
+ + +
+
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+
+ + +
+
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+
+ + +
+
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+
+ + +
+
+
@@ -75,4 +256,4 @@ -{{template "base/footer" .}} +{{template "base/footer" .}} \ No newline at end of file From 4fd1722ed476236ae4688315b79f57a926891f58 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 6 Sep 2022 23:19:26 -0400 Subject: [PATCH 014/118] Update access token form --- services/forms/user_form.go | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/services/forms/user_form.go b/services/forms/user_form.go index 8ce1d85c57781..de07d84dd9ea3 100644 --- a/services/forms/user_form.go +++ b/services/forms/user_form.go @@ -368,7 +368,33 @@ func (f *AddKeyForm) Validate(req *http.Request, errs binding.Errors) binding.Er // NewAccessTokenForm form for creating access token type NewAccessTokenForm struct { - Name string `binding:"Required;MaxSize(255)"` + Name string `binding:"Required;MaxSize(255)"` + ScopeRepo bool + ScopeRepoStatus bool + ScopePublicRepo bool + ScopeAdminOrg bool + ScopeWriteOrg bool + ScopeReadOrg bool + ScopeAdminPublicKey bool + ScopeWritePublicKey bool + ScopeReadPublicKey bool + ScopeAdminRepoHook bool + ScopeWriteRepoHook bool + ScopeReadRepoHook bool + ScopeNotification bool + ScopeUser bool + ScopeReadUser bool + ScopeUserEmail bool + ScopeUserFollow bool + ScopeDeleteRepo bool + ScopePackage bool + ScopeWritePackage bool + ScopeReadPackage bool + ScopeDeletePackage bool + ScopeAdminGPGKey bool + ScopeWriteGPGKey bool + ScopeReadGPGKey bool + ScopeSudo bool } // Validate validates the fields From 4476e1d7778b22f4b5376fbc494079149567d78f Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 6 Sep 2022 23:32:39 -0400 Subject: [PATCH 015/118] Fix integration tests for api_branch --- tests/integration/api_branch_test.go | 14 +++++++------- tests/integration/integration_test.go | 11 ++++++++--- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/tests/integration/api_branch_test.go b/tests/integration/api_branch_test.go index bdfdd3c7520be..e5d58d0b46296 100644 --- a/tests/integration/api_branch_test.go +++ b/tests/integration/api_branch_test.go @@ -17,7 +17,7 @@ import ( func testAPIGetBranch(t *testing.T, branchName string, exists bool) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branches/%s?token=%s", branchName, token) resp := session.MakeRequest(t, req, NoExpectedStatus) if !exists { @@ -34,7 +34,7 @@ func testAPIGetBranch(t *testing.T, branchName string, exists bool) { func testAPIGetBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branch_protections/%s?token=%s", branchName, token) resp := session.MakeRequest(t, req, expectedHTTPStatus) @@ -47,7 +47,7 @@ func testAPIGetBranchProtection(t *testing.T, branchName string, expectedHTTPSta func testAPICreateBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/branch_protections?token="+token, &api.BranchProtection{ BranchName: branchName, }) @@ -62,7 +62,7 @@ func testAPICreateBranchProtection(t *testing.T, branchName string, expectedHTTP func testAPIEditBranchProtection(t *testing.T, branchName string, body *api.BranchProtection, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestWithJSON(t, "PATCH", "/api/v1/repos/user2/repo1/branch_protections/"+branchName+"?token="+token, body) resp := session.MakeRequest(t, req, expectedHTTPStatus) @@ -75,14 +75,14 @@ func testAPIEditBranchProtection(t *testing.T, branchName string, body *api.Bran func testAPIDeleteBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branch_protections/%s?token=%s", branchName, token) session.MakeRequest(t, req, expectedHTTPStatus) } func testAPIDeleteBranch(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branches/%s?token=%s", branchName, token) session.MakeRequest(t, req, expectedHTTPStatus) } @@ -156,7 +156,7 @@ func testAPICreateBranches(t *testing.T, giteaURL *url.URL) { } func testAPICreateBranch(t testing.TB, session *TestSession, user, repo, oldBranch, newBranch string, status int) bool { - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestWithJSON(t, "POST", "/api/v1/repos/"+user+"/"+repo+"/branches?token="+token, &api.CreateBranchRepoOption{ BranchName: newBranch, OldBranchName: oldBranch, diff --git a/tests/integration/integration_test.go b/tests/integration/integration_test.go index 8fc8a854a70dc..1ae4a830809c7 100644 --- a/tests/integration/integration_test.go +++ b/tests/integration/integration_test.go @@ -261,16 +261,21 @@ func loginUserWithPassword(t testing.TB, userName, password string) *TestSession // token has to be unique this counter take care of var tokenCounter int64 -func getTokenForLoggedInUser(t testing.TB, session *TestSession) string { +func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...string) string { + // TODO set the scope for the token t.Helper() tokenCounter++ req := NewRequest(t, "GET", "/user/settings/applications") resp := session.MakeRequest(t, req, http.StatusOK) doc := NewHTMLParser(t, resp.Body) - req = NewRequestWithValues(t, "POST", "/user/settings/applications", map[string]string{ + values := map[string]string{ "_csrf": doc.GetCSRF(), "name": fmt.Sprintf("api-testing-token-%d", tokenCounter), - }) + } + for _, scope := range scopes { + values[fmt.Sprintf("scope_[%s]", scope)] = "on" + } + req = NewRequestWithValues(t, "POST", "/user/settings/applications", values) session.MakeRequest(t, req, http.StatusSeeOther) req = NewRequest(t, "GET", "/user/settings/applications") resp = session.MakeRequest(t, req, http.StatusOK) From 86341c533ea9d582aa72e70937e497e9144954dd Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 6 Sep 2022 23:36:59 -0400 Subject: [PATCH 016/118] Fix ending newline for a template --- templates/user/settings/applications.tmpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/user/settings/applications.tmpl b/templates/user/settings/applications.tmpl index ed54f409e6095..536bdd8e86d2c 100644 --- a/templates/user/settings/applications.tmpl +++ b/templates/user/settings/applications.tmpl @@ -256,4 +256,4 @@ -{{template "base/footer" .}} \ No newline at end of file +{{template "base/footer" .}} From cfcbdba1f89e87c1a7e9d037159cccfe49816260 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 6 Sep 2022 23:42:15 -0400 Subject: [PATCH 017/118] Update the types for ApiTokenScope in context --- services/auth/basic.go | 4 ++-- services/auth/httpsign.go | 2 +- services/auth/oauth2.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/auth/basic.go b/services/auth/basic.go index 2e873daac7bb6..5011a64e02af7 100644 --- a/services/auth/basic.go +++ b/services/auth/basic.go @@ -82,7 +82,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore } store.GetData()["IsApiToken"] = true - store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScopeAll + store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScope(auth_model.AccessTokenScopeAll) return u } @@ -101,7 +101,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore } store.GetData()["IsApiToken"] = true - store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScopeAll + store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScope(auth_model.AccessTokenScopeAll) return u } else if !auth_model.IsErrAccessTokenNotExist(err) && !auth_model.IsErrAccessTokenEmpty(err) { log.Error("GetAccessTokenBySha: %v", err) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index 98226906d0aa4..f800a509d941d 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -81,7 +81,7 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt } store.GetData()["IsApiToken"] = true - store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScopeAll + store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScope(auth_model.AccessTokenScopeAll) log.Trace("HTTP Sign: Logged in user %-v", u) diff --git a/services/auth/oauth2.go b/services/auth/oauth2.go index f3dc1e401376a..ba68e35d6a5d4 100644 --- a/services/auth/oauth2.go +++ b/services/auth/oauth2.go @@ -89,7 +89,7 @@ func (o *OAuth2) userIDFromToken(req *http.Request, store DataStore) int64 { uid := CheckOAuthAccessToken(tokenSHA) if uid != 0 { store.GetData()["IsApiToken"] = true - store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScopeAll // fallback to all + store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScope(auth_model.AccessTokenScopeAll) // fallback to all } return uid } From 4b570b83f83951b84eb94f54d582f335bec4fdd2 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Wed, 7 Sep 2022 10:34:34 -0400 Subject: [PATCH 018/118] Parse scope for request when adding a token --- routers/web/user/setting/applications.go | 5 +++-- services/forms/user_form.go | 16 ++++++++++++++++ services/forms/user_form_test.go | 24 ++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/routers/web/user/setting/applications.go b/routers/web/user/setting/applications.go index e9572a07a6c51..c36436e8934c9 100644 --- a/routers/web/user/setting/applications.go +++ b/routers/web/user/setting/applications.go @@ -44,8 +44,9 @@ func ApplicationsPost(ctx *context.Context) { } t := &auth_model.AccessToken{ - UID: ctx.Doer.ID, - Name: form.Name, + UID: ctx.Doer.ID, + Name: form.Name, + Scope: form.GetScope(), } exist, err := auth_model.AccessTokenByNameExists(t) diff --git a/services/forms/user_form.go b/services/forms/user_form.go index de07d84dd9ea3..fa7cd5a259dc4 100644 --- a/services/forms/user_form.go +++ b/services/forms/user_form.go @@ -8,11 +8,14 @@ package forms import ( "mime/multipart" "net/http" + "reflect" "strings" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/structs" + "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/web/middleware" "gitea.com/go-chi/binding" @@ -403,6 +406,19 @@ func (f *NewAccessTokenForm) Validate(req *http.Request, errs binding.Errors) bi return middleware.Validate(errs, ctx.Data, f, ctx.Locale) } +func (f *NewAccessTokenForm) GetScope() auth_model.AccessTokenScope { + scope := "" + v := reflect.ValueOf(*f) + for i := 0; i < v.NumField(); i++ { + if strings.HasPrefix(v.Type().Field(i).Name, "Scope") && v.Field(i).Bool() { + singleScope := v.Type().Field(i).Name[5:] + scope += util.ToSnakeCase(singleScope) + "," + } + } + scope = strings.TrimSuffix(scope, ",") + return auth_model.AccessTokenScope(scope) +} + // EditOAuth2ApplicationForm form for editing oauth2 applications type EditOAuth2ApplicationForm struct { Name string `binding:"Required;MaxSize(255)" form:"application_name"` diff --git a/services/forms/user_form_test.go b/services/forms/user_form_test.go index 9f67143d12c81..8603694de5fd3 100644 --- a/services/forms/user_form_test.go +++ b/services/forms/user_form_test.go @@ -5,8 +5,10 @@ package forms import ( + "strconv" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" @@ -84,3 +86,25 @@ func TestRegisterForm_IsDomainAllowed_BlocklistedEmail(t *testing.T) { assert.Equal(t, v.valid, form.IsEmailDomainAllowed()) } } + +func TestNewAccessTokenForm_GetScope(t *testing.T) { + tests := []struct { + form NewAccessTokenForm + scope auth_model.AccessTokenScope + }{ + { + form: NewAccessTokenForm{Name: "test", ScopeRepo: true}, + scope: "repo", + }, + { + form: NewAccessTokenForm{Name: "test", ScopeRepo: true, ScopeUser: true}, + scope: "repo,user", + }, + } + + for i, test := range tests { + t.Run(strconv.Itoa(i), func(t *testing.T) { + assert.Equal(t, test.scope, test.form.GetScope()) + }) + } +} From 1ebfc83bb2026dfd0366cc1efafc74a9d22fce78 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Wed, 7 Sep 2022 10:47:08 -0400 Subject: [PATCH 019/118] Fix GetScope method --- services/forms/user_form.go | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/services/forms/user_form.go b/services/forms/user_form.go index fa7cd5a259dc4..726040a5c1600 100644 --- a/services/forms/user_form.go +++ b/services/forms/user_form.go @@ -15,7 +15,6 @@ import ( "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/structs" - "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/web/middleware" "gitea.com/go-chi/binding" @@ -407,12 +406,41 @@ func (f *NewAccessTokenForm) Validate(req *http.Request, errs binding.Errors) bi } func (f *NewAccessTokenForm) GetScope() auth_model.AccessTokenScope { + scopesMapping := map[string]string{ + "Repo": auth_model.AccessTokenScopeRepo, + "RepoStatus": auth_model.AccessTokenScopeRepoStatus, + "PublicRepo": auth_model.AccessTokenScopePublicRepo, + "AdminOrg": auth_model.AccessTokenScopeAdminOrg, + "WriteOrg": auth_model.AccessTokenScopeWriteOrg, + "ReadOrg": auth_model.AccessTokenScopeReadOrg, + "AdminPublicKey": auth_model.AccessTokenScopeAdminPublicKey, + "WritePublicKey": auth_model.AccessTokenScopeWritePublicKey, + "ReadPublicKey": auth_model.AccessTokenScopeReadPublicKey, + "AdminRepoHook": auth_model.AccessTokenScopeAdminRepoHook, + "WriteRepoHook": auth_model.AccessTokenScopeWriteRepoHook, + "ReadRepoHook": auth_model.AccessTokenScopeReadRepoHook, + "Notification": auth_model.AccessTokenScopeNotification, + "User": auth_model.AccessTokenScopeUser, + "ReadUser": auth_model.AccessTokenScopeReadUser, + "UserEmail": auth_model.AccessTokenScopeUserEmail, + "UserFollow": auth_model.AccessTokenScopeUserFollow, + "DeleteRepo": auth_model.AccessTokenScopeDeleteRepo, + "Package": auth_model.AccessTokenScopePackage, + "WritePackage": auth_model.AccessTokenScopeWritePackage, + "ReadPackage": auth_model.AccessTokenScopeReadPackage, + "DeletePackage": auth_model.AccessTokenScopeDeletePackage, + "AdminGPGKey": auth_model.AccessTokenScopeAdminGPGKey, + "WriteGPGKey": auth_model.AccessTokenScopeWriteGPGKey, + "ReadGPGKey": auth_model.AccessTokenScopeReadGPGKey, + "Sudo": auth_model.AccessTokenScopeSudo, + } + scope := "" v := reflect.ValueOf(*f) for i := 0; i < v.NumField(); i++ { if strings.HasPrefix(v.Type().Field(i).Name, "Scope") && v.Field(i).Bool() { - singleScope := v.Type().Field(i).Name[5:] - scope += util.ToSnakeCase(singleScope) + "," + singleScope := strings.TrimPrefix(v.Type().Field(i).Name, "Scope") + scope += scopesMapping[singleScope] + "," } } scope = strings.TrimSuffix(scope, ",") From b751682bc05a00313512ff788b03ac637cdee1ef Mon Sep 17 00:00:00 2001 From: harryzcy Date: Wed, 7 Sep 2022 11:00:45 -0400 Subject: [PATCH 020/118] Normalize scope before storing in database --- services/forms/user_form.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/forms/user_form.go b/services/forms/user_form.go index 726040a5c1600..cd5e76546cf9b 100644 --- a/services/forms/user_form.go +++ b/services/forms/user_form.go @@ -444,7 +444,8 @@ func (f *NewAccessTokenForm) GetScope() auth_model.AccessTokenScope { } } scope = strings.TrimSuffix(scope, ",") - return auth_model.AccessTokenScope(scope) + s, _ := auth_model.AccessTokenScope(scope).Normalize() // error should not happen, since fields are valid scopes + return s } // EditOAuth2ApplicationForm form for editing oauth2 applications From 17f318368a7d9ec5949b9b92fb97f81084468f94 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 10 Sep 2022 22:18:17 -0400 Subject: [PATCH 021/118] Fix many integration test issues --- routers/api/v1/api.go | 4 +-- tests/integration/api_admin_org_test.go | 6 ++-- tests/integration/api_admin_test.go | 20 ++++++------ tests/integration/api_branch_test.go | 14 ++++---- tests/integration/api_comment_test.go | 27 ++++++++++------ tests/integration/api_gpg_keys_test.go | 2 +- .../api_helper_for_declarative_test.go | 2 +- tests/integration/api_httpsig_test.go | 9 +++--- tests/integration/api_issue_label_test.go | 8 ++--- tests/integration/api_issue_milestone_test.go | 2 +- tests/integration/api_issue_reaction_test.go | 4 +-- tests/integration/api_issue_stopwatch_test.go | 8 ++--- .../api_issue_subscription_test.go | 2 +- tests/integration/api_issue_test.go | 6 ++-- .../api_issue_tracked_time_test.go | 6 ++-- tests/integration/api_keys_test.go | 8 ++--- tests/integration/api_notification_test.go | 4 +-- tests/integration/api_oauth2_apps_test.go | 6 ++-- tests/integration/api_org_test.go | 6 ++-- .../api_packages_container_test.go | 2 ++ tests/integration/api_packages_test.go | 2 +- tests/integration/api_pull_commits_test.go | 3 +- tests/integration/api_pull_review_test.go | 6 ++-- tests/integration/api_pull_test.go | 12 +++---- tests/integration/api_releases_test.go | 17 +++++----- tests/integration/api_repo_archive_test.go | 2 +- tests/integration/api_repo_edit_test.go | 4 +-- .../integration/api_repo_file_create_test.go | 4 +-- .../integration/api_repo_file_delete_test.go | 4 +-- .../integration/api_repo_file_update_test.go | 4 +-- .../api_repo_get_contents_list_test.go | 4 +-- .../integration/api_repo_get_contents_test.go | 4 +-- tests/integration/api_repo_git_blobs_test.go | 4 +-- .../integration/api_repo_git_commits_test.go | 12 +++---- tests/integration/api_repo_git_hook_test.go | 18 +++++------ tests/integration/api_repo_git_notes_test.go | 2 +- tests/integration/api_repo_git_ref_test.go | 2 +- tests/integration/api_repo_git_tags_test.go | 4 +-- tests/integration/api_repo_git_trees_test.go | 4 +-- .../integration/api_repo_lfs_migrate_test.go | 2 +- tests/integration/api_repo_raw_test.go | 2 +- tests/integration/api_repo_tags_test.go | 2 +- tests/integration/api_repo_teams_test.go | 4 +-- tests/integration/api_repo_test.go | 32 +++++++++---------- tests/integration/api_team_test.go | 6 ++-- tests/integration/api_team_user_test.go | 2 +- tests/integration/api_user_email_test.go | 6 ++-- tests/integration/api_user_org_perm_test.go | 6 ++-- tests/integration/api_user_orgs_test.go | 4 +-- tests/integration/api_user_search_test.go | 4 +-- tests/integration/api_wiki_test.go | 4 +-- tests/integration/dump_restore_test.go | 2 +- tests/integration/eventsource_test.go | 2 +- tests/integration/integration_test.go | 10 +++--- tests/integration/migrate_test.go | 2 +- tests/integration/privateactivity_test.go | 4 +-- tests/integration/pull_merge_test.go | 4 +-- tests/integration/pull_update_test.go | 4 +-- tests/integration/user_test.go | 2 +- 59 files changed, 188 insertions(+), 174 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 3a1c9fadb7748..54cba53b23866 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -222,7 +222,7 @@ func reqToken(requiredScope string) func(ctx *context.APIContext) { return } if !allow { - ctx.Error(http.StatusUnauthorized, "reqToken", "token does not have required scope") + ctx.Error(http.StatusUnauthorized, "reqToken", "token does not have required scope: "+requiredScope) return } return @@ -1111,7 +1111,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/{org}/permissions", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetUserOrgsPermissions) }, context_service.UserAssignmentAPI()) m.Post("/orgs", reqToken(auth_model.AccessTokenScopeWriteOrg), bind(api.CreateOrgOption{}), org.Create) - m.Get("/orgs", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetAll) + m.Get("/orgs", org.GetAll) m.Group("/orgs/{org}", func() { m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.Get). Patch(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit). diff --git a/tests/integration/api_admin_org_test.go b/tests/integration/api_admin_org_test.go index 720f6fc6b645b..64113c96b4a49 100644 --- a/tests/integration/api_admin_org_test.go +++ b/tests/integration/api_admin_org_test.go @@ -21,7 +21,7 @@ import ( func TestAPIAdminOrgCreate(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") org := api.CreateOrgOption{ UserName: "user2_org", @@ -55,7 +55,7 @@ func TestAPIAdminOrgCreate(t *testing.T) { func TestAPIAdminOrgCreateBadVisibility(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") org := api.CreateOrgOption{ UserName: "user2_org", @@ -74,7 +74,7 @@ func TestAPIAdminOrgCreateNotAdmin(t *testing.T) { defer tests.PrepareTestEnv(t)() nonAdminUsername := "user2" session := loginUser(t, nonAdminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") org := api.CreateOrgOption{ UserName: "user2_org", FullName: "User2's organization", diff --git a/tests/integration/api_admin_test.go b/tests/integration/api_admin_test.go index dea0bdd0632c6..a68fa91b6dc78 100644 --- a/tests/integration/api_admin_test.go +++ b/tests/integration/api_admin_test.go @@ -25,7 +25,7 @@ func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) { session := loginUser(t, "user1") keyOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user2"}) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys?token=%s", keyOwner.Name, token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n", @@ -53,7 +53,7 @@ func TestAPIAdminDeleteMissingSSHKey(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") req := NewRequestf(t, "DELETE", "/api/v1/admin/users/user1/keys/%d?token=%s", unittest.NonexistentID, token) session.MakeRequest(t, req, http.StatusNotFound) } @@ -64,7 +64,7 @@ func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) { normalUsername := "user2" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys?token=%s", adminUsername, token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n", @@ -75,7 +75,7 @@ func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) { DecodeJSON(t, resp, &newPublicKey) session = loginUser(t, normalUsername) - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d?token=%s", adminUsername, newPublicKey.ID, token) session.MakeRequest(t, req, http.StatusForbidden) @@ -86,7 +86,7 @@ func TestAPISudoUser(t *testing.T) { adminUsername := "user1" normalUsername := "user2" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") urlStr := fmt.Sprintf("/api/v1/user?sudo=%s&token=%s", normalUsername, token) req := NewRequest(t, "GET", urlStr) @@ -103,7 +103,7 @@ func TestAPISudoUserForbidden(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") urlStr := fmt.Sprintf("/api/v1/user?sudo=%s&token=%s", adminUsername, token) req := NewRequest(t, "GET", urlStr) @@ -114,7 +114,7 @@ func TestAPIListUsers(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") urlStr := fmt.Sprintf("/api/v1/admin/users?token=%s", token) req := NewRequest(t, "GET", urlStr) @@ -143,7 +143,7 @@ func TestAPIListUsersNonAdmin(t *testing.T) { defer tests.PrepareTestEnv(t)() nonAdminUsername := "user2" session := loginUser(t, nonAdminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") req := NewRequestf(t, "GET", "/api/v1/admin/users?token=%s", token) session.MakeRequest(t, req, http.StatusForbidden) } @@ -152,7 +152,7 @@ func TestAPICreateUserInvalidEmail(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") urlStr := fmt.Sprintf("/api/v1/admin/users?token=%s", token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "email": "invalid_email@domain.com\r\n", @@ -171,7 +171,7 @@ func TestAPIEditUser(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") urlStr := fmt.Sprintf("/api/v1/admin/users/%s?token=%s", "user2", token) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ diff --git a/tests/integration/api_branch_test.go b/tests/integration/api_branch_test.go index e5d58d0b46296..f86605ef92418 100644 --- a/tests/integration/api_branch_test.go +++ b/tests/integration/api_branch_test.go @@ -17,7 +17,7 @@ import ( func testAPIGetBranch(t *testing.T, branchName string, exists bool) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branches/%s?token=%s", branchName, token) resp := session.MakeRequest(t, req, NoExpectedStatus) if !exists { @@ -34,7 +34,7 @@ func testAPIGetBranch(t *testing.T, branchName string, exists bool) { func testAPIGetBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branch_protections/%s?token=%s", branchName, token) resp := session.MakeRequest(t, req, expectedHTTPStatus) @@ -47,7 +47,7 @@ func testAPIGetBranchProtection(t *testing.T, branchName string, expectedHTTPSta func testAPICreateBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/branch_protections?token="+token, &api.BranchProtection{ BranchName: branchName, }) @@ -62,7 +62,7 @@ func testAPICreateBranchProtection(t *testing.T, branchName string, expectedHTTP func testAPIEditBranchProtection(t *testing.T, branchName string, body *api.BranchProtection, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestWithJSON(t, "PATCH", "/api/v1/repos/user2/repo1/branch_protections/"+branchName+"?token="+token, body) resp := session.MakeRequest(t, req, expectedHTTPStatus) @@ -75,14 +75,14 @@ func testAPIEditBranchProtection(t *testing.T, branchName string, body *api.Bran func testAPIDeleteBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branch_protections/%s?token=%s", branchName, token) session.MakeRequest(t, req, expectedHTTPStatus) } func testAPIDeleteBranch(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branches/%s?token=%s", branchName, token) session.MakeRequest(t, req, expectedHTTPStatus) } @@ -156,7 +156,7 @@ func testAPICreateBranches(t *testing.T, giteaURL *url.URL) { } func testAPICreateBranch(t testing.TB, session *TestSession, user, repo, oldBranch, newBranch string, status int) bool { - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestWithJSON(t, "POST", "/api/v1/repos/"+user+"/"+repo+"/branches?token="+token, &api.CreateBranchRepoOption{ BranchName: newBranch, OldBranchName: oldBranch, diff --git a/tests/integration/api_comment_test.go b/tests/integration/api_comment_test.go index 126d886842e49..1c4d57dcf409f 100644 --- a/tests/integration/api_comment_test.go +++ b/tests/integration/api_comment_test.go @@ -31,7 +31,9 @@ func TestAPIListRepoComments(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments", repoOwner.Name, repo.Name)) + token := getTokenForLoggedInUser(t, session, "repo") + link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments?token="+token, repoOwner.Name, repo.Name)) + fmt.Println(36, link.String()) req := NewRequest(t, "GET", link.String()) resp := session.MakeRequest(t, req, http.StatusOK) @@ -50,6 +52,7 @@ func TestAPIListRepoComments(t *testing.T) { before := "2000-01-01T00:00:11+00:00" // unix: 946684811 since := "2000-01-01T00:00:12+00:00" // unix: 946684812 query.Add("before", before) + query.Add("token", token) link.RawQuery = query.Encode() req = NewRequest(t, "GET", link.String()) resp = session.MakeRequest(t, req, http.StatusOK) @@ -59,6 +62,7 @@ func TestAPIListRepoComments(t *testing.T) { query.Del("before") query.Add("since", since) + query.Add("token", token) link.RawQuery = query.Encode() req = NewRequest(t, "GET", link.String()) resp = session.MakeRequest(t, req, http.StatusOK) @@ -77,7 +81,8 @@ func TestAPIListIssueComments(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/comments", + token := getTokenForLoggedInUser(t, session, "repo") + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/comments?token="+token, repoOwner.Name, repo.Name, issue.Index) resp := session.MakeRequest(t, req, http.StatusOK) @@ -97,7 +102,7 @@ func TestAPICreateComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/comments?token=%s", repoOwner.Name, repo.Name, issue.Index, token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ @@ -120,10 +125,11 @@ func TestAPIGetComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID) - session.MakeRequest(t, req, http.StatusOK) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) + token := getTokenForLoggedInUser(t, session, "repo") + // TODO: check if it should be allowed + // req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID) + // session.MakeRequest(t, req, http.StatusOK) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) resp := session.MakeRequest(t, req, http.StatusOK) var apiComment api.Comment @@ -149,7 +155,7 @@ func TestAPIEditComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ @@ -174,7 +180,7 @@ func TestAPIDeleteComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) session.MakeRequest(t, req, http.StatusNoContent) @@ -192,7 +198,8 @@ func TestAPIListIssueTimeline(t *testing.T) { // make request session := loginUser(t, repoOwner.Name) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/timeline", + token := getTokenForLoggedInUser(t, session, "repo") + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/timeline&token="+token, repoOwner.Name, repo.Name, issue.Index) resp := session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/api_gpg_keys_test.go b/tests/integration/api_gpg_keys_test.go index 0ad876c9b97ab..4ffa81ba9f04f 100644 --- a/tests/integration/api_gpg_keys_test.go +++ b/tests/integration/api_gpg_keys_test.go @@ -21,7 +21,7 @@ type makeRequestFunc func(testing.TB, *http.Request, int) *httptest.ResponseReco func TestGPGKeys(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") tt := []struct { name string diff --git a/tests/integration/api_helper_for_declarative_test.go b/tests/integration/api_helper_for_declarative_test.go index 5a798f79f0fc5..6f34543d56a73 100644 --- a/tests/integration/api_helper_for_declarative_test.go +++ b/tests/integration/api_helper_for_declarative_test.go @@ -34,7 +34,7 @@ type APITestContext struct { func NewAPITestContext(t *testing.T, username, reponame string) APITestContext { session := loginUser(t, username) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") return APITestContext{ Session: session, Token: token, diff --git a/tests/integration/api_httpsig_test.go b/tests/integration/api_httpsig_test.go index 80b3c586b432c..a0d1893d66753 100644 --- a/tests/integration/api_httpsig_test.go +++ b/tests/integration/api_httpsig_test.go @@ -53,7 +53,7 @@ func TestHTTPSigPubKey(t *testing.T) { // Add our public key to user1 defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") - token := url.QueryEscape(getTokenForLoggedInUser(t, session)) + token := url.QueryEscape(getTokenForLoggedInUser(t, session, "repo", "admin_public_key", "sudo")) keysURL := fmt.Sprintf("/api/v1/user/keys?token=%s", token) keyType := "ssh-rsa" keyContent := "AAAAB3NzaC1yc2EAAAADAQABAAABAQCqOZB5vkRvXFXups1/0StDRdG8plbNSwsWEnNnP4Bvurxa0+z3W9B8GLKnDiLw5MbpbMNyBlpXw13GfuIeciy10DWTz0xUbiy3J3KabCaT36asIw2y7k6Z0jL0UBnrVENwq5/lUbZYqSZ4rRU744wkhh8TULpzM14npQCZwg6aEbG+MwjzddQ72fR+3BPBrKn5dTmmu8rH99O+U+Nuto81Tg7PA+NUupcHOmhdiEGq49plgVFXK98Vks5tiybL4GuzFyWgyX73Dg/QBMn2eMHt1EMv5Gs3i6GFhKKGo4rjDi9qI6PX5oDR4LTNe6cR8td8YhVD8WFZwLLl/vaYyIqd" @@ -69,7 +69,7 @@ func TestHTTPSigPubKey(t *testing.T) { keyID := ssh.FingerprintSHA256(sshSigner.PublicKey()) // create the request - req = NewRequest(t, "GET", "/api/v1/admin/users") + req = NewRequest(t, "GET", "/api/v1/admin/users?token="+token) signer, _, err := httpsig.NewSSHSigner(sshSigner, httpsig.DigestSha512, []string{httpsig.RequestTarget, "(created)", "(expires)"}, httpsig.Signature, 10) if err != nil { @@ -90,9 +90,10 @@ func TestHTTPSigCert(t *testing.T) { // Add our public key to user1 defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") + token := url.QueryEscape(getTokenForLoggedInUser(t, session, "user", "admin_public_key", "sudo")) csrf := GetCSRF(t, session, "/user/settings/keys") - req := NewRequestWithValues(t, "POST", "/user/settings/keys", map[string]string{ + req := NewRequestWithValues(t, "POST", "/user/settings/keys?token="+token, map[string]string{ "_csrf": csrf, "content": "user1", "title": "principal", @@ -116,7 +117,7 @@ func TestHTTPSigCert(t *testing.T) { } // create the request - req = NewRequest(t, "GET", "/api/v1/admin/users") + req = NewRequest(t, "GET", "/api/v1/admin/users?token="+token) // add our cert to the request certString := base64.RawStdEncoding.EncodeToString(pkcert.(*ssh.Certificate).Marshal()) diff --git a/tests/integration/api_issue_label_test.go b/tests/integration/api_issue_label_test.go index 586c50a55f17a..b4f6e545c351d 100644 --- a/tests/integration/api_issue_label_test.go +++ b/tests/integration/api_issue_label_test.go @@ -25,7 +25,7 @@ func TestAPIModifyLabels(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels?token=%s", owner.Name, repo.Name, token) // CreateLabel @@ -97,7 +97,7 @@ func TestAPIAddIssueLabels(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels?token=%s", repo.OwnerName, repo.Name, issue.Index, token) req := NewRequestWithJSON(t, "POST", urlStr, &api.IssueLabelsOption{ @@ -120,7 +120,7 @@ func TestAPIReplaceIssueLabels(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels?token=%s", owner.Name, repo.Name, issue.Index, token) req := NewRequestWithJSON(t, "PUT", urlStr, &api.IssueLabelsOption{ @@ -144,7 +144,7 @@ func TestAPIModifyOrgLabels(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) user := "user1" session := loginUser(t, user) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") urlStr := fmt.Sprintf("/api/v1/orgs/%s/labels?token=%s", owner.Name, token) // CreateLabel diff --git a/tests/integration/api_issue_milestone_test.go b/tests/integration/api_issue_milestone_test.go index e22a091bb8d16..2eb7eaee2f384 100644 --- a/tests/integration/api_issue_milestone_test.go +++ b/tests/integration/api_issue_milestone_test.go @@ -29,7 +29,7 @@ func TestAPIIssuesMilestone(t *testing.T) { assert.Equal(t, structs.StateOpen, milestone.State()) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // update values of issue milestoneState := "closed" diff --git a/tests/integration/api_issue_reaction_test.go b/tests/integration/api_issue_reaction_test.go index a3cb9303fbcf9..5f790bd92855d 100644 --- a/tests/integration/api_issue_reaction_test.go +++ b/tests/integration/api_issue_reaction_test.go @@ -29,7 +29,7 @@ func TestAPIIssuesReactions(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue.Repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/reactions?token=%s", @@ -88,7 +88,7 @@ func TestAPICommentReactions(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue.Repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) diff --git a/tests/integration/api_issue_stopwatch_test.go b/tests/integration/api_issue_stopwatch_test.go index c2ad9c45e8200..2b3ab815d1648 100644 --- a/tests/integration/api_issue_stopwatch_test.go +++ b/tests/integration/api_issue_stopwatch_test.go @@ -26,7 +26,7 @@ func TestAPIListStopWatches(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "GET", "/api/v1/user/stopwatches?token=%s", token) resp := session.MakeRequest(t, req, http.StatusOK) var apiWatches []*api.StopWatch @@ -52,7 +52,7 @@ func TestAPIStopStopWatches(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/issues/%d/stopwatch/stop?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) session.MakeRequest(t, req, http.StatusCreated) @@ -68,7 +68,7 @@ func TestAPICancelStopWatches(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/stopwatch/delete?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) session.MakeRequest(t, req, http.StatusNoContent) @@ -84,7 +84,7 @@ func TestAPIStartStopWatches(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/issues/%d/stopwatch/start?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) session.MakeRequest(t, req, http.StatusCreated) diff --git a/tests/integration/api_issue_subscription_test.go b/tests/integration/api_issue_subscription_test.go index f4588fbbc42c2..39c4062568809 100644 --- a/tests/integration/api_issue_subscription_test.go +++ b/tests/integration/api_issue_subscription_test.go @@ -31,7 +31,7 @@ func TestAPIIssueSubscriptions(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue1.PosterID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") testSubscription := func(issue *issues_model.Issue, isWatching bool) { issueRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}) diff --git a/tests/integration/api_issue_test.go b/tests/integration/api_issue_test.go index 3e651c620b04f..440bd49e3feb8 100644 --- a/tests/integration/api_issue_test.go +++ b/tests/integration/api_issue_test.go @@ -30,7 +30,7 @@ func TestAPIListIssues(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/issues", owner.Name, repo.Name)) link.RawQuery = url.Values{"token": {token}, "state": {"all"}}.Encode() @@ -81,7 +81,7 @@ func TestAPICreateIssue(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all&token=%s", owner.Name, repoBefore.Name, token) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateIssueOption{ Body: body, @@ -117,7 +117,7 @@ func TestAPIEditIssue(t *testing.T) { assert.Equal(t, api.StateOpen, issueBefore.State()) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // update values of issue issueState := "closed" diff --git a/tests/integration/api_issue_tracked_time_test.go b/tests/integration/api_issue_tracked_time_test.go index 6e2c77030cb7d..91e950363756c 100644 --- a/tests/integration/api_issue_tracked_time_test.go +++ b/tests/integration/api_issue_tracked_time_test.go @@ -28,7 +28,7 @@ func TestAPIGetTrackedTimes(t *testing.T) { assert.NoError(t, issue2.LoadRepo(db.DefaultContext)) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/times?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, token) resp := session.MakeRequest(t, req, http.StatusOK) @@ -71,7 +71,7 @@ func TestAPIDeleteTrackedTime(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // Deletion not allowed req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time6.ID, token) @@ -106,7 +106,7 @@ func TestAPIAddTrackedTimes(t *testing.T) { admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, admin.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/times?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, token) diff --git a/tests/integration/api_keys_test.go b/tests/integration/api_keys_test.go index 1cb0b20ffe162..033c557a8b78c 100644 --- a/tests/integration/api_keys_test.go +++ b/tests/integration/api_keys_test.go @@ -54,7 +54,7 @@ func TestCreateReadOnlyDeployKey(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", repoOwner.Name, repo.Name, token) rawKeyBody := api.CreateKeyOption{ Title: "read-only", @@ -80,7 +80,7 @@ func TestCreateReadWriteDeployKey(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", repoOwner.Name, repo.Name, token) rawKeyBody := api.CreateKeyOption{ Title: "read-write", @@ -104,7 +104,7 @@ func TestCreateUserKey(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user1"}) session := loginUser(t, "user1") - token := url.QueryEscape(getTokenForLoggedInUser(t, session)) + token := url.QueryEscape(getTokenForLoggedInUser(t, session, "user", "admin_public_key")) keysURL := fmt.Sprintf("/api/v1/user/keys?token=%s", token) keyType := "ssh-rsa" keyContent := "AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM=" @@ -168,7 +168,7 @@ func TestCreateUserKey(t *testing.T) { // Now login as user 2 session2 := loginUser(t, "user2") - token2 := url.QueryEscape(getTokenForLoggedInUser(t, session2)) + token2 := url.QueryEscape(getTokenForLoggedInUser(t, session2, "user", "admin_public_key")) // Should find key even though not ours, but we shouldn't know whose it is fingerprintURL = fmt.Sprintf("/api/v1/user/keys?token=%s&fingerprint=%s", token2, newPublicKey.Fingerprint) diff --git a/tests/integration/api_notification_test.go b/tests/integration/api_notification_test.go index bf85520bb53b7..16e541b029b13 100644 --- a/tests/integration/api_notification_test.go +++ b/tests/integration/api_notification_test.go @@ -27,7 +27,7 @@ func TestAPINotification(t *testing.T) { thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) assert.NoError(t, thread5.LoadAttributes()) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // -- GET /notifications -- // test filter @@ -145,7 +145,7 @@ func TestAPINotificationPUT(t *testing.T) { thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) assert.NoError(t, thread5.LoadAttributes()) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // Check notifications are as expected req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?all=true&token=%s", token)) diff --git a/tests/integration/api_oauth2_apps_test.go b/tests/integration/api_oauth2_apps_test.go index fe3525724e26a..6e23cbd14e261 100644 --- a/tests/integration/api_oauth2_apps_test.go +++ b/tests/integration/api_oauth2_apps_test.go @@ -54,7 +54,7 @@ func testAPICreateOAuth2Application(t *testing.T) { func testAPIListOAuth2Applications(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") existApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ UID: user.ID, @@ -83,7 +83,7 @@ func testAPIListOAuth2Applications(t *testing.T) { func testAPIDeleteOAuth2Application(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") oldApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ UID: user.ID, @@ -104,7 +104,7 @@ func testAPIDeleteOAuth2Application(t *testing.T) { func testAPIGetOAuth2Application(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") existApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ UID: user.ID, diff --git a/tests/integration/api_org_test.go b/tests/integration/api_org_test.go index 70bb17bee2e10..66f6e17e976ce 100644 --- a/tests/integration/api_org_test.go +++ b/tests/integration/api_org_test.go @@ -21,7 +21,7 @@ import ( func TestAPIOrgCreate(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { - token := getUserToken(t, "user1") + token := getUserToken(t, "user1", "admin_org") org := api.CreateOrgOption{ UserName: "user1_org", @@ -79,7 +79,7 @@ func TestAPIOrgEdit(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") org := api.EditOrgOption{ FullName: "User3 organization new full name", Description: "A new description", @@ -106,7 +106,7 @@ func TestAPIOrgEditBadVisibility(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") org := api.EditOrgOption{ FullName: "User3 organization new full name", Description: "A new description", diff --git a/tests/integration/api_packages_container_test.go b/tests/integration/api_packages_container_test.go index adced5d661ab4..366fbf37585d0 100644 --- a/tests/integration/api_packages_container_test.go +++ b/tests/integration/api_packages_container_test.go @@ -30,6 +30,8 @@ func TestPackageContainer(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) + // session := loginUser(t, user.Name) + // accessToken := getTokenForLoggedInUser(t, session, "package") has := func(l packages_model.PackagePropertyList, name string) bool { for _, pp := range l { diff --git a/tests/integration/api_packages_test.go b/tests/integration/api_packages_test.go index 86d81994d4d22..f9c7040b4be9e 100644 --- a/tests/integration/api_packages_test.go +++ b/tests/integration/api_packages_test.go @@ -27,7 +27,7 @@ func TestPackageAPI(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") packageName := "test-package" packageVersion := "1.0.3" diff --git a/tests/integration/api_pull_commits_test.go b/tests/integration/api_pull_commits_test.go index aa58f44bbe510..1ab9b03eec375 100644 --- a/tests/integration/api_pull_commits_test.go +++ b/tests/integration/api_pull_commits_test.go @@ -24,7 +24,8 @@ func TestAPIPullCommits(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue.HeadRepoID}) session := loginUser(t, "user2") - req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/commits", repo.OwnerName, repo.Name, pullIssue.Index) + token := getTokenForLoggedInUser(t, session, "repo") + req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/commits?token="+token, repo.OwnerName, repo.Name, pullIssue.Index) resp := session.MakeRequest(t, req, http.StatusOK) var commits []*api.Commit diff --git a/tests/integration/api_pull_review_test.go b/tests/integration/api_pull_review_test.go index 6ebad106fb311..58f91de49f0c0 100644 --- a/tests/integration/api_pull_review_test.go +++ b/tests/integration/api_pull_review_test.go @@ -28,7 +28,7 @@ func TestAPIPullReview(t *testing.T) { // test ListPullReviews session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token) resp := session.MakeRequest(t, req, http.StatusOK) @@ -231,7 +231,7 @@ func TestAPIPullReviewRequest(t *testing.T) { // Test add Review Request session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.PullReviewRequestOptions{ Reviewers: []string{"user4@example.com", "user8"}, }) @@ -251,7 +251,7 @@ func TestAPIPullReviewRequest(t *testing.T) { // Test Remove Review Request session2 := loginUser(t, "user4") - token2 := getTokenForLoggedInUser(t, session2) + token2 := getTokenForLoggedInUser(t, session2, "repo") req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token2), &api.PullReviewRequestOptions{ Reviewers: []string{"user4"}, diff --git a/tests/integration/api_pull_test.go b/tests/integration/api_pull_test.go index 032912a07360a..5c3fe55c5caba 100644 --- a/tests/integration/api_pull_test.go +++ b/tests/integration/api_pull_test.go @@ -28,7 +28,7 @@ func TestAPIViewPulls(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/pulls?state=all&token="+token, owner.Name, repo.Name) resp := session.MakeRequest(t, req, http.StatusOK) @@ -53,7 +53,7 @@ func TestAPIMergePullWIP(t *testing.T) { assert.Contains(t, pr.Issue.Title, setting.Repository.PullRequest.WorkInProgressPrefixes[0]) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", owner.Name, repo.Name, pr.Index, token), &forms.MergePullRequestForm{ MergeMessageField: pr.Issue.Title, Do: string(repo_model.MergeStyleMerge), @@ -72,7 +72,7 @@ func TestAPICreatePullSuccess(t *testing.T) { owner11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo11.OwnerID}) session := loginUser(t, owner11.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", owner10.Name, repo10.Name, token), &api.CreatePullRequestOption{ Head: fmt.Sprintf("%s:master", owner11.Name), Base: "master", @@ -92,7 +92,7 @@ func TestAPICreatePullWithFieldsSuccess(t *testing.T) { owner11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo11.OwnerID}) session := loginUser(t, owner11.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") opts := &api.CreatePullRequestOption{ Head: fmt.Sprintf("%s:master", owner11.Name), @@ -129,7 +129,7 @@ func TestAPICreatePullWithFieldsFailure(t *testing.T) { owner11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo11.OwnerID}) session := loginUser(t, owner11.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") opts := &api.CreatePullRequestOption{ Head: fmt.Sprintf("%s:master", owner11.Name), @@ -159,7 +159,7 @@ func TestAPIEditPull(t *testing.T) { owner10 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo10.OwnerID}) session := loginUser(t, owner10.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", owner10.Name, repo10.Name, token), &api.CreatePullRequestOption{ Head: "develop", Base: "master", diff --git a/tests/integration/api_releases_test.go b/tests/integration/api_releases_test.go index 0c7f5e2d521e7..f97562e57ba63 100644 --- a/tests/integration/api_releases_test.go +++ b/tests/integration/api_releases_test.go @@ -101,7 +101,7 @@ func TestAPICreateAndUpdateRelease(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") gitRepo, err := git.OpenRepository(git.DefaultContext, repo.RepoPath()) assert.NoError(t, err) @@ -153,7 +153,7 @@ func TestAPICreateReleaseToDefaultBranch(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") createNewReleaseUsingAPI(t, session, token, owner, repo, "v0.0.1", "", "v0.0.1", "test") } @@ -164,7 +164,7 @@ func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") gitRepo, err := git.OpenRepository(git.DefaultContext, repo.RepoPath()) assert.NoError(t, err) @@ -182,11 +182,12 @@ func TestAPIGetReleaseByTag(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) + token := getTokenForLoggedInUser(t, session, "repo") tag := "v1.1" - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", - owner.Name, repo.Name, tag) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s?token=%s", + owner.Name, repo.Name, tag, token) req := NewRequestf(t, "GET", urlStr) resp := session.MakeRequest(t, req, http.StatusOK) @@ -198,8 +199,8 @@ func TestAPIGetReleaseByTag(t *testing.T) { nonexistingtag := "nonexistingtag" - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", - owner.Name, repo.Name, nonexistingtag) + urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s?token=%s", + owner.Name, repo.Name, nonexistingtag, token) req = NewRequestf(t, "GET", urlStr) resp = session.MakeRequest(t, req, http.StatusNotFound) @@ -215,7 +216,7 @@ func TestAPIDeleteReleaseByTagName(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") createNewReleaseUsingAPI(t, session, token, owner, repo, "release-tag", "", "Release Tag", "test") diff --git a/tests/integration/api_repo_archive_test.go b/tests/integration/api_repo_archive_test.go index 3707cb7c1c8bb..f601c2dd3ebe7 100644 --- a/tests/integration/api_repo_archive_test.go +++ b/tests/integration/api_repo_archive_test.go @@ -25,7 +25,7 @@ func TestAPIDownloadArchive(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user2.LowerName) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/archive/master.zip", user2.Name, repo.Name)) link.RawQuery = url.Values{"token": {token}}.Encode() diff --git a/tests/integration/api_repo_edit_test.go b/tests/integration/api_repo_edit_test.go index 5ef92bf47cf50..2c15f84af53e2 100644 --- a/tests/integration/api_repo_edit_test.go +++ b/tests/integration/api_repo_edit_test.go @@ -145,10 +145,10 @@ func TestAPIRepoEdit(t *testing.T) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session) + token2 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session) + token4 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") session = emptyTestSession(t) // Test editing a repo1 which user2 owns, changing name and many properties diff --git a/tests/integration/api_repo_file_create_test.go b/tests/integration/api_repo_file_create_test.go index f03efaa0eadf9..7e4181db3cb9c 100644 --- a/tests/integration/api_repo_file_create_test.go +++ b/tests/integration/api_repo_file_create_test.go @@ -151,10 +151,10 @@ func TestAPICreateFile(t *testing.T) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session) + token2 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session) + token4 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") session = emptyTestSession(t) // Test creating a file in repo1 which user2 owns, try both with branch and empty branch diff --git a/tests/integration/api_repo_file_delete_test.go b/tests/integration/api_repo_file_delete_test.go index 2c8b1e381f7c5..2ac749dafc7a8 100644 --- a/tests/integration/api_repo_file_delete_test.go +++ b/tests/integration/api_repo_file_delete_test.go @@ -49,10 +49,10 @@ func TestAPIDeleteFile(t *testing.T) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session) + token2 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session) + token4 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") session = emptyTestSession(t) // Test deleting a file in repo1 which user2 owns, try both with branch and empty branch diff --git a/tests/integration/api_repo_file_update_test.go b/tests/integration/api_repo_file_update_test.go index a3be67ad844f4..fa42934ebd369 100644 --- a/tests/integration/api_repo_file_update_test.go +++ b/tests/integration/api_repo_file_update_test.go @@ -117,10 +117,10 @@ func TestAPIUpdateFile(t *testing.T) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session) + token2 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session) + token4 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") session = emptyTestSession(t) // Test updating a file in repo1 which user2 owns, try both with branch and empty branch diff --git a/tests/integration/api_repo_get_contents_list_test.go b/tests/integration/api_repo_get_contents_list_test.go index 4f2f5cb528c9c..f941be95bcb23 100644 --- a/tests/integration/api_repo_get_contents_list_test.go +++ b/tests/integration/api_repo_get_contents_list_test.go @@ -65,10 +65,10 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session) + token2 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session) + token4 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") session = emptyTestSession(t) // Make a new branch in repo1 diff --git a/tests/integration/api_repo_get_contents_test.go b/tests/integration/api_repo_get_contents_test.go index dddc316e1a963..a5c599f2c400f 100644 --- a/tests/integration/api_repo_get_contents_test.go +++ b/tests/integration/api_repo_get_contents_test.go @@ -66,10 +66,10 @@ func testAPIGetContents(t *testing.T, u *url.URL) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session) + token2 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session) + token4 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") session = emptyTestSession(t) // Make a new branch in repo1 diff --git a/tests/integration/api_repo_git_blobs_test.go b/tests/integration/api_repo_git_blobs_test.go index cb5116c743b5f..c6bf81ca481a0 100644 --- a/tests/integration/api_repo_git_blobs_test.go +++ b/tests/integration/api_repo_git_blobs_test.go @@ -32,7 +32,7 @@ func TestAPIReposGitBlobs(t *testing.T) { // Login as User2. session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") session = emptyTestSession(t) // don't want anyone logged in for this // Test a public repo that anyone can GET the blob of @@ -70,7 +70,7 @@ func TestAPIReposGitBlobs(t *testing.T) { // Login as User4. session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session) + token4 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") session = emptyTestSession(t) // don't want anyone logged in for this // Test using org repo "user3/repo3" where user4 is a NOT collaborator diff --git a/tests/integration/api_repo_git_commits_test.go b/tests/integration/api_repo_git_commits_test.go index 99f83f943c310..81da61903672d 100644 --- a/tests/integration/api_repo_git_commits_test.go +++ b/tests/integration/api_repo_git_commits_test.go @@ -29,7 +29,7 @@ func TestAPIReposGitCommits(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // check invalid requests req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/12345?token="+token, user.Name) @@ -57,7 +57,7 @@ func TestAPIReposGitCommitList(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // Test getting commits (Page 1) req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?token="+token, user.Name) @@ -80,7 +80,7 @@ func TestAPIReposGitCommitListPage2Empty(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // Test getting commits (Page=2) req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?token="+token+"&page=2", user.Name) @@ -97,7 +97,7 @@ func TestAPIReposGitCommitListDifferentBranch(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // Test getting commits (Page=1, Branch=good-sign) req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?token="+token+"&sha=good-sign", user.Name) @@ -116,7 +116,7 @@ func TestDownloadCommitDiffOrPatch(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // Test getting diff reqDiff := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/git/commits/f27c2b2b03dcab38beaf89b0ab4ff61f6de63441.diff?token="+token, user.Name) @@ -138,7 +138,7 @@ func TestGetFileHistory(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?path=readme.md&token="+token+"&sha=good-sign", user.Name) resp := session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/api_repo_git_hook_test.go b/tests/integration/api_repo_git_hook_test.go index a6c4f91d4a5b9..261c64a323c92 100644 --- a/tests/integration/api_repo_git_hook_test.go +++ b/tests/integration/api_repo_git_hook_test.go @@ -31,7 +31,7 @@ func TestAPIListGitHooks(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", owner.Name, repo.Name, token) resp := MakeRequest(t, req, http.StatusOK) @@ -57,7 +57,7 @@ func TestAPIListGitHooksNoHooks(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", owner.Name, repo.Name, token) resp := MakeRequest(t, req, http.StatusOK) @@ -77,7 +77,7 @@ func TestAPIListGitHooksNoAccess(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", owner.Name, repo.Name, token) MakeRequest(t, req, http.StatusForbidden) @@ -91,7 +91,7 @@ func TestAPIGetGitHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) resp := MakeRequest(t, req, http.StatusOK) @@ -108,7 +108,7 @@ func TestAPIGetGitHookNoAccess(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) MakeRequest(t, req, http.StatusForbidden) @@ -122,7 +122,7 @@ func TestAPIEditGitHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) @@ -151,7 +151,7 @@ func TestAPIEditGitHookNoAccess(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) req := NewRequestWithJSON(t, "PATCH", urlStr, &api.EditGitHookOption{ @@ -168,7 +168,7 @@ func TestAPIDeleteGitHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) @@ -190,7 +190,7 @@ func TestAPIDeleteGitHookNoAccess(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) MakeRequest(t, req, http.StatusForbidden) diff --git a/tests/integration/api_repo_git_notes_test.go b/tests/integration/api_repo_git_notes_test.go index 713c7599c3336..d6ed49d46c220 100644 --- a/tests/integration/api_repo_git_notes_test.go +++ b/tests/integration/api_repo_git_notes_test.go @@ -21,7 +21,7 @@ func TestAPIReposGitNotes(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // check invalid requests req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/notes/12345?token=%s", user.Name, token) diff --git a/tests/integration/api_repo_git_ref_test.go b/tests/integration/api_repo_git_ref_test.go index e8fc47f8dc30b..646da11330b66 100644 --- a/tests/integration/api_repo_git_ref_test.go +++ b/tests/integration/api_repo_git_ref_test.go @@ -18,7 +18,7 @@ func TestAPIReposGitRefs(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") for _, ref := range [...]string{ "refs/heads/master", // Branch diff --git a/tests/integration/api_repo_git_tags_test.go b/tests/integration/api_repo_git_tags_test.go index 855eb2451e80c..ef9134a8f90de 100644 --- a/tests/integration/api_repo_git_tags_test.go +++ b/tests/integration/api_repo_git_tags_test.go @@ -26,7 +26,7 @@ func TestAPIGitTags(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // Set up git config for the tagger _ = git.NewCommand(git.DefaultContext, "config", "user.name", user.Name).Run(&git.RunOpts{Dir: repo.RepoPath()}) @@ -70,7 +70,7 @@ func TestAPIDeleteTagByName(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/tags/delete-tag?token=%s", owner.Name, repo.Name, token) diff --git a/tests/integration/api_repo_git_trees_test.go b/tests/integration/api_repo_git_trees_test.go index 385fec12ba158..8d3551b4ca4fc 100644 --- a/tests/integration/api_repo_git_trees_test.go +++ b/tests/integration/api_repo_git_trees_test.go @@ -29,7 +29,7 @@ func TestAPIReposGitTrees(t *testing.T) { // Login as User2. session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") session = emptyTestSession(t) // don't want anyone logged in for this // Test a public repo that anyone can GET the tree of @@ -68,7 +68,7 @@ func TestAPIReposGitTrees(t *testing.T) { // Login as User4. session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session) + token4 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") session = emptyTestSession(t) // don't want anyone logged in for this // Test using org repo "user3/repo3" where user4 is a NOT collaborator diff --git a/tests/integration/api_repo_lfs_migrate_test.go b/tests/integration/api_repo_lfs_migrate_test.go index d2edf67e8be5c..0f940ca4bde84 100644 --- a/tests/integration/api_repo_lfs_migrate_test.go +++ b/tests/integration/api_repo_lfs_migrate_test.go @@ -31,7 +31,7 @@ func TestAPIRepoLFSMigrateLocal(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+token, &api.MigrateRepoOptions{ CloneAddr: path.Join(setting.RepoRootPath, "migration/lfs-test.git"), diff --git a/tests/integration/api_repo_raw_test.go b/tests/integration/api_repo_raw_test.go index 9793e12b42920..6b0ebb7d6cbc6 100644 --- a/tests/integration/api_repo_raw_test.go +++ b/tests/integration/api_repo_raw_test.go @@ -20,7 +20,7 @@ func TestAPIReposRaw(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") for _, ref := range [...]string{ "master", // Branch diff --git a/tests/integration/api_repo_tags_test.go b/tests/integration/api_repo_tags_test.go index 5d3a209a767a0..54866a88d2030 100644 --- a/tests/integration/api_repo_tags_test.go +++ b/tests/integration/api_repo_tags_test.go @@ -23,7 +23,7 @@ func TestAPIRepoTags(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") repoName := "repo1" diff --git a/tests/integration/api_repo_teams_test.go b/tests/integration/api_repo_teams_test.go index 1e476a89e232e..a53eb8ec8e2e8 100644 --- a/tests/integration/api_repo_teams_test.go +++ b/tests/integration/api_repo_teams_test.go @@ -28,7 +28,7 @@ func TestAPIRepoTeams(t *testing.T) { // user4 user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // ListTeams url := fmt.Sprintf("/api/v1/repos/%s/teams?token=%s", publicOrgRepo.FullName(), token) @@ -68,7 +68,7 @@ func TestAPIRepoTeams(t *testing.T) { // AddTeam with user2 user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session = loginUser(t, user.Name) - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "team1", token) req = NewRequest(t, "PUT", url) session.MakeRequest(t, req, http.StatusNoContent) diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index bfe0c0aa9c58e..708f9f948b8be 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -190,7 +190,7 @@ func TestAPISearchRepo(t *testing.T) { if userToLogin != nil && userToLogin.ID > 0 { testName = fmt.Sprintf("LoggedUser%d", userToLogin.ID) session = loginUser(t, userToLogin.Name) - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") userID = userToLogin.ID } else { testName = "AnonymousUser" @@ -300,7 +300,7 @@ func TestAPIOrgRepos(t *testing.T) { if userToLogin != nil && userToLogin.ID > 0 { testName = fmt.Sprintf("LoggedUser%d", userToLogin.ID) session = loginUser(t, userToLogin.Name) - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") } else { testName = "AnonymousUser" session = emptyTestSession(t) @@ -325,7 +325,7 @@ func TestAPIGetRepoByIDUnauthorized(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "GET", "/api/v1/repositories/2?token="+token) session.MakeRequest(t, req, http.StatusNotFound) } @@ -349,7 +349,7 @@ func TestAPIRepoMigrate(t *testing.T) { for _, testCase := range testCases { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+token, &api.MigrateRepoOptions{ CloneAddr: testCase.cloneURL, RepoOwnerID: testCase.userID, @@ -414,7 +414,7 @@ func TestAPIMirrorSyncNonMirrorRepo(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") var repo api.Repository req := NewRequest(t, "GET", "/api/v1/repos/user2/repo1") @@ -446,7 +446,7 @@ func TestAPIOrgRepoCreate(t *testing.T) { for _, testCase := range testCases { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "admin_org") req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/org/%s/repos?token="+token, testCase.orgName), &api.CreateRepoOption{ Name: testCase.repoName, }) @@ -510,7 +510,7 @@ func TestAPIRepoTransfer(t *testing.T) { // create repo to move user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") repoName := "moveME" apiRepo := new(api.Repository) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/user/repos?token=%s", token), &api.CreateRepoOption{ @@ -528,7 +528,7 @@ func TestAPIRepoTransfer(t *testing.T) { user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}) session = loginUser(t, user.Name) - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer?token=%s", repo.OwnerName, repo.Name, token), &api.TransferRepoOption{ NewOwner: testCase.newOwner, TeamIDs: testCase.teams, @@ -545,7 +545,7 @@ func transfer(t *testing.T) *repo_model.Repository { // create repo to move user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") repoName := "moveME" apiRepo := new(api.Repository) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/user/repos?token=%s", token), &api.CreateRepoOption{ @@ -575,7 +575,7 @@ func TestAPIAcceptTransfer(t *testing.T) { // try to accept with not authorized user session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) session.MakeRequest(t, req, http.StatusForbidden) @@ -585,7 +585,7 @@ func TestAPIAcceptTransfer(t *testing.T) { // accept transfer session = loginUser(t, "user4") - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/accept?token=%s", repo.OwnerName, repo.Name, token)) resp := session.MakeRequest(t, req, http.StatusAccepted) @@ -601,7 +601,7 @@ func TestAPIRejectTransfer(t *testing.T) { // try to reject with not authorized user session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) session.MakeRequest(t, req, http.StatusForbidden) @@ -611,7 +611,7 @@ func TestAPIRejectTransfer(t *testing.T) { // reject transfer session = loginUser(t, "user4") - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) resp := session.MakeRequest(t, req, http.StatusOK) @@ -625,7 +625,7 @@ func TestAPIGenerateRepo(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") templateRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 44}) @@ -661,7 +661,7 @@ func TestAPIRepoGetReviewers(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/reviewers?token=%s", user.Name, repo.Name, token) @@ -675,7 +675,7 @@ func TestAPIRepoGetAssignees(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/assignees?token=%s", user.Name, repo.Name, token) diff --git a/tests/integration/api_team_test.go b/tests/integration/api_team_test.go index a667949c096f9..ca10202862ffc 100644 --- a/tests/integration/api_team_test.go +++ b/tests/integration/api_team_test.go @@ -30,7 +30,7 @@ func TestAPITeam(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: teamUser.UID}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamUser.TeamID) resp := session.MakeRequest(t, req, http.StatusOK) @@ -44,7 +44,7 @@ func TestAPITeam(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: teamUser2.UID}) session = loginUser(t, user2.Name) - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req = NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamUser.TeamID) _ = session.MakeRequest(t, req, http.StatusForbidden) @@ -54,7 +54,7 @@ func TestAPITeam(t *testing.T) { // Get an admin user able to create, update and delete teams. user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session = loginUser(t, user.Name) - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 6}) diff --git a/tests/integration/api_team_user_test.go b/tests/integration/api_team_user_test.go index b999b97a2b6f8..859c5935ad527 100644 --- a/tests/integration/api_team_user_test.go +++ b/tests/integration/api_team_user_test.go @@ -23,7 +23,7 @@ func TestAPITeamUser(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequest(t, "GET", "/api/v1/teams/1/members/user1?token="+token) session.MakeRequest(t, req, http.StatusNotFound) diff --git a/tests/integration/api_user_email_test.go b/tests/integration/api_user_email_test.go index 7bd265187ca0f..5f59ae907f658 100644 --- a/tests/integration/api_user_email_test.go +++ b/tests/integration/api_user_email_test.go @@ -19,7 +19,7 @@ func TestAPIListEmails(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequest(t, "GET", "/api/v1/user/emails?token="+token) resp := session.MakeRequest(t, req, http.StatusOK) @@ -46,7 +46,7 @@ func TestAPIAddEmail(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") opts := api.CreateEmailOption{ Emails: []string{"user101@example.com"}, @@ -83,7 +83,7 @@ func TestAPIDeleteEmail(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") opts := api.DeleteEmailOption{ Emails: []string{"user2-3@example.com"}, diff --git a/tests/integration/api_user_org_perm_test.go b/tests/integration/api_user_org_perm_test.go index fef653545c5f6..5c4aee854ca52 100644 --- a/tests/integration/api_user_org_perm_test.go +++ b/tests/integration/api_user_org_perm_test.go @@ -34,7 +34,7 @@ func sampleTest(t *testing.T, auoptc apiUserOrgPermTestCase) { defer tests.PrepareTestEnv(t)() session := loginUser(t, auoptc.LoginUser) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/orgs/%s/permissions?token=%s", auoptc.User, auoptc.Organization, token)) resp := session.MakeRequest(t, req, http.StatusOK) @@ -127,7 +127,7 @@ func TestUnknowUser(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/unknow/orgs/org25/permissions?token=%s", token)) resp := session.MakeRequest(t, req, http.StatusNotFound) @@ -141,7 +141,7 @@ func TestUnknowOrganization(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/user1/orgs/unknow/permissions?token=%s", token)) resp := session.MakeRequest(t, req, http.StatusNotFound) diff --git a/tests/integration/api_user_orgs_test.go b/tests/integration/api_user_orgs_test.go index 622dfdcf21e09..2e511303b2b50 100644 --- a/tests/integration/api_user_orgs_test.go +++ b/tests/integration/api_user_orgs_test.go @@ -70,7 +70,7 @@ func getUserOrgs(t *testing.T, userDoer, userCheck string) (orgs []*api.Organiza session := emptyTestSession(t) if len(userDoer) != 0 { session = loginUser(t, userDoer) - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") } urlStr := fmt.Sprintf("/api/v1/users/%s/orgs?token=%s", userCheck, token) req := NewRequest(t, "GET", urlStr) @@ -88,7 +88,7 @@ func TestMyOrgs(t *testing.T) { normalUsername := "user2" session = loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req = NewRequest(t, "GET", "/api/v1/user/orgs?token="+token) resp := session.MakeRequest(t, req, http.StatusOK) var orgs []*api.Organization diff --git a/tests/integration/api_user_search_test.go b/tests/integration/api_user_search_test.go index 9e9276077b40d..18a98eec6a4c1 100644 --- a/tests/integration/api_user_search_test.go +++ b/tests/integration/api_user_search_test.go @@ -27,7 +27,7 @@ func TestAPIUserSearchLoggedIn(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") query := "user2" req := NewRequestf(t, "GET", "/api/v1/users/search?token=%s&q=%s", token, query) resp := session.MakeRequest(t, req, http.StatusOK) @@ -66,7 +66,7 @@ func TestAPIUserSearchAdminLoggedInUserHidden(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") query := "user31" req := NewRequestf(t, "GET", "/api/v1/users/search?token=%s&q=%s", token, query) req.SetBasicAuth(token, "x-oauth-basic") diff --git a/tests/integration/api_wiki_test.go b/tests/integration/api_wiki_test.go index c6f4841d082ef..1d6d987f9b9bc 100644 --- a/tests/integration/api_wiki_test.go +++ b/tests/integration/api_wiki_test.go @@ -182,7 +182,7 @@ func TestAPINewWikiPage(t *testing.T) { defer tests.PrepareTestEnv(t)() username := "user2" session := loginUser(t, username) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/new?token=%s", username, "repo1", token) @@ -199,7 +199,7 @@ func TestAPIEditWikiPage(t *testing.T) { defer tests.PrepareTestEnv(t)() username := "user2" session := loginUser(t, username) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/page/Page-With-Spaced-Name?token=%s", username, "repo1", token) diff --git a/tests/integration/dump_restore_test.go b/tests/integration/dump_restore_test.go index 19513d0271e17..11cb16b71a11a 100644 --- a/tests/integration/dump_restore_test.go +++ b/tests/integration/dump_restore_test.go @@ -51,7 +51,7 @@ func TestDumpRestore(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // // Phase 1: dump repo1 from the Gitea instance to the filesystem diff --git a/tests/integration/eventsource_test.go b/tests/integration/eventsource_test.go index cd496e01292bb..62611b157c456 100644 --- a/tests/integration/eventsource_test.go +++ b/tests/integration/eventsource_test.go @@ -59,7 +59,7 @@ func TestEventSourceManagerRun(t *testing.T) { thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) assert.NoError(t, thread5.LoadAttributes()) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") var apiNL []api.NotificationThread diff --git a/tests/integration/integration_test.go b/tests/integration/integration_test.go index 1ae4a830809c7..6d67920b674b2 100644 --- a/tests/integration/integration_test.go +++ b/tests/integration/integration_test.go @@ -218,8 +218,8 @@ func emptyTestSession(t testing.TB) *TestSession { return &TestSession{jar: jar} } -func getUserToken(t testing.TB, userName string) string { - return getTokenForLoggedInUser(t, loginUser(t, userName)) +func getUserToken(t testing.TB, userName string, scope ...string) string { + return getTokenForLoggedInUser(t, loginUser(t, userName), scope...) } func loginUser(t testing.TB, userName string) *TestSession { @@ -261,8 +261,10 @@ func loginUserWithPassword(t testing.TB, userName, password string) *TestSession // token has to be unique this counter take care of var tokenCounter int64 +// getTokenForLoggedInUser returns a token for a logged in user. +// The scope is an optional list of snake_case strings like the frontend form fields, +// but without the "scope_" prefix. func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...string) string { - // TODO set the scope for the token t.Helper() tokenCounter++ req := NewRequest(t, "GET", "/user/settings/applications") @@ -273,7 +275,7 @@ func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...strin "name": fmt.Sprintf("api-testing-token-%d", tokenCounter), } for _, scope := range scopes { - values[fmt.Sprintf("scope_[%s]", scope)] = "on" + values[fmt.Sprintf("scope_%s", scope)] = "on" } req = NewRequestWithValues(t, "POST", "/user/settings/applications", values) session.MakeRequest(t, req, http.StatusSeeOther) diff --git a/tests/integration/migrate_test.go b/tests/integration/migrate_test.go index 99d5d6c8dd239..5b01a9eaca067 100644 --- a/tests/integration/migrate_test.go +++ b/tests/integration/migrate_test.go @@ -67,7 +67,7 @@ func TestMigrateGiteaForm(t *testing.T) { repoName := "repo1" repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: ownerName}) session := loginUser(t, ownerName) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") // Step 0: verify the repo is available req := NewRequestf(t, "GET", fmt.Sprintf("/%s/%s", ownerName, repoName)) diff --git a/tests/integration/privateactivity_test.go b/tests/integration/privateactivity_test.go index 3f352e49c6187..74c62e84c68de 100644 --- a/tests/integration/privateactivity_test.go +++ b/tests/integration/privateactivity_test.go @@ -34,7 +34,7 @@ func testPrivateActivityDoSomethingForActionEntries(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}) session := loginUser(t, privateActivityTestUser) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all&token=%s", owner.Name, repoBefore.Name, token) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateIssueOption{ Body: "test", @@ -125,7 +125,7 @@ func testPrivateActivityHelperHasHeatmapContentFromPublic(t *testing.T) bool { } func testPrivateActivityHelperHasHeatmapContentFromSession(t *testing.T, session *TestSession) bool { - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "GET", "/api/v1/users/%s/heatmap?token=%s", privateActivityTestUser, token) resp := session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/pull_merge_test.go b/tests/integration/pull_merge_test.go index 335dae4b38adf..14de61ba2890e 100644 --- a/tests/integration/pull_merge_test.go +++ b/tests/integration/pull_merge_test.go @@ -218,7 +218,7 @@ func TestCantMergeConflict(t *testing.T) { testEditFileToNewBranch(t, session, "user1", "repo1", "master", "base", "README.md", "Hello, World (Edited Twice)\n") // Use API to create a conflicting pr - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", "user1", "repo1", token), &api.CreatePullRequestOption{ Head: "conflict", Base: "base", @@ -326,7 +326,7 @@ func TestCantMergeUnrelated(t *testing.T) { testEditFileToNewBranch(t, session, "user1", "repo1", "master", "conflict", "README.md", "Hello, World (Edited Once)\n") // Use API to create a conflicting pr - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", "user1", "repo1", token), &api.CreatePullRequestOption{ Head: "unrelated", Base: "base", diff --git a/tests/integration/pull_update_test.go b/tests/integration/pull_update_test.go index c08faaaeb6f4e..ff9d2bbe9ebe6 100644 --- a/tests/integration/pull_update_test.go +++ b/tests/integration/pull_update_test.go @@ -39,7 +39,7 @@ func TestAPIPullUpdate(t *testing.T) { assert.NoError(t, pr.LoadIssue()) session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index) session.MakeRequest(t, req, http.StatusOK) @@ -67,7 +67,7 @@ func TestAPIPullUpdateByRebase(t *testing.T) { assert.NoError(t, pr.LoadIssue()) session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase&token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index) session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/user_test.go b/tests/integration/user_test.go index 110f5c89bfbd3..8b0520fcca59e 100644 --- a/tests/integration/user_test.go +++ b/tests/integration/user_test.go @@ -152,7 +152,7 @@ Note: This user hasn't uploaded any GPG keys. // Import key // User1 session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") testCreateGPGKey(t, session.MakeRequest, token, http.StatusCreated, `-----BEGIN PGP PUBLIC KEY BLOCK----- mQENBFyy/VUBCADJ7zbM20Z1RWmFoVgp5WkQfI2rU1Vj9cQHes9i42wVLLtcbPeo From f3942ef05e8fa38af4d717fe7c6ce030be77485d Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 29 Oct 2022 02:42:32 -0400 Subject: [PATCH 022/118] Revert api router and integration tests --- routers/api/v1/api.go | 411 +++++++++--------- tests/integration/api_admin_org_test.go | 6 +- tests/integration/api_admin_test.go | 20 +- tests/integration/api_branch_test.go | 14 +- tests/integration/api_comment_test.go | 27 +- tests/integration/api_gpg_keys_test.go | 2 +- .../api_helper_for_declarative_test.go | 2 +- tests/integration/api_httpsig_test.go | 9 +- tests/integration/api_issue_label_test.go | 8 +- tests/integration/api_issue_milestone_test.go | 2 +- tests/integration/api_issue_reaction_test.go | 4 +- tests/integration/api_issue_stopwatch_test.go | 8 +- .../api_issue_subscription_test.go | 2 +- tests/integration/api_issue_test.go | 6 +- .../api_issue_tracked_time_test.go | 6 +- tests/integration/api_keys_test.go | 8 +- tests/integration/api_notification_test.go | 4 +- tests/integration/api_oauth2_apps_test.go | 6 +- tests/integration/api_org_test.go | 6 +- .../api_packages_container_test.go | 2 - tests/integration/api_packages_test.go | 2 +- tests/integration/api_pull_commits_test.go | 3 +- tests/integration/api_pull_review_test.go | 6 +- tests/integration/api_pull_test.go | 18 +- tests/integration/api_releases_test.go | 17 +- tests/integration/api_repo_archive_test.go | 2 +- tests/integration/api_repo_edit_test.go | 4 +- .../integration/api_repo_file_create_test.go | 4 +- .../integration/api_repo_file_delete_test.go | 4 +- .../integration/api_repo_file_update_test.go | 4 +- .../api_repo_get_contents_list_test.go | 4 +- .../integration/api_repo_get_contents_test.go | 4 +- tests/integration/api_repo_git_blobs_test.go | 4 +- .../integration/api_repo_git_commits_test.go | 12 +- tests/integration/api_repo_git_hook_test.go | 18 +- tests/integration/api_repo_git_notes_test.go | 2 +- tests/integration/api_repo_git_ref_test.go | 2 +- tests/integration/api_repo_git_tags_test.go | 4 +- tests/integration/api_repo_git_trees_test.go | 4 +- .../integration/api_repo_lfs_migrate_test.go | 2 +- tests/integration/api_repo_raw_test.go | 2 +- tests/integration/api_repo_tags_test.go | 2 +- tests/integration/api_repo_teams_test.go | 4 +- tests/integration/api_repo_test.go | 32 +- tests/integration/api_team_test.go | 6 +- tests/integration/api_team_user_test.go | 2 +- tests/integration/api_user_email_test.go | 6 +- tests/integration/api_user_org_perm_test.go | 6 +- tests/integration/api_user_orgs_test.go | 4 +- tests/integration/api_user_search_test.go | 4 +- tests/integration/api_wiki_test.go | 4 +- tests/integration/dump_restore_test.go | 2 +- tests/integration/eventsource_test.go | 2 +- tests/integration/integration_test.go | 11 +- tests/integration/migrate_test.go | 2 +- tests/integration/privateactivity_test.go | 4 +- tests/integration/pull_merge_test.go | 4 +- tests/integration/pull_update_test.go | 4 +- tests/integration/user_test.go | 2 +- 59 files changed, 369 insertions(+), 407 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 9083de0b729b5..0d11674aa9971 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -71,7 +71,6 @@ import ( "reflect" "strings" - auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/perm" access_model "code.gitea.io/gitea/models/perm/access" @@ -209,22 +208,9 @@ func reqPackageAccess(accessMode perm.AccessMode) func(ctx *context.APIContext) } // Contexter middleware already checks token for user sign in process. -func reqToken(requiredScope string) func(ctx *context.APIContext) { +func reqToken() func(ctx *context.APIContext) { return func(ctx *context.APIContext) { if true == ctx.Data["IsApiToken"] { - if requiredScope == "" { - return - } - scope := ctx.Data["ApiTokenScope"].(auth_model.AccessTokenScope) - allow, err := scope.HasScope(requiredScope) - if err != nil { - ctx.Error(http.StatusUnauthorized, "reqToken", "parsing token failed") - return - } - if !allow { - ctx.Error(http.StatusUnauthorized, "reqToken", "token does not have required scope: "+requiredScope) - return - } return } if ctx.Context.IsBasicAuth { @@ -650,7 +636,7 @@ func Routes(ctx gocontext.Context) *web.Route { })) m.Group("", func() { - // Miscellaneous (no scope required) + // Miscellaneous if setting.API.EnableSwagger { m.Get("/swagger", func(ctx *context.APIContext) { ctx.Redirect(setting.AppSubURL + "/api/swagger") @@ -676,7 +662,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/repository", settings.GetGeneralRepoSettings) }) - // Notifications (requires 'notification' scope) + // Notifications m.Group("/notifications", func() { m.Combo(""). Get(notify.ListNotifications). @@ -685,9 +671,9 @@ func Routes(ctx gocontext.Context) *web.Route { m.Combo("/threads/{id}"). Get(notify.GetThread). Patch(notify.ReadThread) - }, reqToken(auth_model.AccessTokenScopeNotification)) + }, reqToken()) - // Users (no scope required) + // Users m.Group("/users", func() { m.Get("/search", reqExploreSignIn(), user.Search) @@ -703,11 +689,10 @@ func Routes(ctx gocontext.Context) *web.Route { m.Combo("").Get(user.ListAccessTokens). Post(bind(api.CreateAccessTokenOption{}), user.CreateAccessToken) m.Combo("/{id}").Delete(user.DeleteAccessToken) - }, reqBasicOrRevProxyAuth()) // basic auth or reverse proxy auth required + }, reqBasicOrRevProxyAuth()) }, context_service.UserAssignmentAPI()) }) - // (no scope required) m.Group("/users", func() { m.Group("/{username}", func() { m.Get("/keys", user.ListPublicKeys) @@ -723,37 +708,34 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/subscriptions", user.GetWatchedRepos) }, context_service.UserAssignmentAPI()) - }, reqToken("")) + }, reqToken()) m.Group("/user", func() { m.Get("", user.GetAuthenticatedUser) m.Group("/settings", func() { - m.Get("", reqToken(auth_model.AccessTokenScopeReadUser), user.GetUserSettings) - m.Patch("", reqToken(auth_model.AccessTokenScopeUser), bind(api.UserSettingsOptions{}), user.UpdateUserSettings) - }, reqToken("")) - m.Combo("/emails").Get(reqToken(auth_model.AccessTokenScopeReadUser), user.ListEmails). - Post(reqToken(auth_model.AccessTokenScopeUser), bind(api.CreateEmailOption{}), user.AddEmail). - Delete(reqToken(auth_model.AccessTokenScopeUser), bind(api.DeleteEmailOption{}), user.DeleteEmail) + m.Get("", user.GetUserSettings) + m.Patch("", bind(api.UserSettingsOptions{}), user.UpdateUserSettings) + }, reqToken()) + m.Combo("/emails").Get(user.ListEmails). + Post(bind(api.CreateEmailOption{}), user.AddEmail). + Delete(bind(api.DeleteEmailOption{}), user.DeleteEmail) m.Get("/followers", user.ListMyFollowers) m.Group("/following", func() { m.Get("", user.ListMyFollowing) m.Group("/{username}", func() { m.Get("", user.CheckMyFollowing) - m.Put("", reqToken(auth_model.AccessTokenScopeUserFollow), user.Follow) // requires 'user:follow' scope - m.Delete("", reqToken(auth_model.AccessTokenScopeUserFollow), user.Unfollow) // requires 'user:follow' scope + m.Put("", user.Follow) + m.Delete("", user.Unfollow) }, context_service.UserAssignmentAPI()) }) - // (admin:public_key scope) m.Group("/keys", func() { - m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadPublicKey), user.ListMyPublicKeys). - Post(reqToken(auth_model.AccessTokenScopeWritePublicKey), bind(api.CreateKeyOption{}), user.CreatePublicKey) - m.Combo("/{id}").Get(reqToken(auth_model.AccessTokenScopeReadPublicKey), user.GetPublicKey). - Delete(reqToken(auth_model.AccessTokenScopeWritePublicKey), user.DeletePublicKey) + m.Combo("").Get(user.ListMyPublicKeys). + Post(bind(api.CreateKeyOption{}), user.CreatePublicKey) + m.Combo("/{id}").Get(user.GetPublicKey). + Delete(user.DeletePublicKey) }) - - // (repo scope) m.Group("/applications", func() { m.Combo("/oauth2"). Get(user.ListOauth2Applications). @@ -762,25 +744,21 @@ func Routes(ctx gocontext.Context) *web.Route { Delete(user.DeleteOauth2Application). Patch(bind(api.CreateOAuth2ApplicationOptions{}), user.UpdateOauth2Application). Get(user.GetOauth2Application) - }, reqToken(auth_model.AccessTokenScopeRepo)) + }, reqToken()) - // (admin:gpg_key scope) m.Group("/gpg_keys", func() { - m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadGPGKey), user.ListMyGPGKeys). - Post(reqToken(auth_model.AccessTokenScopeWriteGPGKey), bind(api.CreateGPGKeyOption{}), user.CreateGPGKey) - m.Combo("/{id}").Get(reqToken(auth_model.AccessTokenScopeReadGPGKey), user.GetGPGKey). - Delete(reqToken(auth_model.AccessTokenScopeWriteGPGKey), user.DeleteGPGKey) + m.Combo("").Get(user.ListMyGPGKeys). + Post(bind(api.CreateGPGKeyOption{}), user.CreateGPGKey) + m.Combo("/{id}").Get(user.GetGPGKey). + Delete(user.DeleteGPGKey) }) - // (read:gpg_key scope) - m.Get("/gpg_key_token", reqToken(auth_model.AccessTokenScopeReadGPGKey), user.GetVerificationToken) - m.Post("/gpg_key_verify", reqToken(auth_model.AccessTokenScopeReadGPGKey), bind(api.VerifyGPGKeyOption{}), user.VerifyUserGPGKey) + m.Get("/gpg_key_token", user.GetVerificationToken) + m.Post("/gpg_key_verify", bind(api.VerifyGPGKeyOption{}), user.VerifyUserGPGKey) - // (repo scope) - m.Combo("/repos", reqToken(auth_model.AccessTokenScopeRepo)).Get(user.ListMyRepos). + m.Combo("/repos").Get(user.ListMyRepos). Post(bind(api.CreateRepoOption{}), repo.Create) - // (repo scope) m.Group("/starred", func() { m.Get("", user.GetMyStarredRepos) m.Group("/{username}/{reponame}", func() { @@ -788,58 +766,57 @@ func Routes(ctx gocontext.Context) *web.Route { m.Put("", user.Star) m.Delete("", user.Unstar) }, repoAssignment()) - }, reqToken(auth_model.AccessTokenScopeRepo)) - m.Get("/times", reqToken(auth_model.AccessTokenScopeRepo), repo.ListMyTrackedTimes) - m.Get("/stopwatches", reqToken(auth_model.AccessTokenScopeRepo), repo.GetStopwatches) - m.Get("/subscriptions", reqToken(auth_model.AccessTokenScopeRepo), user.GetMyWatchedRepos) - m.Get("/teams", reqToken(auth_model.AccessTokenScopeRepo), org.ListUserTeams) - }, reqToken("")) + }) + m.Get("/times", repo.ListMyTrackedTimes) + + m.Get("/stopwatches", repo.GetStopwatches) - // Repositories (admin:org scope) - m.Post("/org/{org}/repos", reqToken(auth_model.AccessTokenScopeAdminOrg), bind(api.CreateRepoOption{}), repo.CreateOrgRepoDeprecated) + m.Get("/subscriptions", user.GetMyWatchedRepos) - // (repo scope) - m.Combo("/repositories/{id}", reqToken(auth_model.AccessTokenScopeRepo)).Get(repo.GetByID) + m.Get("/teams", org.ListUserTeams) + }, reqToken()) + + // Repositories + m.Post("/org/{org}/repos", reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepoDeprecated) + + m.Combo("/repositories/{id}", reqToken()).Get(repo.GetByID) m.Group("/repos", func() { m.Get("/search", repo.Search) m.Get("/issues/search", repo.SearchIssues) - // (repo scope) - m.Post("/migrate", reqToken(auth_model.AccessTokenScopeRepo), bind(api.MigrateRepoOptions{}), repo.Migrate) + m.Post("/migrate", reqToken(), bind(api.MigrateRepoOptions{}), repo.Migrate) m.Group("/{username}/{reponame}", func() { m.Combo("").Get(reqAnyRepoReader(), repo.Get). - Delete(reqToken(auth_model.AccessTokenScopeDeleteRepo), reqOwner(), repo.Delete). - Patch(reqToken(auth_model.AccessTokenScopeRepo), reqAdmin(), bind(api.EditRepoOption{}), repo.Edit) - m.Post("/generate", reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode), bind(api.GenerateRepoOption{}), repo.Generate) - m.Group("/transfer", func() { - m.Post("", reqOwner(), bind(api.TransferRepoOption{}), repo.Transfer) - m.Post("/accept", repo.AcceptTransfer) - m.Post("/reject", repo.RejectTransfer) - }, reqToken(auth_model.AccessTokenScopeRepo)) - m.Combo("/notifications", reqToken(auth_model.AccessTokenScopeNotification)). - Get(notify.ListRepoNotifications). - Put(notify.ReadRepoNotifications) + Delete(reqToken(), reqOwner(), repo.Delete). + Patch(reqToken(), reqAdmin(), bind(api.EditRepoOption{}), repo.Edit) + m.Post("/generate", reqToken(), reqRepoReader(unit.TypeCode), bind(api.GenerateRepoOption{}), repo.Generate) + m.Post("/transfer", reqOwner(), bind(api.TransferRepoOption{}), repo.Transfer) + m.Post("/transfer/accept", reqToken(), repo.AcceptTransfer) + m.Post("/transfer/reject", reqToken(), repo.RejectTransfer) + m.Combo("/notifications"). + Get(reqToken(), notify.ListRepoNotifications). + Put(reqToken(), notify.ReadRepoNotifications) m.Group("/hooks/git", func() { - m.Get("", reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.ListGitHooks) + m.Combo("").Get(repo.ListGitHooks) m.Group("/{id}", func() { - m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.GetGitHook). - Patch(reqToken(auth_model.AccessTokenScopeWriteRepoHook), bind(api.EditGitHookOption{}), repo.EditGitHook). - Delete(reqToken(auth_model.AccessTokenScopeWriteRepoHook), repo.DeleteGitHook) + m.Combo("").Get(repo.GetGitHook). + Patch(bind(api.EditGitHookOption{}), repo.EditGitHook). + Delete(repo.DeleteGitHook) }) - }, reqAdmin(), reqGitHook(), context.ReferencesGitRepo(true)) + }, reqToken(), reqAdmin(), reqGitHook(), context.ReferencesGitRepo(true)) m.Group("/hooks", func() { - m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.ListHooks). - Post(reqToken(auth_model.AccessTokenScopeWriteRepoHook), bind(api.CreateHookOption{}), repo.CreateHook) + m.Combo("").Get(repo.ListHooks). + Post(bind(api.CreateHookOption{}), repo.CreateHook) m.Group("/{id}", func() { - m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.GetHook). - Patch(reqToken(auth_model.AccessTokenScopeWriteRepoHook), bind(api.EditHookOption{}), repo.EditHook). - Delete(reqToken(auth_model.AccessTokenScopeWriteRepoHook), repo.DeleteHook) - m.Post("/tests", reqToken(auth_model.AccessTokenScopeReadRepoHook), context.ReferencesGitRepo(), context.RepoRefForAPI, repo.TestHook) + m.Combo("").Get(repo.GetHook). + Patch(bind(api.EditHookOption{}), repo.EditHook). + Delete(repo.DeleteHook) + m.Post("/tests", context.ReferencesGitRepo(), context.RepoRefForAPI, repo.TestHook) }) - }, reqAdmin(), reqWebhooksEnabled()) + }, reqToken(), reqAdmin(), reqWebhooksEnabled()) m.Group("/collaborators", func() { m.Get("", reqAnyRepoReader(), repo.ListCollaborators) m.Group("/{collaborator}", func() { @@ -847,27 +824,27 @@ func Routes(ctx gocontext.Context) *web.Route { Put(reqAdmin(), bind(api.AddCollaboratorOption{}), repo.AddCollaborator). Delete(reqAdmin(), repo.DeleteCollaborator) m.Get("/permission", repo.GetRepoPermissions) - }, reqToken("")) - }, reqToken(auth_model.AccessTokenScopeRepo)) - m.Get("/assignees", reqToken(auth_model.AccessTokenScopeRepo), reqAnyRepoReader(), repo.GetAssignees) - m.Get("/reviewers", reqToken(auth_model.AccessTokenScopeRepo), reqAnyRepoReader(), repo.GetReviewers) + }, reqToken()) + }, reqToken()) + m.Get("/assignees", reqToken(), reqAnyRepoReader(), repo.GetAssignees) + m.Get("/reviewers", reqToken(), reqAnyRepoReader(), repo.GetReviewers) m.Group("/teams", func() { m.Get("", reqAnyRepoReader(), repo.ListTeams) m.Combo("/{team}").Get(reqAnyRepoReader(), repo.IsTeam). Put(reqAdmin(), repo.AddTeam). Delete(reqAdmin(), repo.DeleteTeam) - }, reqToken(auth_model.AccessTokenScopeRepo)) - m.Get("/raw/*", reqToken(auth_model.AccessTokenScopeRepo), context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFile) - m.Get("/media/*", reqToken(auth_model.AccessTokenScopeRepo), context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFileOrLFS) - m.Get("/archive/*", reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode), repo.GetArchive) - m.Combo("/forks", reqToken(auth_model.AccessTokenScopeRepo)).Get(repo.ListForks). - Post(reqToken(""), reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork) + }, reqToken()) + m.Get("/raw/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFile) + m.Get("/media/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFileOrLFS) + m.Get("/archive/*", reqRepoReader(unit.TypeCode), repo.GetArchive) + m.Combo("/forks").Get(repo.ListForks). + Post(reqToken(), reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork) m.Group("/branches", func() { m.Get("", repo.ListBranches) m.Get("/*", repo.GetBranch) m.Delete("/*", reqRepoWriter(unit.TypeCode), repo.DeleteBranch) m.Post("", reqRepoWriter(unit.TypeCode), bind(api.CreateBranchRepoOption{}), repo.CreateBranch) - }, reqToken(auth_model.AccessTokenScopeRepo), context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode)) + }, context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode)) m.Group("/branch_protections", func() { m.Get("", repo.ListBranchProtections) m.Post("", bind(api.CreateBranchProtectionOption{}), repo.CreateBranchProtection) @@ -876,23 +853,23 @@ func Routes(ctx gocontext.Context) *web.Route { m.Patch("", bind(api.EditBranchProtectionOption{}), repo.EditBranchProtection) m.Delete("", repo.DeleteBranchProtection) }) - }, reqToken(auth_model.AccessTokenScopeRepo), reqAdmin()) + }, reqToken(), reqAdmin()) m.Group("/tags", func() { m.Get("", repo.ListTags) m.Get("/*", repo.GetTag) m.Post("", reqRepoWriter(unit.TypeCode), bind(api.CreateTagOption{}), repo.CreateTag) m.Delete("/*", repo.DeleteTag) - }, reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode), context.ReferencesGitRepo(true)) + }, reqRepoReader(unit.TypeCode), context.ReferencesGitRepo(true)) m.Group("/keys", func() { m.Combo("").Get(repo.ListDeployKeys). Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey) m.Combo("/{id}").Get(repo.GetDeployKey). Delete(repo.DeleteDeploykey) - }, reqToken(auth_model.AccessTokenScopeRepo), reqAdmin()) + }, reqToken(), reqAdmin()) m.Group("/times", func() { m.Combo("").Get(repo.ListTrackedTimesByRepository) m.Combo("/{timetrackingusername}").Get(repo.ListTrackedTimesByUser) - }, reqToken(auth_model.AccessTokenScopeRepo), mustEnableIssues, reqToken("")) + }, mustEnableIssues, reqToken()) m.Group("/wiki", func() { m.Combo("/page/{pageName}"). Get(repo.GetWikiPage). @@ -901,40 +878,40 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/revisions/{pageName}", repo.ListPageRevisions) m.Post("/new", mustNotBeArchived, reqRepoWriter(unit.TypeWiki), bind(api.CreateWikiPageOptions{}), repo.NewWikiPage) m.Get("/pages", repo.ListWikiPages) - }, reqToken(auth_model.AccessTokenScopeRepo), mustEnableWiki) + }, mustEnableWiki) m.Group("/issues", func() { m.Combo("").Get(repo.ListIssues). - Post(reqToken(""), mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue) + Post(reqToken(), mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue) m.Group("/comments", func() { m.Get("", repo.ListRepoIssueComments) m.Group("/{id}", func() { m.Combo(""). Get(repo.GetIssueComment). - Patch(mustNotBeArchived, reqToken(""), bind(api.EditIssueCommentOption{}), repo.EditIssueComment). - Delete(reqToken(""), repo.DeleteIssueComment) + Patch(mustNotBeArchived, reqToken(), bind(api.EditIssueCommentOption{}), repo.EditIssueComment). + Delete(reqToken(), repo.DeleteIssueComment) m.Combo("/reactions"). Get(repo.GetIssueCommentReactions). - Post(reqToken(""), bind(api.EditReactionOption{}), repo.PostIssueCommentReaction). - Delete(reqToken(""), bind(api.EditReactionOption{}), repo.DeleteIssueCommentReaction) + Post(reqToken(), bind(api.EditReactionOption{}), repo.PostIssueCommentReaction). + Delete(reqToken(), bind(api.EditReactionOption{}), repo.DeleteIssueCommentReaction) }) }) m.Group("/{index}", func() { m.Combo("").Get(repo.GetIssue). - Patch(reqToken(""), bind(api.EditIssueOption{}), repo.EditIssue). - Delete(reqToken(""), reqAdmin(), repo.DeleteIssue) + Patch(reqToken(), bind(api.EditIssueOption{}), repo.EditIssue). + Delete(reqToken(), reqAdmin(), repo.DeleteIssue) m.Group("/comments", func() { m.Combo("").Get(repo.ListIssueComments). - Post(reqToken(""), mustNotBeArchived, bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment) - m.Combo("/{id}", reqToken("")).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueCommentDeprecated). + Post(reqToken(), mustNotBeArchived, bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment) + m.Combo("/{id}", reqToken()).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueCommentDeprecated). Delete(repo.DeleteIssueCommentDeprecated) }) m.Get("/timeline", repo.ListIssueCommentsAndTimeline) m.Group("/labels", func() { m.Combo("").Get(repo.ListIssueLabels). - Post(reqToken(""), bind(api.IssueLabelsOption{}), repo.AddIssueLabels). - Put(reqToken(""), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels). - Delete(reqToken(""), repo.ClearIssueLabels) - m.Delete("/{id}", reqToken(""), repo.DeleteIssueLabel) + Post(reqToken(), bind(api.IssueLabelsOption{}), repo.AddIssueLabels). + Put(reqToken(), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels). + Delete(reqToken(), repo.ClearIssueLabels) + m.Delete("/{id}", reqToken(), repo.DeleteIssueLabel) }) m.Group("/times", func() { m.Combo(""). @@ -942,124 +919,124 @@ func Routes(ctx gocontext.Context) *web.Route { Post(bind(api.AddTimeOption{}), repo.AddTime). Delete(repo.ResetIssueTime) m.Delete("/{id}", repo.DeleteTime) - }, reqToken("")) - m.Combo("/deadline").Post(reqToken(""), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline) + }, reqToken()) + m.Combo("/deadline").Post(reqToken(), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline) m.Group("/stopwatch", func() { - m.Post("/start", reqToken(""), repo.StartIssueStopwatch) - m.Post("/stop", reqToken(""), repo.StopIssueStopwatch) - m.Delete("/delete", reqToken(""), repo.DeleteIssueStopwatch) + m.Post("/start", reqToken(), repo.StartIssueStopwatch) + m.Post("/stop", reqToken(), repo.StopIssueStopwatch) + m.Delete("/delete", reqToken(), repo.DeleteIssueStopwatch) }) m.Group("/subscriptions", func() { m.Get("", repo.GetIssueSubscribers) - m.Get("/check", reqToken(""), repo.CheckIssueSubscription) - m.Put("/{user}", reqToken(""), repo.AddIssueSubscription) - m.Delete("/{user}", reqToken(""), repo.DelIssueSubscription) + m.Get("/check", reqToken(), repo.CheckIssueSubscription) + m.Put("/{user}", reqToken(), repo.AddIssueSubscription) + m.Delete("/{user}", reqToken(), repo.DelIssueSubscription) }) m.Combo("/reactions"). Get(repo.GetIssueReactions). - Post(reqToken(""), bind(api.EditReactionOption{}), repo.PostIssueReaction). - Delete(reqToken(""), bind(api.EditReactionOption{}), repo.DeleteIssueReaction) + Post(reqToken(), bind(api.EditReactionOption{}), repo.PostIssueReaction). + Delete(reqToken(), bind(api.EditReactionOption{}), repo.DeleteIssueReaction) }) - }, reqToken(auth_model.AccessTokenScopeRepo), mustEnableIssuesOrPulls) + }, mustEnableIssuesOrPulls) m.Group("/labels", func() { m.Combo("").Get(repo.ListLabels). - Post(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateLabelOption{}), repo.CreateLabel) + Post(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateLabelOption{}), repo.CreateLabel) m.Combo("/{id}").Get(repo.GetLabel). - Patch(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditLabelOption{}), repo.EditLabel). - Delete(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteLabel) - }, reqToken(auth_model.AccessTokenScopeRepo)) - m.Post("/markdown", reqToken(auth_model.AccessTokenScopeRepo), bind(api.MarkdownOption{}), misc.Markdown) - m.Post("/markdown/raw", reqToken(auth_model.AccessTokenScopeRepo), misc.MarkdownRaw) + Patch(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditLabelOption{}), repo.EditLabel). + Delete(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteLabel) + }) + m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown) + m.Post("/markdown/raw", misc.MarkdownRaw) m.Group("/milestones", func() { m.Combo("").Get(repo.ListMilestones). - Post(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateMilestoneOption{}), repo.CreateMilestone) + Post(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateMilestoneOption{}), repo.CreateMilestone) m.Combo("/{id}").Get(repo.GetMilestone). - Patch(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditMilestoneOption{}), repo.EditMilestone). - Delete(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteMilestone) - }, reqToken(auth_model.AccessTokenScopeRepo)) - m.Get("/stargazers", reqToken(auth_model.AccessTokenScopeRepo), repo.ListStargazers) - m.Get("/subscribers", reqToken(auth_model.AccessTokenScopeRepo), repo.ListSubscribers) + Patch(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditMilestoneOption{}), repo.EditMilestone). + Delete(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteMilestone) + }) + m.Get("/stargazers", repo.ListStargazers) + m.Get("/subscribers", repo.ListSubscribers) m.Group("/subscription", func() { m.Get("", user.IsWatching) - m.Put("", reqToken(""), user.Watch) - m.Delete("", reqToken(""), user.Unwatch) - }, reqToken(auth_model.AccessTokenScopeRepo)) + m.Put("", reqToken(), user.Watch) + m.Delete("", reqToken(), user.Unwatch) + }) m.Group("/releases", func() { m.Combo("").Get(repo.ListReleases). - Post(reqToken(""), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.CreateReleaseOption{}), repo.CreateRelease) + Post(reqToken(), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.CreateReleaseOption{}), repo.CreateRelease) m.Group("/{id}", func() { m.Combo("").Get(repo.GetRelease). - Patch(reqToken(""), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.EditReleaseOption{}), repo.EditRelease). - Delete(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.DeleteRelease) + Patch(reqToken(), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.EditReleaseOption{}), repo.EditRelease). + Delete(reqToken(), reqRepoWriter(unit.TypeReleases), repo.DeleteRelease) m.Group("/assets", func() { m.Combo("").Get(repo.ListReleaseAttachments). - Post(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.CreateReleaseAttachment) + Post(reqToken(), reqRepoWriter(unit.TypeReleases), repo.CreateReleaseAttachment) m.Combo("/{asset}").Get(repo.GetReleaseAttachment). - Patch(reqToken(""), reqRepoWriter(unit.TypeReleases), bind(api.EditAttachmentOptions{}), repo.EditReleaseAttachment). - Delete(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseAttachment) + Patch(reqToken(), reqRepoWriter(unit.TypeReleases), bind(api.EditAttachmentOptions{}), repo.EditReleaseAttachment). + Delete(reqToken(), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseAttachment) }) - }, reqToken(auth_model.AccessTokenScopeRepo)) + }) m.Group("/tags", func() { m.Combo("/{tag}"). Get(repo.GetReleaseByTag). - Delete(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseByTag) - }, reqToken(auth_model.AccessTokenScopeRepo)) + Delete(reqToken(), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseByTag) + }) }, reqRepoReader(unit.TypeReleases)) - m.Post("/mirror-sync", reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeCode), repo.MirrorSync) - m.Post("/push_mirrors-sync", reqToken(auth_model.AccessTokenScopeRepo), reqAdmin(), repo.PushMirrorSync) + m.Post("/mirror-sync", reqToken(), reqRepoWriter(unit.TypeCode), repo.MirrorSync) + m.Post("/push_mirrors-sync", reqAdmin(), repo.PushMirrorSync) m.Group("/push_mirrors", func() { m.Combo("").Get(repo.ListPushMirrors). Post(bind(api.CreatePushMirrorOption{}), repo.AddPushMirror) m.Combo("/{name}"). Delete(repo.DeletePushMirrorByRemoteName). Get(repo.GetPushMirrorByName) - }, reqToken(auth_model.AccessTokenScopeRepo), reqAdmin()) + }, reqAdmin()) - m.Get("/editorconfig/{filename}", reqToken(auth_model.AccessTokenScopeRepo), context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetEditorconfig) + m.Get("/editorconfig/{filename}", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetEditorconfig) m.Group("/pulls", func() { m.Combo("").Get(repo.ListPullRequests). - Post(reqToken(""), mustNotBeArchived, bind(api.CreatePullRequestOption{}), repo.CreatePullRequest) + Post(reqToken(), mustNotBeArchived, bind(api.CreatePullRequestOption{}), repo.CreatePullRequest) m.Group("/{index}", func() { m.Combo("").Get(repo.GetPullRequest). - Patch(reqToken(""), bind(api.EditPullRequestOption{}), repo.EditPullRequest) + Patch(reqToken(), bind(api.EditPullRequestOption{}), repo.EditPullRequest) m.Get(".{diffType:diff|patch}", repo.DownloadPullDiffOrPatch) - m.Post("/update", reqToken(""), repo.UpdatePullRequest) + m.Post("/update", reqToken(), repo.UpdatePullRequest) m.Get("/commits", repo.GetPullRequestCommits) m.Get("/files", repo.GetPullRequestFiles) m.Combo("/merge").Get(repo.IsPullRequestMerged). - Post(reqToken(""), mustNotBeArchived, bind(forms.MergePullRequestForm{}), repo.MergePullRequest). - Delete(reqToken(""), mustNotBeArchived, repo.CancelScheduledAutoMerge) + Post(reqToken(), mustNotBeArchived, bind(forms.MergePullRequestForm{}), repo.MergePullRequest). + Delete(reqToken(), mustNotBeArchived, repo.CancelScheduledAutoMerge) m.Group("/reviews", func() { m.Combo(""). Get(repo.ListPullReviews). - Post(reqToken(""), bind(api.CreatePullReviewOptions{}), repo.CreatePullReview) + Post(reqToken(), bind(api.CreatePullReviewOptions{}), repo.CreatePullReview) m.Group("/{id}", func() { m.Combo(""). Get(repo.GetPullReview). - Delete(reqToken(""), repo.DeletePullReview). - Post(reqToken(""), bind(api.SubmitPullReviewOptions{}), repo.SubmitPullReview) + Delete(reqToken(), repo.DeletePullReview). + Post(reqToken(), bind(api.SubmitPullReviewOptions{}), repo.SubmitPullReview) m.Combo("/comments"). Get(repo.GetPullReviewComments) - m.Post("/dismissals", reqToken(""), bind(api.DismissPullReviewOptions{}), repo.DismissPullReview) - m.Post("/undismissals", reqToken(""), repo.UnDismissPullReview) + m.Post("/dismissals", reqToken(), bind(api.DismissPullReviewOptions{}), repo.DismissPullReview) + m.Post("/undismissals", reqToken(), repo.UnDismissPullReview) }) }) m.Combo("/requested_reviewers"). - Delete(reqToken(""), bind(api.PullReviewRequestOptions{}), repo.DeleteReviewRequests). - Post(reqToken(""), bind(api.PullReviewRequestOptions{}), repo.CreateReviewRequests) + Delete(reqToken(), bind(api.PullReviewRequestOptions{}), repo.DeleteReviewRequests). + Post(reqToken(), bind(api.PullReviewRequestOptions{}), repo.CreateReviewRequests) }) - }, reqToken(auth_model.AccessTokenScopeRepo), mustAllowPulls, reqRepoReader(unit.TypeCode), context.ReferencesGitRepo()) + }, mustAllowPulls, reqRepoReader(unit.TypeCode), context.ReferencesGitRepo()) m.Group("/statuses", func() { m.Combo("/{sha}").Get(repo.GetCommitStatuses). - Post(reqToken(""), reqRepoWriter(unit.TypeCode), bind(api.CreateStatusOption{}), repo.NewCommitStatus) - }, reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode)) + Post(reqToken(), reqRepoWriter(unit.TypeCode), bind(api.CreateStatusOption{}), repo.NewCommitStatus) + }, reqRepoReader(unit.TypeCode)) m.Group("/commits", func() { m.Get("", context.ReferencesGitRepo(), repo.GetAllCommits) m.Group("/{ref}", func() { m.Get("/status", repo.GetCombinedCommitStatusByRef) m.Get("/statuses", repo.GetCommitStatusesByRef) }, context.ReferencesGitRepo()) - }, reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode)) + }, reqRepoReader(unit.TypeCode)) m.Group("/git", func() { m.Group("/commits", func() { m.Get("/{sha}", repo.GetSingleCommit) @@ -1071,8 +1048,8 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/blobs/{sha}", repo.GetBlob) m.Get("/tags/{sha}", repo.GetAnnotatedTag) m.Get("/notes/{sha}", repo.GetNote) - }, reqToken(auth_model.AccessTokenScopeRepo), context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode)) - m.Post("/diffpatch", reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeCode), bind(api.ApplyDiffPatchFileOptions{}), repo.ApplyDiffPatch) + }, context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode)) + m.Post("/diffpatch", reqRepoWriter(unit.TypeCode), reqToken(), bind(api.ApplyDiffPatchFileOptions{}), repo.ApplyDiffPatch) m.Group("/contents", func() { m.Get("", repo.GetContentsList) m.Get("/*", repo.GetContents) @@ -1080,17 +1057,17 @@ func Routes(ctx gocontext.Context) *web.Route { m.Post("", bind(api.CreateFileOptions{}), reqRepoBranchWriter, repo.CreateFile) m.Put("", bind(api.UpdateFileOptions{}), reqRepoBranchWriter, repo.UpdateFile) m.Delete("", bind(api.DeleteFileOptions{}), reqRepoBranchWriter, repo.DeleteFile) - }, reqToken(auth_model.AccessTokenScopeRepo)) + }, reqToken()) }, reqRepoReader(unit.TypeCode)) m.Get("/signing-key.gpg", misc.SigningKey) m.Group("/topics", func() { m.Combo("").Get(repo.ListTopics). - Put(reqToken(""), reqAdmin(), bind(api.RepoTopicOptions{}), repo.UpdateTopics) + Put(reqToken(), reqAdmin(), bind(api.RepoTopicOptions{}), repo.UpdateTopics) m.Group("/{topic}", func() { - m.Combo("").Put(reqToken(""), repo.AddTopic). - Delete(reqToken(""), repo.DeleteTopic) + m.Combo("").Put(reqToken(), repo.AddTopic). + Delete(reqToken(), repo.DeleteTopic) }, reqAdmin()) - }, reqToken(auth_model.AccessTokenScopeRepo), reqAnyRepoReader()) + }, reqAnyRepoReader()) m.Get("/issue_templates", context.ReferencesGitRepo(), repo.GetIssueTemplates) m.Get("/languages", reqRepoReader(unit.TypeCode), repo.GetLanguages) }, repoAssignment()) @@ -1098,49 +1075,49 @@ func Routes(ctx gocontext.Context) *web.Route { m.Group("/packages/{username}", func() { m.Group("/{type}/{name}/{version}", func() { - m.Get("", reqToken(auth_model.AccessTokenScopeReadPackage), packages.GetPackage) - m.Delete("", reqToken(auth_model.AccessTokenScopeDeletePackage), reqPackageAccess(perm.AccessModeWrite), packages.DeletePackage) - m.Get("/files", reqToken(auth_model.AccessTokenScopeReadPackage), packages.ListPackageFiles) + m.Get("", packages.GetPackage) + m.Delete("", reqPackageAccess(perm.AccessModeWrite), packages.DeletePackage) + m.Get("/files", packages.ListPackageFiles) }) - m.Get("/", reqToken(auth_model.AccessTokenScopeReadPackage), packages.ListPackages) + m.Get("/", packages.ListPackages) }, context_service.UserAssignmentAPI(), context.PackageAssignmentAPI(), reqPackageAccess(perm.AccessModeRead)) // Organizations - m.Get("/user/orgs", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListMyOrgs) + m.Get("/user/orgs", reqToken(), org.ListMyOrgs) m.Group("/users/{username}/orgs", func() { - m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListUserOrgs) - m.Get("/{org}/permissions", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetUserOrgsPermissions) + m.Get("", org.ListUserOrgs) + m.Get("/{org}/permissions", reqToken(), org.GetUserOrgsPermissions) }, context_service.UserAssignmentAPI()) - m.Post("/orgs", reqToken(auth_model.AccessTokenScopeWriteOrg), bind(api.CreateOrgOption{}), org.Create) + m.Post("/orgs", reqToken(), bind(api.CreateOrgOption{}), org.Create) m.Get("/orgs", org.GetAll) m.Group("/orgs/{org}", func() { - m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.Get). - Patch(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit). - Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.Delete) - m.Combo("/repos").Get(reqToken(auth_model.AccessTokenScopeReadOrg), user.ListOrgRepos). - Post(reqToken(auth_model.AccessTokenScopeWriteOrg), bind(api.CreateRepoOption{}), repo.CreateOrgRepo) + m.Combo("").Get(org.Get). + Patch(reqToken(), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit). + Delete(reqToken(), reqOrgOwnership(), org.Delete) + m.Combo("/repos").Get(user.ListOrgRepos). + Post(reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepo) m.Group("/members", func() { - m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListMembers) + m.Get("", org.ListMembers) m.Combo("/{username}").Get(org.IsMember). - Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.DeleteMember) + Delete(reqToken(), reqOrgOwnership(), org.DeleteMember) }) m.Group("/public_members", func() { - m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListPublicMembers) - m.Combo("/{username}").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.IsPublicMember). - Put(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgMembership(), org.PublicizeMember). - Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgMembership(), org.ConcealMember) + m.Get("", org.ListPublicMembers) + m.Combo("/{username}").Get(org.IsPublicMember). + Put(reqToken(), reqOrgMembership(), org.PublicizeMember). + Delete(reqToken(), reqOrgMembership(), org.ConcealMember) }) m.Group("/teams", func() { - m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListTeams) - m.Post("", reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.CreateTeamOption{}), org.CreateTeam) - m.Get("/search", reqToken(auth_model.AccessTokenScopeReadOrg), org.SearchTeam) - }, reqOrgMembership()) + m.Get("", org.ListTeams) + m.Post("", reqOrgOwnership(), bind(api.CreateTeamOption{}), org.CreateTeam) + m.Get("/search", org.SearchTeam) + }, reqToken(), reqOrgMembership()) m.Group("/labels", func() { - m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListLabels) - m.Post("", reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.CreateLabelOption{}), org.CreateLabel) - m.Combo("/{id}").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetLabel). - Patch(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.EditLabelOption{}), org.EditLabel). - Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.DeleteLabel) + m.Get("", org.ListLabels) + m.Post("", reqToken(), reqOrgOwnership(), bind(api.CreateLabelOption{}), org.CreateLabel) + m.Combo("/{id}").Get(org.GetLabel). + Patch(reqToken(), reqOrgOwnership(), bind(api.EditLabelOption{}), org.EditLabel). + Delete(reqToken(), reqOrgOwnership(), org.DeleteLabel) }) m.Group("/hooks", func() { m.Combo("").Get(org.ListHooks). @@ -1148,27 +1125,27 @@ func Routes(ctx gocontext.Context) *web.Route { m.Combo("/{id}").Get(org.GetHook). Patch(bind(api.EditHookOption{}), org.EditHook). Delete(org.DeleteHook) - }, reqToken(auth_model.AccessTokenScopeAdminOrgHook), reqOrgOwnership(), reqWebhooksEnabled()) + }, reqToken(), reqOrgOwnership(), reqWebhooksEnabled()) }, orgAssignment(true)) m.Group("/teams/{teamid}", func() { - m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeam). - Patch(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.EditTeamOption{}), org.EditTeam). - Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.DeleteTeam) + m.Combo("").Get(org.GetTeam). + Patch(reqOrgOwnership(), bind(api.EditTeamOption{}), org.EditTeam). + Delete(reqOrgOwnership(), org.DeleteTeam) m.Group("/members", func() { - m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamMembers) + m.Get("", org.GetTeamMembers) m.Combo("/{username}"). - Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamMember). - Put(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.AddTeamMember). - Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.RemoveTeamMember) + Get(org.GetTeamMember). + Put(reqOrgOwnership(), org.AddTeamMember). + Delete(reqOrgOwnership(), org.RemoveTeamMember) }) m.Group("/repos", func() { - m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamRepos) + m.Get("", org.GetTeamRepos) m.Combo("/{org}/{reponame}"). - Put(reqToken(auth_model.AccessTokenScopeWriteOrg), org.AddTeamRepository). - Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), org.RemoveTeamRepository). - Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamRepo) + Put(org.AddTeamRepository). + Delete(org.RemoveTeamRepository). + Get(org.GetTeamRepo) }) - }, orgAssignment(false, true), reqTeamMembership()) + }, orgAssignment(false, true), reqToken(), reqTeamMembership()) m.Group("/admin", func() { m.Group("/cron", func() { @@ -1196,7 +1173,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Post("/{username}/{reponame}", admin.AdoptRepository) m.Delete("/{username}/{reponame}", admin.DeleteUnadoptedRepository) }) - }, reqToken(auth_model.AccessTokenScopeSudo), reqSiteAdmin()) + }, reqToken(), reqSiteAdmin()) m.Group("/topics", func() { m.Get("/search", repo.TopicSearch) diff --git a/tests/integration/api_admin_org_test.go b/tests/integration/api_admin_org_test.go index 46649b2df7d1c..a8770db4ca40a 100644 --- a/tests/integration/api_admin_org_test.go +++ b/tests/integration/api_admin_org_test.go @@ -21,7 +21,7 @@ import ( func TestAPIAdminOrgCreate(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") + token := getTokenForLoggedInUser(t, session) org := api.CreateOrgOption{ UserName: "user2_org", @@ -55,7 +55,7 @@ func TestAPIAdminOrgCreate(t *testing.T) { func TestAPIAdminOrgCreateBadVisibility(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") + token := getTokenForLoggedInUser(t, session) org := api.CreateOrgOption{ UserName: "user2_org", @@ -74,7 +74,7 @@ func TestAPIAdminOrgCreateNotAdmin(t *testing.T) { defer tests.PrepareTestEnv(t)() nonAdminUsername := "user2" session := loginUser(t, nonAdminUsername) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") + token := getTokenForLoggedInUser(t, session) org := api.CreateOrgOption{ UserName: "user2_org", FullName: "User2's organization", diff --git a/tests/integration/api_admin_test.go b/tests/integration/api_admin_test.go index b28f22fe6cfc5..d6bc6016ff7f6 100644 --- a/tests/integration/api_admin_test.go +++ b/tests/integration/api_admin_test.go @@ -25,7 +25,7 @@ func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) { session := loginUser(t, "user1") keyOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user2"}) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys?token=%s", keyOwner.Name, token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n", @@ -53,7 +53,7 @@ func TestAPIAdminDeleteMissingSSHKey(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "DELETE", "/api/v1/admin/users/user1/keys/%d?token=%s", unittest.NonexistentID, token) session.MakeRequest(t, req, http.StatusNotFound) } @@ -64,7 +64,7 @@ func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) { normalUsername := "user2" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys?token=%s", adminUsername, token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n", @@ -75,7 +75,7 @@ func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) { DecodeJSON(t, resp, &newPublicKey) session = loginUser(t, normalUsername) - token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") + token = getTokenForLoggedInUser(t, session) req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d?token=%s", adminUsername, newPublicKey.ID, token) session.MakeRequest(t, req, http.StatusForbidden) @@ -86,7 +86,7 @@ func TestAPISudoUser(t *testing.T) { adminUsername := "user1" normalUsername := "user2" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/user?sudo=%s&token=%s", normalUsername, token) req := NewRequest(t, "GET", urlStr) @@ -103,7 +103,7 @@ func TestAPISudoUserForbidden(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/user?sudo=%s&token=%s", adminUsername, token) req := NewRequest(t, "GET", urlStr) @@ -114,7 +114,7 @@ func TestAPIListUsers(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/admin/users?token=%s", token) req := NewRequest(t, "GET", urlStr) @@ -143,7 +143,7 @@ func TestAPIListUsersNonAdmin(t *testing.T) { defer tests.PrepareTestEnv(t)() nonAdminUsername := "user2" session := loginUser(t, nonAdminUsername) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/admin/users?token=%s", token) session.MakeRequest(t, req, http.StatusForbidden) } @@ -152,7 +152,7 @@ func TestAPICreateUserInvalidEmail(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/admin/users?token=%s", token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "email": "invalid_email@domain.com\r\n", @@ -198,7 +198,7 @@ func TestAPIEditUser(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key", "sudo") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/admin/users/%s?token=%s", "user2", token) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ diff --git a/tests/integration/api_branch_test.go b/tests/integration/api_branch_test.go index f86605ef92418..bdfdd3c7520be 100644 --- a/tests/integration/api_branch_test.go +++ b/tests/integration/api_branch_test.go @@ -17,7 +17,7 @@ import ( func testAPIGetBranch(t *testing.T, branchName string, exists bool) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branches/%s?token=%s", branchName, token) resp := session.MakeRequest(t, req, NoExpectedStatus) if !exists { @@ -34,7 +34,7 @@ func testAPIGetBranch(t *testing.T, branchName string, exists bool) { func testAPIGetBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branch_protections/%s?token=%s", branchName, token) resp := session.MakeRequest(t, req, expectedHTTPStatus) @@ -47,7 +47,7 @@ func testAPIGetBranchProtection(t *testing.T, branchName string, expectedHTTPSta func testAPICreateBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/branch_protections?token="+token, &api.BranchProtection{ BranchName: branchName, }) @@ -62,7 +62,7 @@ func testAPICreateBranchProtection(t *testing.T, branchName string, expectedHTTP func testAPIEditBranchProtection(t *testing.T, branchName string, body *api.BranchProtection, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestWithJSON(t, "PATCH", "/api/v1/repos/user2/repo1/branch_protections/"+branchName+"?token="+token, body) resp := session.MakeRequest(t, req, expectedHTTPStatus) @@ -75,14 +75,14 @@ func testAPIEditBranchProtection(t *testing.T, branchName string, body *api.Bran func testAPIDeleteBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branch_protections/%s?token=%s", branchName, token) session.MakeRequest(t, req, expectedHTTPStatus) } func testAPIDeleteBranch(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branches/%s?token=%s", branchName, token) session.MakeRequest(t, req, expectedHTTPStatus) } @@ -156,7 +156,7 @@ func testAPICreateBranches(t *testing.T, giteaURL *url.URL) { } func testAPICreateBranch(t testing.TB, session *TestSession, user, repo, oldBranch, newBranch string, status int) bool { - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestWithJSON(t, "POST", "/api/v1/repos/"+user+"/"+repo+"/branches?token="+token, &api.CreateBranchRepoOption{ BranchName: newBranch, OldBranchName: oldBranch, diff --git a/tests/integration/api_comment_test.go b/tests/integration/api_comment_test.go index 1c4d57dcf409f..126d886842e49 100644 --- a/tests/integration/api_comment_test.go +++ b/tests/integration/api_comment_test.go @@ -31,9 +31,7 @@ func TestAPIListRepoComments(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") - link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments?token="+token, repoOwner.Name, repo.Name)) - fmt.Println(36, link.String()) + link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments", repoOwner.Name, repo.Name)) req := NewRequest(t, "GET", link.String()) resp := session.MakeRequest(t, req, http.StatusOK) @@ -52,7 +50,6 @@ func TestAPIListRepoComments(t *testing.T) { before := "2000-01-01T00:00:11+00:00" // unix: 946684811 since := "2000-01-01T00:00:12+00:00" // unix: 946684812 query.Add("before", before) - query.Add("token", token) link.RawQuery = query.Encode() req = NewRequest(t, "GET", link.String()) resp = session.MakeRequest(t, req, http.StatusOK) @@ -62,7 +59,6 @@ func TestAPIListRepoComments(t *testing.T) { query.Del("before") query.Add("since", since) - query.Add("token", token) link.RawQuery = query.Encode() req = NewRequest(t, "GET", link.String()) resp = session.MakeRequest(t, req, http.StatusOK) @@ -81,8 +77,7 @@ func TestAPIListIssueComments(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/comments?token="+token, + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/comments", repoOwner.Name, repo.Name, issue.Index) resp := session.MakeRequest(t, req, http.StatusOK) @@ -102,7 +97,7 @@ func TestAPICreateComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/comments?token=%s", repoOwner.Name, repo.Name, issue.Index, token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ @@ -125,11 +120,10 @@ func TestAPIGetComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") - // TODO: check if it should be allowed - // req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID) - // session.MakeRequest(t, req, http.StatusOK) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) + token := getTokenForLoggedInUser(t, session) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID) + session.MakeRequest(t, req, http.StatusOK) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) resp := session.MakeRequest(t, req, http.StatusOK) var apiComment api.Comment @@ -155,7 +149,7 @@ func TestAPIEditComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ @@ -180,7 +174,7 @@ func TestAPIDeleteComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) session.MakeRequest(t, req, http.StatusNoContent) @@ -198,8 +192,7 @@ func TestAPIListIssueTimeline(t *testing.T) { // make request session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/timeline&token="+token, + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/timeline", repoOwner.Name, repo.Name, issue.Index) resp := session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/api_gpg_keys_test.go b/tests/integration/api_gpg_keys_test.go index 4ffa81ba9f04f..0ad876c9b97ab 100644 --- a/tests/integration/api_gpg_keys_test.go +++ b/tests/integration/api_gpg_keys_test.go @@ -21,7 +21,7 @@ type makeRequestFunc func(testing.TB, *http.Request, int) *httptest.ResponseReco func TestGPGKeys(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) tt := []struct { name string diff --git a/tests/integration/api_helper_for_declarative_test.go b/tests/integration/api_helper_for_declarative_test.go index 6f34543d56a73..5a798f79f0fc5 100644 --- a/tests/integration/api_helper_for_declarative_test.go +++ b/tests/integration/api_helper_for_declarative_test.go @@ -34,7 +34,7 @@ type APITestContext struct { func NewAPITestContext(t *testing.T, username, reponame string) APITestContext { session := loginUser(t, username) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) return APITestContext{ Session: session, Token: token, diff --git a/tests/integration/api_httpsig_test.go b/tests/integration/api_httpsig_test.go index a0d1893d66753..80b3c586b432c 100644 --- a/tests/integration/api_httpsig_test.go +++ b/tests/integration/api_httpsig_test.go @@ -53,7 +53,7 @@ func TestHTTPSigPubKey(t *testing.T) { // Add our public key to user1 defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") - token := url.QueryEscape(getTokenForLoggedInUser(t, session, "repo", "admin_public_key", "sudo")) + token := url.QueryEscape(getTokenForLoggedInUser(t, session)) keysURL := fmt.Sprintf("/api/v1/user/keys?token=%s", token) keyType := "ssh-rsa" keyContent := "AAAAB3NzaC1yc2EAAAADAQABAAABAQCqOZB5vkRvXFXups1/0StDRdG8plbNSwsWEnNnP4Bvurxa0+z3W9B8GLKnDiLw5MbpbMNyBlpXw13GfuIeciy10DWTz0xUbiy3J3KabCaT36asIw2y7k6Z0jL0UBnrVENwq5/lUbZYqSZ4rRU744wkhh8TULpzM14npQCZwg6aEbG+MwjzddQ72fR+3BPBrKn5dTmmu8rH99O+U+Nuto81Tg7PA+NUupcHOmhdiEGq49plgVFXK98Vks5tiybL4GuzFyWgyX73Dg/QBMn2eMHt1EMv5Gs3i6GFhKKGo4rjDi9qI6PX5oDR4LTNe6cR8td8YhVD8WFZwLLl/vaYyIqd" @@ -69,7 +69,7 @@ func TestHTTPSigPubKey(t *testing.T) { keyID := ssh.FingerprintSHA256(sshSigner.PublicKey()) // create the request - req = NewRequest(t, "GET", "/api/v1/admin/users?token="+token) + req = NewRequest(t, "GET", "/api/v1/admin/users") signer, _, err := httpsig.NewSSHSigner(sshSigner, httpsig.DigestSha512, []string{httpsig.RequestTarget, "(created)", "(expires)"}, httpsig.Signature, 10) if err != nil { @@ -90,10 +90,9 @@ func TestHTTPSigCert(t *testing.T) { // Add our public key to user1 defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") - token := url.QueryEscape(getTokenForLoggedInUser(t, session, "user", "admin_public_key", "sudo")) csrf := GetCSRF(t, session, "/user/settings/keys") - req := NewRequestWithValues(t, "POST", "/user/settings/keys?token="+token, map[string]string{ + req := NewRequestWithValues(t, "POST", "/user/settings/keys", map[string]string{ "_csrf": csrf, "content": "user1", "title": "principal", @@ -117,7 +116,7 @@ func TestHTTPSigCert(t *testing.T) { } // create the request - req = NewRequest(t, "GET", "/api/v1/admin/users?token="+token) + req = NewRequest(t, "GET", "/api/v1/admin/users") // add our cert to the request certString := base64.RawStdEncoding.EncodeToString(pkcert.(*ssh.Certificate).Marshal()) diff --git a/tests/integration/api_issue_label_test.go b/tests/integration/api_issue_label_test.go index b4f6e545c351d..586c50a55f17a 100644 --- a/tests/integration/api_issue_label_test.go +++ b/tests/integration/api_issue_label_test.go @@ -25,7 +25,7 @@ func TestAPIModifyLabels(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels?token=%s", owner.Name, repo.Name, token) // CreateLabel @@ -97,7 +97,7 @@ func TestAPIAddIssueLabels(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels?token=%s", repo.OwnerName, repo.Name, issue.Index, token) req := NewRequestWithJSON(t, "POST", urlStr, &api.IssueLabelsOption{ @@ -120,7 +120,7 @@ func TestAPIReplaceIssueLabels(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels?token=%s", owner.Name, repo.Name, issue.Index, token) req := NewRequestWithJSON(t, "PUT", urlStr, &api.IssueLabelsOption{ @@ -144,7 +144,7 @@ func TestAPIModifyOrgLabels(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) user := "user1" session := loginUser(t, user) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/orgs/%s/labels?token=%s", owner.Name, token) // CreateLabel diff --git a/tests/integration/api_issue_milestone_test.go b/tests/integration/api_issue_milestone_test.go index 2eb7eaee2f384..e22a091bb8d16 100644 --- a/tests/integration/api_issue_milestone_test.go +++ b/tests/integration/api_issue_milestone_test.go @@ -29,7 +29,7 @@ func TestAPIIssuesMilestone(t *testing.T) { assert.Equal(t, structs.StateOpen, milestone.State()) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) // update values of issue milestoneState := "closed" diff --git a/tests/integration/api_issue_reaction_test.go b/tests/integration/api_issue_reaction_test.go index 5f790bd92855d..a3cb9303fbcf9 100644 --- a/tests/integration/api_issue_reaction_test.go +++ b/tests/integration/api_issue_reaction_test.go @@ -29,7 +29,7 @@ func TestAPIIssuesReactions(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue.Repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/reactions?token=%s", @@ -88,7 +88,7 @@ func TestAPICommentReactions(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue.Repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) diff --git a/tests/integration/api_issue_stopwatch_test.go b/tests/integration/api_issue_stopwatch_test.go index 2b3ab815d1648..c2ad9c45e8200 100644 --- a/tests/integration/api_issue_stopwatch_test.go +++ b/tests/integration/api_issue_stopwatch_test.go @@ -26,7 +26,7 @@ func TestAPIListStopWatches(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/user/stopwatches?token=%s", token) resp := session.MakeRequest(t, req, http.StatusOK) var apiWatches []*api.StopWatch @@ -52,7 +52,7 @@ func TestAPIStopStopWatches(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/issues/%d/stopwatch/stop?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) session.MakeRequest(t, req, http.StatusCreated) @@ -68,7 +68,7 @@ func TestAPICancelStopWatches(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/stopwatch/delete?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) session.MakeRequest(t, req, http.StatusNoContent) @@ -84,7 +84,7 @@ func TestAPIStartStopWatches(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/issues/%d/stopwatch/start?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) session.MakeRequest(t, req, http.StatusCreated) diff --git a/tests/integration/api_issue_subscription_test.go b/tests/integration/api_issue_subscription_test.go index 39c4062568809..f4588fbbc42c2 100644 --- a/tests/integration/api_issue_subscription_test.go +++ b/tests/integration/api_issue_subscription_test.go @@ -31,7 +31,7 @@ func TestAPIIssueSubscriptions(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue1.PosterID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) testSubscription := func(issue *issues_model.Issue, isWatching bool) { issueRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}) diff --git a/tests/integration/api_issue_test.go b/tests/integration/api_issue_test.go index 440bd49e3feb8..3e651c620b04f 100644 --- a/tests/integration/api_issue_test.go +++ b/tests/integration/api_issue_test.go @@ -30,7 +30,7 @@ func TestAPIListIssues(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/issues", owner.Name, repo.Name)) link.RawQuery = url.Values{"token": {token}, "state": {"all"}}.Encode() @@ -81,7 +81,7 @@ func TestAPICreateIssue(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all&token=%s", owner.Name, repoBefore.Name, token) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateIssueOption{ Body: body, @@ -117,7 +117,7 @@ func TestAPIEditIssue(t *testing.T) { assert.Equal(t, api.StateOpen, issueBefore.State()) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) // update values of issue issueState := "closed" diff --git a/tests/integration/api_issue_tracked_time_test.go b/tests/integration/api_issue_tracked_time_test.go index 91e950363756c..6e2c77030cb7d 100644 --- a/tests/integration/api_issue_tracked_time_test.go +++ b/tests/integration/api_issue_tracked_time_test.go @@ -28,7 +28,7 @@ func TestAPIGetTrackedTimes(t *testing.T) { assert.NoError(t, issue2.LoadRepo(db.DefaultContext)) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/times?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, token) resp := session.MakeRequest(t, req, http.StatusOK) @@ -71,7 +71,7 @@ func TestAPIDeleteTrackedTime(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) // Deletion not allowed req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time6.ID, token) @@ -106,7 +106,7 @@ func TestAPIAddTrackedTimes(t *testing.T) { admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, admin.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/times?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, token) diff --git a/tests/integration/api_keys_test.go b/tests/integration/api_keys_test.go index 033c557a8b78c..1cb0b20ffe162 100644 --- a/tests/integration/api_keys_test.go +++ b/tests/integration/api_keys_test.go @@ -54,7 +54,7 @@ func TestCreateReadOnlyDeployKey(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", repoOwner.Name, repo.Name, token) rawKeyBody := api.CreateKeyOption{ Title: "read-only", @@ -80,7 +80,7 @@ func TestCreateReadWriteDeployKey(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", repoOwner.Name, repo.Name, token) rawKeyBody := api.CreateKeyOption{ Title: "read-write", @@ -104,7 +104,7 @@ func TestCreateUserKey(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user1"}) session := loginUser(t, "user1") - token := url.QueryEscape(getTokenForLoggedInUser(t, session, "user", "admin_public_key")) + token := url.QueryEscape(getTokenForLoggedInUser(t, session)) keysURL := fmt.Sprintf("/api/v1/user/keys?token=%s", token) keyType := "ssh-rsa" keyContent := "AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM=" @@ -168,7 +168,7 @@ func TestCreateUserKey(t *testing.T) { // Now login as user 2 session2 := loginUser(t, "user2") - token2 := url.QueryEscape(getTokenForLoggedInUser(t, session2, "user", "admin_public_key")) + token2 := url.QueryEscape(getTokenForLoggedInUser(t, session2)) // Should find key even though not ours, but we shouldn't know whose it is fingerprintURL = fmt.Sprintf("/api/v1/user/keys?token=%s&fingerprint=%s", token2, newPublicKey.Fingerprint) diff --git a/tests/integration/api_notification_test.go b/tests/integration/api_notification_test.go index 16e541b029b13..bf85520bb53b7 100644 --- a/tests/integration/api_notification_test.go +++ b/tests/integration/api_notification_test.go @@ -27,7 +27,7 @@ func TestAPINotification(t *testing.T) { thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) assert.NoError(t, thread5.LoadAttributes()) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) // -- GET /notifications -- // test filter @@ -145,7 +145,7 @@ func TestAPINotificationPUT(t *testing.T) { thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) assert.NoError(t, thread5.LoadAttributes()) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) // Check notifications are as expected req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?all=true&token=%s", token)) diff --git a/tests/integration/api_oauth2_apps_test.go b/tests/integration/api_oauth2_apps_test.go index 620838d1dcfe5..6352449d6acb1 100644 --- a/tests/integration/api_oauth2_apps_test.go +++ b/tests/integration/api_oauth2_apps_test.go @@ -56,7 +56,7 @@ func testAPICreateOAuth2Application(t *testing.T) { func testAPIListOAuth2Applications(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) existApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ UID: user.ID, @@ -87,7 +87,7 @@ func testAPIListOAuth2Applications(t *testing.T) { func testAPIDeleteOAuth2Application(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) oldApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ UID: user.ID, @@ -108,7 +108,7 @@ func testAPIDeleteOAuth2Application(t *testing.T) { func testAPIGetOAuth2Application(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) existApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ UID: user.ID, diff --git a/tests/integration/api_org_test.go b/tests/integration/api_org_test.go index 832c5ec65cec5..16e53d6b81581 100644 --- a/tests/integration/api_org_test.go +++ b/tests/integration/api_org_test.go @@ -22,7 +22,7 @@ import ( func TestAPIOrgCreate(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { - token := getUserToken(t, "user1", "admin_org") + token := getUserToken(t, "user1") org := api.CreateOrgOption{ UserName: "user1_org", @@ -80,7 +80,7 @@ func TestAPIOrgEdit(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) org := api.EditOrgOption{ FullName: "User3 organization new full name", Description: "A new description", @@ -107,7 +107,7 @@ func TestAPIOrgEditBadVisibility(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) org := api.EditOrgOption{ FullName: "User3 organization new full name", Description: "A new description", diff --git a/tests/integration/api_packages_container_test.go b/tests/integration/api_packages_container_test.go index 1724430f7c107..ba76ee4baa7dd 100644 --- a/tests/integration/api_packages_container_test.go +++ b/tests/integration/api_packages_container_test.go @@ -30,8 +30,6 @@ func TestPackageContainer(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - // session := loginUser(t, user.Name) - // accessToken := getTokenForLoggedInUser(t, session, "package") has := func(l packages_model.PackagePropertyList, name string) bool { for _, pp := range l { diff --git a/tests/integration/api_packages_test.go b/tests/integration/api_packages_test.go index 086afcb56079d..25f5b3f2a12da 100644 --- a/tests/integration/api_packages_test.go +++ b/tests/integration/api_packages_test.go @@ -28,7 +28,7 @@ func TestPackageAPI(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) packageName := "test-package" packageVersion := "1.0.3" diff --git a/tests/integration/api_pull_commits_test.go b/tests/integration/api_pull_commits_test.go index 1ab9b03eec375..aa58f44bbe510 100644 --- a/tests/integration/api_pull_commits_test.go +++ b/tests/integration/api_pull_commits_test.go @@ -24,8 +24,7 @@ func TestAPIPullCommits(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue.HeadRepoID}) session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") - req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/commits?token="+token, repo.OwnerName, repo.Name, pullIssue.Index) + req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/commits", repo.OwnerName, repo.Name, pullIssue.Index) resp := session.MakeRequest(t, req, http.StatusOK) var commits []*api.Commit diff --git a/tests/integration/api_pull_review_test.go b/tests/integration/api_pull_review_test.go index 58f91de49f0c0..6ebad106fb311 100644 --- a/tests/integration/api_pull_review_test.go +++ b/tests/integration/api_pull_review_test.go @@ -28,7 +28,7 @@ func TestAPIPullReview(t *testing.T) { // test ListPullReviews session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token) resp := session.MakeRequest(t, req, http.StatusOK) @@ -231,7 +231,7 @@ func TestAPIPullReviewRequest(t *testing.T) { // Test add Review Request session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session) req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.PullReviewRequestOptions{ Reviewers: []string{"user4@example.com", "user8"}, }) @@ -251,7 +251,7 @@ func TestAPIPullReviewRequest(t *testing.T) { // Test Remove Review Request session2 := loginUser(t, "user4") - token2 := getTokenForLoggedInUser(t, session2, "repo") + token2 := getTokenForLoggedInUser(t, session2) req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token2), &api.PullReviewRequestOptions{ Reviewers: []string{"user4"}, diff --git a/tests/integration/api_pull_test.go b/tests/integration/api_pull_test.go index b09ed85b2874c..8ce92f3d4a622 100644 --- a/tests/integration/api_pull_test.go +++ b/tests/integration/api_pull_test.go @@ -28,10 +28,10 @@ func TestAPIViewPulls(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) - session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/pulls?state=all&token="+token, owner.Name, repo.Name) - resp := session.MakeRequest(t, req, http.StatusOK) + ctx := NewAPITestContext(t, "user2", repo.Name) + + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/pulls?state=all&token="+ctx.Token, owner.Name, repo.Name) + resp := ctx.Session.MakeRequest(t, req, http.StatusOK) var pulls []*api.PullRequest DecodeJSON(t, resp, &pulls) @@ -74,7 +74,7 @@ func TestAPIMergePullWIP(t *testing.T) { assert.Contains(t, pr.Issue.Title, setting.Repository.PullRequest.WorkInProgressPrefixes[0]) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", owner.Name, repo.Name, pr.Index, token), &forms.MergePullRequestForm{ MergeMessageField: pr.Issue.Title, Do: string(repo_model.MergeStyleMerge), @@ -93,7 +93,7 @@ func TestAPICreatePullSuccess(t *testing.T) { owner11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo11.OwnerID}) session := loginUser(t, owner11.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", owner10.Name, repo10.Name, token), &api.CreatePullRequestOption{ Head: fmt.Sprintf("%s:master", owner11.Name), Base: "master", @@ -113,7 +113,7 @@ func TestAPICreatePullWithFieldsSuccess(t *testing.T) { owner11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo11.OwnerID}) session := loginUser(t, owner11.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) opts := &api.CreatePullRequestOption{ Head: fmt.Sprintf("%s:master", owner11.Name), @@ -150,7 +150,7 @@ func TestAPICreatePullWithFieldsFailure(t *testing.T) { owner11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo11.OwnerID}) session := loginUser(t, owner11.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) opts := &api.CreatePullRequestOption{ Head: fmt.Sprintf("%s:master", owner11.Name), @@ -180,7 +180,7 @@ func TestAPIEditPull(t *testing.T) { owner10 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo10.OwnerID}) session := loginUser(t, owner10.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", owner10.Name, repo10.Name, token), &api.CreatePullRequestOption{ Head: "develop", Base: "master", diff --git a/tests/integration/api_releases_test.go b/tests/integration/api_releases_test.go index f97562e57ba63..0c7f5e2d521e7 100644 --- a/tests/integration/api_releases_test.go +++ b/tests/integration/api_releases_test.go @@ -101,7 +101,7 @@ func TestAPICreateAndUpdateRelease(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session) gitRepo, err := git.OpenRepository(git.DefaultContext, repo.RepoPath()) assert.NoError(t, err) @@ -153,7 +153,7 @@ func TestAPICreateReleaseToDefaultBranch(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session) createNewReleaseUsingAPI(t, session, token, owner, repo, "v0.0.1", "", "v0.0.1", "test") } @@ -164,7 +164,7 @@ func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) gitRepo, err := git.OpenRepository(git.DefaultContext, repo.RepoPath()) assert.NoError(t, err) @@ -182,12 +182,11 @@ func TestAPIGetReleaseByTag(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session, "repo") tag := "v1.1" - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s?token=%s", - owner.Name, repo.Name, tag, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", + owner.Name, repo.Name, tag) req := NewRequestf(t, "GET", urlStr) resp := session.MakeRequest(t, req, http.StatusOK) @@ -199,8 +198,8 @@ func TestAPIGetReleaseByTag(t *testing.T) { nonexistingtag := "nonexistingtag" - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s?token=%s", - owner.Name, repo.Name, nonexistingtag, token) + urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", + owner.Name, repo.Name, nonexistingtag) req = NewRequestf(t, "GET", urlStr) resp = session.MakeRequest(t, req, http.StatusNotFound) @@ -216,7 +215,7 @@ func TestAPIDeleteReleaseByTagName(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session) createNewReleaseUsingAPI(t, session, token, owner, repo, "release-tag", "", "Release Tag", "test") diff --git a/tests/integration/api_repo_archive_test.go b/tests/integration/api_repo_archive_test.go index f601c2dd3ebe7..3707cb7c1c8bb 100644 --- a/tests/integration/api_repo_archive_test.go +++ b/tests/integration/api_repo_archive_test.go @@ -25,7 +25,7 @@ func TestAPIDownloadArchive(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user2.LowerName) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/archive/master.zip", user2.Name, repo.Name)) link.RawQuery = url.Values{"token": {token}}.Encode() diff --git a/tests/integration/api_repo_edit_test.go b/tests/integration/api_repo_edit_test.go index cfedb7ab53b30..4dfae97e43794 100644 --- a/tests/integration/api_repo_edit_test.go +++ b/tests/integration/api_repo_edit_test.go @@ -146,10 +146,10 @@ func TestAPIRepoEdit(t *testing.T) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token2 := getTokenForLoggedInUser(t, session) // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token4 := getTokenForLoggedInUser(t, session) session = emptyTestSession(t) // Test editing a repo1 which user2 owns, changing name and many properties diff --git a/tests/integration/api_repo_file_create_test.go b/tests/integration/api_repo_file_create_test.go index 7e4181db3cb9c..f03efaa0eadf9 100644 --- a/tests/integration/api_repo_file_create_test.go +++ b/tests/integration/api_repo_file_create_test.go @@ -151,10 +151,10 @@ func TestAPICreateFile(t *testing.T) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token2 := getTokenForLoggedInUser(t, session) // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token4 := getTokenForLoggedInUser(t, session) session = emptyTestSession(t) // Test creating a file in repo1 which user2 owns, try both with branch and empty branch diff --git a/tests/integration/api_repo_file_delete_test.go b/tests/integration/api_repo_file_delete_test.go index 2ac749dafc7a8..2c8b1e381f7c5 100644 --- a/tests/integration/api_repo_file_delete_test.go +++ b/tests/integration/api_repo_file_delete_test.go @@ -49,10 +49,10 @@ func TestAPIDeleteFile(t *testing.T) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token2 := getTokenForLoggedInUser(t, session) // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token4 := getTokenForLoggedInUser(t, session) session = emptyTestSession(t) // Test deleting a file in repo1 which user2 owns, try both with branch and empty branch diff --git a/tests/integration/api_repo_file_update_test.go b/tests/integration/api_repo_file_update_test.go index fa42934ebd369..a3be67ad844f4 100644 --- a/tests/integration/api_repo_file_update_test.go +++ b/tests/integration/api_repo_file_update_test.go @@ -117,10 +117,10 @@ func TestAPIUpdateFile(t *testing.T) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token2 := getTokenForLoggedInUser(t, session) // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token4 := getTokenForLoggedInUser(t, session) session = emptyTestSession(t) // Test updating a file in repo1 which user2 owns, try both with branch and empty branch diff --git a/tests/integration/api_repo_get_contents_list_test.go b/tests/integration/api_repo_get_contents_list_test.go index f941be95bcb23..4f2f5cb528c9c 100644 --- a/tests/integration/api_repo_get_contents_list_test.go +++ b/tests/integration/api_repo_get_contents_list_test.go @@ -65,10 +65,10 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token2 := getTokenForLoggedInUser(t, session) // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token4 := getTokenForLoggedInUser(t, session) session = emptyTestSession(t) // Make a new branch in repo1 diff --git a/tests/integration/api_repo_get_contents_test.go b/tests/integration/api_repo_get_contents_test.go index a5c599f2c400f..dddc316e1a963 100644 --- a/tests/integration/api_repo_get_contents_test.go +++ b/tests/integration/api_repo_get_contents_test.go @@ -66,10 +66,10 @@ func testAPIGetContents(t *testing.T, u *url.URL) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token2 := getTokenForLoggedInUser(t, session) // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token4 := getTokenForLoggedInUser(t, session) session = emptyTestSession(t) // Make a new branch in repo1 diff --git a/tests/integration/api_repo_git_blobs_test.go b/tests/integration/api_repo_git_blobs_test.go index c6bf81ca481a0..cb5116c743b5f 100644 --- a/tests/integration/api_repo_git_blobs_test.go +++ b/tests/integration/api_repo_git_blobs_test.go @@ -32,7 +32,7 @@ func TestAPIReposGitBlobs(t *testing.T) { // Login as User2. session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) session = emptyTestSession(t) // don't want anyone logged in for this // Test a public repo that anyone can GET the blob of @@ -70,7 +70,7 @@ func TestAPIReposGitBlobs(t *testing.T) { // Login as User4. session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token4 := getTokenForLoggedInUser(t, session) session = emptyTestSession(t) // don't want anyone logged in for this // Test using org repo "user3/repo3" where user4 is a NOT collaborator diff --git a/tests/integration/api_repo_git_commits_test.go b/tests/integration/api_repo_git_commits_test.go index 81da61903672d..99f83f943c310 100644 --- a/tests/integration/api_repo_git_commits_test.go +++ b/tests/integration/api_repo_git_commits_test.go @@ -29,7 +29,7 @@ func TestAPIReposGitCommits(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) // check invalid requests req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/12345?token="+token, user.Name) @@ -57,7 +57,7 @@ func TestAPIReposGitCommitList(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) // Test getting commits (Page 1) req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?token="+token, user.Name) @@ -80,7 +80,7 @@ func TestAPIReposGitCommitListPage2Empty(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) // Test getting commits (Page=2) req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?token="+token+"&page=2", user.Name) @@ -97,7 +97,7 @@ func TestAPIReposGitCommitListDifferentBranch(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) // Test getting commits (Page=1, Branch=good-sign) req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?token="+token+"&sha=good-sign", user.Name) @@ -116,7 +116,7 @@ func TestDownloadCommitDiffOrPatch(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) // Test getting diff reqDiff := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/git/commits/f27c2b2b03dcab38beaf89b0ab4ff61f6de63441.diff?token="+token, user.Name) @@ -138,7 +138,7 @@ func TestGetFileHistory(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?path=readme.md&token="+token+"&sha=good-sign", user.Name) resp := session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/api_repo_git_hook_test.go b/tests/integration/api_repo_git_hook_test.go index 261c64a323c92..a6c4f91d4a5b9 100644 --- a/tests/integration/api_repo_git_hook_test.go +++ b/tests/integration/api_repo_git_hook_test.go @@ -31,7 +31,7 @@ func TestAPIListGitHooks(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", owner.Name, repo.Name, token) resp := MakeRequest(t, req, http.StatusOK) @@ -57,7 +57,7 @@ func TestAPIListGitHooksNoHooks(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", owner.Name, repo.Name, token) resp := MakeRequest(t, req, http.StatusOK) @@ -77,7 +77,7 @@ func TestAPIListGitHooksNoAccess(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", owner.Name, repo.Name, token) MakeRequest(t, req, http.StatusForbidden) @@ -91,7 +91,7 @@ func TestAPIGetGitHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) resp := MakeRequest(t, req, http.StatusOK) @@ -108,7 +108,7 @@ func TestAPIGetGitHookNoAccess(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) MakeRequest(t, req, http.StatusForbidden) @@ -122,7 +122,7 @@ func TestAPIEditGitHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) @@ -151,7 +151,7 @@ func TestAPIEditGitHookNoAccess(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) req := NewRequestWithJSON(t, "PATCH", urlStr, &api.EditGitHookOption{ @@ -168,7 +168,7 @@ func TestAPIDeleteGitHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) @@ -190,7 +190,7 @@ func TestAPIDeleteGitHookNoAccess(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) MakeRequest(t, req, http.StatusForbidden) diff --git a/tests/integration/api_repo_git_notes_test.go b/tests/integration/api_repo_git_notes_test.go index d6ed49d46c220..713c7599c3336 100644 --- a/tests/integration/api_repo_git_notes_test.go +++ b/tests/integration/api_repo_git_notes_test.go @@ -21,7 +21,7 @@ func TestAPIReposGitNotes(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) // check invalid requests req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/notes/12345?token=%s", user.Name, token) diff --git a/tests/integration/api_repo_git_ref_test.go b/tests/integration/api_repo_git_ref_test.go index 646da11330b66..e8fc47f8dc30b 100644 --- a/tests/integration/api_repo_git_ref_test.go +++ b/tests/integration/api_repo_git_ref_test.go @@ -18,7 +18,7 @@ func TestAPIReposGitRefs(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) for _, ref := range [...]string{ "refs/heads/master", // Branch diff --git a/tests/integration/api_repo_git_tags_test.go b/tests/integration/api_repo_git_tags_test.go index 2445d614c4321..3357f9568dbda 100644 --- a/tests/integration/api_repo_git_tags_test.go +++ b/tests/integration/api_repo_git_tags_test.go @@ -26,7 +26,7 @@ func TestAPIGitTags(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) // Set up git config for the tagger _ = git.NewCommand(git.DefaultContext, "config", "user.name").AddDynamicArguments(user.Name).Run(&git.RunOpts{Dir: repo.RepoPath()}) @@ -70,7 +70,7 @@ func TestAPIDeleteTagByName(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/tags/delete-tag?token=%s", owner.Name, repo.Name, token) diff --git a/tests/integration/api_repo_git_trees_test.go b/tests/integration/api_repo_git_trees_test.go index 8d3551b4ca4fc..385fec12ba158 100644 --- a/tests/integration/api_repo_git_trees_test.go +++ b/tests/integration/api_repo_git_trees_test.go @@ -29,7 +29,7 @@ func TestAPIReposGitTrees(t *testing.T) { // Login as User2. session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) session = emptyTestSession(t) // don't want anyone logged in for this // Test a public repo that anyone can GET the tree of @@ -68,7 +68,7 @@ func TestAPIReposGitTrees(t *testing.T) { // Login as User4. session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token4 := getTokenForLoggedInUser(t, session) session = emptyTestSession(t) // don't want anyone logged in for this // Test using org repo "user3/repo3" where user4 is a NOT collaborator diff --git a/tests/integration/api_repo_lfs_migrate_test.go b/tests/integration/api_repo_lfs_migrate_test.go index 0f940ca4bde84..d2edf67e8be5c 100644 --- a/tests/integration/api_repo_lfs_migrate_test.go +++ b/tests/integration/api_repo_lfs_migrate_test.go @@ -31,7 +31,7 @@ func TestAPIRepoLFSMigrateLocal(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+token, &api.MigrateRepoOptions{ CloneAddr: path.Join(setting.RepoRootPath, "migration/lfs-test.git"), diff --git a/tests/integration/api_repo_raw_test.go b/tests/integration/api_repo_raw_test.go index 6b0ebb7d6cbc6..9793e12b42920 100644 --- a/tests/integration/api_repo_raw_test.go +++ b/tests/integration/api_repo_raw_test.go @@ -20,7 +20,7 @@ func TestAPIReposRaw(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) for _, ref := range [...]string{ "master", // Branch diff --git a/tests/integration/api_repo_tags_test.go b/tests/integration/api_repo_tags_test.go index 54866a88d2030..5d3a209a767a0 100644 --- a/tests/integration/api_repo_tags_test.go +++ b/tests/integration/api_repo_tags_test.go @@ -23,7 +23,7 @@ func TestAPIRepoTags(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) repoName := "repo1" diff --git a/tests/integration/api_repo_teams_test.go b/tests/integration/api_repo_teams_test.go index a53eb8ec8e2e8..1e476a89e232e 100644 --- a/tests/integration/api_repo_teams_test.go +++ b/tests/integration/api_repo_teams_test.go @@ -28,7 +28,7 @@ func TestAPIRepoTeams(t *testing.T) { // user4 user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) // ListTeams url := fmt.Sprintf("/api/v1/repos/%s/teams?token=%s", publicOrgRepo.FullName(), token) @@ -68,7 +68,7 @@ func TestAPIRepoTeams(t *testing.T) { // AddTeam with user2 user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session = loginUser(t, user.Name) - token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token = getTokenForLoggedInUser(t, session) url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "team1", token) req = NewRequest(t, "PUT", url) session.MakeRequest(t, req, http.StatusNoContent) diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index 708f9f948b8be..bfe0c0aa9c58e 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -190,7 +190,7 @@ func TestAPISearchRepo(t *testing.T) { if userToLogin != nil && userToLogin.ID > 0 { testName = fmt.Sprintf("LoggedUser%d", userToLogin.ID) session = loginUser(t, userToLogin.Name) - token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token = getTokenForLoggedInUser(t, session) userID = userToLogin.ID } else { testName = "AnonymousUser" @@ -300,7 +300,7 @@ func TestAPIOrgRepos(t *testing.T) { if userToLogin != nil && userToLogin.ID > 0 { testName = fmt.Sprintf("LoggedUser%d", userToLogin.ID) session = loginUser(t, userToLogin.Name) - token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token = getTokenForLoggedInUser(t, session) } else { testName = "AnonymousUser" session = emptyTestSession(t) @@ -325,7 +325,7 @@ func TestAPIGetRepoByIDUnauthorized(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/repositories/2?token="+token) session.MakeRequest(t, req, http.StatusNotFound) } @@ -349,7 +349,7 @@ func TestAPIRepoMigrate(t *testing.T) { for _, testCase := range testCases { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+token, &api.MigrateRepoOptions{ CloneAddr: testCase.cloneURL, RepoOwnerID: testCase.userID, @@ -414,7 +414,7 @@ func TestAPIMirrorSyncNonMirrorRepo(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) var repo api.Repository req := NewRequest(t, "GET", "/api/v1/repos/user2/repo1") @@ -446,7 +446,7 @@ func TestAPIOrgRepoCreate(t *testing.T) { for _, testCase := range testCases { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "admin_org") + token := getTokenForLoggedInUser(t, session) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/org/%s/repos?token="+token, testCase.orgName), &api.CreateRepoOption{ Name: testCase.repoName, }) @@ -510,7 +510,7 @@ func TestAPIRepoTransfer(t *testing.T) { // create repo to move user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) repoName := "moveME" apiRepo := new(api.Repository) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/user/repos?token=%s", token), &api.CreateRepoOption{ @@ -528,7 +528,7 @@ func TestAPIRepoTransfer(t *testing.T) { user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}) session = loginUser(t, user.Name) - token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token = getTokenForLoggedInUser(t, session) req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer?token=%s", repo.OwnerName, repo.Name, token), &api.TransferRepoOption{ NewOwner: testCase.newOwner, TeamIDs: testCase.teams, @@ -545,7 +545,7 @@ func transfer(t *testing.T) *repo_model.Repository { // create repo to move user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) repoName := "moveME" apiRepo := new(api.Repository) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/user/repos?token=%s", token), &api.CreateRepoOption{ @@ -575,7 +575,7 @@ func TestAPIAcceptTransfer(t *testing.T) { // try to accept with not authorized user session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) session.MakeRequest(t, req, http.StatusForbidden) @@ -585,7 +585,7 @@ func TestAPIAcceptTransfer(t *testing.T) { // accept transfer session = loginUser(t, "user4") - token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token = getTokenForLoggedInUser(t, session) req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/accept?token=%s", repo.OwnerName, repo.Name, token)) resp := session.MakeRequest(t, req, http.StatusAccepted) @@ -601,7 +601,7 @@ func TestAPIRejectTransfer(t *testing.T) { // try to reject with not authorized user session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) session.MakeRequest(t, req, http.StatusForbidden) @@ -611,7 +611,7 @@ func TestAPIRejectTransfer(t *testing.T) { // reject transfer session = loginUser(t, "user4") - token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token = getTokenForLoggedInUser(t, session) req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) resp := session.MakeRequest(t, req, http.StatusOK) @@ -625,7 +625,7 @@ func TestAPIGenerateRepo(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) templateRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 44}) @@ -661,7 +661,7 @@ func TestAPIRepoGetReviewers(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/reviewers?token=%s", user.Name, repo.Name, token) @@ -675,7 +675,7 @@ func TestAPIRepoGetAssignees(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/assignees?token=%s", user.Name, repo.Name, token) diff --git a/tests/integration/api_team_test.go b/tests/integration/api_team_test.go index ca10202862ffc..a667949c096f9 100644 --- a/tests/integration/api_team_test.go +++ b/tests/integration/api_team_test.go @@ -30,7 +30,7 @@ func TestAPITeam(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: teamUser.UID}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamUser.TeamID) resp := session.MakeRequest(t, req, http.StatusOK) @@ -44,7 +44,7 @@ func TestAPITeam(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: teamUser2.UID}) session = loginUser(t, user2.Name) - token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token = getTokenForLoggedInUser(t, session) req = NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamUser.TeamID) _ = session.MakeRequest(t, req, http.StatusForbidden) @@ -54,7 +54,7 @@ func TestAPITeam(t *testing.T) { // Get an admin user able to create, update and delete teams. user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session = loginUser(t, user.Name) - token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token = getTokenForLoggedInUser(t, session) org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 6}) diff --git a/tests/integration/api_team_user_test.go b/tests/integration/api_team_user_test.go index 859c5935ad527..b999b97a2b6f8 100644 --- a/tests/integration/api_team_user_test.go +++ b/tests/integration/api_team_user_test.go @@ -23,7 +23,7 @@ func TestAPITeamUser(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequest(t, "GET", "/api/v1/teams/1/members/user1?token="+token) session.MakeRequest(t, req, http.StatusNotFound) diff --git a/tests/integration/api_user_email_test.go b/tests/integration/api_user_email_test.go index 5f59ae907f658..7bd265187ca0f 100644 --- a/tests/integration/api_user_email_test.go +++ b/tests/integration/api_user_email_test.go @@ -19,7 +19,7 @@ func TestAPIListEmails(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequest(t, "GET", "/api/v1/user/emails?token="+token) resp := session.MakeRequest(t, req, http.StatusOK) @@ -46,7 +46,7 @@ func TestAPIAddEmail(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) opts := api.CreateEmailOption{ Emails: []string{"user101@example.com"}, @@ -83,7 +83,7 @@ func TestAPIDeleteEmail(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) opts := api.DeleteEmailOption{ Emails: []string{"user2-3@example.com"}, diff --git a/tests/integration/api_user_org_perm_test.go b/tests/integration/api_user_org_perm_test.go index 5c4aee854ca52..fef653545c5f6 100644 --- a/tests/integration/api_user_org_perm_test.go +++ b/tests/integration/api_user_org_perm_test.go @@ -34,7 +34,7 @@ func sampleTest(t *testing.T, auoptc apiUserOrgPermTestCase) { defer tests.PrepareTestEnv(t)() session := loginUser(t, auoptc.LoginUser) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/orgs/%s/permissions?token=%s", auoptc.User, auoptc.Organization, token)) resp := session.MakeRequest(t, req, http.StatusOK) @@ -127,7 +127,7 @@ func TestUnknowUser(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/unknow/orgs/org25/permissions?token=%s", token)) resp := session.MakeRequest(t, req, http.StatusNotFound) @@ -141,7 +141,7 @@ func TestUnknowOrganization(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/user1/orgs/unknow/permissions?token=%s", token)) resp := session.MakeRequest(t, req, http.StatusNotFound) diff --git a/tests/integration/api_user_orgs_test.go b/tests/integration/api_user_orgs_test.go index 0412fba67dd8d..c28bf391eb3af 100644 --- a/tests/integration/api_user_orgs_test.go +++ b/tests/integration/api_user_orgs_test.go @@ -72,7 +72,7 @@ func getUserOrgs(t *testing.T, userDoer, userCheck string) (orgs []*api.Organiza session := emptyTestSession(t) if len(userDoer) != 0 { session = loginUser(t, userDoer) - token = getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token = getTokenForLoggedInUser(t, session) } urlStr := fmt.Sprintf("/api/v1/users/%s/orgs?token=%s", userCheck, token) req := NewRequest(t, "GET", urlStr) @@ -90,7 +90,7 @@ func TestMyOrgs(t *testing.T) { normalUsername := "user2" session = loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req = NewRequest(t, "GET", "/api/v1/user/orgs?token="+token) resp := session.MakeRequest(t, req, http.StatusOK) var orgs []*api.Organization diff --git a/tests/integration/api_user_search_test.go b/tests/integration/api_user_search_test.go index 18a98eec6a4c1..9e9276077b40d 100644 --- a/tests/integration/api_user_search_test.go +++ b/tests/integration/api_user_search_test.go @@ -27,7 +27,7 @@ func TestAPIUserSearchLoggedIn(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) query := "user2" req := NewRequestf(t, "GET", "/api/v1/users/search?token=%s&q=%s", token, query) resp := session.MakeRequest(t, req, http.StatusOK) @@ -66,7 +66,7 @@ func TestAPIUserSearchAdminLoggedInUserHidden(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) query := "user31" req := NewRequestf(t, "GET", "/api/v1/users/search?token=%s&q=%s", token, query) req.SetBasicAuth(token, "x-oauth-basic") diff --git a/tests/integration/api_wiki_test.go b/tests/integration/api_wiki_test.go index 1d6d987f9b9bc..c6f4841d082ef 100644 --- a/tests/integration/api_wiki_test.go +++ b/tests/integration/api_wiki_test.go @@ -182,7 +182,7 @@ func TestAPINewWikiPage(t *testing.T) { defer tests.PrepareTestEnv(t)() username := "user2" session := loginUser(t, username) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/new?token=%s", username, "repo1", token) @@ -199,7 +199,7 @@ func TestAPIEditWikiPage(t *testing.T) { defer tests.PrepareTestEnv(t)() username := "user2" session := loginUser(t, username) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/page/Page-With-Spaced-Name?token=%s", username, "repo1", token) diff --git a/tests/integration/dump_restore_test.go b/tests/integration/dump_restore_test.go index 11cb16b71a11a..19513d0271e17 100644 --- a/tests/integration/dump_restore_test.go +++ b/tests/integration/dump_restore_test.go @@ -51,7 +51,7 @@ func TestDumpRestore(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) // // Phase 1: dump repo1 from the Gitea instance to the filesystem diff --git a/tests/integration/eventsource_test.go b/tests/integration/eventsource_test.go index 62611b157c456..cd496e01292bb 100644 --- a/tests/integration/eventsource_test.go +++ b/tests/integration/eventsource_test.go @@ -59,7 +59,7 @@ func TestEventSourceManagerRun(t *testing.T) { thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) assert.NoError(t, thread5.LoadAttributes()) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) var apiNL []api.NotificationThread diff --git a/tests/integration/integration_test.go b/tests/integration/integration_test.go index 23ae7adb427ec..416cc126bda74 100644 --- a/tests/integration/integration_test.go +++ b/tests/integration/integration_test.go @@ -219,8 +219,8 @@ func emptyTestSession(t testing.TB) *TestSession { return &TestSession{jar: jar} } -func getUserToken(t testing.TB, userName string, scope ...string) string { - return getTokenForLoggedInUser(t, loginUser(t, userName), scope...) +func getUserToken(t testing.TB, userName string) string { + return getTokenForLoggedInUser(t, loginUser(t, userName)) } func loginUser(t testing.TB, userName string) *TestSession { @@ -262,15 +262,12 @@ func loginUserWithPassword(t testing.TB, userName, password string) *TestSession // token has to be unique this counter take care of var tokenCounter int64 -// getTokenForLoggedInUser returns a token for a logged in user. -// The scope is an optional list of snake_case strings like the frontend form fields, -// but without the "scope_" prefix. -func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...string) string { +func getTokenForLoggedInUser(t testing.TB, session *TestSession) string { t.Helper() req := NewRequest(t, "GET", "/user/settings/applications") resp := session.MakeRequest(t, req, http.StatusOK) doc := NewHTMLParser(t, resp.Body) - values := map[string]string{ + req = NewRequestWithValues(t, "POST", "/user/settings/applications", map[string]string{ "_csrf": doc.GetCSRF(), "name": fmt.Sprintf("api-testing-token-%d", atomic.AddInt64(&tokenCounter, 1)), }) diff --git a/tests/integration/migrate_test.go b/tests/integration/migrate_test.go index 5b01a9eaca067..99d5d6c8dd239 100644 --- a/tests/integration/migrate_test.go +++ b/tests/integration/migrate_test.go @@ -67,7 +67,7 @@ func TestMigrateGiteaForm(t *testing.T) { repoName := "repo1" repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: ownerName}) session := loginUser(t, ownerName) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) // Step 0: verify the repo is available req := NewRequestf(t, "GET", fmt.Sprintf("/%s/%s", ownerName, repoName)) diff --git a/tests/integration/privateactivity_test.go b/tests/integration/privateactivity_test.go index 74c62e84c68de..3f352e49c6187 100644 --- a/tests/integration/privateactivity_test.go +++ b/tests/integration/privateactivity_test.go @@ -34,7 +34,7 @@ func testPrivateActivityDoSomethingForActionEntries(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}) session := loginUser(t, privateActivityTestUser) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all&token=%s", owner.Name, repoBefore.Name, token) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateIssueOption{ Body: "test", @@ -125,7 +125,7 @@ func testPrivateActivityHelperHasHeatmapContentFromPublic(t *testing.T) bool { } func testPrivateActivityHelperHasHeatmapContentFromSession(t *testing.T, session *TestSession) bool { - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/users/%s/heatmap?token=%s", privateActivityTestUser, token) resp := session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/pull_merge_test.go b/tests/integration/pull_merge_test.go index dd062604ae894..9bd430084dcc8 100644 --- a/tests/integration/pull_merge_test.go +++ b/tests/integration/pull_merge_test.go @@ -218,7 +218,7 @@ func TestCantMergeConflict(t *testing.T) { testEditFileToNewBranch(t, session, "user1", "repo1", "master", "base", "README.md", "Hello, World (Edited Twice)\n") // Use API to create a conflicting pr - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", "user1", "repo1", token), &api.CreatePullRequestOption{ Head: "conflict", Base: "base", @@ -326,7 +326,7 @@ func TestCantMergeUnrelated(t *testing.T) { testEditFileToNewBranch(t, session, "user1", "repo1", "master", "conflict", "README.md", "Hello, World (Edited Once)\n") // Use API to create a conflicting pr - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", "user1", "repo1", token), &api.CreatePullRequestOption{ Head: "unrelated", Base: "base", diff --git a/tests/integration/pull_update_test.go b/tests/integration/pull_update_test.go index ff9d2bbe9ebe6..c08faaaeb6f4e 100644 --- a/tests/integration/pull_update_test.go +++ b/tests/integration/pull_update_test.go @@ -39,7 +39,7 @@ func TestAPIPullUpdate(t *testing.T) { assert.NoError(t, pr.LoadIssue()) session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index) session.MakeRequest(t, req, http.StatusOK) @@ -67,7 +67,7 @@ func TestAPIPullUpdateByRebase(t *testing.T) { assert.NoError(t, pr.LoadIssue()) session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase&token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index) session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/user_test.go b/tests/integration/user_test.go index 8b0520fcca59e..110f5c89bfbd3 100644 --- a/tests/integration/user_test.go +++ b/tests/integration/user_test.go @@ -152,7 +152,7 @@ Note: This user hasn't uploaded any GPG keys. // Import key // User1 session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "repo", "admin_org", "admin_public_key", "admin_repo_hook", "admin_org_hook", "notification", "user", "delete_repo", "package", "admin_gpg_key") + token := getTokenForLoggedInUser(t, session) testCreateGPGKey(t, session.MakeRequest, token, http.StatusCreated, `-----BEGIN PGP PUBLIC KEY BLOCK----- mQENBFyy/VUBCADJ7zbM20Z1RWmFoVgp5WkQfI2rU1Vj9cQHes9i42wVLLtcbPeo From fafc36d7ff371d3afff7b30e5bd9a1076cb0b20d Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 29 Oct 2022 03:06:06 -0400 Subject: [PATCH 023/118] Support specifying scope in reqToken --- routers/api/v1/api.go | 214 ++++++++++++++++++++++-------------------- 1 file changed, 114 insertions(+), 100 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 0d11674aa9971..b86db484b1db4 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -71,6 +71,7 @@ import ( "reflect" "strings" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/perm" access_model "code.gitea.io/gitea/models/perm/access" @@ -208,9 +209,22 @@ func reqPackageAccess(accessMode perm.AccessMode) func(ctx *context.APIContext) } // Contexter middleware already checks token for user sign in process. -func reqToken() func(ctx *context.APIContext) { +func reqToken(requiredScope string) func(ctx *context.APIContext) { return func(ctx *context.APIContext) { if true == ctx.Data["IsApiToken"] { + if requiredScope == "" { + return + } + scope := ctx.Data["ApiTokenScope"].(auth_model.AccessTokenScope) + allow, err := scope.HasScope(requiredScope) + if err != nil { + ctx.Error(http.StatusUnauthorized, "reqToken", "parsing token failed") + return + } + if !allow { + ctx.Error(http.StatusUnauthorized, "reqToken", "token does not have required scope: "+requiredScope) + return + } return } if ctx.Context.IsBasicAuth { @@ -671,7 +685,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Combo("/threads/{id}"). Get(notify.GetThread). Patch(notify.ReadThread) - }, reqToken()) + }, reqToken("")) // Users m.Group("/users", func() { @@ -708,14 +722,14 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/subscriptions", user.GetWatchedRepos) }, context_service.UserAssignmentAPI()) - }, reqToken()) + }, reqToken("")) m.Group("/user", func() { m.Get("", user.GetAuthenticatedUser) m.Group("/settings", func() { m.Get("", user.GetUserSettings) m.Patch("", bind(api.UserSettingsOptions{}), user.UpdateUserSettings) - }, reqToken()) + }, reqToken("")) m.Combo("/emails").Get(user.ListEmails). Post(bind(api.CreateEmailOption{}), user.AddEmail). Delete(bind(api.DeleteEmailOption{}), user.DeleteEmail) @@ -744,7 +758,7 @@ func Routes(ctx gocontext.Context) *web.Route { Delete(user.DeleteOauth2Application). Patch(bind(api.CreateOAuth2ApplicationOptions{}), user.UpdateOauth2Application). Get(user.GetOauth2Application) - }, reqToken()) + }, reqToken("")) m.Group("/gpg_keys", func() { m.Combo("").Get(user.ListMyGPGKeys). @@ -774,31 +788,31 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/subscriptions", user.GetMyWatchedRepos) m.Get("/teams", org.ListUserTeams) - }, reqToken()) + }, reqToken("")) // Repositories - m.Post("/org/{org}/repos", reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepoDeprecated) + m.Post("/org/{org}/repos", reqToken(""), bind(api.CreateRepoOption{}), repo.CreateOrgRepoDeprecated) - m.Combo("/repositories/{id}", reqToken()).Get(repo.GetByID) + m.Combo("/repositories/{id}", reqToken("")).Get(repo.GetByID) m.Group("/repos", func() { m.Get("/search", repo.Search) m.Get("/issues/search", repo.SearchIssues) - m.Post("/migrate", reqToken(), bind(api.MigrateRepoOptions{}), repo.Migrate) + m.Post("/migrate", reqToken(""), bind(api.MigrateRepoOptions{}), repo.Migrate) m.Group("/{username}/{reponame}", func() { m.Combo("").Get(reqAnyRepoReader(), repo.Get). - Delete(reqToken(), reqOwner(), repo.Delete). - Patch(reqToken(), reqAdmin(), bind(api.EditRepoOption{}), repo.Edit) - m.Post("/generate", reqToken(), reqRepoReader(unit.TypeCode), bind(api.GenerateRepoOption{}), repo.Generate) + Delete(reqToken(""), reqOwner(), repo.Delete). + Patch(reqToken(""), reqAdmin(), bind(api.EditRepoOption{}), repo.Edit) + m.Post("/generate", reqToken(""), reqRepoReader(unit.TypeCode), bind(api.GenerateRepoOption{}), repo.Generate) m.Post("/transfer", reqOwner(), bind(api.TransferRepoOption{}), repo.Transfer) - m.Post("/transfer/accept", reqToken(), repo.AcceptTransfer) - m.Post("/transfer/reject", reqToken(), repo.RejectTransfer) + m.Post("/transfer/accept", reqToken(""), repo.AcceptTransfer) + m.Post("/transfer/reject", reqToken(""), repo.RejectTransfer) m.Combo("/notifications"). - Get(reqToken(), notify.ListRepoNotifications). - Put(reqToken(), notify.ReadRepoNotifications) + Get(reqToken(""), notify.ListRepoNotifications). + Put(reqToken(""), notify.ReadRepoNotifications) m.Group("/hooks/git", func() { m.Combo("").Get(repo.ListGitHooks) m.Group("/{id}", func() { @@ -806,7 +820,7 @@ func Routes(ctx gocontext.Context) *web.Route { Patch(bind(api.EditGitHookOption{}), repo.EditGitHook). Delete(repo.DeleteGitHook) }) - }, reqToken(), reqAdmin(), reqGitHook(), context.ReferencesGitRepo(true)) + }, reqToken(""), reqAdmin(), reqGitHook(), context.ReferencesGitRepo(true)) m.Group("/hooks", func() { m.Combo("").Get(repo.ListHooks). Post(bind(api.CreateHookOption{}), repo.CreateHook) @@ -816,7 +830,7 @@ func Routes(ctx gocontext.Context) *web.Route { Delete(repo.DeleteHook) m.Post("/tests", context.ReferencesGitRepo(), context.RepoRefForAPI, repo.TestHook) }) - }, reqToken(), reqAdmin(), reqWebhooksEnabled()) + }, reqToken(""), reqAdmin(), reqWebhooksEnabled()) m.Group("/collaborators", func() { m.Get("", reqAnyRepoReader(), repo.ListCollaborators) m.Group("/{collaborator}", func() { @@ -824,21 +838,21 @@ func Routes(ctx gocontext.Context) *web.Route { Put(reqAdmin(), bind(api.AddCollaboratorOption{}), repo.AddCollaborator). Delete(reqAdmin(), repo.DeleteCollaborator) m.Get("/permission", repo.GetRepoPermissions) - }, reqToken()) - }, reqToken()) - m.Get("/assignees", reqToken(), reqAnyRepoReader(), repo.GetAssignees) - m.Get("/reviewers", reqToken(), reqAnyRepoReader(), repo.GetReviewers) + }, reqToken("")) + }, reqToken("")) + m.Get("/assignees", reqToken(""), reqAnyRepoReader(), repo.GetAssignees) + m.Get("/reviewers", reqToken(""), reqAnyRepoReader(), repo.GetReviewers) m.Group("/teams", func() { m.Get("", reqAnyRepoReader(), repo.ListTeams) m.Combo("/{team}").Get(reqAnyRepoReader(), repo.IsTeam). Put(reqAdmin(), repo.AddTeam). Delete(reqAdmin(), repo.DeleteTeam) - }, reqToken()) + }, reqToken("")) m.Get("/raw/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFile) m.Get("/media/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFileOrLFS) m.Get("/archive/*", reqRepoReader(unit.TypeCode), repo.GetArchive) m.Combo("/forks").Get(repo.ListForks). - Post(reqToken(), reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork) + Post(reqToken(""), reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork) m.Group("/branches", func() { m.Get("", repo.ListBranches) m.Get("/*", repo.GetBranch) @@ -853,7 +867,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Patch("", bind(api.EditBranchProtectionOption{}), repo.EditBranchProtection) m.Delete("", repo.DeleteBranchProtection) }) - }, reqToken(), reqAdmin()) + }, reqToken(""), reqAdmin()) m.Group("/tags", func() { m.Get("", repo.ListTags) m.Get("/*", repo.GetTag) @@ -865,11 +879,11 @@ func Routes(ctx gocontext.Context) *web.Route { Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey) m.Combo("/{id}").Get(repo.GetDeployKey). Delete(repo.DeleteDeploykey) - }, reqToken(), reqAdmin()) + }, reqToken(""), reqAdmin()) m.Group("/times", func() { m.Combo("").Get(repo.ListTrackedTimesByRepository) m.Combo("/{timetrackingusername}").Get(repo.ListTrackedTimesByUser) - }, mustEnableIssues, reqToken()) + }, mustEnableIssues, reqToken("")) m.Group("/wiki", func() { m.Combo("/page/{pageName}"). Get(repo.GetWikiPage). @@ -881,37 +895,37 @@ func Routes(ctx gocontext.Context) *web.Route { }, mustEnableWiki) m.Group("/issues", func() { m.Combo("").Get(repo.ListIssues). - Post(reqToken(), mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue) + Post(reqToken(""), mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue) m.Group("/comments", func() { m.Get("", repo.ListRepoIssueComments) m.Group("/{id}", func() { m.Combo(""). Get(repo.GetIssueComment). - Patch(mustNotBeArchived, reqToken(), bind(api.EditIssueCommentOption{}), repo.EditIssueComment). - Delete(reqToken(), repo.DeleteIssueComment) + Patch(mustNotBeArchived, reqToken(""), bind(api.EditIssueCommentOption{}), repo.EditIssueComment). + Delete(reqToken(""), repo.DeleteIssueComment) m.Combo("/reactions"). Get(repo.GetIssueCommentReactions). - Post(reqToken(), bind(api.EditReactionOption{}), repo.PostIssueCommentReaction). - Delete(reqToken(), bind(api.EditReactionOption{}), repo.DeleteIssueCommentReaction) + Post(reqToken(""), bind(api.EditReactionOption{}), repo.PostIssueCommentReaction). + Delete(reqToken(""), bind(api.EditReactionOption{}), repo.DeleteIssueCommentReaction) }) }) m.Group("/{index}", func() { m.Combo("").Get(repo.GetIssue). - Patch(reqToken(), bind(api.EditIssueOption{}), repo.EditIssue). - Delete(reqToken(), reqAdmin(), repo.DeleteIssue) + Patch(reqToken(""), bind(api.EditIssueOption{}), repo.EditIssue). + Delete(reqToken(""), reqAdmin(), repo.DeleteIssue) m.Group("/comments", func() { m.Combo("").Get(repo.ListIssueComments). - Post(reqToken(), mustNotBeArchived, bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment) - m.Combo("/{id}", reqToken()).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueCommentDeprecated). + Post(reqToken(""), mustNotBeArchived, bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment) + m.Combo("/{id}", reqToken("")).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueCommentDeprecated). Delete(repo.DeleteIssueCommentDeprecated) }) m.Get("/timeline", repo.ListIssueCommentsAndTimeline) m.Group("/labels", func() { m.Combo("").Get(repo.ListIssueLabels). - Post(reqToken(), bind(api.IssueLabelsOption{}), repo.AddIssueLabels). - Put(reqToken(), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels). - Delete(reqToken(), repo.ClearIssueLabels) - m.Delete("/{id}", reqToken(), repo.DeleteIssueLabel) + Post(reqToken(""), bind(api.IssueLabelsOption{}), repo.AddIssueLabels). + Put(reqToken(""), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels). + Delete(reqToken(""), repo.ClearIssueLabels) + m.Delete("/{id}", reqToken(""), repo.DeleteIssueLabel) }) m.Group("/times", func() { m.Combo(""). @@ -919,70 +933,70 @@ func Routes(ctx gocontext.Context) *web.Route { Post(bind(api.AddTimeOption{}), repo.AddTime). Delete(repo.ResetIssueTime) m.Delete("/{id}", repo.DeleteTime) - }, reqToken()) - m.Combo("/deadline").Post(reqToken(), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline) + }, reqToken("")) + m.Combo("/deadline").Post(reqToken(""), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline) m.Group("/stopwatch", func() { - m.Post("/start", reqToken(), repo.StartIssueStopwatch) - m.Post("/stop", reqToken(), repo.StopIssueStopwatch) - m.Delete("/delete", reqToken(), repo.DeleteIssueStopwatch) + m.Post("/start", reqToken(""), repo.StartIssueStopwatch) + m.Post("/stop", reqToken(""), repo.StopIssueStopwatch) + m.Delete("/delete", reqToken(""), repo.DeleteIssueStopwatch) }) m.Group("/subscriptions", func() { m.Get("", repo.GetIssueSubscribers) - m.Get("/check", reqToken(), repo.CheckIssueSubscription) - m.Put("/{user}", reqToken(), repo.AddIssueSubscription) - m.Delete("/{user}", reqToken(), repo.DelIssueSubscription) + m.Get("/check", reqToken(""), repo.CheckIssueSubscription) + m.Put("/{user}", reqToken(""), repo.AddIssueSubscription) + m.Delete("/{user}", reqToken(""), repo.DelIssueSubscription) }) m.Combo("/reactions"). Get(repo.GetIssueReactions). - Post(reqToken(), bind(api.EditReactionOption{}), repo.PostIssueReaction). - Delete(reqToken(), bind(api.EditReactionOption{}), repo.DeleteIssueReaction) + Post(reqToken(""), bind(api.EditReactionOption{}), repo.PostIssueReaction). + Delete(reqToken(""), bind(api.EditReactionOption{}), repo.DeleteIssueReaction) }) }, mustEnableIssuesOrPulls) m.Group("/labels", func() { m.Combo("").Get(repo.ListLabels). - Post(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateLabelOption{}), repo.CreateLabel) + Post(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateLabelOption{}), repo.CreateLabel) m.Combo("/{id}").Get(repo.GetLabel). - Patch(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditLabelOption{}), repo.EditLabel). - Delete(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteLabel) + Patch(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditLabelOption{}), repo.EditLabel). + Delete(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteLabel) }) m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown) m.Post("/markdown/raw", misc.MarkdownRaw) m.Group("/milestones", func() { m.Combo("").Get(repo.ListMilestones). - Post(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateMilestoneOption{}), repo.CreateMilestone) + Post(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateMilestoneOption{}), repo.CreateMilestone) m.Combo("/{id}").Get(repo.GetMilestone). - Patch(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditMilestoneOption{}), repo.EditMilestone). - Delete(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteMilestone) + Patch(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditMilestoneOption{}), repo.EditMilestone). + Delete(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteMilestone) }) m.Get("/stargazers", repo.ListStargazers) m.Get("/subscribers", repo.ListSubscribers) m.Group("/subscription", func() { m.Get("", user.IsWatching) - m.Put("", reqToken(), user.Watch) - m.Delete("", reqToken(), user.Unwatch) + m.Put("", reqToken(""), user.Watch) + m.Delete("", reqToken(""), user.Unwatch) }) m.Group("/releases", func() { m.Combo("").Get(repo.ListReleases). - Post(reqToken(), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.CreateReleaseOption{}), repo.CreateRelease) + Post(reqToken(""), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.CreateReleaseOption{}), repo.CreateRelease) m.Group("/{id}", func() { m.Combo("").Get(repo.GetRelease). - Patch(reqToken(), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.EditReleaseOption{}), repo.EditRelease). - Delete(reqToken(), reqRepoWriter(unit.TypeReleases), repo.DeleteRelease) + Patch(reqToken(""), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.EditReleaseOption{}), repo.EditRelease). + Delete(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.DeleteRelease) m.Group("/assets", func() { m.Combo("").Get(repo.ListReleaseAttachments). - Post(reqToken(), reqRepoWriter(unit.TypeReleases), repo.CreateReleaseAttachment) + Post(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.CreateReleaseAttachment) m.Combo("/{asset}").Get(repo.GetReleaseAttachment). - Patch(reqToken(), reqRepoWriter(unit.TypeReleases), bind(api.EditAttachmentOptions{}), repo.EditReleaseAttachment). - Delete(reqToken(), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseAttachment) + Patch(reqToken(""), reqRepoWriter(unit.TypeReleases), bind(api.EditAttachmentOptions{}), repo.EditReleaseAttachment). + Delete(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseAttachment) }) }) m.Group("/tags", func() { m.Combo("/{tag}"). Get(repo.GetReleaseByTag). - Delete(reqToken(), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseByTag) + Delete(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseByTag) }) }, reqRepoReader(unit.TypeReleases)) - m.Post("/mirror-sync", reqToken(), reqRepoWriter(unit.TypeCode), repo.MirrorSync) + m.Post("/mirror-sync", reqToken(""), reqRepoWriter(unit.TypeCode), repo.MirrorSync) m.Post("/push_mirrors-sync", reqAdmin(), repo.PushMirrorSync) m.Group("/push_mirrors", func() { m.Combo("").Get(repo.ListPushMirrors). @@ -995,40 +1009,40 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/editorconfig/{filename}", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetEditorconfig) m.Group("/pulls", func() { m.Combo("").Get(repo.ListPullRequests). - Post(reqToken(), mustNotBeArchived, bind(api.CreatePullRequestOption{}), repo.CreatePullRequest) + Post(reqToken(""), mustNotBeArchived, bind(api.CreatePullRequestOption{}), repo.CreatePullRequest) m.Group("/{index}", func() { m.Combo("").Get(repo.GetPullRequest). - Patch(reqToken(), bind(api.EditPullRequestOption{}), repo.EditPullRequest) + Patch(reqToken(""), bind(api.EditPullRequestOption{}), repo.EditPullRequest) m.Get(".{diffType:diff|patch}", repo.DownloadPullDiffOrPatch) - m.Post("/update", reqToken(), repo.UpdatePullRequest) + m.Post("/update", reqToken(""), repo.UpdatePullRequest) m.Get("/commits", repo.GetPullRequestCommits) m.Get("/files", repo.GetPullRequestFiles) m.Combo("/merge").Get(repo.IsPullRequestMerged). - Post(reqToken(), mustNotBeArchived, bind(forms.MergePullRequestForm{}), repo.MergePullRequest). - Delete(reqToken(), mustNotBeArchived, repo.CancelScheduledAutoMerge) + Post(reqToken(""), mustNotBeArchived, bind(forms.MergePullRequestForm{}), repo.MergePullRequest). + Delete(reqToken(""), mustNotBeArchived, repo.CancelScheduledAutoMerge) m.Group("/reviews", func() { m.Combo(""). Get(repo.ListPullReviews). - Post(reqToken(), bind(api.CreatePullReviewOptions{}), repo.CreatePullReview) + Post(reqToken(""), bind(api.CreatePullReviewOptions{}), repo.CreatePullReview) m.Group("/{id}", func() { m.Combo(""). Get(repo.GetPullReview). - Delete(reqToken(), repo.DeletePullReview). - Post(reqToken(), bind(api.SubmitPullReviewOptions{}), repo.SubmitPullReview) + Delete(reqToken(""), repo.DeletePullReview). + Post(reqToken(""), bind(api.SubmitPullReviewOptions{}), repo.SubmitPullReview) m.Combo("/comments"). Get(repo.GetPullReviewComments) - m.Post("/dismissals", reqToken(), bind(api.DismissPullReviewOptions{}), repo.DismissPullReview) - m.Post("/undismissals", reqToken(), repo.UnDismissPullReview) + m.Post("/dismissals", reqToken(""), bind(api.DismissPullReviewOptions{}), repo.DismissPullReview) + m.Post("/undismissals", reqToken(""), repo.UnDismissPullReview) }) }) m.Combo("/requested_reviewers"). - Delete(reqToken(), bind(api.PullReviewRequestOptions{}), repo.DeleteReviewRequests). - Post(reqToken(), bind(api.PullReviewRequestOptions{}), repo.CreateReviewRequests) + Delete(reqToken(""), bind(api.PullReviewRequestOptions{}), repo.DeleteReviewRequests). + Post(reqToken(""), bind(api.PullReviewRequestOptions{}), repo.CreateReviewRequests) }) }, mustAllowPulls, reqRepoReader(unit.TypeCode), context.ReferencesGitRepo()) m.Group("/statuses", func() { m.Combo("/{sha}").Get(repo.GetCommitStatuses). - Post(reqToken(), reqRepoWriter(unit.TypeCode), bind(api.CreateStatusOption{}), repo.NewCommitStatus) + Post(reqToken(""), reqRepoWriter(unit.TypeCode), bind(api.CreateStatusOption{}), repo.NewCommitStatus) }, reqRepoReader(unit.TypeCode)) m.Group("/commits", func() { m.Get("", context.ReferencesGitRepo(), repo.GetAllCommits) @@ -1049,7 +1063,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/tags/{sha}", repo.GetAnnotatedTag) m.Get("/notes/{sha}", repo.GetNote) }, context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode)) - m.Post("/diffpatch", reqRepoWriter(unit.TypeCode), reqToken(), bind(api.ApplyDiffPatchFileOptions{}), repo.ApplyDiffPatch) + m.Post("/diffpatch", reqRepoWriter(unit.TypeCode), reqToken(""), bind(api.ApplyDiffPatchFileOptions{}), repo.ApplyDiffPatch) m.Group("/contents", func() { m.Get("", repo.GetContentsList) m.Get("/*", repo.GetContents) @@ -1057,15 +1071,15 @@ func Routes(ctx gocontext.Context) *web.Route { m.Post("", bind(api.CreateFileOptions{}), reqRepoBranchWriter, repo.CreateFile) m.Put("", bind(api.UpdateFileOptions{}), reqRepoBranchWriter, repo.UpdateFile) m.Delete("", bind(api.DeleteFileOptions{}), reqRepoBranchWriter, repo.DeleteFile) - }, reqToken()) + }, reqToken("")) }, reqRepoReader(unit.TypeCode)) m.Get("/signing-key.gpg", misc.SigningKey) m.Group("/topics", func() { m.Combo("").Get(repo.ListTopics). - Put(reqToken(), reqAdmin(), bind(api.RepoTopicOptions{}), repo.UpdateTopics) + Put(reqToken(""), reqAdmin(), bind(api.RepoTopicOptions{}), repo.UpdateTopics) m.Group("/{topic}", func() { - m.Combo("").Put(reqToken(), repo.AddTopic). - Delete(reqToken(), repo.DeleteTopic) + m.Combo("").Put(reqToken(""), repo.AddTopic). + Delete(reqToken(""), repo.DeleteTopic) }, reqAdmin()) }, reqAnyRepoReader()) m.Get("/issue_templates", context.ReferencesGitRepo(), repo.GetIssueTemplates) @@ -1083,41 +1097,41 @@ func Routes(ctx gocontext.Context) *web.Route { }, context_service.UserAssignmentAPI(), context.PackageAssignmentAPI(), reqPackageAccess(perm.AccessModeRead)) // Organizations - m.Get("/user/orgs", reqToken(), org.ListMyOrgs) + m.Get("/user/orgs", reqToken(""), org.ListMyOrgs) m.Group("/users/{username}/orgs", func() { m.Get("", org.ListUserOrgs) - m.Get("/{org}/permissions", reqToken(), org.GetUserOrgsPermissions) + m.Get("/{org}/permissions", reqToken(""), org.GetUserOrgsPermissions) }, context_service.UserAssignmentAPI()) - m.Post("/orgs", reqToken(), bind(api.CreateOrgOption{}), org.Create) + m.Post("/orgs", reqToken(""), bind(api.CreateOrgOption{}), org.Create) m.Get("/orgs", org.GetAll) m.Group("/orgs/{org}", func() { m.Combo("").Get(org.Get). - Patch(reqToken(), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit). - Delete(reqToken(), reqOrgOwnership(), org.Delete) + Patch(reqToken(""), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit). + Delete(reqToken(""), reqOrgOwnership(), org.Delete) m.Combo("/repos").Get(user.ListOrgRepos). - Post(reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepo) + Post(reqToken(""), bind(api.CreateRepoOption{}), repo.CreateOrgRepo) m.Group("/members", func() { m.Get("", org.ListMembers) m.Combo("/{username}").Get(org.IsMember). - Delete(reqToken(), reqOrgOwnership(), org.DeleteMember) + Delete(reqToken(""), reqOrgOwnership(), org.DeleteMember) }) m.Group("/public_members", func() { m.Get("", org.ListPublicMembers) m.Combo("/{username}").Get(org.IsPublicMember). - Put(reqToken(), reqOrgMembership(), org.PublicizeMember). - Delete(reqToken(), reqOrgMembership(), org.ConcealMember) + Put(reqToken(""), reqOrgMembership(), org.PublicizeMember). + Delete(reqToken(""), reqOrgMembership(), org.ConcealMember) }) m.Group("/teams", func() { m.Get("", org.ListTeams) m.Post("", reqOrgOwnership(), bind(api.CreateTeamOption{}), org.CreateTeam) m.Get("/search", org.SearchTeam) - }, reqToken(), reqOrgMembership()) + }, reqToken(""), reqOrgMembership()) m.Group("/labels", func() { m.Get("", org.ListLabels) - m.Post("", reqToken(), reqOrgOwnership(), bind(api.CreateLabelOption{}), org.CreateLabel) + m.Post("", reqToken(""), reqOrgOwnership(), bind(api.CreateLabelOption{}), org.CreateLabel) m.Combo("/{id}").Get(org.GetLabel). - Patch(reqToken(), reqOrgOwnership(), bind(api.EditLabelOption{}), org.EditLabel). - Delete(reqToken(), reqOrgOwnership(), org.DeleteLabel) + Patch(reqToken(""), reqOrgOwnership(), bind(api.EditLabelOption{}), org.EditLabel). + Delete(reqToken(""), reqOrgOwnership(), org.DeleteLabel) }) m.Group("/hooks", func() { m.Combo("").Get(org.ListHooks). @@ -1125,7 +1139,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Combo("/{id}").Get(org.GetHook). Patch(bind(api.EditHookOption{}), org.EditHook). Delete(org.DeleteHook) - }, reqToken(), reqOrgOwnership(), reqWebhooksEnabled()) + }, reqToken(""), reqOrgOwnership(), reqWebhooksEnabled()) }, orgAssignment(true)) m.Group("/teams/{teamid}", func() { m.Combo("").Get(org.GetTeam). @@ -1145,7 +1159,7 @@ func Routes(ctx gocontext.Context) *web.Route { Delete(org.RemoveTeamRepository). Get(org.GetTeamRepo) }) - }, orgAssignment(false, true), reqToken(), reqTeamMembership()) + }, orgAssignment(false, true), reqToken(""), reqTeamMembership()) m.Group("/admin", func() { m.Group("/cron", func() { @@ -1173,7 +1187,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Post("/{username}/{reponame}", admin.AdoptRepository) m.Delete("/{username}/{reponame}", admin.DeleteUnadoptedRepository) }) - }, reqToken(), reqSiteAdmin()) + }, reqToken(""), reqSiteAdmin()) m.Group("/topics", func() { m.Get("/search", repo.TopicSearch) From 06e9c81b649011b46cedfd6fa26ff47608d53ab9 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 29 Oct 2022 03:36:19 -0400 Subject: [PATCH 024/118] Support getting scoped token in integration tests --- tests/integration/integration_test.go | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/tests/integration/integration_test.go b/tests/integration/integration_test.go index 416cc126bda74..7affd41e7b56d 100644 --- a/tests/integration/integration_test.go +++ b/tests/integration/integration_test.go @@ -18,7 +18,6 @@ import ( "os" "path/filepath" "strings" - "sync/atomic" "testing" "time" @@ -219,8 +218,8 @@ func emptyTestSession(t testing.TB) *TestSession { return &TestSession{jar: jar} } -func getUserToken(t testing.TB, userName string) string { - return getTokenForLoggedInUser(t, loginUser(t, userName)) +func getUserToken(t testing.TB, userName string, scope ...string) string { + return getTokenForLoggedInUser(t, loginUser(t, userName), scope...) } func loginUser(t testing.TB, userName string) *TestSession { @@ -262,15 +261,23 @@ func loginUserWithPassword(t testing.TB, userName, password string) *TestSession // token has to be unique this counter take care of var tokenCounter int64 -func getTokenForLoggedInUser(t testing.TB, session *TestSession) string { +// getTokenForLoggedInUser returns a token for a logged in user. +// The scope is an optional list of snake_case strings like the frontend form fields, +// but without the "scope_" prefix. +func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...string) string { t.Helper() + tokenCounter++ req := NewRequest(t, "GET", "/user/settings/applications") resp := session.MakeRequest(t, req, http.StatusOK) doc := NewHTMLParser(t, resp.Body) - req = NewRequestWithValues(t, "POST", "/user/settings/applications", map[string]string{ + values := map[string]string{ "_csrf": doc.GetCSRF(), - "name": fmt.Sprintf("api-testing-token-%d", atomic.AddInt64(&tokenCounter, 1)), - }) + "name": fmt.Sprintf("api-testing-token-%d", tokenCounter), + } + for _, scope := range scopes { + values[fmt.Sprintf("scope_%s", scope)] = "on" + } + req = NewRequestWithValues(t, "POST", "/user/settings/applications", values) session.MakeRequest(t, req, http.StatusSeeOther) req = NewRequest(t, "GET", "/user/settings/applications") resp = session.MakeRequest(t, req, http.StatusOK) From be5164b4f4f039a3038a3f9d42d582b1c3081ef6 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 29 Oct 2022 15:14:59 -0400 Subject: [PATCH 025/118] Restrict token scope for notifications --- routers/api/v1/api.go | 2 +- tests/integration/api_notification_test.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index b86db484b1db4..27b4e07d4e280 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -685,7 +685,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Combo("/threads/{id}"). Get(notify.GetThread). Patch(notify.ReadThread) - }, reqToken("")) + }, reqToken(auth_model.AccessTokenScopeNotification)) // Users m.Group("/users", func() { diff --git a/tests/integration/api_notification_test.go b/tests/integration/api_notification_test.go index bf85520bb53b7..75dd8a288c84a 100644 --- a/tests/integration/api_notification_test.go +++ b/tests/integration/api_notification_test.go @@ -27,7 +27,7 @@ func TestAPINotification(t *testing.T) { thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) assert.NoError(t, thread5.LoadAttributes()) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "notification") // -- GET /notifications -- // test filter @@ -145,7 +145,7 @@ func TestAPINotificationPUT(t *testing.T) { thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) assert.NoError(t, thread5.LoadAttributes()) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "notification") // Check notifications are as expected req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?all=true&token=%s", token)) From 9f7db16b7941b5c03178b8d56c3d57dbfa5452e1 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 29 Oct 2022 18:08:54 -0400 Subject: [PATCH 026/118] Add notification scope to TestEventSourceManagerRun --- tests/integration/eventsource_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/eventsource_test.go b/tests/integration/eventsource_test.go index cd496e01292bb..f43f48b33880f 100644 --- a/tests/integration/eventsource_test.go +++ b/tests/integration/eventsource_test.go @@ -59,7 +59,7 @@ func TestEventSourceManagerRun(t *testing.T) { thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) assert.NoError(t, thread5.LoadAttributes()) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "notification") var apiNL []api.NotificationThread From 4464289e5cf978100f5f7f456dfc1a11974e3694 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 29 Oct 2022 19:00:43 -0400 Subject: [PATCH 027/118] Add scope to 'user' api --- routers/api/v1/api.go | 67 ++++++++++--------- tests/integration/api_branch_test.go | 2 +- tests/integration/api_gpg_keys_test.go | 5 ++ .../api_helper_for_declarative_test.go | 4 +- tests/integration/api_httpsig_test.go | 2 +- tests/integration/api_issue_stopwatch_test.go | 2 +- tests/integration/api_keys_test.go | 4 +- .../integration/api_repo_file_create_test.go | 2 +- tests/integration/api_repo_file_get_test.go | 2 +- tests/integration/api_repo_lfs_test.go | 2 +- tests/integration/api_repo_test.go | 4 +- tests/integration/api_user_email_test.go | 6 +- tests/integration/api_user_follow_test.go | 2 +- tests/integration/api_user_star_test.go | 11 +-- tests/integration/api_user_watch_test.go | 3 +- tests/integration/git_test.go | 2 +- tests/integration/gpg_git_test.go | 10 +-- tests/integration/ssh_key_test.go | 4 +- 18 files changed, 72 insertions(+), 62 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 27b4e07d4e280..aab66c767a3cd 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -650,7 +650,7 @@ func Routes(ctx gocontext.Context) *web.Route { })) m.Group("", func() { - // Miscellaneous + // Miscellaneous (no scope required) if setting.API.EnableSwagger { m.Get("/swagger", func(ctx *context.APIContext) { ctx.Redirect(setting.AppSubURL + "/api/swagger") @@ -676,7 +676,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/repository", settings.GetGeneralRepoSettings) }) - // Notifications + // Notifications (requires 'notification' scope) m.Group("/notifications", func() { m.Combo(""). Get(notify.ListNotifications). @@ -687,7 +687,7 @@ func Routes(ctx gocontext.Context) *web.Route { Patch(notify.ReadThread) }, reqToken(auth_model.AccessTokenScopeNotification)) - // Users + // Users (no scope required) m.Group("/users", func() { m.Get("/search", reqExploreSignIn(), user.Search) @@ -707,6 +707,7 @@ func Routes(ctx gocontext.Context) *web.Route { }, context_service.UserAssignmentAPI()) }) + // (no scope required) m.Group("/users", func() { m.Group("/{username}", func() { m.Get("/keys", user.ListPublicKeys) @@ -727,29 +728,32 @@ func Routes(ctx gocontext.Context) *web.Route { m.Group("/user", func() { m.Get("", user.GetAuthenticatedUser) m.Group("/settings", func() { - m.Get("", user.GetUserSettings) - m.Patch("", bind(api.UserSettingsOptions{}), user.UpdateUserSettings) - }, reqToken("")) - m.Combo("/emails").Get(user.ListEmails). - Post(bind(api.CreateEmailOption{}), user.AddEmail). - Delete(bind(api.DeleteEmailOption{}), user.DeleteEmail) + m.Get("", reqToken(auth_model.AccessTokenScopeReadUser), user.GetUserSettings) + m.Patch("", reqToken(auth_model.AccessTokenScopeUser), bind(api.UserSettingsOptions{}), user.UpdateUserSettings) + }) + m.Combo("/emails").Get(reqToken(auth_model.AccessTokenScopeReadUser), user.ListEmails). + Post(reqToken(auth_model.AccessTokenScopeUser), bind(api.CreateEmailOption{}), user.AddEmail). + Delete(reqToken(auth_model.AccessTokenScopeUser), bind(api.DeleteEmailOption{}), user.DeleteEmail) m.Get("/followers", user.ListMyFollowers) m.Group("/following", func() { m.Get("", user.ListMyFollowing) m.Group("/{username}", func() { m.Get("", user.CheckMyFollowing) - m.Put("", user.Follow) - m.Delete("", user.Unfollow) + m.Put("", reqToken(auth_model.AccessTokenScopeUserFollow), user.Follow) // requires 'user:follow' scope + m.Delete("", reqToken(auth_model.AccessTokenScopeUserFollow), user.Unfollow) // requires 'user:follow' scope }, context_service.UserAssignmentAPI()) }) + // (admin:public_key scope) m.Group("/keys", func() { - m.Combo("").Get(user.ListMyPublicKeys). - Post(bind(api.CreateKeyOption{}), user.CreatePublicKey) - m.Combo("/{id}").Get(user.GetPublicKey). - Delete(user.DeletePublicKey) + m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadPublicKey), user.ListMyPublicKeys). + Post(reqToken(auth_model.AccessTokenScopeWritePublicKey), bind(api.CreateKeyOption{}), user.CreatePublicKey) + m.Combo("/{id}").Get(reqToken(auth_model.AccessTokenScopeReadPublicKey), user.GetPublicKey). + Delete(reqToken(auth_model.AccessTokenScopeWritePublicKey), user.DeletePublicKey) }) + + // (repo scope) m.Group("/applications", func() { m.Combo("/oauth2"). Get(user.ListOauth2Applications). @@ -758,21 +762,23 @@ func Routes(ctx gocontext.Context) *web.Route { Delete(user.DeleteOauth2Application). Patch(bind(api.CreateOAuth2ApplicationOptions{}), user.UpdateOauth2Application). Get(user.GetOauth2Application) - }, reqToken("")) + }, reqToken(auth_model.AccessTokenScopeRepo)) + // (admin:gpg_key scope) m.Group("/gpg_keys", func() { - m.Combo("").Get(user.ListMyGPGKeys). - Post(bind(api.CreateGPGKeyOption{}), user.CreateGPGKey) - m.Combo("/{id}").Get(user.GetGPGKey). - Delete(user.DeleteGPGKey) + m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadGPGKey), user.ListMyGPGKeys). + Post(reqToken(auth_model.AccessTokenScopeWriteGPGKey), bind(api.CreateGPGKeyOption{}), user.CreateGPGKey) + m.Combo("/{id}").Get(reqToken(auth_model.AccessTokenScopeReadGPGKey), user.GetGPGKey). + Delete(reqToken(auth_model.AccessTokenScopeWriteGPGKey), user.DeleteGPGKey) }) + m.Get("/gpg_key_token", reqToken(auth_model.AccessTokenScopeReadGPGKey), user.GetVerificationToken) + m.Post("/gpg_key_verify", reqToken(auth_model.AccessTokenScopeReadGPGKey), bind(api.VerifyGPGKeyOption{}), user.VerifyUserGPGKey) - m.Get("/gpg_key_token", user.GetVerificationToken) - m.Post("/gpg_key_verify", bind(api.VerifyGPGKeyOption{}), user.VerifyUserGPGKey) - - m.Combo("/repos").Get(user.ListMyRepos). + // (repo scope) + m.Combo("/repos", reqToken(auth_model.AccessTokenScopeRepo)).Get(user.ListMyRepos). Post(bind(api.CreateRepoOption{}), repo.Create) + // (repo scope) m.Group("/starred", func() { m.Get("", user.GetMyStarredRepos) m.Group("/{username}/{reponame}", func() { @@ -780,14 +786,11 @@ func Routes(ctx gocontext.Context) *web.Route { m.Put("", user.Star) m.Delete("", user.Unstar) }, repoAssignment()) - }) - m.Get("/times", repo.ListMyTrackedTimes) - - m.Get("/stopwatches", repo.GetStopwatches) - - m.Get("/subscriptions", user.GetMyWatchedRepos) - - m.Get("/teams", org.ListUserTeams) + }, reqToken(auth_model.AccessTokenScopeRepo)) + m.Get("/times", reqToken(auth_model.AccessTokenScopeRepo), repo.ListMyTrackedTimes) + m.Get("/stopwatches", reqToken(auth_model.AccessTokenScopeRepo), repo.GetStopwatches) + m.Get("/subscriptions", reqToken(auth_model.AccessTokenScopeRepo), user.GetMyWatchedRepos) + m.Get("/teams", reqToken(auth_model.AccessTokenScopeRepo), org.ListUserTeams) }, reqToken("")) // Repositories diff --git a/tests/integration/api_branch_test.go b/tests/integration/api_branch_test.go index bdfdd3c7520be..d858ac8dc0c10 100644 --- a/tests/integration/api_branch_test.go +++ b/tests/integration/api_branch_test.go @@ -108,7 +108,7 @@ func TestAPICreateBranch(t *testing.T) { func testAPICreateBranches(t *testing.T, giteaURL *url.URL) { username := "user2" - ctx := NewAPITestContext(t, username, "my-noo-repo") + ctx := NewAPITestContext(t, username, "my-noo-repo", "repo") giteaURL.Path = ctx.GitPath() t.Run("CreateRepo", doAPICreateRepository(ctx, false)) diff --git a/tests/integration/api_gpg_keys_test.go b/tests/integration/api_gpg_keys_test.go index 0ad876c9b97ab..bd0762cf0c955 100644 --- a/tests/integration/api_gpg_keys_test.go +++ b/tests/integration/api_gpg_keys_test.go @@ -22,6 +22,7 @@ func TestGPGKeys(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session) + tokenWithGPGKeyScope := getTokenForLoggedInUser(t, session, "admin_gpg_key") tt := []struct { name string @@ -35,6 +36,10 @@ func TestGPGKeys(t *testing.T) { }, { name: "LoggedAsUser2", makeRequest: session.MakeRequest, token: token, + results: []int{http.StatusUnauthorized, http.StatusOK, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized}, + }, + { + name: "LoggedAsUser2WithScope", makeRequest: session.MakeRequest, token: tokenWithGPGKeyScope, results: []int{http.StatusOK, http.StatusOK, http.StatusNotFound, http.StatusNoContent, http.StatusUnprocessableEntity, http.StatusNotFound, http.StatusCreated, http.StatusNotFound, http.StatusCreated}, }, } diff --git a/tests/integration/api_helper_for_declarative_test.go b/tests/integration/api_helper_for_declarative_test.go index 5a798f79f0fc5..14a9081f86acc 100644 --- a/tests/integration/api_helper_for_declarative_test.go +++ b/tests/integration/api_helper_for_declarative_test.go @@ -32,9 +32,9 @@ type APITestContext struct { ExpectedCode int } -func NewAPITestContext(t *testing.T, username, reponame string) APITestContext { +func NewAPITestContext(t *testing.T, username, reponame string, scope ...string) APITestContext { session := loginUser(t, username) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, scope...) return APITestContext{ Session: session, Token: token, diff --git a/tests/integration/api_httpsig_test.go b/tests/integration/api_httpsig_test.go index 80b3c586b432c..e553cb57e7601 100644 --- a/tests/integration/api_httpsig_test.go +++ b/tests/integration/api_httpsig_test.go @@ -53,7 +53,7 @@ func TestHTTPSigPubKey(t *testing.T) { // Add our public key to user1 defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") - token := url.QueryEscape(getTokenForLoggedInUser(t, session)) + token := url.QueryEscape(getTokenForLoggedInUser(t, session, "admin_public_key")) keysURL := fmt.Sprintf("/api/v1/user/keys?token=%s", token) keyType := "ssh-rsa" keyContent := "AAAAB3NzaC1yc2EAAAADAQABAAABAQCqOZB5vkRvXFXups1/0StDRdG8plbNSwsWEnNnP4Bvurxa0+z3W9B8GLKnDiLw5MbpbMNyBlpXw13GfuIeciy10DWTz0xUbiy3J3KabCaT36asIw2y7k6Z0jL0UBnrVENwq5/lUbZYqSZ4rRU744wkhh8TULpzM14npQCZwg6aEbG+MwjzddQ72fR+3BPBrKn5dTmmu8rH99O+U+Nuto81Tg7PA+NUupcHOmhdiEGq49plgVFXK98Vks5tiybL4GuzFyWgyX73Dg/QBMn2eMHt1EMv5Gs3i6GFhKKGo4rjDi9qI6PX5oDR4LTNe6cR8td8YhVD8WFZwLLl/vaYyIqd" diff --git a/tests/integration/api_issue_stopwatch_test.go b/tests/integration/api_issue_stopwatch_test.go index c2ad9c45e8200..bb40b016c2611 100644 --- a/tests/integration/api_issue_stopwatch_test.go +++ b/tests/integration/api_issue_stopwatch_test.go @@ -26,7 +26,7 @@ func TestAPIListStopWatches(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "GET", "/api/v1/user/stopwatches?token=%s", token) resp := session.MakeRequest(t, req, http.StatusOK) var apiWatches []*api.StopWatch diff --git a/tests/integration/api_keys_test.go b/tests/integration/api_keys_test.go index 1cb0b20ffe162..e9f731ffe3737 100644 --- a/tests/integration/api_keys_test.go +++ b/tests/integration/api_keys_test.go @@ -104,7 +104,7 @@ func TestCreateUserKey(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user1"}) session := loginUser(t, "user1") - token := url.QueryEscape(getTokenForLoggedInUser(t, session)) + token := url.QueryEscape(getTokenForLoggedInUser(t, session, "admin_public_key")) keysURL := fmt.Sprintf("/api/v1/user/keys?token=%s", token) keyType := "ssh-rsa" keyContent := "AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM=" @@ -168,7 +168,7 @@ func TestCreateUserKey(t *testing.T) { // Now login as user 2 session2 := loginUser(t, "user2") - token2 := url.QueryEscape(getTokenForLoggedInUser(t, session2)) + token2 := url.QueryEscape(getTokenForLoggedInUser(t, session2, "admin_public_key")) // Should find key even though not ours, but we shouldn't know whose it is fingerprintURL = fmt.Sprintf("/api/v1/user/keys?token=%s&fingerprint=%s", token2, newPublicKey.Fingerprint) diff --git a/tests/integration/api_repo_file_create_test.go b/tests/integration/api_repo_file_create_test.go index f03efaa0eadf9..ec43b938e86b3 100644 --- a/tests/integration/api_repo_file_create_test.go +++ b/tests/integration/api_repo_file_create_test.go @@ -281,7 +281,7 @@ func TestAPICreateFile(t *testing.T) { session.MakeRequest(t, req, http.StatusForbidden) // Test creating a file in an empty repository - doAPICreateRepository(NewAPITestContext(t, "user2", "empty-repo"), true)(t) + doAPICreateRepository(NewAPITestContext(t, "user2", "empty-repo", "repo"), true)(t) createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) diff --git a/tests/integration/api_repo_file_get_test.go b/tests/integration/api_repo_file_get_test.go index cca72c2b3ec8f..4649e189d2239 100644 --- a/tests/integration/api_repo_file_get_test.go +++ b/tests/integration/api_repo_file_get_test.go @@ -25,7 +25,7 @@ func TestAPIGetRawFileOrLFS(t *testing.T) { // Test with LFS onGiteaRun(t, func(t *testing.T, u *url.URL) { - httpContext := NewAPITestContext(t, "user2", "repo-lfs-test") + httpContext := NewAPITestContext(t, "user2", "repo-lfs-test", "repo") doAPICreateRepository(httpContext, false, func(t *testing.T, repository api.Repository) { u.Path = httpContext.GitPath() dstPath := t.TempDir() diff --git a/tests/integration/api_repo_lfs_test.go b/tests/integration/api_repo_lfs_test.go index 440dd04a8106d..76f79fcad7904 100644 --- a/tests/integration/api_repo_lfs_test.go +++ b/tests/integration/api_repo_lfs_test.go @@ -59,7 +59,7 @@ func TestAPILFSMediaType(t *testing.T) { } func createLFSTestRepository(t *testing.T, name string) *repo_model.Repository { - ctx := NewAPITestContext(t, "user2", "lfs-"+name+"-repo") + ctx := NewAPITestContext(t, "user2", "lfs-"+name+"-repo", "repo") t.Run("CreateRepo", doAPICreateRepository(ctx, false)) repo, err := repo_model.GetRepositoryByOwnerAndName("user2", "lfs-"+name+"-repo") diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index bfe0c0aa9c58e..5677e5d48a514 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -379,7 +379,7 @@ func TestAPIRepoMigrateConflict(t *testing.T) { func testAPIRepoMigrateConflict(t *testing.T, u *url.URL) { username := "user2" - baseAPITestContext := NewAPITestContext(t, username, "repo1") + baseAPITestContext := NewAPITestContext(t, username, "repo1", "repo") u.Path = baseAPITestContext.GitPath() @@ -460,7 +460,7 @@ func TestAPIRepoCreateConflict(t *testing.T) { func testAPIRepoCreateConflict(t *testing.T, u *url.URL) { username := "user2" - baseAPITestContext := NewAPITestContext(t, username, "repo1") + baseAPITestContext := NewAPITestContext(t, username, "repo1", "repo") u.Path = baseAPITestContext.GitPath() diff --git a/tests/integration/api_user_email_test.go b/tests/integration/api_user_email_test.go index 7bd265187ca0f..62c66014693e0 100644 --- a/tests/integration/api_user_email_test.go +++ b/tests/integration/api_user_email_test.go @@ -19,7 +19,7 @@ func TestAPIListEmails(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "read_user") req := NewRequest(t, "GET", "/api/v1/user/emails?token="+token) resp := session.MakeRequest(t, req, http.StatusOK) @@ -46,7 +46,7 @@ func TestAPIAddEmail(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "user") opts := api.CreateEmailOption{ Emails: []string{"user101@example.com"}, @@ -83,7 +83,7 @@ func TestAPIDeleteEmail(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "user") opts := api.DeleteEmailOption{ Emails: []string{"user2-3@example.com"}, diff --git a/tests/integration/api_user_follow_test.go b/tests/integration/api_user_follow_test.go index e21556aa5b2de..e87791761fde3 100644 --- a/tests/integration/api_user_follow_test.go +++ b/tests/integration/api_user_follow_test.go @@ -25,7 +25,7 @@ func TestAPIFollow(t *testing.T) { token1 := getTokenForLoggedInUser(t, session1) session2 := loginUser(t, user2) - token2 := getTokenForLoggedInUser(t, session2) + token2 := getTokenForLoggedInUser(t, session2, "user_follow") t.Run("Follow", func(t *testing.T) { defer tests.PrintCurrentTest(t)() diff --git a/tests/integration/api_user_star_test.go b/tests/integration/api_user_star_test.go index 76c3dc2d17755..3395b399cfbcb 100644 --- a/tests/integration/api_user_star_test.go +++ b/tests/integration/api_user_star_test.go @@ -23,11 +23,12 @@ func TestAPIStar(t *testing.T) { session := loginUser(t, user) token := getTokenForLoggedInUser(t, session) + tokenWithRepoScope := getTokenForLoggedInUser(t, session, "repo") t.Run("Star", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/starred/%s?token=%s", repo, token)) + req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/starred/%s?token=%s", repo, tokenWithRepoScope)) MakeRequest(t, req, http.StatusNoContent) }) @@ -48,7 +49,7 @@ func TestAPIStar(t *testing.T) { t.Run("GetMyStarredRepos", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred?token=%s", token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred?token=%s", tokenWithRepoScope)) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("X-Total-Count")) @@ -62,17 +63,17 @@ func TestAPIStar(t *testing.T) { t.Run("IsStarring", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred/%s?token=%s", repo, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred/%s?token=%s", repo, tokenWithRepoScope)) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred/%s?token=%s", repo+"notexisting", token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred/%s?token=%s", repo+"notexisting", tokenWithRepoScope)) MakeRequest(t, req, http.StatusNotFound) }) t.Run("Unstar", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/starred/%s?token=%s", repo, token)) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/starred/%s?token=%s", repo, tokenWithRepoScope)) MakeRequest(t, req, http.StatusNoContent) }) } diff --git a/tests/integration/api_user_watch_test.go b/tests/integration/api_user_watch_test.go index e45050a2783e6..94941c1274f0d 100644 --- a/tests/integration/api_user_watch_test.go +++ b/tests/integration/api_user_watch_test.go @@ -23,6 +23,7 @@ func TestAPIWatch(t *testing.T) { session := loginUser(t, user) token := getTokenForLoggedInUser(t, session) + tokenWithRepoScope := getTokenForLoggedInUser(t, session, "repo") t.Run("Watch", func(t *testing.T) { defer tests.PrintCurrentTest(t)() @@ -48,7 +49,7 @@ func TestAPIWatch(t *testing.T) { t.Run("GetMyWatchedRepos", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/subscriptions?token=%s", token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/subscriptions?token=%s", tokenWithRepoScope)) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("X-Total-Count")) diff --git a/tests/integration/git_test.go b/tests/integration/git_test.go index 6f656ef2ce6dd..cfffa343108c3 100644 --- a/tests/integration/git_test.go +++ b/tests/integration/git_test.go @@ -47,7 +47,7 @@ func testGit(t *testing.T, u *url.URL) { u.Path = baseAPITestContext.GitPath() - forkedUserCtx := NewAPITestContext(t, "user4", "repo1") + forkedUserCtx := NewAPITestContext(t, "user4", "repo1", "repo") t.Run("HTTP", func(t *testing.T) { defer tests.PrintCurrentTest(t)() diff --git a/tests/integration/gpg_git_test.go b/tests/integration/gpg_git_test.go index 4dcf6276c27d3..bb509b0a81c90 100644 --- a/tests/integration/gpg_git_test.go +++ b/tests/integration/gpg_git_test.go @@ -70,7 +70,7 @@ func TestGPGGit(t *testing.T) { t.Run("Unsigned-Initial", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-unsigned") + testCtx := NewAPITestContext(t, username, "initial-unsigned", "repo") t.Run("CreateRepository", doAPICreateRepository(testCtx, false)) t.Run("CheckMasterBranchUnsigned", doAPIGetBranch(testCtx, "master", func(t *testing.T, branch api.Branch) { assert.NotNil(t, branch.Commit) @@ -184,7 +184,7 @@ func TestGPGGit(t *testing.T) { t.Run("AlwaysSign-Initial", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-always") + testCtx := NewAPITestContext(t, username, "initial-always", "repo") t.Run("CreateRepository", doAPICreateRepository(testCtx, false)) t.Run("CheckMasterBranchSigned", doAPIGetBranch(testCtx, "master", func(t *testing.T, branch api.Branch) { assert.NotNil(t, branch.Commit) @@ -212,7 +212,7 @@ func TestGPGGit(t *testing.T) { t.Run("AlwaysSign-Initial-CRUD-Never", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-always-never") + testCtx := NewAPITestContext(t, username, "initial-always-never", "repo") t.Run("CreateRepository", doAPICreateRepository(testCtx, false)) t.Run("CreateCRUDFile-Never", crudActionCreateFile( t, testCtx, user, "master", "never", "unsigned-never.txt", func(t *testing.T, response api.FileResponse) { @@ -225,7 +225,7 @@ func TestGPGGit(t *testing.T) { u.Path = baseAPITestContext.GitPath() t.Run("AlwaysSign-Initial-CRUD-ParentSigned-On-Always", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-always-parent") + testCtx := NewAPITestContext(t, username, "initial-always-parent", "repo") t.Run("CreateRepository", doAPICreateRepository(testCtx, false)) t.Run("CreateCRUDFile-ParentSigned", crudActionCreateFile( t, testCtx, user, "master", "parentsigned", "signed-parent.txt", func(t *testing.T, response api.FileResponse) { @@ -244,7 +244,7 @@ func TestGPGGit(t *testing.T) { t.Run("AlwaysSign-Initial-CRUD-Always", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-always-always") + testCtx := NewAPITestContext(t, username, "initial-always-always", "repo") t.Run("CreateRepository", doAPICreateRepository(testCtx, false)) t.Run("CreateCRUDFile-Always", crudActionCreateFile( t, testCtx, user, "master", "always", "signed-always.txt", func(t *testing.T, response api.FileResponse) { diff --git a/tests/integration/ssh_key_test.go b/tests/integration/ssh_key_test.go index fd98af512516a..7c1d9685891e7 100644 --- a/tests/integration/ssh_key_test.go +++ b/tests/integration/ssh_key_test.go @@ -48,7 +48,7 @@ func TestPushDeployKeyOnEmptyRepo(t *testing.T) { func testPushDeployKeyOnEmptyRepo(t *testing.T, u *url.URL) { // OK login - ctx := NewAPITestContext(t, "user2", "deploy-key-empty-repo-1") + ctx := NewAPITestContext(t, "user2", "deploy-key-empty-repo-1", "repo") keyname := fmt.Sprintf("%s-push", ctx.Reponame) u.Path = ctx.GitPath() @@ -90,7 +90,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) { keyname := fmt.Sprintf("%s-push", reponame) // OK login - ctx := NewAPITestContext(t, username, reponame) + ctx := NewAPITestContext(t, username, reponame, "repo", "admin_public_key") otherCtx := ctx otherCtx.Reponame = "ssh-key-test-repo-2" From 800de93c47b254a53892090d1ee2b84a85326e2e Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 29 Oct 2022 20:43:49 -0400 Subject: [PATCH 028/118] Fix gpg key token tests --- tests/integration/api_gpg_keys_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/integration/api_gpg_keys_test.go b/tests/integration/api_gpg_keys_test.go index bd0762cf0c955..1e2aa03d4e4aa 100644 --- a/tests/integration/api_gpg_keys_test.go +++ b/tests/integration/api_gpg_keys_test.go @@ -79,7 +79,7 @@ func TestGPGKeys(t *testing.T) { t.Run("CheckState", func(t *testing.T) { var keys []*api.GPGKey - req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+token) // GET all keys + req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+tokenWithGPGKeyScope) // GET all keys resp := session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &keys) assert.Len(t, keys, 1) @@ -95,7 +95,7 @@ func TestGPGKeys(t *testing.T) { assert.Empty(t, subKey.Emails) var key api.GPGKey - req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey1.ID, 10)+"?token="+token) // Primary key 1 + req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey1.ID, 10)+"?token="+tokenWithGPGKeyScope) // Primary key 1 resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &key) assert.EqualValues(t, "38EA3BCED732982C", key.KeyID) @@ -103,7 +103,7 @@ func TestGPGKeys(t *testing.T) { assert.EqualValues(t, "user2@example.com", key.Emails[0].Email) assert.True(t, key.Emails[0].Verified) - req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(subKey.ID, 10)+"?token="+token) // Subkey of 38EA3BCED732982C + req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(subKey.ID, 10)+"?token="+tokenWithGPGKeyScope) // Subkey of 38EA3BCED732982C resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &key) assert.EqualValues(t, "70D7C694D17D03AD", key.KeyID) From 1fe42fbe1a25e6519170944e71ca721e31436d35 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 29 Oct 2022 20:57:33 -0400 Subject: [PATCH 029/118] Add repo scope to user/applications --- tests/integration/api_oauth2_apps_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/integration/api_oauth2_apps_test.go b/tests/integration/api_oauth2_apps_test.go index 6352449d6acb1..0ab97843a96a0 100644 --- a/tests/integration/api_oauth2_apps_test.go +++ b/tests/integration/api_oauth2_apps_test.go @@ -56,7 +56,7 @@ func testAPICreateOAuth2Application(t *testing.T) { func testAPIListOAuth2Applications(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") existApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ UID: user.ID, @@ -87,7 +87,7 @@ func testAPIListOAuth2Applications(t *testing.T) { func testAPIDeleteOAuth2Application(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") oldApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ UID: user.ID, @@ -108,7 +108,7 @@ func testAPIDeleteOAuth2Application(t *testing.T) { func testAPIGetOAuth2Application(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") existApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ UID: user.ID, From 32cac396cf167876ee20b2ec51cb52a9cdf63748 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 29 Oct 2022 21:10:13 -0400 Subject: [PATCH 030/118] Fix gpg key token name in web --- templates/user/settings/applications.tmpl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/templates/user/settings/applications.tmpl b/templates/user/settings/applications.tmpl index 5c2b5060ea56e..fd32d2cb5723c 100644 --- a/templates/user/settings/applications.tmpl +++ b/templates/user/settings/applications.tmpl @@ -197,8 +197,8 @@
- - + +
From 99f30f6f166f7fb10975e116381b5ad275c83ded Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 29 Oct 2022 21:19:06 -0400 Subject: [PATCH 031/118] Add more repo scope to integration tests --- tests/integration/api_repo_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index 5677e5d48a514..d3af91c34a213 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -510,7 +510,7 @@ func TestAPIRepoTransfer(t *testing.T) { // create repo to move user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") repoName := "moveME" apiRepo := new(api.Repository) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/user/repos?token=%s", token), &api.CreateRepoOption{ @@ -545,7 +545,7 @@ func transfer(t *testing.T) *repo_model.Repository { // create repo to move user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") repoName := "moveME" apiRepo := new(api.Repository) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/user/repos?token=%s", token), &api.CreateRepoOption{ From f839856e3c4261c9159a27e8d59672bbb7cdf382 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 29 Oct 2022 21:43:37 -0400 Subject: [PATCH 032/118] Fix git tests --- tests/integration/git_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/git_test.go b/tests/integration/git_test.go index cfffa343108c3..301a635f71d60 100644 --- a/tests/integration/git_test.go +++ b/tests/integration/git_test.go @@ -43,7 +43,7 @@ func TestGit(t *testing.T) { func testGit(t *testing.T, u *url.URL) { username := "user2" - baseAPITestContext := NewAPITestContext(t, username, "repo1") + baseAPITestContext := NewAPITestContext(t, username, "repo1", "write_public_key") u.Path = baseAPITestContext.GitPath() From 0583e79f3791f70c019287638e87a4a03dccd5a6 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 29 Oct 2022 22:29:32 -0400 Subject: [PATCH 033/118] Add gpg key scope to a user test --- tests/integration/user_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/user_test.go b/tests/integration/user_test.go index 110f5c89bfbd3..c6b2a7fd771fd 100644 --- a/tests/integration/user_test.go +++ b/tests/integration/user_test.go @@ -152,7 +152,7 @@ Note: This user hasn't uploaded any GPG keys. // Import key // User1 session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "write_gpg_key") testCreateGPGKey(t, session.MakeRequest, token, http.StatusCreated, `-----BEGIN PGP PUBLIC KEY BLOCK----- mQENBFyy/VUBCADJ7zbM20Z1RWmFoVgp5WkQfI2rU1Vj9cQHes9i42wVLLtcbPeo From a282f02de691fa876fcefea5db43fd7b6e741496 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 01:14:12 -0400 Subject: [PATCH 034/118] Limit token scope for some repo APIs --- routers/api/v1/api.go | 83 ++++++++++--------- tests/integration/api_keys_test.go | 4 +- tests/integration/api_releases_test.go | 2 +- tests/integration/api_repo_archive_test.go | 2 +- .../integration/api_repo_collaborator_test.go | 8 +- tests/integration/api_repo_edit_test.go | 4 +- tests/integration/api_repo_git_hook_test.go | 18 ++-- tests/integration/api_repo_git_tags_test.go | 2 +- .../integration/api_repo_lfs_migrate_test.go | 2 +- tests/integration/api_repo_tags_test.go | 2 +- tests/integration/api_repo_test.go | 16 ++-- tests/integration/api_wiki_test.go | 13 +-- tests/integration/git_test.go | 2 +- tests/integration/gpg_git_test.go | 6 +- 14 files changed, 86 insertions(+), 78 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index aab66c767a3cd..5a312c9cd8caf 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -794,74 +794,77 @@ func Routes(ctx gocontext.Context) *web.Route { }, reqToken("")) // Repositories - m.Post("/org/{org}/repos", reqToken(""), bind(api.CreateRepoOption{}), repo.CreateOrgRepoDeprecated) + m.Post("/org/{org}/repos", reqToken("auth_model.AccessTokenScopeAdminOrg"), bind(api.CreateRepoOption{}), repo.CreateOrgRepoDeprecated) - m.Combo("/repositories/{id}", reqToken("")).Get(repo.GetByID) + m.Combo("/repositories/{id}", reqToken(auth_model.AccessTokenScopeRepo)).Get(repo.GetByID) m.Group("/repos", func() { m.Get("/search", repo.Search) m.Get("/issues/search", repo.SearchIssues) - m.Post("/migrate", reqToken(""), bind(api.MigrateRepoOptions{}), repo.Migrate) + // (repo scope) + m.Post("/migrate", reqToken(auth_model.AccessTokenScopeRepo), bind(api.MigrateRepoOptions{}), repo.Migrate) m.Group("/{username}/{reponame}", func() { m.Combo("").Get(reqAnyRepoReader(), repo.Get). - Delete(reqToken(""), reqOwner(), repo.Delete). - Patch(reqToken(""), reqAdmin(), bind(api.EditRepoOption{}), repo.Edit) - m.Post("/generate", reqToken(""), reqRepoReader(unit.TypeCode), bind(api.GenerateRepoOption{}), repo.Generate) - m.Post("/transfer", reqOwner(), bind(api.TransferRepoOption{}), repo.Transfer) - m.Post("/transfer/accept", reqToken(""), repo.AcceptTransfer) - m.Post("/transfer/reject", reqToken(""), repo.RejectTransfer) - m.Combo("/notifications"). + Delete(reqToken(auth_model.AccessTokenScopeDeleteRepo), reqOwner(), repo.Delete). + Patch(reqToken(auth_model.AccessTokenScopeRepo), reqAdmin(), bind(api.EditRepoOption{}), repo.Edit) + m.Post("/generate", reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode), bind(api.GenerateRepoOption{}), repo.Generate) + m.Group("/transfer", func() { + m.Post("", reqOwner(), bind(api.TransferRepoOption{}), repo.Transfer) + m.Post("/accept", repo.AcceptTransfer) + m.Post("/reject", repo.RejectTransfer) + }, reqToken(auth_model.AccessTokenScopeRepo)) + m.Combo("/notifications", reqToken(auth_model.AccessTokenScopeNotification)). Get(reqToken(""), notify.ListRepoNotifications). Put(reqToken(""), notify.ReadRepoNotifications) m.Group("/hooks/git", func() { - m.Combo("").Get(repo.ListGitHooks) + m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.ListGitHooks) m.Group("/{id}", func() { - m.Combo("").Get(repo.GetGitHook). - Patch(bind(api.EditGitHookOption{}), repo.EditGitHook). - Delete(repo.DeleteGitHook) + m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.GetGitHook). + Patch(reqToken(auth_model.AccessTokenScopeWriteRepoHook), bind(api.EditGitHookOption{}), repo.EditGitHook). + Delete(reqToken(auth_model.AccessTokenScopeWriteRepoHook), repo.DeleteGitHook) }) - }, reqToken(""), reqAdmin(), reqGitHook(), context.ReferencesGitRepo(true)) + }, reqAdmin(), reqGitHook(), context.ReferencesGitRepo(true)) m.Group("/hooks", func() { - m.Combo("").Get(repo.ListHooks). - Post(bind(api.CreateHookOption{}), repo.CreateHook) + m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.ListHooks). + Post(reqToken(auth_model.AccessTokenScopeWriteRepoHook), bind(api.CreateHookOption{}), repo.CreateHook) m.Group("/{id}", func() { - m.Combo("").Get(repo.GetHook). - Patch(bind(api.EditHookOption{}), repo.EditHook). - Delete(repo.DeleteHook) - m.Post("/tests", context.ReferencesGitRepo(), context.RepoRefForAPI, repo.TestHook) + m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.GetHook). + Patch(reqToken(auth_model.AccessTokenScopeWriteRepoHook), bind(api.EditHookOption{}), repo.EditHook). + Delete(reqToken(auth_model.AccessTokenScopeWriteRepoHook), repo.DeleteHook) + m.Post("/tests", reqToken(auth_model.AccessTokenScopeReadRepoHook), context.ReferencesGitRepo(), context.RepoRefForAPI, repo.TestHook) }) - }, reqToken(""), reqAdmin(), reqWebhooksEnabled()) + }, reqAdmin(), reqWebhooksEnabled()) m.Group("/collaborators", func() { - m.Get("", reqAnyRepoReader(), repo.ListCollaborators) + m.Get("", reqToken(auth_model.AccessTokenScopeRepo), reqAnyRepoReader(), repo.ListCollaborators) m.Group("/{collaborator}", func() { m.Combo("").Get(reqAnyRepoReader(), repo.IsCollaborator). Put(reqAdmin(), bind(api.AddCollaboratorOption{}), repo.AddCollaborator). Delete(reqAdmin(), repo.DeleteCollaborator) m.Get("/permission", repo.GetRepoPermissions) - }, reqToken("")) - }, reqToken("")) - m.Get("/assignees", reqToken(""), reqAnyRepoReader(), repo.GetAssignees) - m.Get("/reviewers", reqToken(""), reqAnyRepoReader(), repo.GetReviewers) + }) + }, reqToken(auth_model.AccessTokenScopeRepo)) + m.Get("/assignees", reqToken(auth_model.AccessTokenScopeRepo), reqAnyRepoReader(), repo.GetAssignees) + m.Get("/reviewers", reqToken(auth_model.AccessTokenScopeRepo), reqAnyRepoReader(), repo.GetReviewers) m.Group("/teams", func() { m.Get("", reqAnyRepoReader(), repo.ListTeams) m.Combo("/{team}").Get(reqAnyRepoReader(), repo.IsTeam). Put(reqAdmin(), repo.AddTeam). Delete(reqAdmin(), repo.DeleteTeam) - }, reqToken("")) - m.Get("/raw/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFile) - m.Get("/media/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFileOrLFS) - m.Get("/archive/*", reqRepoReader(unit.TypeCode), repo.GetArchive) - m.Combo("/forks").Get(repo.ListForks). - Post(reqToken(""), reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork) + }, reqToken(auth_model.AccessTokenScopeRepo)) + m.Get("/raw/*", reqToken(auth_model.AccessTokenScopeRepo), context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFile) + m.Get("/media/*", reqToken(auth_model.AccessTokenScopeRepo), context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFileOrLFS) + m.Get("/archive/*", reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode), repo.GetArchive) + m.Combo("/forks", reqToken(auth_model.AccessTokenScopeRepo)).Get(repo.ListForks). + Post(reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork) m.Group("/branches", func() { m.Get("", repo.ListBranches) m.Get("/*", repo.GetBranch) m.Delete("/*", reqRepoWriter(unit.TypeCode), repo.DeleteBranch) m.Post("", reqRepoWriter(unit.TypeCode), bind(api.CreateBranchRepoOption{}), repo.CreateBranch) - }, context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode)) + }, reqToken(auth_model.AccessTokenScopeRepo), context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode)) m.Group("/branch_protections", func() { m.Get("", repo.ListBranchProtections) m.Post("", bind(api.CreateBranchProtectionOption{}), repo.CreateBranchProtection) @@ -870,23 +873,23 @@ func Routes(ctx gocontext.Context) *web.Route { m.Patch("", bind(api.EditBranchProtectionOption{}), repo.EditBranchProtection) m.Delete("", repo.DeleteBranchProtection) }) - }, reqToken(""), reqAdmin()) + }, reqToken(auth_model.AccessTokenScopeRepo), reqAdmin()) m.Group("/tags", func() { m.Get("", repo.ListTags) m.Get("/*", repo.GetTag) m.Post("", reqRepoWriter(unit.TypeCode), bind(api.CreateTagOption{}), repo.CreateTag) m.Delete("/*", repo.DeleteTag) - }, reqRepoReader(unit.TypeCode), context.ReferencesGitRepo(true)) + }, reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode), context.ReferencesGitRepo(true)) m.Group("/keys", func() { m.Combo("").Get(repo.ListDeployKeys). Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey) m.Combo("/{id}").Get(repo.GetDeployKey). Delete(repo.DeleteDeploykey) - }, reqToken(""), reqAdmin()) + }, reqToken(auth_model.AccessTokenScopeRepo), reqAdmin()) m.Group("/times", func() { m.Combo("").Get(repo.ListTrackedTimesByRepository) m.Combo("/{timetrackingusername}").Get(repo.ListTrackedTimesByUser) - }, mustEnableIssues, reqToken("")) + }, mustEnableIssues, reqToken(auth_model.AccessTokenScopeRepo)) m.Group("/wiki", func() { m.Combo("/page/{pageName}"). Get(repo.GetWikiPage). @@ -895,7 +898,9 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/revisions/{pageName}", repo.ListPageRevisions) m.Post("/new", mustNotBeArchived, reqRepoWriter(unit.TypeWiki), bind(api.CreateWikiPageOptions{}), repo.NewWikiPage) m.Get("/pages", repo.ListWikiPages) - }, mustEnableWiki) + }, mustEnableWiki, reqToken(auth_model.AccessTokenScopeRepo)) + + // TODO: continue here m.Group("/issues", func() { m.Combo("").Get(repo.ListIssues). Post(reqToken(""), mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue) diff --git a/tests/integration/api_keys_test.go b/tests/integration/api_keys_test.go index e9f731ffe3737..efb12edd013ec 100644 --- a/tests/integration/api_keys_test.go +++ b/tests/integration/api_keys_test.go @@ -54,7 +54,7 @@ func TestCreateReadOnlyDeployKey(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", repoOwner.Name, repo.Name, token) rawKeyBody := api.CreateKeyOption{ Title: "read-only", @@ -80,7 +80,7 @@ func TestCreateReadWriteDeployKey(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", repoOwner.Name, repo.Name, token) rawKeyBody := api.CreateKeyOption{ Title: "read-write", diff --git a/tests/integration/api_releases_test.go b/tests/integration/api_releases_test.go index 0c7f5e2d521e7..11aba531c4ed4 100644 --- a/tests/integration/api_releases_test.go +++ b/tests/integration/api_releases_test.go @@ -215,7 +215,7 @@ func TestAPIDeleteReleaseByTagName(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") createNewReleaseUsingAPI(t, session, token, owner, repo, "release-tag", "", "Release Tag", "test") diff --git a/tests/integration/api_repo_archive_test.go b/tests/integration/api_repo_archive_test.go index 3707cb7c1c8bb..fb60d3f509f2a 100644 --- a/tests/integration/api_repo_archive_test.go +++ b/tests/integration/api_repo_archive_test.go @@ -25,7 +25,7 @@ func TestAPIDownloadArchive(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user2.LowerName) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/archive/master.zip", user2.Name, repo.Name)) link.RawQuery = url.Values{"token": {token}}.Encode() diff --git a/tests/integration/api_repo_collaborator_test.go b/tests/integration/api_repo_collaborator_test.go index 3527e16572d9e..c680b27748e37 100644 --- a/tests/integration/api_repo_collaborator_test.go +++ b/tests/integration/api_repo_collaborator_test.go @@ -29,7 +29,7 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { user11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 11}) session := loginUser(t, repo2Owner.Name) - testCtx := NewAPITestContext(t, repo2Owner.Name, repo2.Name) + testCtx := NewAPITestContext(t, repo2Owner.Name, repo2.Name, "repo") t.Run("RepoOwnerShouldBeOwner", func(t *testing.T) { req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, repo2Owner.Name, testCtx.Token) @@ -86,7 +86,7 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { t.Run("AddUserAsCollaboratorWithReadAccess", doAPIAddCollaborator(testCtx, user5.Name, perm.AccessModeRead)) _session := loginUser(t, user5.Name) - _testCtx := NewAPITestContext(t, user5.Name, repo2.Name) + _testCtx := NewAPITestContext(t, user5.Name, repo2.Name, "repo") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user5.Name, _testCtx.Token) resp := _session.MakeRequest(t, req, http.StatusOK) @@ -101,7 +101,7 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { t.Run("AddUserAsCollaboratorWithReadAccess", doAPIAddCollaborator(testCtx, user5.Name, perm.AccessModeRead)) _session := loginUser(t, user5.Name) - _testCtx := NewAPITestContext(t, user5.Name, repo2.Name) + _testCtx := NewAPITestContext(t, user5.Name, repo2.Name, "repo") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user5.Name, _testCtx.Token) resp := _session.MakeRequest(t, req, http.StatusOK) @@ -117,7 +117,7 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { t.Run("AddUserAsCollaboratorWithReadAccess", doAPIAddCollaborator(testCtx, user11.Name, perm.AccessModeRead)) _session := loginUser(t, user10.Name) - _testCtx := NewAPITestContext(t, user10.Name, repo2.Name) + _testCtx := NewAPITestContext(t, user10.Name, repo2.Name, "repo") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user11.Name, _testCtx.Token) resp := _session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/api_repo_edit_test.go b/tests/integration/api_repo_edit_test.go index 4dfae97e43794..eec7c0bb0d31b 100644 --- a/tests/integration/api_repo_edit_test.go +++ b/tests/integration/api_repo_edit_test.go @@ -146,10 +146,10 @@ func TestAPIRepoEdit(t *testing.T) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session) + token2 := getTokenForLoggedInUser(t, session, "repo") // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session) + token4 := getTokenForLoggedInUser(t, session, "repo") session = emptyTestSession(t) // Test editing a repo1 which user2 owns, changing name and many properties diff --git a/tests/integration/api_repo_git_hook_test.go b/tests/integration/api_repo_git_hook_test.go index a6c4f91d4a5b9..17067acf755d9 100644 --- a/tests/integration/api_repo_git_hook_test.go +++ b/tests/integration/api_repo_git_hook_test.go @@ -31,7 +31,7 @@ func TestAPIListGitHooks(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "read_repo_hook") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", owner.Name, repo.Name, token) resp := MakeRequest(t, req, http.StatusOK) @@ -57,7 +57,7 @@ func TestAPIListGitHooksNoHooks(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "read_repo_hook") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", owner.Name, repo.Name, token) resp := MakeRequest(t, req, http.StatusOK) @@ -77,7 +77,7 @@ func TestAPIListGitHooksNoAccess(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "read_repo_hook") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", owner.Name, repo.Name, token) MakeRequest(t, req, http.StatusForbidden) @@ -91,7 +91,7 @@ func TestAPIGetGitHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "read_repo_hook") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) resp := MakeRequest(t, req, http.StatusOK) @@ -108,7 +108,7 @@ func TestAPIGetGitHookNoAccess(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "read_repo_hook") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) MakeRequest(t, req, http.StatusForbidden) @@ -122,7 +122,7 @@ func TestAPIEditGitHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "write_repo_hook") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) @@ -151,7 +151,7 @@ func TestAPIEditGitHookNoAccess(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "write_repo_hook") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) req := NewRequestWithJSON(t, "PATCH", urlStr, &api.EditGitHookOption{ @@ -168,7 +168,7 @@ func TestAPIDeleteGitHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "write_repo_hook") req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) @@ -190,7 +190,7 @@ func TestAPIDeleteGitHookNoAccess(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "write_repo_hook") req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) MakeRequest(t, req, http.StatusForbidden) diff --git a/tests/integration/api_repo_git_tags_test.go b/tests/integration/api_repo_git_tags_test.go index 3357f9568dbda..36bee8abd7163 100644 --- a/tests/integration/api_repo_git_tags_test.go +++ b/tests/integration/api_repo_git_tags_test.go @@ -70,7 +70,7 @@ func TestAPIDeleteTagByName(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/tags/delete-tag?token=%s", owner.Name, repo.Name, token) diff --git a/tests/integration/api_repo_lfs_migrate_test.go b/tests/integration/api_repo_lfs_migrate_test.go index d2edf67e8be5c..66fdb8b921fe6 100644 --- a/tests/integration/api_repo_lfs_migrate_test.go +++ b/tests/integration/api_repo_lfs_migrate_test.go @@ -31,7 +31,7 @@ func TestAPIRepoLFSMigrateLocal(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+token, &api.MigrateRepoOptions{ CloneAddr: path.Join(setting.RepoRootPath, "migration/lfs-test.git"), diff --git a/tests/integration/api_repo_tags_test.go b/tests/integration/api_repo_tags_test.go index 5d3a209a767a0..5c6f4a6a3eec9 100644 --- a/tests/integration/api_repo_tags_test.go +++ b/tests/integration/api_repo_tags_test.go @@ -23,7 +23,7 @@ func TestAPIRepoTags(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") repoName := "repo1" diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index d3af91c34a213..1e5bd0247a429 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -349,7 +349,7 @@ func TestAPIRepoMigrate(t *testing.T) { for _, testCase := range testCases { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+token, &api.MigrateRepoOptions{ CloneAddr: testCase.cloneURL, RepoOwnerID: testCase.userID, @@ -528,7 +528,7 @@ func TestAPIRepoTransfer(t *testing.T) { user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}) session = loginUser(t, user.Name) - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "repo") req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer?token=%s", repo.OwnerName, repo.Name, token), &api.TransferRepoOption{ NewOwner: testCase.newOwner, TeamIDs: testCase.teams, @@ -575,7 +575,7 @@ func TestAPIAcceptTransfer(t *testing.T) { // try to accept with not authorized user session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) session.MakeRequest(t, req, http.StatusForbidden) @@ -601,7 +601,7 @@ func TestAPIRejectTransfer(t *testing.T) { // try to reject with not authorized user session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) session.MakeRequest(t, req, http.StatusForbidden) @@ -611,7 +611,7 @@ func TestAPIRejectTransfer(t *testing.T) { // reject transfer session = loginUser(t, "user4") - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "repo") req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) resp := session.MakeRequest(t, req, http.StatusOK) @@ -625,7 +625,7 @@ func TestAPIGenerateRepo(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") templateRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 44}) @@ -661,7 +661,7 @@ func TestAPIRepoGetReviewers(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/reviewers?token=%s", user.Name, repo.Name, token) @@ -675,7 +675,7 @@ func TestAPIRepoGetAssignees(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/assignees?token=%s", user.Name, repo.Name, token) diff --git a/tests/integration/api_wiki_test.go b/tests/integration/api_wiki_test.go index c6f4841d082ef..8378273bf7db3 100644 --- a/tests/integration/api_wiki_test.go +++ b/tests/integration/api_wiki_test.go @@ -21,8 +21,9 @@ func TestAPIGetWikiPage(t *testing.T) { username := "user2" session := loginUser(t, username) + token := getTokenForLoggedInUser(t, session, "repo") - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/page/Home", username, "repo1") + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/page/Home?token=%s", username, "repo1", token) req := NewRequest(t, "GET", urlStr) resp := session.MakeRequest(t, req, http.StatusOK) @@ -67,8 +68,9 @@ func TestAPIListWikiPages(t *testing.T) { username := "user2" session := loginUser(t, username) + token := getTokenForLoggedInUser(t, session, "repo") - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/pages", username, "repo1") + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/pages?token=%s", username, "repo1", token) req := NewRequest(t, "GET", urlStr) resp := session.MakeRequest(t, req, http.StatusOK) @@ -182,7 +184,7 @@ func TestAPINewWikiPage(t *testing.T) { defer tests.PrepareTestEnv(t)() username := "user2" session := loginUser(t, username) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/new?token=%s", username, "repo1", token) @@ -199,7 +201,7 @@ func TestAPIEditWikiPage(t *testing.T) { defer tests.PrepareTestEnv(t)() username := "user2" session := loginUser(t, username) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/page/Page-With-Spaced-Name?token=%s", username, "repo1", token) @@ -215,8 +217,9 @@ func TestAPIListPageRevisions(t *testing.T) { defer tests.PrepareTestEnv(t)() username := "user2" session := loginUser(t, username) + token := getTokenForLoggedInUser(t, session, "repo") - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/revisions/Home", username, "repo1") + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/revisions/Home>token=%s", username, "repo1", token) req := NewRequest(t, "GET", urlStr) resp := session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/git_test.go b/tests/integration/git_test.go index 301a635f71d60..5ee5dedbd4c2a 100644 --- a/tests/integration/git_test.go +++ b/tests/integration/git_test.go @@ -43,7 +43,7 @@ func TestGit(t *testing.T) { func testGit(t *testing.T, u *url.URL) { username := "user2" - baseAPITestContext := NewAPITestContext(t, username, "repo1", "write_public_key") + baseAPITestContext := NewAPITestContext(t, username, "repo1", "repo", "write_public_key") u.Path = baseAPITestContext.GitPath() diff --git a/tests/integration/gpg_git_test.go b/tests/integration/gpg_git_test.go index bb509b0a81c90..608d1958a41c2 100644 --- a/tests/integration/gpg_git_test.go +++ b/tests/integration/gpg_git_test.go @@ -264,7 +264,7 @@ func TestGPGGit(t *testing.T) { t.Run("UnsignedMerging", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-unsigned") + testCtx := NewAPITestContext(t, username, "initial-unsigned", "repo") var err error t.Run("CreatePullRequest", func(t *testing.T) { pr, err = doAPICreatePullRequest(testCtx, testCtx.Username, testCtx.Reponame, "master", "never2")(t) @@ -285,7 +285,7 @@ func TestGPGGit(t *testing.T) { t.Run("BaseSignedMerging", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-unsigned") + testCtx := NewAPITestContext(t, username, "initial-unsigned", "repo") var err error t.Run("CreatePullRequest", func(t *testing.T) { pr, err = doAPICreatePullRequest(testCtx, testCtx.Username, testCtx.Reponame, "master", "parentsigned2")(t) @@ -306,7 +306,7 @@ func TestGPGGit(t *testing.T) { t.Run("CommitsSignedMerging", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-unsigned") + testCtx := NewAPITestContext(t, username, "initial-unsigned", "repo") var err error t.Run("CreatePullRequest", func(t *testing.T) { pr, err = doAPICreatePullRequest(testCtx, testCtx.Username, testCtx.Reponame, "master", "always-parentsigned")(t) From 0bee9696828645e29e982764b6e6a674f3710cfa Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 01:32:34 -0400 Subject: [PATCH 035/118] Add repo scope in TestGPGKeys --- tests/integration/api_gpg_keys_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/api_gpg_keys_test.go b/tests/integration/api_gpg_keys_test.go index 1e2aa03d4e4aa..98060699f1b23 100644 --- a/tests/integration/api_gpg_keys_test.go +++ b/tests/integration/api_gpg_keys_test.go @@ -22,7 +22,7 @@ func TestGPGKeys(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session) - tokenWithGPGKeyScope := getTokenForLoggedInUser(t, session, "admin_gpg_key") + tokenWithGPGKeyScope := getTokenForLoggedInUser(t, session, "admin_gpg_key", "repo") tt := []struct { name string From 182b98478572d2c10af664b2308bdb4099d680a4 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 02:12:46 -0400 Subject: [PATCH 036/118] Fix repo scope in TestGPGKeys again --- tests/integration/api_gpg_keys_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/api_gpg_keys_test.go b/tests/integration/api_gpg_keys_test.go index 98060699f1b23..46a7e8d702d9d 100644 --- a/tests/integration/api_gpg_keys_test.go +++ b/tests/integration/api_gpg_keys_test.go @@ -21,7 +21,7 @@ type makeRequestFunc func(testing.TB, *http.Request, int) *httptest.ResponseReco func TestGPGKeys(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") tokenWithGPGKeyScope := getTokenForLoggedInUser(t, session, "admin_gpg_key", "repo") tt := []struct { From 965de5327dd78ae4a7a97eeec7e62cbcaf5a3400 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 02:35:54 -0400 Subject: [PATCH 037/118] Fix more repo scope issues --- tests/integration/api_branch_test.go | 14 +++++++------- tests/integration/api_repo_file_get_test.go | 5 ++++- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/tests/integration/api_branch_test.go b/tests/integration/api_branch_test.go index d858ac8dc0c10..7614aee117ec0 100644 --- a/tests/integration/api_branch_test.go +++ b/tests/integration/api_branch_test.go @@ -17,7 +17,7 @@ import ( func testAPIGetBranch(t *testing.T, branchName string, exists bool) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branches/%s?token=%s", branchName, token) resp := session.MakeRequest(t, req, NoExpectedStatus) if !exists { @@ -34,7 +34,7 @@ func testAPIGetBranch(t *testing.T, branchName string, exists bool) { func testAPIGetBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branch_protections/%s?token=%s", branchName, token) resp := session.MakeRequest(t, req, expectedHTTPStatus) @@ -47,7 +47,7 @@ func testAPIGetBranchProtection(t *testing.T, branchName string, expectedHTTPSta func testAPICreateBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/branch_protections?token="+token, &api.BranchProtection{ BranchName: branchName, }) @@ -62,7 +62,7 @@ func testAPICreateBranchProtection(t *testing.T, branchName string, expectedHTTP func testAPIEditBranchProtection(t *testing.T, branchName string, body *api.BranchProtection, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestWithJSON(t, "PATCH", "/api/v1/repos/user2/repo1/branch_protections/"+branchName+"?token="+token, body) resp := session.MakeRequest(t, req, expectedHTTPStatus) @@ -75,14 +75,14 @@ func testAPIEditBranchProtection(t *testing.T, branchName string, body *api.Bran func testAPIDeleteBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branch_protections/%s?token=%s", branchName, token) session.MakeRequest(t, req, expectedHTTPStatus) } func testAPIDeleteBranch(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branches/%s?token=%s", branchName, token) session.MakeRequest(t, req, expectedHTTPStatus) } @@ -156,7 +156,7 @@ func testAPICreateBranches(t *testing.T, giteaURL *url.URL) { } func testAPICreateBranch(t testing.TB, session *TestSession, user, repo, oldBranch, newBranch string, status int) bool { - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestWithJSON(t, "POST", "/api/v1/repos/"+user+"/"+repo+"/branches?token="+token, &api.CreateBranchRepoOption{ BranchName: newBranch, OldBranchName: oldBranch, diff --git a/tests/integration/api_repo_file_get_test.go b/tests/integration/api_repo_file_get_test.go index 4649e189d2239..283ad6aecb8ff 100644 --- a/tests/integration/api_repo_file_get_test.go +++ b/tests/integration/api_repo_file_get_test.go @@ -18,8 +18,11 @@ import ( func TestAPIGetRawFileOrLFS(t *testing.T) { defer tests.PrepareTestEnv(t)() + session := loginUser(t, "user1") + token := getTokenForLoggedInUser(t, session, "repo") + // Test with raw file - req := NewRequest(t, "GET", "/api/v1/repos/user2/repo1/media/README.md") + req := NewRequest(t, "GET", "/api/v1/repos/user2/repo1/media/README.md?token="+token) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "# repo1\n\nDescription for repo1", resp.Body.String()) From f376275b071f9339e95705ba63aa90784fe7c345 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 02:38:03 -0400 Subject: [PATCH 038/118] Fix the token for repo hooks --- tests/integration/api_repo_git_hook_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/integration/api_repo_git_hook_test.go b/tests/integration/api_repo_git_hook_test.go index 17067acf755d9..8c195753ffaf3 100644 --- a/tests/integration/api_repo_git_hook_test.go +++ b/tests/integration/api_repo_git_hook_test.go @@ -122,7 +122,7 @@ func TestAPIEditGitHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "write_repo_hook") + token := getTokenForLoggedInUser(t, session, "admin_repo_hook") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) @@ -168,7 +168,7 @@ func TestAPIDeleteGitHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "write_repo_hook") + token := getTokenForLoggedInUser(t, session, "admin_repo_hook") req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) From 0a837e7e884cd4df25c0470b3388dc940d701a5a Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 02:54:55 -0400 Subject: [PATCH 039/118] Include repo scope in TestAPIReposRaw --- tests/integration/api_repo_raw_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/api_repo_raw_test.go b/tests/integration/api_repo_raw_test.go index 9793e12b42920..f892a9236d3ed 100644 --- a/tests/integration/api_repo_raw_test.go +++ b/tests/integration/api_repo_raw_test.go @@ -20,7 +20,7 @@ func TestAPIReposRaw(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") for _, ref := range [...]string{ "master", // Branch From a44f62e262794265dbc7834b8834494ca78b95ff Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 03:32:11 -0400 Subject: [PATCH 040/118] Add repo scope to TestAPIRepoTeams --- tests/integration/api_repo_teams_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/api_repo_teams_test.go b/tests/integration/api_repo_teams_test.go index 1e476a89e232e..511256c893bfb 100644 --- a/tests/integration/api_repo_teams_test.go +++ b/tests/integration/api_repo_teams_test.go @@ -28,7 +28,7 @@ func TestAPIRepoTeams(t *testing.T) { // user4 user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") // ListTeams url := fmt.Sprintf("/api/v1/repos/%s/teams?token=%s", publicOrgRepo.FullName(), token) From 755faf64020264d231573cbf96c5b493b60ead97 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 04:33:55 -0400 Subject: [PATCH 041/118] Fix more integration tests --- tests/integration/api_repo_teams_test.go | 2 +- tests/integration/api_repo_test.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/integration/api_repo_teams_test.go b/tests/integration/api_repo_teams_test.go index 511256c893bfb..f39a06c31aa0b 100644 --- a/tests/integration/api_repo_teams_test.go +++ b/tests/integration/api_repo_teams_test.go @@ -68,7 +68,7 @@ func TestAPIRepoTeams(t *testing.T) { // AddTeam with user2 user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session = loginUser(t, user.Name) - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "repo") url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "team1", token) req = NewRequest(t, "PUT", url) session.MakeRequest(t, req, http.StatusNoContent) diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index 1e5bd0247a429..11084e5c9a8da 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -325,7 +325,7 @@ func TestAPIGetRepoByIDUnauthorized(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "GET", "/api/v1/repositories/2?token="+token) session.MakeRequest(t, req, http.StatusNotFound) } @@ -585,7 +585,7 @@ func TestAPIAcceptTransfer(t *testing.T) { // accept transfer session = loginUser(t, "user4") - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "repo") req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/accept?token=%s", repo.OwnerName, repo.Name, token)) resp := session.MakeRequest(t, req, http.StatusAccepted) From b4c35e82bb21f33eb3105d1c05db919951a57b67 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 04:47:21 -0400 Subject: [PATCH 042/118] Fix typos that causes errors --- routers/api/v1/api.go | 4 ++-- tests/integration/api_repo_test.go | 2 +- tests/integration/api_wiki_test.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 5a312c9cd8caf..1db5b6c95eb1c 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -218,7 +218,7 @@ func reqToken(requiredScope string) func(ctx *context.APIContext) { scope := ctx.Data["ApiTokenScope"].(auth_model.AccessTokenScope) allow, err := scope.HasScope(requiredScope) if err != nil { - ctx.Error(http.StatusUnauthorized, "reqToken", "parsing token failed") + ctx.Error(http.StatusUnauthorized, "reqToken", "parsing token failed: "+err.Error()) return } if !allow { @@ -794,7 +794,7 @@ func Routes(ctx gocontext.Context) *web.Route { }, reqToken("")) // Repositories - m.Post("/org/{org}/repos", reqToken("auth_model.AccessTokenScopeAdminOrg"), bind(api.CreateRepoOption{}), repo.CreateOrgRepoDeprecated) + m.Post("/org/{org}/repos", reqToken(auth_model.AccessTokenScopeAdminOrg), bind(api.CreateRepoOption{}), repo.CreateOrgRepoDeprecated) m.Combo("/repositories/{id}", reqToken(auth_model.AccessTokenScopeRepo)).Get(repo.GetByID) diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index 11084e5c9a8da..9c08f7a1e3f2d 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -446,7 +446,7 @@ func TestAPIOrgRepoCreate(t *testing.T) { for _, testCase := range testCases { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/org/%s/repos?token="+token, testCase.orgName), &api.CreateRepoOption{ Name: testCase.repoName, }) diff --git a/tests/integration/api_wiki_test.go b/tests/integration/api_wiki_test.go index 8378273bf7db3..78c1555ff2cd4 100644 --- a/tests/integration/api_wiki_test.go +++ b/tests/integration/api_wiki_test.go @@ -219,7 +219,7 @@ func TestAPIListPageRevisions(t *testing.T) { session := loginUser(t, username) token := getTokenForLoggedInUser(t, session, "repo") - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/revisions/Home>token=%s", username, "repo1", token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/revisions/Home?token=%s", username, "repo1", token) req := NewRequest(t, "GET", urlStr) resp := session.MakeRequest(t, req, http.StatusOK) From 0ff93b83ecd2fd6989a7c8a769b7b2fc77348e5d Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 05:17:46 -0400 Subject: [PATCH 043/118] Add fixes for delete_repo scope --- tests/integration/git_test.go | 2 +- tests/integration/ssh_key_test.go | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/tests/integration/git_test.go b/tests/integration/git_test.go index 5ee5dedbd4c2a..ff0124abf75d0 100644 --- a/tests/integration/git_test.go +++ b/tests/integration/git_test.go @@ -43,7 +43,7 @@ func TestGit(t *testing.T) { func testGit(t *testing.T, u *url.URL) { username := "user2" - baseAPITestContext := NewAPITestContext(t, username, "repo1", "repo", "write_public_key") + baseAPITestContext := NewAPITestContext(t, username, "repo1", "repo", "write_public_key", "delete_repo") u.Path = baseAPITestContext.GitPath() diff --git a/tests/integration/ssh_key_test.go b/tests/integration/ssh_key_test.go index 7c1d9685891e7..11f8e437e35b1 100644 --- a/tests/integration/ssh_key_test.go +++ b/tests/integration/ssh_key_test.go @@ -49,6 +49,8 @@ func TestPushDeployKeyOnEmptyRepo(t *testing.T) { func testPushDeployKeyOnEmptyRepo(t *testing.T, u *url.URL) { // OK login ctx := NewAPITestContext(t, "user2", "deploy-key-empty-repo-1", "repo") + ctxWithDeleteRepo := NewAPITestContext(t, "user2", "deploy-key-empty-repo-1", "repo", "delete_repo") + keyname := fmt.Sprintf("%s-push", ctx.Reponame) u.Path = ctx.GitPath() @@ -73,7 +75,7 @@ func testPushDeployKeyOnEmptyRepo(t *testing.T, u *url.URL) { t.Run("CheckIsNotEmpty", doCheckRepositoryEmptyStatus(ctx, false)) - t.Run("DeleteRepository", doAPIDeleteRepository(ctx)) + t.Run("DeleteRepository", doAPIDeleteRepository(ctxWithDeleteRepo)) }) } @@ -91,9 +93,12 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) { // OK login ctx := NewAPITestContext(t, username, reponame, "repo", "admin_public_key") + ctxWithDeleteRepo := NewAPITestContext(t, username, reponame, "repo", "admin_public_key", "delete_repo") otherCtx := ctx otherCtx.Reponame = "ssh-key-test-repo-2" + otherCtxWithDeleteRepo := ctxWithDeleteRepo + otherCtxWithDeleteRepo.Reponame = otherCtx.Reponame failCtx := ctx failCtx.ExpectedCode = http.StatusUnprocessableEntity @@ -171,9 +176,9 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) { t.Run("PushToOther", doGitPushTestRepository(dstOtherPath, "origin", "master")) - t.Run("DeleteOtherRepository", doAPIDeleteRepository(otherCtx)) + t.Run("DeleteOtherRepository", doAPIDeleteRepository(otherCtxWithDeleteRepo)) - t.Run("RecreateRepository", doAPICreateRepository(ctx, false)) + t.Run("RecreateRepository", doAPICreateRepository(ctxWithDeleteRepo, false)) t.Run("CreateUserKey", doAPICreateUserKey(ctx, keyname, keyFile, func(t *testing.T, publicKey api.PublicKey) { userKeyPublicKeyID = publicKey.ID From 37c59c9136d8c72a44f6db6e845beddd8758e865 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 15:46:42 -0400 Subject: [PATCH 044/118] There are so many fixes --- tests/integration/api_repo_file_get_test.go | 2 +- tests/integration/api_repo_test.go | 2 +- tests/integration/ssh_key_test.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/integration/api_repo_file_get_test.go b/tests/integration/api_repo_file_get_test.go index 283ad6aecb8ff..e4d351fb91473 100644 --- a/tests/integration/api_repo_file_get_test.go +++ b/tests/integration/api_repo_file_get_test.go @@ -28,7 +28,7 @@ func TestAPIGetRawFileOrLFS(t *testing.T) { // Test with LFS onGiteaRun(t, func(t *testing.T, u *url.URL) { - httpContext := NewAPITestContext(t, "user2", "repo-lfs-test", "repo") + httpContext := NewAPITestContext(t, "user2", "repo-lfs-test", "repo", "delete_repo") doAPICreateRepository(httpContext, false, func(t *testing.T, repository api.Repository) { u.Path = httpContext.GitPath() dstPath := t.TempDir() diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index 9c08f7a1e3f2d..b12b7d9bb42b7 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -446,7 +446,7 @@ func TestAPIOrgRepoCreate(t *testing.T) { for _, testCase := range testCases { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, "admin_org") req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/org/%s/repos?token="+token, testCase.orgName), &api.CreateRepoOption{ Name: testCase.repoName, }) diff --git a/tests/integration/ssh_key_test.go b/tests/integration/ssh_key_test.go index 11f8e437e35b1..43d20c86060ef 100644 --- a/tests/integration/ssh_key_test.go +++ b/tests/integration/ssh_key_test.go @@ -166,7 +166,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) { otherSSHURL := createSSHUrl(otherCtx.GitPath(), u) dstOtherPath := t.TempDir() - t.Run("DeleteRepository", doAPIDeleteRepository(ctx)) + t.Run("DeleteRepository", doAPIDeleteRepository(ctxWithDeleteRepo)) t.Run("FailToCreateUserKeyAsStillDeploy", doAPICreateUserKey(failCtx, keyname, keyFile)) From f13904ade832fa6adafe6e91559c388d23c4b9bf Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 16:26:04 -0400 Subject: [PATCH 045/118] Reuse code in `modules/util` --- models/auth/token_scope.go | 54 +++++++++++++++--------------------- modules/util/compare.go | 22 +++++++++------ modules/util/compare_test.go | 50 +++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+), 39 deletions(-) create mode 100644 modules/util/compare_test.go diff --git a/models/auth/token_scope.go b/models/auth/token_scope.go index f41ba618a167a..467c67d223cf4 100644 --- a/models/auth/token_scope.go +++ b/models/auth/token_scope.go @@ -7,6 +7,8 @@ package auth import ( "fmt" "strings" + + "code.gitea.io/gitea/modules/util" ) // AccessTokenScope represents the scope for an access token. @@ -90,7 +92,7 @@ func (s AccessTokenScope) Parse() (AccessTokenScopeBitmap, error) { continue } - idx := sliceIndex(AllAccessTokenScopes, v) + idx := util.FindStringInSlice(v, AllAccessTokenScopes) if idx < 0 { return 0, fmt.Errorf("invalid access token scope: %s", v) } @@ -99,32 +101,32 @@ func (s AccessTokenScope) Parse() (AccessTokenScopeBitmap, error) { // take care of child scopes switch v { case AccessTokenScopeRepo: - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeRepoStatus)) - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopePublicRepo)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeRepoStatus, AllAccessTokenScopes)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopePublicRepo, AllAccessTokenScopes)) // admin:repo_hook, write:repo_hook, read:repo_hook - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeAdminRepoHook)) - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeWriteRepoHook)) - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeReadRepoHook)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeAdminRepoHook, AllAccessTokenScopes)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeWriteRepoHook, AllAccessTokenScopes)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeReadRepoHook, AllAccessTokenScopes)) case AccessTokenScopeAdminOrg: - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeWriteOrg)) - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeReadOrg)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeWriteOrg, AllAccessTokenScopes)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeReadOrg, AllAccessTokenScopes)) case AccessTokenScopeAdminPublicKey: - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeWritePublicKey)) - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeReadPublicKey)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeWritePublicKey, AllAccessTokenScopes)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeReadPublicKey, AllAccessTokenScopes)) case AccessTokenScopeAdminRepoHook: - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeWriteRepoHook)) - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeReadRepoHook)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeWriteRepoHook, AllAccessTokenScopes)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeReadRepoHook, AllAccessTokenScopes)) case AccessTokenScopeUser: - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeReadUser)) - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeUserEmail)) - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeUserFollow)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeReadUser, AllAccessTokenScopes)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeUserEmail, AllAccessTokenScopes)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeUserFollow, AllAccessTokenScopes)) case AccessTokenScopePackage: - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeWritePackage)) - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeReadPackage)) - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeDeletePackage)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeWritePackage, AllAccessTokenScopes)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeReadPackage, AllAccessTokenScopes)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeDeletePackage, AllAccessTokenScopes)) case AccessTokenScopeAdminGPGKey: - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeWriteGPGKey)) - bitmap |= 1 << uint(sliceIndex(AllAccessTokenScopes, AccessTokenScopeReadGPGKey)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeWriteGPGKey, AllAccessTokenScopes)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeReadGPGKey, AllAccessTokenScopes)) } } return bitmap, nil @@ -142,7 +144,7 @@ func (s AccessTokenScope) Normalize() (AccessTokenScope, error) { // HasScope returns true if the string has the given scope func (s AccessTokenScope) HasScope(scope string) (bool, error) { - index := sliceIndex(AllAccessTokenScopes, scope) + index := util.FindStringInSlice(scope, AllAccessTokenScopes) if index == -1 { return false, fmt.Errorf("invalid access token scope: %s", scope) } @@ -218,13 +220,3 @@ func (bitmap AccessTokenScopeBitmap) ToScope() AccessTokenScope { )) return scope } - -// sliceIndex returns the index of the first instance of str in slice, or -1 if str is not present in slice. -func sliceIndex(slice []string, element string) int { - for i, v := range slice { - if v == element { - return i - } - } - return -1 -} diff --git a/modules/util/compare.go b/modules/util/compare.go index 49891ef02496e..e018b52f74413 100644 --- a/modules/util/compare.go +++ b/modules/util/compare.go @@ -38,26 +38,32 @@ func ExistsInSlice(target string, slice []string) bool { return i < len(slice) } -// IsStringInSlice sequential searches if string exists in slice. -func IsStringInSlice(target string, slice []string, insensitive ...bool) bool { +// FindStringInSlice returns the index of the first instance of target in slice. +// If target is not present in slice, -1 is returned. +func FindStringInSlice(target string, slice []string, insensitive ...bool) int { caseInsensitive := false if len(insensitive) != 0 && insensitive[0] { caseInsensitive = true target = strings.ToLower(target) } - for i := 0; i < len(slice); i++ { + for i, s := range slice { if caseInsensitive { - if strings.ToLower(slice[i]) == target { - return true + if strings.ToLower(s) == target { + return i } } else { - if slice[i] == target { - return true + if s == target { + return i } } } - return false + return -1 +} + +// IsStringInSlice sequential searches if string exists in slice. +func IsStringInSlice(target string, slice []string, insensitive ...bool) bool { + return FindStringInSlice(target, slice, insensitive...) >= 0 } // IsInt64InSlice sequential searches if int64 exists in slice. diff --git a/modules/util/compare_test.go b/modules/util/compare_test.go new file mode 100644 index 0000000000000..98455466a64f1 --- /dev/null +++ b/modules/util/compare_test.go @@ -0,0 +1,50 @@ +package util + +import ( + "strconv" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestFindStringInSlice(t *testing.T) { + tests := []struct { + target string + slice []string + caseInsensitive bool + want int + }{ + {target: "a", slice: []string{"a", "b", "c"}, want: 0}, + {target: "c", slice: []string{"a", "b", "c"}, want: 2}, + {target: "d", slice: []string{"a", "b", "c"}, want: -1}, + {target: "C", slice: []string{"a", "b", "c"}, caseInsensitive: true, want: 2}, + } + + for i, test := range tests { + t.Run(strconv.Itoa(i), func(t *testing.T) { + got := FindStringInSlice(test.target, test.slice, test.caseInsensitive) + assert.Equal(t, test.want, got) + }) + } +} + +func TestIsStringInSlice(t *testing.T) { + tests := []struct { + target string + slice []string + caseInsensitive bool + want bool + }{ + {target: "a", slice: []string{"a", "b", "c"}, want: true}, + {target: "c", slice: []string{"a", "b", "c"}, want: true}, + {target: "d", slice: []string{"a", "b", "c"}, want: false}, + {target: "C", slice: []string{"a", "b", "c"}, caseInsensitive: true, want: true}, + } + + for i, test := range tests { + t.Run(strconv.Itoa(i), func(t *testing.T) { + got := IsStringInSlice(test.target, test.slice, test.caseInsensitive) + assert.Equal(t, test.want, got) + }) + } +} From 7a3b16548598ea8daaaaed33fd9f9b78fb031d5a Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 16:42:13 -0400 Subject: [PATCH 046/118] Include copyright statement --- modules/util/compare_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/modules/util/compare_test.go b/modules/util/compare_test.go index 98455466a64f1..f8972f4da548c 100644 --- a/modules/util/compare_test.go +++ b/modules/util/compare_test.go @@ -1,3 +1,7 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + package util import ( From 62c9f703966bf337a7a540f8dcc69c130213c472 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 16:57:11 -0400 Subject: [PATCH 047/118] Limit repo scope on /api/v1/{user}/{repo}/issues --- routers/api/v1/api.go | 45 +++++++++---------- tests/integration/api_comment_test.go | 25 ++++++----- tests/integration/api_issue_label_test.go | 6 +-- tests/integration/api_issue_reaction_test.go | 4 +- tests/integration/api_issue_stopwatch_test.go | 6 +-- .../api_issue_subscription_test.go | 2 +- tests/integration/api_issue_test.go | 6 +-- .../api_issue_tracked_time_test.go | 6 +-- tests/integration/privateactivity_test.go | 2 +- 9 files changed, 51 insertions(+), 51 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 1db5b6c95eb1c..ef1a48b875471 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -900,40 +900,39 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/pages", repo.ListWikiPages) }, mustEnableWiki, reqToken(auth_model.AccessTokenScopeRepo)) - // TODO: continue here m.Group("/issues", func() { m.Combo("").Get(repo.ListIssues). - Post(reqToken(""), mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue) + Post(mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue) m.Group("/comments", func() { m.Get("", repo.ListRepoIssueComments) m.Group("/{id}", func() { m.Combo(""). Get(repo.GetIssueComment). - Patch(mustNotBeArchived, reqToken(""), bind(api.EditIssueCommentOption{}), repo.EditIssueComment). - Delete(reqToken(""), repo.DeleteIssueComment) + Patch(mustNotBeArchived, bind(api.EditIssueCommentOption{}), repo.EditIssueComment). + Delete(repo.DeleteIssueComment) m.Combo("/reactions"). Get(repo.GetIssueCommentReactions). - Post(reqToken(""), bind(api.EditReactionOption{}), repo.PostIssueCommentReaction). - Delete(reqToken(""), bind(api.EditReactionOption{}), repo.DeleteIssueCommentReaction) + Post(bind(api.EditReactionOption{}), repo.PostIssueCommentReaction). + Delete(bind(api.EditReactionOption{}), repo.DeleteIssueCommentReaction) }) }) m.Group("/{index}", func() { m.Combo("").Get(repo.GetIssue). - Patch(reqToken(""), bind(api.EditIssueOption{}), repo.EditIssue). - Delete(reqToken(""), reqAdmin(), repo.DeleteIssue) + Patch(bind(api.EditIssueOption{}), repo.EditIssue). + Delete(reqAdmin(), repo.DeleteIssue) m.Group("/comments", func() { m.Combo("").Get(repo.ListIssueComments). - Post(reqToken(""), mustNotBeArchived, bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment) + Post(mustNotBeArchived, bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment) m.Combo("/{id}", reqToken("")).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueCommentDeprecated). Delete(repo.DeleteIssueCommentDeprecated) }) m.Get("/timeline", repo.ListIssueCommentsAndTimeline) m.Group("/labels", func() { m.Combo("").Get(repo.ListIssueLabels). - Post(reqToken(""), bind(api.IssueLabelsOption{}), repo.AddIssueLabels). - Put(reqToken(""), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels). - Delete(reqToken(""), repo.ClearIssueLabels) - m.Delete("/{id}", reqToken(""), repo.DeleteIssueLabel) + Post(bind(api.IssueLabelsOption{}), repo.AddIssueLabels). + Put(bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels). + Delete(repo.ClearIssueLabels) + m.Delete("/{id}", repo.DeleteIssueLabel) }) m.Group("/times", func() { m.Combo(""). @@ -942,24 +941,24 @@ func Routes(ctx gocontext.Context) *web.Route { Delete(repo.ResetIssueTime) m.Delete("/{id}", repo.DeleteTime) }, reqToken("")) - m.Combo("/deadline").Post(reqToken(""), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline) + m.Combo("/deadline").Post(bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline) m.Group("/stopwatch", func() { - m.Post("/start", reqToken(""), repo.StartIssueStopwatch) - m.Post("/stop", reqToken(""), repo.StopIssueStopwatch) - m.Delete("/delete", reqToken(""), repo.DeleteIssueStopwatch) + m.Post("/start", repo.StartIssueStopwatch) + m.Post("/stop", repo.StopIssueStopwatch) + m.Delete("/delete", repo.DeleteIssueStopwatch) }) m.Group("/subscriptions", func() { m.Get("", repo.GetIssueSubscribers) - m.Get("/check", reqToken(""), repo.CheckIssueSubscription) - m.Put("/{user}", reqToken(""), repo.AddIssueSubscription) - m.Delete("/{user}", reqToken(""), repo.DelIssueSubscription) + m.Get("/check", repo.CheckIssueSubscription) + m.Put("/{user}", repo.AddIssueSubscription) + m.Delete("/{user}", repo.DelIssueSubscription) }) m.Combo("/reactions"). Get(repo.GetIssueReactions). - Post(reqToken(""), bind(api.EditReactionOption{}), repo.PostIssueReaction). - Delete(reqToken(""), bind(api.EditReactionOption{}), repo.DeleteIssueReaction) + Post(bind(api.EditReactionOption{}), repo.PostIssueReaction). + Delete(bind(api.EditReactionOption{}), repo.DeleteIssueReaction) }) - }, mustEnableIssuesOrPulls) + }, mustEnableIssuesOrPulls, reqToken(auth_model.AccessTokenScopeRepo)) m.Group("/labels", func() { m.Combo("").Get(repo.ListLabels). Post(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateLabelOption{}), repo.CreateLabel) diff --git a/tests/integration/api_comment_test.go b/tests/integration/api_comment_test.go index 126d886842e49..1fe3fb71bad6f 100644 --- a/tests/integration/api_comment_test.go +++ b/tests/integration/api_comment_test.go @@ -31,7 +31,8 @@ func TestAPIListRepoComments(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments", repoOwner.Name, repo.Name)) + token := getTokenForLoggedInUser(t, session, "repo") + link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments?token=%s", repoOwner.Name, repo.Name, token)) req := NewRequest(t, "GET", link.String()) resp := session.MakeRequest(t, req, http.StatusOK) @@ -77,8 +78,9 @@ func TestAPIListIssueComments(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/comments", - repoOwner.Name, repo.Name, issue.Index) + token := getTokenForLoggedInUser(t, session, "repo") + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/comments?token=%s", + repoOwner.Name, repo.Name, issue.Index, token) resp := session.MakeRequest(t, req, http.StatusOK) var comments []*api.Comment @@ -97,7 +99,7 @@ func TestAPICreateComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/comments?token=%s", repoOwner.Name, repo.Name, issue.Index, token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ @@ -120,10 +122,8 @@ func TestAPIGetComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID) - session.MakeRequest(t, req, http.StatusOK) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) + token := getTokenForLoggedInUser(t, session, "repo") + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) resp := session.MakeRequest(t, req, http.StatusOK) var apiComment api.Comment @@ -149,7 +149,7 @@ func TestAPIEditComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ @@ -174,7 +174,7 @@ func TestAPIDeleteComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) session.MakeRequest(t, req, http.StatusNoContent) @@ -192,8 +192,9 @@ func TestAPIListIssueTimeline(t *testing.T) { // make request session := loginUser(t, repoOwner.Name) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/timeline", - repoOwner.Name, repo.Name, issue.Index) + token := getTokenForLoggedInUser(t, session, "repo") + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/timeline?token=%s", + repoOwner.Name, repo.Name, issue.Index, token) resp := session.MakeRequest(t, req, http.StatusOK) // check if lens of list returned by API and diff --git a/tests/integration/api_issue_label_test.go b/tests/integration/api_issue_label_test.go index 586c50a55f17a..210d4804aba47 100644 --- a/tests/integration/api_issue_label_test.go +++ b/tests/integration/api_issue_label_test.go @@ -97,7 +97,7 @@ func TestAPIAddIssueLabels(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels?token=%s", repo.OwnerName, repo.Name, issue.Index, token) req := NewRequestWithJSON(t, "POST", urlStr, &api.IssueLabelsOption{ @@ -120,7 +120,7 @@ func TestAPIReplaceIssueLabels(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels?token=%s", owner.Name, repo.Name, issue.Index, token) req := NewRequestWithJSON(t, "PUT", urlStr, &api.IssueLabelsOption{ @@ -144,7 +144,7 @@ func TestAPIModifyOrgLabels(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) user := "user1" session := loginUser(t, user) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") urlStr := fmt.Sprintf("/api/v1/orgs/%s/labels?token=%s", owner.Name, token) // CreateLabel diff --git a/tests/integration/api_issue_reaction_test.go b/tests/integration/api_issue_reaction_test.go index a3cb9303fbcf9..30f9d08df3cf8 100644 --- a/tests/integration/api_issue_reaction_test.go +++ b/tests/integration/api_issue_reaction_test.go @@ -29,7 +29,7 @@ func TestAPIIssuesReactions(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue.Repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/reactions?token=%s", @@ -88,7 +88,7 @@ func TestAPICommentReactions(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue.Repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) diff --git a/tests/integration/api_issue_stopwatch_test.go b/tests/integration/api_issue_stopwatch_test.go index bb40b016c2611..5d2e6cdd434f0 100644 --- a/tests/integration/api_issue_stopwatch_test.go +++ b/tests/integration/api_issue_stopwatch_test.go @@ -52,7 +52,7 @@ func TestAPIStopStopWatches(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/issues/%d/stopwatch/stop?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) session.MakeRequest(t, req, http.StatusCreated) @@ -68,7 +68,7 @@ func TestAPICancelStopWatches(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/stopwatch/delete?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) session.MakeRequest(t, req, http.StatusNoContent) @@ -84,7 +84,7 @@ func TestAPIStartStopWatches(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/issues/%d/stopwatch/start?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) session.MakeRequest(t, req, http.StatusCreated) diff --git a/tests/integration/api_issue_subscription_test.go b/tests/integration/api_issue_subscription_test.go index f4588fbbc42c2..60256f63a9fe3 100644 --- a/tests/integration/api_issue_subscription_test.go +++ b/tests/integration/api_issue_subscription_test.go @@ -31,7 +31,7 @@ func TestAPIIssueSubscriptions(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue1.PosterID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") testSubscription := func(issue *issues_model.Issue, isWatching bool) { issueRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}) diff --git a/tests/integration/api_issue_test.go b/tests/integration/api_issue_test.go index 3e651c620b04f..16293f35ff272 100644 --- a/tests/integration/api_issue_test.go +++ b/tests/integration/api_issue_test.go @@ -30,7 +30,7 @@ func TestAPIListIssues(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/issues", owner.Name, repo.Name)) link.RawQuery = url.Values{"token": {token}, "state": {"all"}}.Encode() @@ -81,7 +81,7 @@ func TestAPICreateIssue(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all&token=%s", owner.Name, repoBefore.Name, token) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateIssueOption{ Body: body, @@ -117,7 +117,7 @@ func TestAPIEditIssue(t *testing.T) { assert.Equal(t, api.StateOpen, issueBefore.State()) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") // update values of issue issueState := "closed" diff --git a/tests/integration/api_issue_tracked_time_test.go b/tests/integration/api_issue_tracked_time_test.go index 6e2c77030cb7d..fdb604c754075 100644 --- a/tests/integration/api_issue_tracked_time_test.go +++ b/tests/integration/api_issue_tracked_time_test.go @@ -28,7 +28,7 @@ func TestAPIGetTrackedTimes(t *testing.T) { assert.NoError(t, issue2.LoadRepo(db.DefaultContext)) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/times?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, token) resp := session.MakeRequest(t, req, http.StatusOK) @@ -71,7 +71,7 @@ func TestAPIDeleteTrackedTime(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") // Deletion not allowed req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time6.ID, token) @@ -106,7 +106,7 @@ func TestAPIAddTrackedTimes(t *testing.T) { admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, admin.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/times?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, token) diff --git a/tests/integration/privateactivity_test.go b/tests/integration/privateactivity_test.go index 3f352e49c6187..b29418ef95bfa 100644 --- a/tests/integration/privateactivity_test.go +++ b/tests/integration/privateactivity_test.go @@ -34,7 +34,7 @@ func testPrivateActivityDoSomethingForActionEntries(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}) session := loginUser(t, privateActivityTestUser) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all&token=%s", owner.Name, repoBefore.Name, token) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateIssueOption{ Body: "test", From 15ed960dc511d751edba0677cc031eaf70613ccf Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 17:22:09 -0400 Subject: [PATCH 048/118] Fix several integration tests --- tests/integration/api_comment_test.go | 1 + tests/integration/dump_restore_test.go | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/integration/api_comment_test.go b/tests/integration/api_comment_test.go index 1fe3fb71bad6f..1573c2e5495f5 100644 --- a/tests/integration/api_comment_test.go +++ b/tests/integration/api_comment_test.go @@ -51,6 +51,7 @@ func TestAPIListRepoComments(t *testing.T) { before := "2000-01-01T00:00:11+00:00" // unix: 946684811 since := "2000-01-01T00:00:12+00:00" // unix: 946684812 query.Add("before", before) + query.Add("token", token) link.RawQuery = query.Encode() req = NewRequest(t, "GET", link.String()) resp = session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/dump_restore_test.go b/tests/integration/dump_restore_test.go index 19513d0271e17..9004a65d426a9 100644 --- a/tests/integration/dump_restore_test.go +++ b/tests/integration/dump_restore_test.go @@ -51,7 +51,7 @@ func TestDumpRestore(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") // // Phase 1: dump repo1 from the Gitea instance to the filesystem From 11a51038aded9aef63dd301dd242dc0af1728067 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 17:43:08 -0400 Subject: [PATCH 049/118] Include repo scope in TestMigrateGiteaForm --- tests/integration/migrate_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/migrate_test.go b/tests/integration/migrate_test.go index 99d5d6c8dd239..7b2412cabd042 100644 --- a/tests/integration/migrate_test.go +++ b/tests/integration/migrate_test.go @@ -67,7 +67,7 @@ func TestMigrateGiteaForm(t *testing.T) { repoName := "repo1" repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: ownerName}) session := loginUser(t, ownerName) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") // Step 0: verify the repo is available req := NewRequestf(t, "GET", fmt.Sprintf("/%s/%s", ownerName, repoName)) From d6d6d975207786b85923d91422f75eb15c7c1be8 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 19:09:50 -0400 Subject: [PATCH 050/118] Apply repo scope to more APIs --- routers/api/v1/api.go | 42 +++++++++---------- tests/integration/api_issue_label_test.go | 2 +- tests/integration/api_issue_milestone_test.go | 2 +- tests/integration/api_releases_test.go | 8 ++-- tests/integration/api_repo_test.go | 2 +- tests/integration/api_user_watch_test.go | 8 ++-- 6 files changed, 32 insertions(+), 32 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index ef1a48b875471..fd5143c0d9fe8 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -899,7 +899,6 @@ func Routes(ctx gocontext.Context) *web.Route { m.Post("/new", mustNotBeArchived, reqRepoWriter(unit.TypeWiki), bind(api.CreateWikiPageOptions{}), repo.NewWikiPage) m.Get("/pages", repo.ListWikiPages) }, mustEnableWiki, reqToken(auth_model.AccessTokenScopeRepo)) - m.Group("/issues", func() { m.Combo("").Get(repo.ListIssues). Post(mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue) @@ -961,58 +960,59 @@ func Routes(ctx gocontext.Context) *web.Route { }, mustEnableIssuesOrPulls, reqToken(auth_model.AccessTokenScopeRepo)) m.Group("/labels", func() { m.Combo("").Get(repo.ListLabels). - Post(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateLabelOption{}), repo.CreateLabel) + Post(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateLabelOption{}), repo.CreateLabel) m.Combo("/{id}").Get(repo.GetLabel). - Patch(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditLabelOption{}), repo.EditLabel). - Delete(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteLabel) + Patch(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditLabelOption{}), repo.EditLabel). + Delete(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteLabel) }) - m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown) - m.Post("/markdown/raw", misc.MarkdownRaw) + m.Post("/markdown", reqToken(auth_model.AccessTokenScopeRepo), bind(api.MarkdownOption{}), misc.Markdown) + m.Post("/markdown/raw", reqToken(auth_model.AccessTokenScopeRepo), misc.MarkdownRaw) m.Group("/milestones", func() { m.Combo("").Get(repo.ListMilestones). - Post(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateMilestoneOption{}), repo.CreateMilestone) + Post(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateMilestoneOption{}), repo.CreateMilestone) m.Combo("/{id}").Get(repo.GetMilestone). - Patch(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditMilestoneOption{}), repo.EditMilestone). - Delete(reqToken(""), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteMilestone) + Patch(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditMilestoneOption{}), repo.EditMilestone). + Delete(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteMilestone) }) m.Get("/stargazers", repo.ListStargazers) m.Get("/subscribers", repo.ListSubscribers) m.Group("/subscription", func() { m.Get("", user.IsWatching) - m.Put("", reqToken(""), user.Watch) - m.Delete("", reqToken(""), user.Unwatch) + m.Put("", reqToken(auth_model.AccessTokenScopeRepo), user.Watch) + m.Delete("", reqToken(auth_model.AccessTokenScopeRepo), user.Unwatch) }) m.Group("/releases", func() { m.Combo("").Get(repo.ListReleases). - Post(reqToken(""), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.CreateReleaseOption{}), repo.CreateRelease) + Post(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.CreateReleaseOption{}), repo.CreateRelease) m.Group("/{id}", func() { m.Combo("").Get(repo.GetRelease). - Patch(reqToken(""), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.EditReleaseOption{}), repo.EditRelease). - Delete(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.DeleteRelease) + Patch(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.EditReleaseOption{}), repo.EditRelease). + Delete(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeReleases), repo.DeleteRelease) m.Group("/assets", func() { m.Combo("").Get(repo.ListReleaseAttachments). - Post(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.CreateReleaseAttachment) + Post(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeReleases), repo.CreateReleaseAttachment) m.Combo("/{asset}").Get(repo.GetReleaseAttachment). - Patch(reqToken(""), reqRepoWriter(unit.TypeReleases), bind(api.EditAttachmentOptions{}), repo.EditReleaseAttachment). - Delete(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseAttachment) + Patch(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeReleases), bind(api.EditAttachmentOptions{}), repo.EditReleaseAttachment). + Delete(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseAttachment) }) }) m.Group("/tags", func() { m.Combo("/{tag}"). Get(repo.GetReleaseByTag). - Delete(reqToken(""), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseByTag) + Delete(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeReleases), repo.DeleteReleaseByTag) }) }, reqRepoReader(unit.TypeReleases)) - m.Post("/mirror-sync", reqToken(""), reqRepoWriter(unit.TypeCode), repo.MirrorSync) - m.Post("/push_mirrors-sync", reqAdmin(), repo.PushMirrorSync) + m.Post("/mirror-sync", reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeCode), repo.MirrorSync) + m.Post("/push_mirrors-sync", reqAdmin(), reqToken(auth_model.AccessTokenScopeRepo), repo.PushMirrorSync) m.Group("/push_mirrors", func() { m.Combo("").Get(repo.ListPushMirrors). Post(bind(api.CreatePushMirrorOption{}), repo.AddPushMirror) m.Combo("/{name}"). Delete(repo.DeletePushMirrorByRemoteName). Get(repo.GetPushMirrorByName) - }, reqAdmin()) + }, reqAdmin(), reqToken(auth_model.AccessTokenScopeRepo)) + // TODO: continue here m.Get("/editorconfig/{filename}", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetEditorconfig) m.Group("/pulls", func() { m.Combo("").Get(repo.ListPullRequests). diff --git a/tests/integration/api_issue_label_test.go b/tests/integration/api_issue_label_test.go index 210d4804aba47..378ed7381771c 100644 --- a/tests/integration/api_issue_label_test.go +++ b/tests/integration/api_issue_label_test.go @@ -25,7 +25,7 @@ func TestAPIModifyLabels(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels?token=%s", owner.Name, repo.Name, token) // CreateLabel diff --git a/tests/integration/api_issue_milestone_test.go b/tests/integration/api_issue_milestone_test.go index e22a091bb8d16..949a99b5460f0 100644 --- a/tests/integration/api_issue_milestone_test.go +++ b/tests/integration/api_issue_milestone_test.go @@ -29,7 +29,7 @@ func TestAPIIssuesMilestone(t *testing.T) { assert.Equal(t, structs.StateOpen, milestone.State()) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") // update values of issue milestoneState := "closed" diff --git a/tests/integration/api_releases_test.go b/tests/integration/api_releases_test.go index 11aba531c4ed4..10a52a1b295b0 100644 --- a/tests/integration/api_releases_test.go +++ b/tests/integration/api_releases_test.go @@ -25,7 +25,7 @@ func TestAPIListReleases(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - token := getUserToken(t, user2.LowerName) + token := getUserToken(t, user2.LowerName, "repo") link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/releases", user2.Name, repo.Name)) link.RawQuery = url.Values{"token": {token}}.Encode() @@ -101,7 +101,7 @@ func TestAPICreateAndUpdateRelease(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") gitRepo, err := git.OpenRepository(git.DefaultContext, repo.RepoPath()) assert.NoError(t, err) @@ -153,7 +153,7 @@ func TestAPICreateReleaseToDefaultBranch(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") createNewReleaseUsingAPI(t, session, token, owner, repo, "v0.0.1", "", "v0.0.1", "test") } @@ -164,7 +164,7 @@ func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") gitRepo, err := git.OpenRepository(git.DefaultContext, repo.RepoPath()) assert.NoError(t, err) diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index b12b7d9bb42b7..a71c26926e34f 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -414,7 +414,7 @@ func TestAPIMirrorSyncNonMirrorRepo(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") var repo api.Repository req := NewRequest(t, "GET", "/api/v1/repos/user2/repo1") diff --git a/tests/integration/api_user_watch_test.go b/tests/integration/api_user_watch_test.go index 94941c1274f0d..36c0f8030a3d0 100644 --- a/tests/integration/api_user_watch_test.go +++ b/tests/integration/api_user_watch_test.go @@ -28,7 +28,7 @@ func TestAPIWatch(t *testing.T) { t.Run("Watch", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/subscription?token=%s", repo, token)) + req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/subscription?token=%s", repo, tokenWithRepoScope)) MakeRequest(t, req, http.StatusOK) }) @@ -63,17 +63,17 @@ func TestAPIWatch(t *testing.T) { t.Run("IsWatching", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/subscription?token=%s", repo, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/subscription?token=%s", repo, tokenWithRepoScope)) MakeRequest(t, req, http.StatusOK) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/subscription?token=%s", repo+"notexisting", token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/subscription?token=%s", repo+"notexisting", tokenWithRepoScope)) MakeRequest(t, req, http.StatusNotFound) }) t.Run("Unwatch", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/subscription?token=%s", repo, token)) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/subscription?token=%s", repo, tokenWithRepoScope)) MakeRequest(t, req, http.StatusNoContent) }) } From 0a8ab09258282589b588fcf7ee90c0f6bc16086c Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 21:54:55 -0400 Subject: [PATCH 051/118] Restrict repo scope to remaining repos endpoints --- routers/api/v1/api.go | 39 +++++++++---------- tests/integration/api_pull_review_test.go | 6 +-- tests/integration/api_pull_test.go | 12 +++--- .../integration/api_repo_file_create_test.go | 4 +- .../integration/api_repo_file_delete_test.go | 4 +- .../integration/api_repo_file_update_test.go | 4 +- tests/integration/api_repo_topic_test.go | 4 +- tests/integration/git_test.go | 4 +- tests/integration/gpg_git_test.go | 8 ++-- tests/integration/pull_merge_test.go | 4 +- tests/integration/pull_status_test.go | 2 +- tests/integration/pull_update_test.go | 4 +- tests/integration/repo_commits_test.go | 3 +- 13 files changed, 49 insertions(+), 49 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index fd5143c0d9fe8..12f9d2574286c 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -1012,44 +1012,43 @@ func Routes(ctx gocontext.Context) *web.Route { Get(repo.GetPushMirrorByName) }, reqAdmin(), reqToken(auth_model.AccessTokenScopeRepo)) - // TODO: continue here m.Get("/editorconfig/{filename}", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetEditorconfig) m.Group("/pulls", func() { m.Combo("").Get(repo.ListPullRequests). - Post(reqToken(""), mustNotBeArchived, bind(api.CreatePullRequestOption{}), repo.CreatePullRequest) + Post(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, bind(api.CreatePullRequestOption{}), repo.CreatePullRequest) m.Group("/{index}", func() { m.Combo("").Get(repo.GetPullRequest). - Patch(reqToken(""), bind(api.EditPullRequestOption{}), repo.EditPullRequest) + Patch(reqToken(auth_model.AccessTokenScopeRepo), bind(api.EditPullRequestOption{}), repo.EditPullRequest) m.Get(".{diffType:diff|patch}", repo.DownloadPullDiffOrPatch) - m.Post("/update", reqToken(""), repo.UpdatePullRequest) + m.Post("/update", reqToken(auth_model.AccessTokenScopeRepo), repo.UpdatePullRequest) m.Get("/commits", repo.GetPullRequestCommits) m.Get("/files", repo.GetPullRequestFiles) m.Combo("/merge").Get(repo.IsPullRequestMerged). - Post(reqToken(""), mustNotBeArchived, bind(forms.MergePullRequestForm{}), repo.MergePullRequest). - Delete(reqToken(""), mustNotBeArchived, repo.CancelScheduledAutoMerge) + Post(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, bind(forms.MergePullRequestForm{}), repo.MergePullRequest). + Delete(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, repo.CancelScheduledAutoMerge) m.Group("/reviews", func() { m.Combo(""). Get(repo.ListPullReviews). - Post(reqToken(""), bind(api.CreatePullReviewOptions{}), repo.CreatePullReview) + Post(reqToken(auth_model.AccessTokenScopeRepo), bind(api.CreatePullReviewOptions{}), repo.CreatePullReview) m.Group("/{id}", func() { m.Combo(""). Get(repo.GetPullReview). - Delete(reqToken(""), repo.DeletePullReview). - Post(reqToken(""), bind(api.SubmitPullReviewOptions{}), repo.SubmitPullReview) + Delete(reqToken(auth_model.AccessTokenScopeRepo), repo.DeletePullReview). + Post(reqToken(auth_model.AccessTokenScopeRepo), bind(api.SubmitPullReviewOptions{}), repo.SubmitPullReview) m.Combo("/comments"). Get(repo.GetPullReviewComments) - m.Post("/dismissals", reqToken(""), bind(api.DismissPullReviewOptions{}), repo.DismissPullReview) - m.Post("/undismissals", reqToken(""), repo.UnDismissPullReview) + m.Post("/dismissals", reqToken(auth_model.AccessTokenScopeRepo), bind(api.DismissPullReviewOptions{}), repo.DismissPullReview) + m.Post("/undismissals", reqToken(auth_model.AccessTokenScopeRepo), repo.UnDismissPullReview) }) }) - m.Combo("/requested_reviewers"). - Delete(reqToken(""), bind(api.PullReviewRequestOptions{}), repo.DeleteReviewRequests). - Post(reqToken(""), bind(api.PullReviewRequestOptions{}), repo.CreateReviewRequests) + m.Combo("/requested_reviewers", reqToken(auth_model.AccessTokenScopeRepo)). + Delete(bind(api.PullReviewRequestOptions{}), repo.DeleteReviewRequests). + Post(bind(api.PullReviewRequestOptions{}), repo.CreateReviewRequests) }) }, mustAllowPulls, reqRepoReader(unit.TypeCode), context.ReferencesGitRepo()) m.Group("/statuses", func() { m.Combo("/{sha}").Get(repo.GetCommitStatuses). - Post(reqToken(""), reqRepoWriter(unit.TypeCode), bind(api.CreateStatusOption{}), repo.NewCommitStatus) + Post(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeCode), bind(api.CreateStatusOption{}), repo.NewCommitStatus) }, reqRepoReader(unit.TypeCode)) m.Group("/commits", func() { m.Get("", context.ReferencesGitRepo(), repo.GetAllCommits) @@ -1070,7 +1069,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Get("/tags/{sha}", repo.GetAnnotatedTag) m.Get("/notes/{sha}", repo.GetNote) }, context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode)) - m.Post("/diffpatch", reqRepoWriter(unit.TypeCode), reqToken(""), bind(api.ApplyDiffPatchFileOptions{}), repo.ApplyDiffPatch) + m.Post("/diffpatch", reqRepoWriter(unit.TypeCode), reqToken(auth_model.AccessTokenScopeRepo), bind(api.ApplyDiffPatchFileOptions{}), repo.ApplyDiffPatch) m.Group("/contents", func() { m.Get("", repo.GetContentsList) m.Get("/*", repo.GetContents) @@ -1078,15 +1077,15 @@ func Routes(ctx gocontext.Context) *web.Route { m.Post("", bind(api.CreateFileOptions{}), reqRepoBranchWriter, repo.CreateFile) m.Put("", bind(api.UpdateFileOptions{}), reqRepoBranchWriter, repo.UpdateFile) m.Delete("", bind(api.DeleteFileOptions{}), reqRepoBranchWriter, repo.DeleteFile) - }, reqToken("")) + }, reqToken(auth_model.AccessTokenScopeRepo)) }, reqRepoReader(unit.TypeCode)) m.Get("/signing-key.gpg", misc.SigningKey) m.Group("/topics", func() { m.Combo("").Get(repo.ListTopics). - Put(reqToken(""), reqAdmin(), bind(api.RepoTopicOptions{}), repo.UpdateTopics) + Put(reqToken(auth_model.AccessTokenScopeRepo), reqAdmin(), bind(api.RepoTopicOptions{}), repo.UpdateTopics) m.Group("/{topic}", func() { - m.Combo("").Put(reqToken(""), repo.AddTopic). - Delete(reqToken(""), repo.DeleteTopic) + m.Combo("").Put(reqToken(auth_model.AccessTokenScopeRepo), repo.AddTopic). + Delete(reqToken(auth_model.AccessTokenScopeRepo), repo.DeleteTopic) }, reqAdmin()) }, reqAnyRepoReader()) m.Get("/issue_templates", context.ReferencesGitRepo(), repo.GetIssueTemplates) diff --git a/tests/integration/api_pull_review_test.go b/tests/integration/api_pull_review_test.go index 6ebad106fb311..dc4f2d3d97ff5 100644 --- a/tests/integration/api_pull_review_test.go +++ b/tests/integration/api_pull_review_test.go @@ -28,7 +28,7 @@ func TestAPIPullReview(t *testing.T) { // test ListPullReviews session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token) resp := session.MakeRequest(t, req, http.StatusOK) @@ -231,7 +231,7 @@ func TestAPIPullReviewRequest(t *testing.T) { // Test add Review Request session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.PullReviewRequestOptions{ Reviewers: []string{"user4@example.com", "user8"}, }) @@ -251,7 +251,7 @@ func TestAPIPullReviewRequest(t *testing.T) { // Test Remove Review Request session2 := loginUser(t, "user4") - token2 := getTokenForLoggedInUser(t, session2) + token2 := getTokenForLoggedInUser(t, session2, "repo") req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token2), &api.PullReviewRequestOptions{ Reviewers: []string{"user4"}, diff --git a/tests/integration/api_pull_test.go b/tests/integration/api_pull_test.go index 8ce92f3d4a622..68625f56c34f5 100644 --- a/tests/integration/api_pull_test.go +++ b/tests/integration/api_pull_test.go @@ -28,7 +28,7 @@ func TestAPIViewPulls(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) - ctx := NewAPITestContext(t, "user2", repo.Name) + ctx := NewAPITestContext(t, "user2", repo.Name, "repo") req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/pulls?state=all&token="+ctx.Token, owner.Name, repo.Name) resp := ctx.Session.MakeRequest(t, req, http.StatusOK) @@ -74,7 +74,7 @@ func TestAPIMergePullWIP(t *testing.T) { assert.Contains(t, pr.Issue.Title, setting.Repository.PullRequest.WorkInProgressPrefixes[0]) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", owner.Name, repo.Name, pr.Index, token), &forms.MergePullRequestForm{ MergeMessageField: pr.Issue.Title, Do: string(repo_model.MergeStyleMerge), @@ -93,7 +93,7 @@ func TestAPICreatePullSuccess(t *testing.T) { owner11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo11.OwnerID}) session := loginUser(t, owner11.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", owner10.Name, repo10.Name, token), &api.CreatePullRequestOption{ Head: fmt.Sprintf("%s:master", owner11.Name), Base: "master", @@ -113,7 +113,7 @@ func TestAPICreatePullWithFieldsSuccess(t *testing.T) { owner11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo11.OwnerID}) session := loginUser(t, owner11.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") opts := &api.CreatePullRequestOption{ Head: fmt.Sprintf("%s:master", owner11.Name), @@ -150,7 +150,7 @@ func TestAPICreatePullWithFieldsFailure(t *testing.T) { owner11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo11.OwnerID}) session := loginUser(t, owner11.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") opts := &api.CreatePullRequestOption{ Head: fmt.Sprintf("%s:master", owner11.Name), @@ -180,7 +180,7 @@ func TestAPIEditPull(t *testing.T) { owner10 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo10.OwnerID}) session := loginUser(t, owner10.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", owner10.Name, repo10.Name, token), &api.CreatePullRequestOption{ Head: "develop", Base: "master", diff --git a/tests/integration/api_repo_file_create_test.go b/tests/integration/api_repo_file_create_test.go index ec43b938e86b3..6810526a64a4d 100644 --- a/tests/integration/api_repo_file_create_test.go +++ b/tests/integration/api_repo_file_create_test.go @@ -151,10 +151,10 @@ func TestAPICreateFile(t *testing.T) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session) + token2 := getTokenForLoggedInUser(t, session, "repo") // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session) + token4 := getTokenForLoggedInUser(t, session, "repo") session = emptyTestSession(t) // Test creating a file in repo1 which user2 owns, try both with branch and empty branch diff --git a/tests/integration/api_repo_file_delete_test.go b/tests/integration/api_repo_file_delete_test.go index 2c8b1e381f7c5..9a548c652c983 100644 --- a/tests/integration/api_repo_file_delete_test.go +++ b/tests/integration/api_repo_file_delete_test.go @@ -49,10 +49,10 @@ func TestAPIDeleteFile(t *testing.T) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session) + token2 := getTokenForLoggedInUser(t, session, "repo") // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session) + token4 := getTokenForLoggedInUser(t, session, "repo") session = emptyTestSession(t) // Test deleting a file in repo1 which user2 owns, try both with branch and empty branch diff --git a/tests/integration/api_repo_file_update_test.go b/tests/integration/api_repo_file_update_test.go index a3be67ad844f4..910410b5fd60d 100644 --- a/tests/integration/api_repo_file_update_test.go +++ b/tests/integration/api_repo_file_update_test.go @@ -117,10 +117,10 @@ func TestAPIUpdateFile(t *testing.T) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session) + token2 := getTokenForLoggedInUser(t, session, "repo") // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session) + token4 := getTokenForLoggedInUser(t, session, "repo") session = emptyTestSession(t) // Test updating a file in repo1 which user2 owns, try both with branch and empty branch diff --git a/tests/integration/api_repo_topic_test.go b/tests/integration/api_repo_topic_test.go index 4e1e293890686..bd789e49a1ebb 100644 --- a/tests/integration/api_repo_topic_test.go +++ b/tests/integration/api_repo_topic_test.go @@ -60,7 +60,7 @@ func TestAPIRepoTopic(t *testing.T) { repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) // Get user2's token - token2 := getUserToken(t, user2.Name) + token2 := getUserToken(t, user2.Name, "repo") // Test read topics using login url := fmt.Sprintf("/api/v1/repos/%s/%s/topics", user2.Name, repo2.Name) @@ -140,7 +140,7 @@ func TestAPIRepoTopic(t *testing.T) { MakeRequest(t, req, http.StatusNotFound) // Get user4's token - token4 := getUserToken(t, user4.Name) + token4 := getUserToken(t, user4.Name, "repo") // Test read topics with write access url = fmt.Sprintf("/api/v1/repos/%s/%s/topics?token=%s", user3.Name, repo3.Name, token4) diff --git a/tests/integration/git_test.go b/tests/integration/git_test.go index ff0124abf75d0..73fe63a3cea10 100644 --- a/tests/integration/git_test.go +++ b/tests/integration/git_test.go @@ -358,7 +358,7 @@ func doBranchProtectPRMerge(baseCtx *APITestContext, dstPath string) func(t *tes t.Run("CreateBranchProtected", doGitCreateBranch(dstPath, "protected")) t.Run("PushProtectedBranch", doGitPushTestRepository(dstPath, "origin", "protected")) - ctx := NewAPITestContext(t, baseCtx.Username, baseCtx.Reponame) + ctx := NewAPITestContext(t, baseCtx.Username, baseCtx.Reponame, "repo") t.Run("ProtectProtectedBranchNoWhitelist", doProtectBranch(ctx, "protected", "", "")) t.Run("GenerateCommit", func(t *testing.T) { _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-") @@ -602,7 +602,7 @@ func doAutoPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) { return func(t *testing.T) { defer tests.PrintCurrentTest(t)() - ctx := NewAPITestContext(t, baseCtx.Username, baseCtx.Reponame) + ctx := NewAPITestContext(t, baseCtx.Username, baseCtx.Reponame, "repo") t.Run("CheckoutProtected", doGitCheckoutBranch(dstPath, "protected")) t.Run("PullProtected", doGitPull(dstPath, "origin", "protected")) diff --git a/tests/integration/gpg_git_test.go b/tests/integration/gpg_git_test.go index 608d1958a41c2..4a224bf881421 100644 --- a/tests/integration/gpg_git_test.go +++ b/tests/integration/gpg_git_test.go @@ -94,7 +94,7 @@ func TestGPGGit(t *testing.T) { t.Run("Unsigned-Initial-CRUD-ParentSigned", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-unsigned") + testCtx := NewAPITestContext(t, username, "initial-unsigned", "repo") t.Run("CreateCRUDFile-ParentSigned", crudActionCreateFile( t, testCtx, user, "master", "parentsigned", "signed-parent.txt", func(t *testing.T, response api.FileResponse) { assert.False(t, response.Verification.Verified) @@ -111,7 +111,7 @@ func TestGPGGit(t *testing.T) { t.Run("Unsigned-Initial-CRUD-Never", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-unsigned") + testCtx := NewAPITestContext(t, username, "initial-unsigned", "repo") t.Run("CreateCRUDFile-Never", crudActionCreateFile( t, testCtx, user, "parentsigned", "parentsigned-never", "unsigned-never2.txt", func(t *testing.T, response api.FileResponse) { assert.False(t, response.Verification.Verified) @@ -124,7 +124,7 @@ func TestGPGGit(t *testing.T) { t.Run("Unsigned-Initial-CRUD-Always", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-unsigned") + testCtx := NewAPITestContext(t, username, "initial-unsigned", "repo") t.Run("CreateCRUDFile-Always", crudActionCreateFile( t, testCtx, user, "master", "always", "signed-always.txt", func(t *testing.T, response api.FileResponse) { assert.NotNil(t, response.Verification) @@ -161,7 +161,7 @@ func TestGPGGit(t *testing.T) { t.Run("Unsigned-Initial-CRUD-ParentSigned", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-unsigned") + testCtx := NewAPITestContext(t, username, "initial-unsigned", "repo") t.Run("CreateCRUDFile-Always-ParentSigned", crudActionCreateFile( t, testCtx, user, "always", "always-parentsigned", "signed-always-parentsigned.txt", func(t *testing.T, response api.FileResponse) { assert.NotNil(t, response.Verification) diff --git a/tests/integration/pull_merge_test.go b/tests/integration/pull_merge_test.go index 9bd430084dcc8..bcb09728b6c38 100644 --- a/tests/integration/pull_merge_test.go +++ b/tests/integration/pull_merge_test.go @@ -218,7 +218,7 @@ func TestCantMergeConflict(t *testing.T) { testEditFileToNewBranch(t, session, "user1", "repo1", "master", "base", "README.md", "Hello, World (Edited Twice)\n") // Use API to create a conflicting pr - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", "user1", "repo1", token), &api.CreatePullRequestOption{ Head: "conflict", Base: "base", @@ -326,7 +326,7 @@ func TestCantMergeUnrelated(t *testing.T) { testEditFileToNewBranch(t, session, "user1", "repo1", "master", "conflict", "README.md", "Hello, World (Edited Once)\n") // Use API to create a conflicting pr - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", "user1", "repo1", token), &api.CreatePullRequestOption{ Head: "unrelated", Base: "base", diff --git a/tests/integration/pull_status_test.go b/tests/integration/pull_status_test.go index 381cc73cd19b8..cb34b188db607 100644 --- a/tests/integration/pull_status_test.go +++ b/tests/integration/pull_status_test.go @@ -63,7 +63,7 @@ func TestPullCreate_CommitStatus(t *testing.T) { api.CommitStatusWarning: "gitea-exclamation", } - testCtx := NewAPITestContext(t, "user1", "repo1") + testCtx := NewAPITestContext(t, "user1", "repo1", "repo") // Update commit status, and check if icon is updated as well for _, status := range statusList { diff --git a/tests/integration/pull_update_test.go b/tests/integration/pull_update_test.go index c08faaaeb6f4e..4c869c3dc2e4e 100644 --- a/tests/integration/pull_update_test.go +++ b/tests/integration/pull_update_test.go @@ -39,7 +39,7 @@ func TestAPIPullUpdate(t *testing.T) { assert.NoError(t, pr.LoadIssue()) session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index) session.MakeRequest(t, req, http.StatusOK) @@ -67,7 +67,7 @@ func TestAPIPullUpdateByRebase(t *testing.T) { assert.NoError(t, pr.LoadIssue()) session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "repo") req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase&token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index) session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/repo_commits_test.go b/tests/integration/repo_commits_test.go index c9e77535962b4..dfcf5bf17ddd5 100644 --- a/tests/integration/repo_commits_test.go +++ b/tests/integration/repo_commits_test.go @@ -49,7 +49,8 @@ func doTestRepoCommitWithStatus(t *testing.T, state string, classes ...string) { assert.NotEmpty(t, commitURL) // Call API to add status for commit - t.Run("CreateStatus", doAPICreateCommitStatus(NewAPITestContext(t, "user2", "repo1"), path.Base(commitURL), api.CommitStatusState(state))) + ctx := NewAPITestContext(t, "user2", "repo1", "repo") + t.Run("CreateStatus", doAPICreateCommitStatus(ctx, path.Base(commitURL), api.CommitStatusState(state))) req = NewRequest(t, "GET", "/user2/repo1/commits/branch/master") resp = session.MakeRequest(t, req, http.StatusOK) From f45bfe3b4dc5f2fc748f40d20b1cc58ac227fc56 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 22:33:14 -0400 Subject: [PATCH 052/118] No token needed for some public info --- routers/api/v1/api.go | 80 ++++++++++----------- tests/integration/api_comment_test.go | 9 +-- tests/integration/api_repo_file_get_test.go | 5 +- tests/integration/api_wiki_test.go | 9 +-- 4 files changed, 47 insertions(+), 56 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 12f9d2574286c..74d28fa51c453 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -838,7 +838,7 @@ func Routes(ctx gocontext.Context) *web.Route { }) }, reqAdmin(), reqWebhooksEnabled()) m.Group("/collaborators", func() { - m.Get("", reqToken(auth_model.AccessTokenScopeRepo), reqAnyRepoReader(), repo.ListCollaborators) + m.Get("", reqAnyRepoReader(), repo.ListCollaborators) m.Group("/{collaborator}", func() { m.Combo("").Get(reqAnyRepoReader(), repo.IsCollaborator). Put(reqAdmin(), bind(api.AddCollaboratorOption{}), repo.AddCollaborator). @@ -854,17 +854,17 @@ func Routes(ctx gocontext.Context) *web.Route { Put(reqAdmin(), repo.AddTeam). Delete(reqAdmin(), repo.DeleteTeam) }, reqToken(auth_model.AccessTokenScopeRepo)) - m.Get("/raw/*", reqToken(auth_model.AccessTokenScopeRepo), context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFile) - m.Get("/media/*", reqToken(auth_model.AccessTokenScopeRepo), context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFileOrLFS) - m.Get("/archive/*", reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode), repo.GetArchive) - m.Combo("/forks", reqToken(auth_model.AccessTokenScopeRepo)).Get(repo.ListForks). - Post(reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork) + m.Get("/raw/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFile) + m.Get("/media/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFileOrLFS) + m.Get("/archive/*", reqRepoReader(unit.TypeCode), repo.GetArchive) + m.Combo("/forks").Get(repo.ListForks). + Post(reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork) m.Group("/branches", func() { m.Get("", repo.ListBranches) m.Get("/*", repo.GetBranch) - m.Delete("/*", reqRepoWriter(unit.TypeCode), repo.DeleteBranch) - m.Post("", reqRepoWriter(unit.TypeCode), bind(api.CreateBranchRepoOption{}), repo.CreateBranch) - }, reqToken(auth_model.AccessTokenScopeRepo), context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode)) + m.Delete("/*", reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeCode), repo.DeleteBranch) + m.Post("", reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeCode), bind(api.CreateBranchRepoOption{}), repo.CreateBranch) + }, context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode)) m.Group("/branch_protections", func() { m.Get("", repo.ListBranchProtections) m.Post("", bind(api.CreateBranchProtectionOption{}), repo.CreateBranchProtection) @@ -877,9 +877,9 @@ func Routes(ctx gocontext.Context) *web.Route { m.Group("/tags", func() { m.Get("", repo.ListTags) m.Get("/*", repo.GetTag) - m.Post("", reqRepoWriter(unit.TypeCode), bind(api.CreateTagOption{}), repo.CreateTag) - m.Delete("/*", repo.DeleteTag) - }, reqToken(auth_model.AccessTokenScopeRepo), reqRepoReader(unit.TypeCode), context.ReferencesGitRepo(true)) + m.Post("", reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeCode), bind(api.CreateTagOption{}), repo.CreateTag) + m.Delete("/*", reqToken(auth_model.AccessTokenScopeRepo), repo.DeleteTag) + }, reqRepoReader(unit.TypeCode), context.ReferencesGitRepo(true)) m.Group("/keys", func() { m.Combo("").Get(repo.ListDeployKeys). Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey) @@ -893,45 +893,45 @@ func Routes(ctx gocontext.Context) *web.Route { m.Group("/wiki", func() { m.Combo("/page/{pageName}"). Get(repo.GetWikiPage). - Patch(mustNotBeArchived, reqRepoWriter(unit.TypeWiki), bind(api.CreateWikiPageOptions{}), repo.EditWikiPage). - Delete(mustNotBeArchived, reqRepoWriter(unit.TypeWiki), repo.DeleteWikiPage) + Patch(mustNotBeArchived, reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeWiki), bind(api.CreateWikiPageOptions{}), repo.EditWikiPage). + Delete(mustNotBeArchived, reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeWiki), repo.DeleteWikiPage) m.Get("/revisions/{pageName}", repo.ListPageRevisions) - m.Post("/new", mustNotBeArchived, reqRepoWriter(unit.TypeWiki), bind(api.CreateWikiPageOptions{}), repo.NewWikiPage) + m.Post("/new", mustNotBeArchived, reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeWiki), bind(api.CreateWikiPageOptions{}), repo.NewWikiPage) m.Get("/pages", repo.ListWikiPages) - }, mustEnableWiki, reqToken(auth_model.AccessTokenScopeRepo)) + }, mustEnableWiki) m.Group("/issues", func() { m.Combo("").Get(repo.ListIssues). - Post(mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue) + Post(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue) m.Group("/comments", func() { m.Get("", repo.ListRepoIssueComments) m.Group("/{id}", func() { m.Combo(""). Get(repo.GetIssueComment). - Patch(mustNotBeArchived, bind(api.EditIssueCommentOption{}), repo.EditIssueComment). - Delete(repo.DeleteIssueComment) + Patch(mustNotBeArchived, reqToken(auth_model.AccessTokenScopeRepo), bind(api.EditIssueCommentOption{}), repo.EditIssueComment). + Delete(reqToken(auth_model.AccessTokenScopeRepo), repo.DeleteIssueComment) m.Combo("/reactions"). Get(repo.GetIssueCommentReactions). - Post(bind(api.EditReactionOption{}), repo.PostIssueCommentReaction). - Delete(bind(api.EditReactionOption{}), repo.DeleteIssueCommentReaction) + Post(reqToken(auth_model.AccessTokenScopeRepo), bind(api.EditReactionOption{}), repo.PostIssueCommentReaction). + Delete(reqToken(auth_model.AccessTokenScopeRepo), bind(api.EditReactionOption{}), repo.DeleteIssueCommentReaction) }) }) m.Group("/{index}", func() { m.Combo("").Get(repo.GetIssue). - Patch(bind(api.EditIssueOption{}), repo.EditIssue). - Delete(reqAdmin(), repo.DeleteIssue) + Patch(reqToken(auth_model.AccessTokenScopeRepo), bind(api.EditIssueOption{}), repo.EditIssue). + Delete(reqToken(auth_model.AccessTokenScopeRepo), reqAdmin(), repo.DeleteIssue) m.Group("/comments", func() { m.Combo("").Get(repo.ListIssueComments). - Post(mustNotBeArchived, bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment) - m.Combo("/{id}", reqToken("")).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueCommentDeprecated). + Post(reqToken(auth_model.AccessTokenScopeRepo), mustNotBeArchived, bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment) + m.Combo("/{id}", reqToken(auth_model.AccessTokenScopeRepo)).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueCommentDeprecated). Delete(repo.DeleteIssueCommentDeprecated) }) m.Get("/timeline", repo.ListIssueCommentsAndTimeline) m.Group("/labels", func() { m.Combo("").Get(repo.ListIssueLabels). - Post(bind(api.IssueLabelsOption{}), repo.AddIssueLabels). - Put(bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels). - Delete(repo.ClearIssueLabels) - m.Delete("/{id}", repo.DeleteIssueLabel) + Post(reqToken(auth_model.AccessTokenScopeRepo), bind(api.IssueLabelsOption{}), repo.AddIssueLabels). + Put(reqToken(auth_model.AccessTokenScopeRepo), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels). + Delete(reqToken(auth_model.AccessTokenScopeRepo), repo.ClearIssueLabels) + m.Delete("/{id}", reqToken(auth_model.AccessTokenScopeRepo), repo.DeleteIssueLabel) }) m.Group("/times", func() { m.Combo(""). @@ -939,25 +939,25 @@ func Routes(ctx gocontext.Context) *web.Route { Post(bind(api.AddTimeOption{}), repo.AddTime). Delete(repo.ResetIssueTime) m.Delete("/{id}", repo.DeleteTime) - }, reqToken("")) - m.Combo("/deadline").Post(bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline) + }, reqToken(auth_model.AccessTokenScopeRepo)) + m.Combo("/deadline").Post(reqToken(auth_model.AccessTokenScopeRepo), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline) m.Group("/stopwatch", func() { - m.Post("/start", repo.StartIssueStopwatch) - m.Post("/stop", repo.StopIssueStopwatch) - m.Delete("/delete", repo.DeleteIssueStopwatch) + m.Post("/start", reqToken(auth_model.AccessTokenScopeRepo), repo.StartIssueStopwatch) + m.Post("/stop", reqToken(auth_model.AccessTokenScopeRepo), repo.StopIssueStopwatch) + m.Delete("/delete", reqToken(auth_model.AccessTokenScopeRepo), repo.DeleteIssueStopwatch) }) m.Group("/subscriptions", func() { m.Get("", repo.GetIssueSubscribers) - m.Get("/check", repo.CheckIssueSubscription) - m.Put("/{user}", repo.AddIssueSubscription) - m.Delete("/{user}", repo.DelIssueSubscription) + m.Get("/check", reqToken(auth_model.AccessTokenScopeRepo), repo.CheckIssueSubscription) + m.Put("/{user}", reqToken(auth_model.AccessTokenScopeRepo), repo.AddIssueSubscription) + m.Delete("/{user}", reqToken(auth_model.AccessTokenScopeRepo), repo.DelIssueSubscription) }) m.Combo("/reactions"). Get(repo.GetIssueReactions). - Post(bind(api.EditReactionOption{}), repo.PostIssueReaction). - Delete(bind(api.EditReactionOption{}), repo.DeleteIssueReaction) + Post(reqToken(auth_model.AccessTokenScopeRepo), bind(api.EditReactionOption{}), repo.PostIssueReaction). + Delete(reqToken(auth_model.AccessTokenScopeRepo), bind(api.EditReactionOption{}), repo.DeleteIssueReaction) }) - }, mustEnableIssuesOrPulls, reqToken(auth_model.AccessTokenScopeRepo)) + }, mustEnableIssuesOrPulls) m.Group("/labels", func() { m.Combo("").Get(repo.ListLabels). Post(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.CreateLabelOption{}), repo.CreateLabel) diff --git a/tests/integration/api_comment_test.go b/tests/integration/api_comment_test.go index 1573c2e5495f5..c076ef0bb5d6a 100644 --- a/tests/integration/api_comment_test.go +++ b/tests/integration/api_comment_test.go @@ -31,8 +31,7 @@ func TestAPIListRepoComments(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") - link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments?token=%s", repoOwner.Name, repo.Name, token)) + link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments", repoOwner.Name, repo.Name)) req := NewRequest(t, "GET", link.String()) resp := session.MakeRequest(t, req, http.StatusOK) @@ -51,7 +50,6 @@ func TestAPIListRepoComments(t *testing.T) { before := "2000-01-01T00:00:11+00:00" // unix: 946684811 since := "2000-01-01T00:00:12+00:00" // unix: 946684812 query.Add("before", before) - query.Add("token", token) link.RawQuery = query.Encode() req = NewRequest(t, "GET", link.String()) resp = session.MakeRequest(t, req, http.StatusOK) @@ -193,9 +191,8 @@ func TestAPIListIssueTimeline(t *testing.T) { // make request session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/timeline?token=%s", - repoOwner.Name, repo.Name, issue.Index, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/timeline", + repoOwner.Name, repo.Name, issue.Index) resp := session.MakeRequest(t, req, http.StatusOK) // check if lens of list returned by API and diff --git a/tests/integration/api_repo_file_get_test.go b/tests/integration/api_repo_file_get_test.go index e4d351fb91473..9ce88bd913b99 100644 --- a/tests/integration/api_repo_file_get_test.go +++ b/tests/integration/api_repo_file_get_test.go @@ -18,11 +18,8 @@ import ( func TestAPIGetRawFileOrLFS(t *testing.T) { defer tests.PrepareTestEnv(t)() - session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "repo") - // Test with raw file - req := NewRequest(t, "GET", "/api/v1/repos/user2/repo1/media/README.md?token="+token) + req := NewRequest(t, "GET", "/api/v1/repos/user2/repo1/media/README.md") resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "# repo1\n\nDescription for repo1", resp.Body.String()) diff --git a/tests/integration/api_wiki_test.go b/tests/integration/api_wiki_test.go index 78c1555ff2cd4..e154c1c438705 100644 --- a/tests/integration/api_wiki_test.go +++ b/tests/integration/api_wiki_test.go @@ -21,9 +21,8 @@ func TestAPIGetWikiPage(t *testing.T) { username := "user2" session := loginUser(t, username) - token := getTokenForLoggedInUser(t, session, "repo") - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/page/Home?token=%s", username, "repo1", token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/page/Home", username, "repo1") req := NewRequest(t, "GET", urlStr) resp := session.MakeRequest(t, req, http.StatusOK) @@ -68,9 +67,8 @@ func TestAPIListWikiPages(t *testing.T) { username := "user2" session := loginUser(t, username) - token := getTokenForLoggedInUser(t, session, "repo") - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/pages?token=%s", username, "repo1", token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/pages", username, "repo1") req := NewRequest(t, "GET", urlStr) resp := session.MakeRequest(t, req, http.StatusOK) @@ -217,9 +215,8 @@ func TestAPIListPageRevisions(t *testing.T) { defer tests.PrepareTestEnv(t)() username := "user2" session := loginUser(t, username) - token := getTokenForLoggedInUser(t, session, "repo") - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/revisions/Home?token=%s", username, "repo1", token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/revisions/Home", username, "repo1") req := NewRequest(t, "GET", urlStr) resp := session.MakeRequest(t, req, http.StatusOK) From 0f25b04505a2a114958e6d59c4c66bce5647ea11 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 30 Oct 2022 22:47:42 -0400 Subject: [PATCH 053/118] Cleanup one duplicated reqToken call --- routers/api/v1/api.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 74d28fa51c453..e677d3ae20c07 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -817,8 +817,8 @@ func Routes(ctx gocontext.Context) *web.Route { m.Post("/reject", repo.RejectTransfer) }, reqToken(auth_model.AccessTokenScopeRepo)) m.Combo("/notifications", reqToken(auth_model.AccessTokenScopeNotification)). - Get(reqToken(""), notify.ListRepoNotifications). - Put(reqToken(""), notify.ReadRepoNotifications) + Get(notify.ListRepoNotifications). + Put(notify.ReadRepoNotifications) m.Group("/hooks/git", func() { m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadRepoHook), repo.ListGitHooks) m.Group("/{id}", func() { From f76259b22d041997220513bf00026821252a1afe Mon Sep 17 00:00:00 2001 From: harryzcy Date: Mon, 31 Oct 2022 00:13:49 -0400 Subject: [PATCH 054/118] Add package scope for package APIs --- routers/api/v1/api.go | 8 +++--- .../api_packages_container_test.go | 4 ++- tests/integration/api_packages_test.go | 28 +++++++++++-------- 3 files changed, 23 insertions(+), 17 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index e677d3ae20c07..2a84c59ebc23b 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -1095,11 +1095,11 @@ func Routes(ctx gocontext.Context) *web.Route { m.Group("/packages/{username}", func() { m.Group("/{type}/{name}/{version}", func() { - m.Get("", packages.GetPackage) - m.Delete("", reqPackageAccess(perm.AccessModeWrite), packages.DeletePackage) - m.Get("/files", packages.ListPackageFiles) + m.Get("", reqToken(auth_model.AccessTokenScopeReadPackage), packages.GetPackage) + m.Delete("", reqToken(auth_model.AccessTokenScopeDeletePackage), reqPackageAccess(perm.AccessModeWrite), packages.DeletePackage) + m.Get("/files", reqToken(auth_model.AccessTokenScopeReadPackage), packages.ListPackageFiles) }) - m.Get("/", packages.ListPackages) + m.Get("/", reqToken(auth_model.AccessTokenScopeReadPackage), packages.ListPackages) }, context_service.UserAssignmentAPI(), context.PackageAssignmentAPI(), reqPackageAccess(perm.AccessModeRead)) // Organizations diff --git a/tests/integration/api_packages_container_test.go b/tests/integration/api_packages_container_test.go index ba76ee4baa7dd..5ba47dbd11cd4 100644 --- a/tests/integration/api_packages_container_test.go +++ b/tests/integration/api_packages_container_test.go @@ -30,6 +30,8 @@ func TestPackageContainer(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) + session := loginUser(t, user.Name) + token := getTokenForLoggedInUser(t, session, "read_package") has := func(l packages_model.PackagePropertyList, name string) bool { for _, pp := range l { @@ -546,7 +548,7 @@ func TestPackageContainer(t *testing.T) { assert.Equal(t, c.ExpectedLink, resp.Header().Get("Link")) } - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s?type=container&q=%s", user.Name, image)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s?type=container&q=%s&token=%s", user.Name, image, token)) resp := MakeRequest(t, req, http.StatusOK) var apiPackages []*api.Package diff --git a/tests/integration/api_packages_test.go b/tests/integration/api_packages_test.go index 25f5b3f2a12da..053432e2ffcda 100644 --- a/tests/integration/api_packages_test.go +++ b/tests/integration/api_packages_test.go @@ -28,7 +28,8 @@ func TestPackageAPI(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + tokenReadPackage := getTokenForLoggedInUser(t, session, "read_package") + tokenWritePackage := getTokenForLoggedInUser(t, session, "write_package") packageName := "test-package" packageVersion := "1.0.3" @@ -42,7 +43,7 @@ func TestPackageAPI(t *testing.T) { t.Run("ListPackages", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s?token=%s", user.Name, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s?token=%s", user.Name, tokenReadPackage)) resp := MakeRequest(t, req, http.StatusOK) var apiPackages []*api.Package @@ -59,10 +60,10 @@ func TestPackageAPI(t *testing.T) { t.Run("GetPackage", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s?token=%s", user.Name, packageName, packageVersion, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) resp := MakeRequest(t, req, http.StatusOK) var p *api.Package @@ -81,7 +82,7 @@ func TestPackageAPI(t *testing.T) { assert.NoError(t, err) // no repository link - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) resp := MakeRequest(t, req, http.StatusOK) var ap1 *api.Package @@ -91,7 +92,7 @@ func TestPackageAPI(t *testing.T) { // link to public repository assert.NoError(t, packages_model.SetRepositoryLink(db.DefaultContext, p.ID, 1)) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) resp = MakeRequest(t, req, http.StatusOK) var ap2 *api.Package @@ -102,7 +103,7 @@ func TestPackageAPI(t *testing.T) { // link to private repository assert.NoError(t, packages_model.SetRepositoryLink(db.DefaultContext, p.ID, 2)) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) resp = MakeRequest(t, req, http.StatusOK) var ap3 *api.Package @@ -116,10 +117,10 @@ func TestPackageAPI(t *testing.T) { t.Run("ListPackageFiles", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s/files?token=%s", user.Name, packageName, packageVersion, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s/files?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s/files?token=%s", user.Name, packageName, packageVersion, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s/files?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) resp := MakeRequest(t, req, http.StatusOK) var files []*api.PackageFile @@ -137,10 +138,10 @@ func TestPackageAPI(t *testing.T) { t.Run("DeletePackage", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s?token=%s", user.Name, packageName, packageVersion, token)) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenWritePackage)) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, token)) + req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenWritePackage)) MakeRequest(t, req, http.StatusNoContent) }) } @@ -152,8 +153,11 @@ func TestPackageAccess(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) inactive := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 9}) + session := loginUser(t, user.Name) + token := getTokenForLoggedInUser(t, session, "write_package") + uploadPackage := func(doer, owner *user_model.User, expectedStatus int) { - url := fmt.Sprintf("/api/packages/%s/generic/test-package/1.0/file.bin", owner.Name) + url := fmt.Sprintf("/api/packages/%s/generic/test-package/1.0/file.bin?token=%s", owner.Name, token) req := NewRequestWithBody(t, "PUT", url, bytes.NewReader([]byte{1})) AddBasicAuthHeader(req, doer.Name) MakeRequest(t, req, expectedStatus) From 6d7e7e5a64faf22d632c17f94f1b7743ad11f9c8 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Mon, 31 Oct 2022 00:40:10 -0400 Subject: [PATCH 055/118] Fix package integration tests --- tests/integration/api_packages_test.go | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/tests/integration/api_packages_test.go b/tests/integration/api_packages_test.go index 053432e2ffcda..9e2366c4e4bf9 100644 --- a/tests/integration/api_packages_test.go +++ b/tests/integration/api_packages_test.go @@ -29,7 +29,7 @@ func TestPackageAPI(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) session := loginUser(t, user.Name) tokenReadPackage := getTokenForLoggedInUser(t, session, "read_package") - tokenWritePackage := getTokenForLoggedInUser(t, session, "write_package") + tokenDeletePackage := getTokenForLoggedInUser(t, session, "delete_package") packageName := "test-package" packageVersion := "1.0.3" @@ -138,10 +138,10 @@ func TestPackageAPI(t *testing.T) { t.Run("DeletePackage", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenWritePackage)) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenDeletePackage)) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenWritePackage)) + req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenDeletePackage)) MakeRequest(t, req, http.StatusNoContent) }) } @@ -153,11 +153,8 @@ func TestPackageAccess(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) inactive := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 9}) - session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "write_package") - uploadPackage := func(doer, owner *user_model.User, expectedStatus int) { - url := fmt.Sprintf("/api/packages/%s/generic/test-package/1.0/file.bin?token=%s", owner.Name, token) + url := fmt.Sprintf("/api/packages/%s/generic/test-package/1.0/file.bin", owner.Name) req := NewRequestWithBody(t, "PUT", url, bytes.NewReader([]byte{1})) AddBasicAuthHeader(req, doer.Name) MakeRequest(t, req, expectedStatus) From e8af871f988ab5f3857e007b8f3355478e2b11a7 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 1 Nov 2022 01:23:17 -0400 Subject: [PATCH 056/118] Limit scope for `/api/v1/orgs` --- routers/api/v1/api.go | 50 ++++++++++----------- tests/integration/api_issue_label_test.go | 2 +- tests/integration/api_org_test.go | 20 +++++---- tests/integration/api_repo_test.go | 2 +- tests/integration/api_team_test.go | 8 ++-- tests/integration/api_user_org_perm_test.go | 6 +-- tests/integration/api_user_orgs_test.go | 4 +- tests/integration/org_count_test.go | 2 +- tests/integration/org_test.go | 2 +- 9 files changed, 50 insertions(+), 46 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 2a84c59ebc23b..cf7d1f3b41f33 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -1103,41 +1103,41 @@ func Routes(ctx gocontext.Context) *web.Route { }, context_service.UserAssignmentAPI(), context.PackageAssignmentAPI(), reqPackageAccess(perm.AccessModeRead)) // Organizations - m.Get("/user/orgs", reqToken(""), org.ListMyOrgs) + m.Get("/user/orgs", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListMyOrgs) m.Group("/users/{username}/orgs", func() { - m.Get("", org.ListUserOrgs) - m.Get("/{org}/permissions", reqToken(""), org.GetUserOrgsPermissions) + m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListUserOrgs) + m.Get("/{org}/permissions", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetUserOrgsPermissions) }, context_service.UserAssignmentAPI()) - m.Post("/orgs", reqToken(""), bind(api.CreateOrgOption{}), org.Create) - m.Get("/orgs", org.GetAll) + m.Post("/orgs", reqToken(auth_model.AccessTokenScopeWriteOrg), bind(api.CreateOrgOption{}), org.Create) + m.Get("/orgs", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetAll) m.Group("/orgs/{org}", func() { - m.Combo("").Get(org.Get). - Patch(reqToken(""), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit). - Delete(reqToken(""), reqOrgOwnership(), org.Delete) - m.Combo("/repos").Get(user.ListOrgRepos). - Post(reqToken(""), bind(api.CreateRepoOption{}), repo.CreateOrgRepo) + m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.Get). + Patch(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit). + Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.Delete) + m.Combo("/repos").Get(reqToken(auth_model.AccessTokenScopeReadOrg), user.ListOrgRepos). + Post(reqToken(auth_model.AccessTokenScopeWriteOrg), bind(api.CreateRepoOption{}), repo.CreateOrgRepo) m.Group("/members", func() { - m.Get("", org.ListMembers) - m.Combo("/{username}").Get(org.IsMember). - Delete(reqToken(""), reqOrgOwnership(), org.DeleteMember) + m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListMembers) + m.Combo("/{username}").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.IsMember). + Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.DeleteMember) }) m.Group("/public_members", func() { - m.Get("", org.ListPublicMembers) - m.Combo("/{username}").Get(org.IsPublicMember). - Put(reqToken(""), reqOrgMembership(), org.PublicizeMember). - Delete(reqToken(""), reqOrgMembership(), org.ConcealMember) + m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListPublicMembers) + m.Combo("/{username}").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.IsPublicMember). + Put(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgMembership(), org.PublicizeMember). + Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgMembership(), org.ConcealMember) }) m.Group("/teams", func() { - m.Get("", org.ListTeams) + m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListTeams) m.Post("", reqOrgOwnership(), bind(api.CreateTeamOption{}), org.CreateTeam) m.Get("/search", org.SearchTeam) - }, reqToken(""), reqOrgMembership()) + }, reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgMembership()) m.Group("/labels", func() { - m.Get("", org.ListLabels) - m.Post("", reqToken(""), reqOrgOwnership(), bind(api.CreateLabelOption{}), org.CreateLabel) - m.Combo("/{id}").Get(org.GetLabel). - Patch(reqToken(""), reqOrgOwnership(), bind(api.EditLabelOption{}), org.EditLabel). - Delete(reqToken(""), reqOrgOwnership(), org.DeleteLabel) + m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListLabels) + m.Post("", reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.CreateLabelOption{}), org.CreateLabel) + m.Combo("/{id}").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetLabel). + Patch(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.EditLabelOption{}), org.EditLabel). + Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.DeleteLabel) }) m.Group("/hooks", func() { m.Combo("").Get(org.ListHooks). @@ -1145,7 +1145,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Combo("/{id}").Get(org.GetHook). Patch(bind(api.EditHookOption{}), org.EditHook). Delete(org.DeleteHook) - }, reqToken(""), reqOrgOwnership(), reqWebhooksEnabled()) + }, reqToken(auth_model.AccessTokenScopeAdminOrgHook), reqOrgOwnership(), reqWebhooksEnabled()) }, orgAssignment(true)) m.Group("/teams/{teamid}", func() { m.Combo("").Get(org.GetTeam). diff --git a/tests/integration/api_issue_label_test.go b/tests/integration/api_issue_label_test.go index 378ed7381771c..b4c96e3838463 100644 --- a/tests/integration/api_issue_label_test.go +++ b/tests/integration/api_issue_label_test.go @@ -144,7 +144,7 @@ func TestAPIModifyOrgLabels(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) user := "user1" session := loginUser(t, user) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, "repo", "admin_org") urlStr := fmt.Sprintf("/api/v1/orgs/%s/labels?token=%s", owner.Name, token) // CreateLabel diff --git a/tests/integration/api_org_test.go b/tests/integration/api_org_test.go index 16e53d6b81581..67902f8550567 100644 --- a/tests/integration/api_org_test.go +++ b/tests/integration/api_org_test.go @@ -22,7 +22,7 @@ import ( func TestAPIOrgCreate(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { - token := getUserToken(t, "user1") + token := getUserToken(t, "user1", "write_org", "read_org") org := api.CreateOrgOption{ UserName: "user1_org", @@ -80,7 +80,7 @@ func TestAPIOrgEdit(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "write_org") org := api.EditOrgOption{ FullName: "User3 organization new full name", Description: "A new description", @@ -107,7 +107,7 @@ func TestAPIOrgEditBadVisibility(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "write_org") org := api.EditOrgOption{ FullName: "User3 organization new full name", Description: "A new description", @@ -127,14 +127,16 @@ func TestAPIOrgDeny(t *testing.T) { setting.Service.RequireSignInView = false }() + token := getUserToken(t, "user1", "read_org") + orgName := "user1_org" - req := NewRequestf(t, "GET", "/api/v1/orgs/%s", orgName) + req := NewRequestf(t, "GET", "/api/v1/orgs/%s?token=%s", orgName, token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequestf(t, "GET", "/api/v1/orgs/%s/repos", orgName) + req = NewRequestf(t, "GET", "/api/v1/orgs/%s/repos?token=%s", orgName, token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequestf(t, "GET", "/api/v1/orgs/%s/members", orgName) + req = NewRequestf(t, "GET", "/api/v1/orgs/%s/members?token=%s", orgName, token) MakeRequest(t, req, http.StatusNotFound) }) } @@ -142,7 +144,9 @@ func TestAPIOrgDeny(t *testing.T) { func TestAPIGetAll(t *testing.T) { defer tests.PrepareTestEnv(t)() - req := NewRequestf(t, "GET", "/api/v1/orgs") + token := getUserToken(t, "user1", "read_org") + + req := NewRequestf(t, "GET", "/api/v1/orgs?token=%s", token) resp := MakeRequest(t, req, http.StatusOK) var apiOrgList []*api.Organization @@ -155,7 +159,7 @@ func TestAPIGetAll(t *testing.T) { func TestAPIOrgSearchEmptyTeam(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { - token := getUserToken(t, "user1") + token := getUserToken(t, "user1", "admin_org") orgName := "org_with_empty_team" // create org diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index a71c26926e34f..7e9e899799e5b 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -300,7 +300,7 @@ func TestAPIOrgRepos(t *testing.T) { if userToLogin != nil && userToLogin.ID > 0 { testName = fmt.Sprintf("LoggedUser%d", userToLogin.ID) session = loginUser(t, userToLogin.Name) - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "read_org") } else { testName = "AnonymousUser" session = emptyTestSession(t) diff --git a/tests/integration/api_team_test.go b/tests/integration/api_team_test.go index a667949c096f9..8ba350adc27bf 100644 --- a/tests/integration/api_team_test.go +++ b/tests/integration/api_team_test.go @@ -30,7 +30,7 @@ func TestAPITeam(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: teamUser.UID}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "admin_org") req := NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamUser.TeamID) resp := session.MakeRequest(t, req, http.StatusOK) @@ -228,7 +228,7 @@ func TestAPITeamSearch(t *testing.T) { var results TeamSearchResults - token := getUserToken(t, user.Name) + token := getUserToken(t, user.Name, "read_org") req := NewRequestf(t, "GET", "/api/v1/orgs/%s/teams/search?q=%s&token=%s", org.Name, "_team", token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &results) @@ -253,7 +253,7 @@ func TestAPIGetTeamRepo(t *testing.T) { var results api.Repository - token := getUserToken(t, user.Name) + token := getUserToken(t, user.Name, "read_org") req := NewRequestf(t, "GET", "/api/v1/teams/%d/repos/%s/?token=%s", team.ID, teamRepo.FullName(), token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &results) @@ -261,7 +261,7 @@ func TestAPIGetTeamRepo(t *testing.T) { // no access if not organization member user5 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) - token5 := getUserToken(t, user5.Name) + token5 := getUserToken(t, user5.Name, "read_org") req = NewRequestf(t, "GET", "/api/v1/teams/%d/repos/%s/?token=%s", team.ID, teamRepo.FullName(), token5) MakeRequest(t, req, http.StatusNotFound) diff --git a/tests/integration/api_user_org_perm_test.go b/tests/integration/api_user_org_perm_test.go index fef653545c5f6..e083cce7d34dd 100644 --- a/tests/integration/api_user_org_perm_test.go +++ b/tests/integration/api_user_org_perm_test.go @@ -34,7 +34,7 @@ func sampleTest(t *testing.T, auoptc apiUserOrgPermTestCase) { defer tests.PrepareTestEnv(t)() session := loginUser(t, auoptc.LoginUser) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "read_org") req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/orgs/%s/permissions?token=%s", auoptc.User, auoptc.Organization, token)) resp := session.MakeRequest(t, req, http.StatusOK) @@ -127,7 +127,7 @@ func TestUnknowUser(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "read_org") req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/unknow/orgs/org25/permissions?token=%s", token)) resp := session.MakeRequest(t, req, http.StatusNotFound) @@ -141,7 +141,7 @@ func TestUnknowOrganization(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "read_org") req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/user1/orgs/unknow/permissions?token=%s", token)) resp := session.MakeRequest(t, req, http.StatusNotFound) diff --git a/tests/integration/api_user_orgs_test.go b/tests/integration/api_user_orgs_test.go index c28bf391eb3af..93a3c9c04703b 100644 --- a/tests/integration/api_user_orgs_test.go +++ b/tests/integration/api_user_orgs_test.go @@ -72,7 +72,7 @@ func getUserOrgs(t *testing.T, userDoer, userCheck string) (orgs []*api.Organiza session := emptyTestSession(t) if len(userDoer) != 0 { session = loginUser(t, userDoer) - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "read_org") } urlStr := fmt.Sprintf("/api/v1/users/%s/orgs?token=%s", userCheck, token) req := NewRequest(t, "GET", urlStr) @@ -90,7 +90,7 @@ func TestMyOrgs(t *testing.T) { normalUsername := "user2" session = loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "read_org") req = NewRequest(t, "GET", "/api/v1/user/orgs?token="+token) resp := session.MakeRequest(t, req, http.StatusOK) var orgs []*api.Organization diff --git a/tests/integration/org_count_test.go b/tests/integration/org_count_test.go index 96f39924f133b..6c15ec79b79e2 100644 --- a/tests/integration/org_count_test.go +++ b/tests/integration/org_count_test.go @@ -25,7 +25,7 @@ func testOrgCounts(t *testing.T, u *url.URL) { orgOwner := "user2" orgName := "testOrg" orgCollaborator := "user4" - ctx := NewAPITestContext(t, orgOwner, "repo1") + ctx := NewAPITestContext(t, orgOwner, "repo1", "admin_org") var ownerCountRepos map[string]int var collabCountRepos map[string]int diff --git a/tests/integration/org_test.go b/tests/integration/org_test.go index d04fcf7f57aa4..91cab00e4737f 100644 --- a/tests/integration/org_test.go +++ b/tests/integration/org_test.go @@ -159,7 +159,7 @@ func TestOrgRestrictedUser(t *testing.T) { // Therefore create a read-only team adminSession := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, adminSession) + token := getTokenForLoggedInUser(t, adminSession, "admin_org") teamToCreate := &api.CreateTeamOption{ Name: "codereader", From dc6ac14cc68477002ebd197d762e0772b485adad Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 1 Nov 2022 01:47:34 -0400 Subject: [PATCH 057/118] Fix some test but still have works to do --- tests/integration/api_repo_test.go | 17 +++++------------ tests/integration/api_team_test.go | 2 +- 2 files changed, 6 insertions(+), 13 deletions(-) diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index 7e9e899799e5b..0c165c085752c 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -287,24 +287,17 @@ func TestAPIOrgRepos(t *testing.T) { count int includesPrivate bool }{ - nil: {count: 1}, + user: {count: 1}, user: {count: 3, includesPrivate: true}, user2: {count: 3, includesPrivate: true}, user3: {count: 1}, } for userToLogin, expected := range expectedResults { - var session *TestSession - var testName string - var token string - if userToLogin != nil && userToLogin.ID > 0 { - testName = fmt.Sprintf("LoggedUser%d", userToLogin.ID) - session = loginUser(t, userToLogin.Name) - token = getTokenForLoggedInUser(t, session, "read_org") - } else { - testName = "AnonymousUser" - session = emptyTestSession(t) - } + testName := fmt.Sprintf("LoggedUser%d", userToLogin.ID) + session := loginUser(t, userToLogin.Name) + token := getTokenForLoggedInUser(t, session, "read_org") + t.Run(testName, func(t *testing.T) { req := NewRequestf(t, "GET", "/api/v1/orgs/%s/repos?token="+token, sourceOrg.Name) resp := session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/api_team_test.go b/tests/integration/api_team_test.go index 8ba350adc27bf..1d55f7818ff4b 100644 --- a/tests/integration/api_team_test.go +++ b/tests/integration/api_team_test.go @@ -54,7 +54,7 @@ func TestAPITeam(t *testing.T) { // Get an admin user able to create, update and delete teams. user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session = loginUser(t, user.Name) - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "admin_org") org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 6}) From 853eb68d23a726064ca1a1cb4a40450f1f2b8f36 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 1 Nov 2022 02:04:09 -0400 Subject: [PATCH 058/118] One more fix --- tests/integration/api_team_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/api_team_test.go b/tests/integration/api_team_test.go index 1d55f7818ff4b..76f39360f291e 100644 --- a/tests/integration/api_team_test.go +++ b/tests/integration/api_team_test.go @@ -238,7 +238,7 @@ func TestAPITeamSearch(t *testing.T) { // no access if not organization member user5 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) - token5 := getUserToken(t, user5.Name) + token5 := getUserToken(t, user5.Name, "read_org") req = NewRequestf(t, "GET", "/api/v1/orgs/%s/teams/search?q=%s&token=%s", org.Name, "team", token5) MakeRequest(t, req, http.StatusForbidden) From 45f716f5c81d356779e8c01c60160f697ad9172a Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 1 Nov 2022 02:38:44 -0400 Subject: [PATCH 059/118] Fix the scope required for /api/v1/orgs/{org}/teams --- routers/api/v1/api.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index cf7d1f3b41f33..c37d458fee76a 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -1129,9 +1129,9 @@ func Routes(ctx gocontext.Context) *web.Route { }) m.Group("/teams", func() { m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListTeams) - m.Post("", reqOrgOwnership(), bind(api.CreateTeamOption{}), org.CreateTeam) - m.Get("/search", org.SearchTeam) - }, reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgMembership()) + m.Post("", reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.CreateTeamOption{}), org.CreateTeam) + m.Get("/search", reqToken(auth_model.AccessTokenScopeReadOrg), org.SearchTeam) + }, reqOrgMembership()) m.Group("/labels", func() { m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.ListLabels) m.Post("", reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.CreateLabelOption{}), org.CreateLabel) From 8b0bc32902ea9c237bccb991cc3f68c99f4f8b40 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 1 Nov 2022 03:46:37 -0400 Subject: [PATCH 060/118] Disallow unauthenticated call to users/{user}/orgs --- tests/integration/api_user_orgs_test.go | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/tests/integration/api_user_orgs_test.go b/tests/integration/api_user_orgs_test.go index 93a3c9c04703b..6b0a03ff83ee4 100644 --- a/tests/integration/api_user_orgs_test.go +++ b/tests/integration/api_user_orgs_test.go @@ -62,18 +62,13 @@ func TestUserOrgs(t *testing.T) { orgs = getUserOrgs(t, unrelatedUsername, privateMemberUsername) assert.Len(t, orgs, 0) - // not authenticated call also should hide org membership - orgs = getUserOrgs(t, "", privateMemberUsername) - assert.Len(t, orgs, 0) + // not authenticated call should not be allowed + testUserOrgsUnauthenticated(t, privateMemberUsername) } func getUserOrgs(t *testing.T, userDoer, userCheck string) (orgs []*api.Organization) { - token := "" - session := emptyTestSession(t) - if len(userDoer) != 0 { - session = loginUser(t, userDoer) - token = getTokenForLoggedInUser(t, session, "read_org") - } + session := loginUser(t, userDoer) + token := getTokenForLoggedInUser(t, session, "read_org") urlStr := fmt.Sprintf("/api/v1/users/%s/orgs?token=%s", userCheck, token) req := NewRequest(t, "GET", urlStr) resp := session.MakeRequest(t, req, http.StatusOK) @@ -81,6 +76,12 @@ func getUserOrgs(t *testing.T, userDoer, userCheck string) (orgs []*api.Organiza return orgs } +func testUserOrgsUnauthenticated(t *testing.T, userCheck string) { + session := emptyTestSession(t) + req := NewRequestf(t, "GET", "/api/v1/users/%s/orgs", userCheck) + session.MakeRequest(t, req, http.StatusUnauthorized) +} + func TestMyOrgs(t *testing.T) { defer tests.PrepareTestEnv(t)() From 8f03691e0a5f22ea99f65d2b0d30fe4d08afa2aa Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 1 Nov 2022 04:02:31 -0400 Subject: [PATCH 061/118] Fix TestAPIGetAll --- tests/integration/api_org_test.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/integration/api_org_test.go b/tests/integration/api_org_test.go index 67902f8550567..98807af5684e4 100644 --- a/tests/integration/api_org_test.go +++ b/tests/integration/api_org_test.go @@ -152,9 +152,10 @@ func TestAPIGetAll(t *testing.T) { var apiOrgList []*api.Organization DecodeJSON(t, resp, &apiOrgList) - assert.Len(t, apiOrgList, 7) - assert.Equal(t, "org25", apiOrgList[0].FullName) - assert.Equal(t, "public", apiOrgList[0].Visibility) + // accessing with a token will return all orgs + assert.Len(t, apiOrgList, 9) + assert.Equal(t, "org25", apiOrgList[1].FullName) + assert.Equal(t, "public", apiOrgList[1].Visibility) } func TestAPIOrgSearchEmptyTeam(t *testing.T) { From 2451accb56fd4edd4db032dec34b3121748e2c12 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 1 Nov 2022 23:33:48 -0400 Subject: [PATCH 062/118] Add scope to teams APIs --- routers/api/v1/api.go | 24 ++++++++++++------------ tests/integration/api_team_test.go | 2 +- tests/integration/api_team_user_test.go | 2 +- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index c37d458fee76a..508c99880dead 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -1148,24 +1148,24 @@ func Routes(ctx gocontext.Context) *web.Route { }, reqToken(auth_model.AccessTokenScopeAdminOrgHook), reqOrgOwnership(), reqWebhooksEnabled()) }, orgAssignment(true)) m.Group("/teams/{teamid}", func() { - m.Combo("").Get(org.GetTeam). - Patch(reqOrgOwnership(), bind(api.EditTeamOption{}), org.EditTeam). - Delete(reqOrgOwnership(), org.DeleteTeam) + m.Combo("").Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeam). + Patch(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), bind(api.EditTeamOption{}), org.EditTeam). + Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.DeleteTeam) m.Group("/members", func() { - m.Get("", org.GetTeamMembers) + m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamMembers) m.Combo("/{username}"). - Get(org.GetTeamMember). - Put(reqOrgOwnership(), org.AddTeamMember). - Delete(reqOrgOwnership(), org.RemoveTeamMember) + Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamMember). + Put(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.AddTeamMember). + Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), reqOrgOwnership(), org.RemoveTeamMember) }) m.Group("/repos", func() { - m.Get("", org.GetTeamRepos) + m.Get("", reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamRepos) m.Combo("/{org}/{reponame}"). - Put(org.AddTeamRepository). - Delete(org.RemoveTeamRepository). - Get(org.GetTeamRepo) + Put(reqToken(auth_model.AccessTokenScopeWriteOrg), org.AddTeamRepository). + Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), org.RemoveTeamRepository). + Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamRepo) }) - }, orgAssignment(false, true), reqToken(""), reqTeamMembership()) + }, orgAssignment(false, true), reqTeamMembership()) m.Group("/admin", func() { m.Group("/cron", func() { diff --git a/tests/integration/api_team_test.go b/tests/integration/api_team_test.go index 76f39360f291e..07bdfb4376c3e 100644 --- a/tests/integration/api_team_test.go +++ b/tests/integration/api_team_test.go @@ -44,7 +44,7 @@ func TestAPITeam(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: teamUser2.UID}) session = loginUser(t, user2.Name) - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "read_org") req = NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamUser.TeamID) _ = session.MakeRequest(t, req, http.StatusForbidden) diff --git a/tests/integration/api_team_user_test.go b/tests/integration/api_team_user_test.go index b999b97a2b6f8..de66454822756 100644 --- a/tests/integration/api_team_user_test.go +++ b/tests/integration/api_team_user_test.go @@ -23,7 +23,7 @@ func TestAPITeamUser(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "read_org") req := NewRequest(t, "GET", "/api/v1/teams/1/members/user1?token="+token) session.MakeRequest(t, req, http.StatusNotFound) From 93fbca368ec038733317266cc71a321cf1447d83 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Wed, 2 Nov 2022 00:00:49 -0400 Subject: [PATCH 063/118] Ensure token exists before running reqTeamMembership --- routers/api/v1/api.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 508c99880dead..241943ce1136b 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -1165,7 +1165,7 @@ func Routes(ctx gocontext.Context) *web.Route { Delete(reqToken(auth_model.AccessTokenScopeWriteOrg), org.RemoveTeamRepository). Get(reqToken(auth_model.AccessTokenScopeReadOrg), org.GetTeamRepo) }) - }, orgAssignment(false, true), reqTeamMembership()) + }, orgAssignment(false, true), reqToken(""), reqTeamMembership()) m.Group("/admin", func() { m.Group("/cron", func() { From a10b8dc28bbde9da855354600cc3f9debc36289f Mon Sep 17 00:00:00 2001 From: harryzcy Date: Wed, 2 Nov 2022 01:07:11 -0400 Subject: [PATCH 064/118] Add sudo token to /admin API --- routers/api/v1/api.go | 2 +- tests/integration/api_admin_org_test.go | 6 +++--- tests/integration/api_admin_test.go | 24 ++++++++++++------------ tests/integration/api_httpsig_test.go | 7 ++++--- 4 files changed, 20 insertions(+), 19 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 241943ce1136b..91f2c5912262e 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -1193,7 +1193,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Post("/{username}/{reponame}", admin.AdoptRepository) m.Delete("/{username}/{reponame}", admin.DeleteUnadoptedRepository) }) - }, reqToken(""), reqSiteAdmin()) + }, reqToken(auth_model.AccessTokenScopeSudo), reqSiteAdmin()) m.Group("/topics", func() { m.Get("/search", repo.TopicSearch) diff --git a/tests/integration/api_admin_org_test.go b/tests/integration/api_admin_org_test.go index a8770db4ca40a..95e8ad4753656 100644 --- a/tests/integration/api_admin_org_test.go +++ b/tests/integration/api_admin_org_test.go @@ -21,7 +21,7 @@ import ( func TestAPIAdminOrgCreate(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "sudo") org := api.CreateOrgOption{ UserName: "user2_org", @@ -55,7 +55,7 @@ func TestAPIAdminOrgCreate(t *testing.T) { func TestAPIAdminOrgCreateBadVisibility(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "sudo") org := api.CreateOrgOption{ UserName: "user2_org", @@ -74,7 +74,7 @@ func TestAPIAdminOrgCreateNotAdmin(t *testing.T) { defer tests.PrepareTestEnv(t)() nonAdminUsername := "user2" session := loginUser(t, nonAdminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "sudo") org := api.CreateOrgOption{ UserName: "user2_org", FullName: "User2's organization", diff --git a/tests/integration/api_admin_test.go b/tests/integration/api_admin_test.go index d6bc6016ff7f6..a861ca8e8c329 100644 --- a/tests/integration/api_admin_test.go +++ b/tests/integration/api_admin_test.go @@ -25,7 +25,7 @@ func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) { session := loginUser(t, "user1") keyOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user2"}) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "sudo") urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys?token=%s", keyOwner.Name, token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n", @@ -53,7 +53,7 @@ func TestAPIAdminDeleteMissingSSHKey(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "sudo") req := NewRequestf(t, "DELETE", "/api/v1/admin/users/user1/keys/%d?token=%s", unittest.NonexistentID, token) session.MakeRequest(t, req, http.StatusNotFound) } @@ -64,7 +64,7 @@ func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) { normalUsername := "user2" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "sudo") urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys?token=%s", adminUsername, token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n", @@ -75,7 +75,7 @@ func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) { DecodeJSON(t, resp, &newPublicKey) session = loginUser(t, normalUsername) - token = getTokenForLoggedInUser(t, session) + token = getTokenForLoggedInUser(t, session, "sudo") req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d?token=%s", adminUsername, newPublicKey.ID, token) session.MakeRequest(t, req, http.StatusForbidden) @@ -86,7 +86,7 @@ func TestAPISudoUser(t *testing.T) { adminUsername := "user1" normalUsername := "user2" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "sudo") urlStr := fmt.Sprintf("/api/v1/user?sudo=%s&token=%s", normalUsername, token) req := NewRequest(t, "GET", urlStr) @@ -103,7 +103,7 @@ func TestAPISudoUserForbidden(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "sudo") urlStr := fmt.Sprintf("/api/v1/user?sudo=%s&token=%s", adminUsername, token) req := NewRequest(t, "GET", urlStr) @@ -114,7 +114,7 @@ func TestAPIListUsers(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "sudo") urlStr := fmt.Sprintf("/api/v1/admin/users?token=%s", token) req := NewRequest(t, "GET", urlStr) @@ -143,7 +143,7 @@ func TestAPIListUsersNonAdmin(t *testing.T) { defer tests.PrepareTestEnv(t)() nonAdminUsername := "user2" session := loginUser(t, nonAdminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "sudo") req := NewRequestf(t, "GET", "/api/v1/admin/users?token=%s", token) session.MakeRequest(t, req, http.StatusForbidden) } @@ -152,7 +152,7 @@ func TestAPICreateUserInvalidEmail(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "sudo") urlStr := fmt.Sprintf("/api/v1/admin/users?token=%s", token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "email": "invalid_email@domain.com\r\n", @@ -171,7 +171,7 @@ func TestAPICreateAndDeleteUser(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "sudo") req := NewRequestWithValues( t, @@ -198,7 +198,7 @@ func TestAPIEditUser(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "sudo") urlStr := fmt.Sprintf("/api/v1/admin/users/%s?token=%s", "user2", token) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ @@ -241,7 +241,7 @@ func TestAPICreateRepoForUser(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "sudo") req := NewRequestWithJSON( t, diff --git a/tests/integration/api_httpsig_test.go b/tests/integration/api_httpsig_test.go index e553cb57e7601..7c28f2d0a177f 100644 --- a/tests/integration/api_httpsig_test.go +++ b/tests/integration/api_httpsig_test.go @@ -53,7 +53,7 @@ func TestHTTPSigPubKey(t *testing.T) { // Add our public key to user1 defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") - token := url.QueryEscape(getTokenForLoggedInUser(t, session, "admin_public_key")) + token := url.QueryEscape(getTokenForLoggedInUser(t, session, "admin_public_key", "sudo")) keysURL := fmt.Sprintf("/api/v1/user/keys?token=%s", token) keyType := "ssh-rsa" keyContent := "AAAAB3NzaC1yc2EAAAADAQABAAABAQCqOZB5vkRvXFXups1/0StDRdG8plbNSwsWEnNnP4Bvurxa0+z3W9B8GLKnDiLw5MbpbMNyBlpXw13GfuIeciy10DWTz0xUbiy3J3KabCaT36asIw2y7k6Z0jL0UBnrVENwq5/lUbZYqSZ4rRU744wkhh8TULpzM14npQCZwg6aEbG+MwjzddQ72fR+3BPBrKn5dTmmu8rH99O+U+Nuto81Tg7PA+NUupcHOmhdiEGq49plgVFXK98Vks5tiybL4GuzFyWgyX73Dg/QBMn2eMHt1EMv5Gs3i6GFhKKGo4rjDi9qI6PX5oDR4LTNe6cR8td8YhVD8WFZwLLl/vaYyIqd" @@ -69,7 +69,7 @@ func TestHTTPSigPubKey(t *testing.T) { keyID := ssh.FingerprintSHA256(sshSigner.PublicKey()) // create the request - req = NewRequest(t, "GET", "/api/v1/admin/users") + req = NewRequest(t, "GET", "/api/v1/admin/users?token="+token) signer, _, err := httpsig.NewSSHSigner(sshSigner, httpsig.DigestSha512, []string{httpsig.RequestTarget, "(created)", "(expires)"}, httpsig.Signature, 10) if err != nil { @@ -90,6 +90,7 @@ func TestHTTPSigCert(t *testing.T) { // Add our public key to user1 defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") + token := getTokenForLoggedInUser(t, session, "sudo") csrf := GetCSRF(t, session, "/user/settings/keys") req := NewRequestWithValues(t, "POST", "/user/settings/keys", map[string]string{ @@ -116,7 +117,7 @@ func TestHTTPSigCert(t *testing.T) { } // create the request - req = NewRequest(t, "GET", "/api/v1/admin/users") + req = NewRequest(t, "GET", "/api/v1/admin/users?token="+token) // add our cert to the request certString := base64.RawStdEncoding.EncodeToString(pkcert.(*ssh.Certificate).Marshal()) From 99f05e8c09082e3b42796b685169c5e82a47a333 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Wed, 2 Nov 2022 02:35:07 -0400 Subject: [PATCH 065/118] Support public_repo scope --- routers/api/v1/api.go | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 91f2c5912262e..3c217074244f7 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -212,19 +212,32 @@ func reqPackageAccess(accessMode perm.AccessMode) func(ctx *context.APIContext) func reqToken(requiredScope string) func(ctx *context.APIContext) { return func(ctx *context.APIContext) { if true == ctx.Data["IsApiToken"] { + // no scope required if requiredScope == "" { return } + + // check scope scope := ctx.Data["ApiTokenScope"].(auth_model.AccessTokenScope) allow, err := scope.HasScope(requiredScope) if err != nil { ctx.Error(http.StatusUnauthorized, "reqToken", "parsing token failed: "+err.Error()) return } - if !allow { - ctx.Error(http.StatusUnauthorized, "reqToken", "token does not have required scope: "+requiredScope) + if allow { return } + + // if requires 'repo' scope, but only has 'public_repo' scope, allow it only if the repo is public + if requiredScope == auth_model.AccessTokenScopeRepo { + if allowPublicRepo, err := scope.HasScope(auth_model.AccessTokenScopeUser); err == nil && allowPublicRepo { + if ctx.Repo.Repository != nil && !ctx.Repo.Repository.IsPrivate { + return + } + } + } + + ctx.Error(http.StatusUnauthorized, "reqToken", "token does not have required scope: "+requiredScope) return } if ctx.Context.IsBasicAuth { From 8e45f8140b1925dd9fe02c80a65944b6fd5de9be Mon Sep 17 00:00:00 2001 From: harryzcy Date: Wed, 2 Nov 2022 03:01:51 -0400 Subject: [PATCH 066/118] Introduce database migration --- models/migrations/migrations.go | 4 ++++ models/migrations/v232.go | 37 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 models/migrations/v232.go diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go index 31b88a7981103..0ef28857c2bcf 100644 --- a/models/migrations/migrations.go +++ b/models/migrations/migrations.go @@ -425,6 +425,10 @@ var migrations = []Migration{ NewMigration("Add ConfidentialClient column (default true) to OAuth2Application table", addConfidentialClientColumnToOAuth2ApplicationTable), // v231 -> v232 NewMigration("Add index for hook_task", addIndexForHookTask), + + // TODO: where does Gitea 1.18.0 end? + // v232 -> v233 + NewMigration("Add index for issue_user", addScopeForAccessTokens), } // GetCurrentDBVersion returns the current db version diff --git a/models/migrations/v232.go b/models/migrations/v232.go new file mode 100644 index 0000000000000..b982e1dafd307 --- /dev/null +++ b/models/migrations/v232.go @@ -0,0 +1,37 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package migrations + +import ( + auth_models "code.gitea.io/gitea/models/auth" + "code.gitea.io/gitea/modules/timeutil" + "xorm.io/xorm" +) + +func addScopeForAccessTokens(x *xorm.Engine) error { + type AccessTokenWithDefaultScope struct { + ID int64 `xorm:"pk autoincr"` + UID int64 `xorm:"INDEX"` + Name string + Token string `xorm:"-"` + TokenHash string `xorm:"UNIQUE"` // sha256 of token + TokenSalt string + TokenLastEight string `xorm:"token_last_eight"` + Scope auth_models.AccessTokenScope `xorm:"NOT NULL DEFAULT 'all'"` + + CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` + UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` + HasRecentActivity bool `xorm:"-"` + HasUsed bool `xorm:"-"` + } + + err := x.Sync(new(AccessTokenWithDefaultScope)) + if err != nil { + return err + } + + // remove default 'all' + return x.Sync(new(auth_models.AccessToken)) +} From af08a1e04ea164e1f6de51f41c3141a5baa9cd31 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Wed, 2 Nov 2022 11:26:32 -0400 Subject: [PATCH 067/118] Run make fmt --- models/migrations/v232.go | 1 + 1 file changed, 1 insertion(+) diff --git a/models/migrations/v232.go b/models/migrations/v232.go index b982e1dafd307..f5a91ddf3f6a0 100644 --- a/models/migrations/v232.go +++ b/models/migrations/v232.go @@ -7,6 +7,7 @@ package migrations import ( auth_models "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/modules/timeutil" + "xorm.io/xorm" ) From 9a63bb928af6324fde28c3ab3ffde353921b0a81 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Wed, 2 Nov 2022 11:47:58 -0400 Subject: [PATCH 068/118] Copy and define struct definition in migrations --- models/migrations/v1_19/v232.go | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/models/migrations/v1_19/v232.go b/models/migrations/v1_19/v232.go index ba88b14dee4c5..cd5907c368630 100644 --- a/models/migrations/v1_19/v232.go +++ b/models/migrations/v1_19/v232.go @@ -33,6 +33,22 @@ func AddScopeForAccessTokens(x *xorm.Engine) error { return err } - // remove default 'all' - return x.Sync(new(auth_models.AccessToken)) + // remove default 'all' for scope + type AccessToken struct { + ID int64 `xorm:"pk autoincr"` + UID int64 `xorm:"INDEX"` + Name string + Token string `xorm:"-"` + TokenHash string `xorm:"UNIQUE"` // sha256 of token + TokenSalt string + TokenLastEight string `xorm:"token_last_eight"` + Scope auth_models.AccessTokenScope + + CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` + UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` + HasRecentActivity bool `xorm:"-"` + HasUsed bool `xorm:"-"` + } + + return x.Sync(new(AccessToken)) } From 45d0c22d983fbcacd74fd7695d2faace0ff9175e Mon Sep 17 00:00:00 2001 From: harryzcy Date: Thu, 3 Nov 2022 13:40:07 -0400 Subject: [PATCH 069/118] Update migration description --- models/migrations/migrations.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go index 96e0d79b72524..2fbc42b51ab15 100644 --- a/models/migrations/migrations.go +++ b/models/migrations/migrations.go @@ -436,7 +436,7 @@ var migrations = []Migration{ // v232 -> v233 NewMigration("Alter package_version.metadata_json to LONGTEXT", v1_19.AlterPackageVersionMetadataToLongText), // v233 -> v234 - NewMigration("Add index for issue_user", v1_19.AddScopeForAccessTokens), + NewMigration("Add scope for access_token", v1_19.AddScopeForAccessTokens), } // GetCurrentDBVersion returns the current db version From 32fa981a0cc4b62a4615c313936e1d7236ef1b9a Mon Sep 17 00:00:00 2001 From: harryzcy Date: Thu, 3 Nov 2022 17:59:51 -0400 Subject: [PATCH 070/118] Fix test error introduced by merge commits --- tests/integration/api_repo_hook_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/api_repo_hook_test.go b/tests/integration/api_repo_hook_test.go index e503834e188c9..7ad3f4f42caab 100644 --- a/tests/integration/api_repo_hook_test.go +++ b/tests/integration/api_repo_hook_test.go @@ -26,7 +26,7 @@ func TestAPICreateHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, "write_repo_hook") completeURL := func(lastSegment string) string { return fmt.Sprintf("/api/v1/repos/%s/%s/%s?token=%s", owner.Name, repo.Name, lastSegment, token) } From 13cd621de57f9db50d938a440875483121d54c66 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Thu, 3 Nov 2022 21:52:31 -0400 Subject: [PATCH 071/118] List only the modified fields in migration --- models/migrations/v1_19/v234.go | 43 +++++++++------------------------ 1 file changed, 12 insertions(+), 31 deletions(-) diff --git a/models/migrations/v1_19/v234.go b/models/migrations/v1_19/v234.go index cd5907c368630..b7d7d9f812329 100644 --- a/models/migrations/v1_19/v234.go +++ b/models/migrations/v1_19/v234.go @@ -6,49 +6,30 @@ package v1_19 //nolint import ( auth_models "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/modules/timeutil" "xorm.io/xorm" ) func AddScopeForAccessTokens(x *xorm.Engine) error { - type AccessTokenWithDefaultScope struct { - ID int64 `xorm:"pk autoincr"` - UID int64 `xorm:"INDEX"` - Name string - Token string `xorm:"-"` - TokenHash string `xorm:"UNIQUE"` // sha256 of token - TokenSalt string - TokenLastEight string `xorm:"token_last_eight"` - Scope auth_models.AccessTokenScope `xorm:"NOT NULL DEFAULT 'all'"` - - CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` - UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` - HasRecentActivity bool `xorm:"-"` - HasUsed bool `xorm:"-"` - } - - err := x.Sync(new(AccessTokenWithDefaultScope)) + err := addScopeField(x) if err != nil { return err } // remove default 'all' for scope - type AccessToken struct { - ID int64 `xorm:"pk autoincr"` - UID int64 `xorm:"INDEX"` - Name string - Token string `xorm:"-"` - TokenHash string `xorm:"UNIQUE"` // sha256 of token - TokenSalt string - TokenLastEight string `xorm:"token_last_eight"` - Scope auth_models.AccessTokenScope + return removeDefaultAll(x) +} - CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` - UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` - HasRecentActivity bool `xorm:"-"` - HasUsed bool `xorm:"-"` +func addScopeField(x *xorm.Engine) error { + type AccessToken struct { + Scope auth_models.AccessTokenScope `xorm:"NOT NULL DEFAULT 'all'"` } + return x.Sync(new(AccessToken)) +} +func removeDefaultAll(x *xorm.Engine) error { + type AccessToken struct { + Scope auth_models.AccessTokenScope + } return x.Sync(new(AccessToken)) } From f99cb7fbc549b29f27b1c10cedc6918a6578d659 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 5 Nov 2022 13:37:32 -0400 Subject: [PATCH 072/118] Restore a test for comments api --- tests/integration/api_comment_test.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/integration/api_comment_test.go b/tests/integration/api_comment_test.go index c076ef0bb5d6a..570f85e2d270e 100644 --- a/tests/integration/api_comment_test.go +++ b/tests/integration/api_comment_test.go @@ -121,8 +121,11 @@ func TestAPIGetComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) + token := getTokenForLoggedInUser(t, session) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID) + session.MakeRequest(t, req, http.StatusOK) + token = getTokenForLoggedInUser(t, session, "repo") + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) resp := session.MakeRequest(t, req, http.StatusOK) var apiComment api.Comment From 7706cb38ee392224e03ddd9e86d3a0d53bbbcaaf Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 5 Nov 2022 13:43:54 -0400 Subject: [PATCH 073/118] Fix linting issues --- tests/integration/api_comment_test.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/integration/api_comment_test.go b/tests/integration/api_comment_test.go index 570f85e2d270e..0025c58b11e28 100644 --- a/tests/integration/api_comment_test.go +++ b/tests/integration/api_comment_test.go @@ -121,10 +121,9 @@ func TestAPIGetComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID) session.MakeRequest(t, req, http.StatusOK) - token = getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, "repo") req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) resp := session.MakeRequest(t, req, http.StatusOK) From 38da63aec8085198257fada58e1fbfa119579854 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 5 Nov 2022 13:44:39 -0400 Subject: [PATCH 074/118] Migrate without default and update old records --- models/migrations/v1_19/v234.go | 23 ++++++----------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/models/migrations/v1_19/v234.go b/models/migrations/v1_19/v234.go index b7d7d9f812329..c17caff734ab8 100644 --- a/models/migrations/v1_19/v234.go +++ b/models/migrations/v1_19/v234.go @@ -11,25 +11,14 @@ import ( ) func AddScopeForAccessTokens(x *xorm.Engine) error { - err := addScopeField(x) - if err != nil { - return err - } - - // remove default 'all' for scope - return removeDefaultAll(x) -} - -func addScopeField(x *xorm.Engine) error { type AccessToken struct { - Scope auth_models.AccessTokenScope `xorm:"NOT NULL DEFAULT 'all'"` + Scope auth_models.AccessTokenScope } - return x.Sync(new(AccessToken)) -} -func removeDefaultAll(x *xorm.Engine) error { - type AccessToken struct { - Scope auth_models.AccessTokenScope + if err := x.Sync(new(AccessToken)); err != nil { + return err } - return x.Sync(new(AccessToken)) + + _, err := x.Exec("UPDATE access_token SET scope = ?", auth_models.AccessTokenScopeAll) + return err } From bef352a87db29c41cb4be801b9882311cbf4a062 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 5 Nov 2022 14:13:59 -0400 Subject: [PATCH 075/118] Update httpsig test --- tests/integration/api_httpsig_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/api_httpsig_test.go b/tests/integration/api_httpsig_test.go index 7c28f2d0a177f..380bb3bda0054 100644 --- a/tests/integration/api_httpsig_test.go +++ b/tests/integration/api_httpsig_test.go @@ -69,7 +69,7 @@ func TestHTTPSigPubKey(t *testing.T) { keyID := ssh.FingerprintSHA256(sshSigner.PublicKey()) // create the request - req = NewRequest(t, "GET", "/api/v1/admin/users?token="+token) + req = NewRequest(t, "GET", "/api/v1/admin/users") signer, _, err := httpsig.NewSSHSigner(sshSigner, httpsig.DigestSha512, []string{httpsig.RequestTarget, "(created)", "(expires)"}, httpsig.Signature, 10) if err != nil { From d60b20ba6fb4c8d59aa4e42d3f23d93fa6e57863 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 5 Nov 2022 21:03:31 -0400 Subject: [PATCH 076/118] Allow auth via signatures for admin apis --- routers/api/v1/api.go | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 3c217074244f7..12db1940f6394 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -251,6 +251,18 @@ func reqToken(requiredScope string) func(ctx *context.APIContext) { } } +func reqTokenOrSiteAdmin(requiredScope string) func(ctx *context.APIContext) { + return func(ctx *context.APIContext) { + // if is site admin, allow it + if ctx.IsUserSiteAdmin() { + return + } + + // otherwise, check token + reqToken(requiredScope)(ctx) + } +} + func reqExploreSignIn() func(ctx *context.APIContext) { return func(ctx *context.APIContext) { if setting.Service.Explore.RequireSigninView && !ctx.IsSigned { @@ -1206,7 +1218,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Post("/{username}/{reponame}", admin.AdoptRepository) m.Delete("/{username}/{reponame}", admin.DeleteUnadoptedRepository) }) - }, reqToken(auth_model.AccessTokenScopeSudo), reqSiteAdmin()) + }, reqTokenOrSiteAdmin(auth_model.AccessTokenScopeSudo)) m.Group("/topics", func() { m.Get("/search", repo.TopicSearch) From 191f3b48152bca84fd7b54cb9592008395889f68 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 5 Nov 2022 21:08:24 -0400 Subject: [PATCH 077/118] Remove token in TestHTTPSigCert --- tests/integration/api_httpsig_test.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/integration/api_httpsig_test.go b/tests/integration/api_httpsig_test.go index 380bb3bda0054..e8af69dcf7028 100644 --- a/tests/integration/api_httpsig_test.go +++ b/tests/integration/api_httpsig_test.go @@ -90,7 +90,6 @@ func TestHTTPSigCert(t *testing.T) { // Add our public key to user1 defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "sudo") csrf := GetCSRF(t, session, "/user/settings/keys") req := NewRequestWithValues(t, "POST", "/user/settings/keys", map[string]string{ @@ -117,7 +116,7 @@ func TestHTTPSigCert(t *testing.T) { } // create the request - req = NewRequest(t, "GET", "/api/v1/admin/users?token="+token) + req = NewRequest(t, "GET", "/api/v1/admin/users") // add our cert to the request certString := base64.RawStdEncoding.EncodeToString(pkcert.(*ssh.Certificate).Marshal()) From de662207a4ba1fdcb7c50b73d950e61fc59a23ac Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 5 Nov 2022 21:12:26 -0400 Subject: [PATCH 078/118] Remove unused function --- routers/api/v1/api.go | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 12db1940f6394..38ff8e4ec2843 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -251,7 +251,8 @@ func reqToken(requiredScope string) func(ctx *context.APIContext) { } } -func reqTokenOrSiteAdmin(requiredScope string) func(ctx *context.APIContext) { +// reqSiteAdminOrToken user should be the site admin, or the token should have 'sudo' scope. +func reqSiteAdminOrToken() func(ctx *context.APIContext) { return func(ctx *context.APIContext) { // if is site admin, allow it if ctx.IsUserSiteAdmin() { @@ -259,7 +260,7 @@ func reqTokenOrSiteAdmin(requiredScope string) func(ctx *context.APIContext) { } // otherwise, check token - reqToken(requiredScope)(ctx) + reqToken("sudo")(ctx) } } @@ -284,16 +285,6 @@ func reqBasicOrRevProxyAuth() func(ctx *context.APIContext) { } } -// reqSiteAdmin user should be the site admin -func reqSiteAdmin() func(ctx *context.APIContext) { - return func(ctx *context.APIContext) { - if !ctx.IsUserSiteAdmin() { - ctx.Error(http.StatusForbidden, "reqSiteAdmin", "user should be the site admin") - return - } - } -} - // reqOwner user should be the owner of the repo or site admin. func reqOwner() func(ctx *context.APIContext) { return func(ctx *context.APIContext) { @@ -1218,7 +1209,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Post("/{username}/{reponame}", admin.AdoptRepository) m.Delete("/{username}/{reponame}", admin.DeleteUnadoptedRepository) }) - }, reqTokenOrSiteAdmin(auth_model.AccessTokenScopeSudo)) + }, reqSiteAdminOrToken()) m.Group("/topics", func() { m.Get("/search", repo.TopicSearch) From 071fe391c296600149fd4197d1258ea44675384a Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 5 Nov 2022 21:36:21 -0400 Subject: [PATCH 079/118] Fix failing tests --- tests/integration/api_admin_org_test.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/integration/api_admin_org_test.go b/tests/integration/api_admin_org_test.go index 95e8ad4753656..aaa27517496ba 100644 --- a/tests/integration/api_admin_org_test.go +++ b/tests/integration/api_admin_org_test.go @@ -74,7 +74,6 @@ func TestAPIAdminOrgCreateNotAdmin(t *testing.T) { defer tests.PrepareTestEnv(t)() nonAdminUsername := "user2" session := loginUser(t, nonAdminUsername) - token := getTokenForLoggedInUser(t, session, "sudo") org := api.CreateOrgOption{ UserName: "user2_org", FullName: "User2's organization", @@ -83,6 +82,6 @@ func TestAPIAdminOrgCreateNotAdmin(t *testing.T) { Location: "Shanghai", Visibility: "public", } - req := NewRequestWithJSON(t, "POST", "/api/v1/admin/users/user2/orgs?token="+token, &org) - session.MakeRequest(t, req, http.StatusForbidden) + req := NewRequestWithJSON(t, "POST", "/api/v1/admin/users/user2/orgs", &org) + session.MakeRequest(t, req, http.StatusUnauthorized) } From 9123e54c5d0d902b64c40b0d0b65281518a3d4d6 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 5 Nov 2022 22:20:19 -0400 Subject: [PATCH 080/118] Update integration tests --- tests/integration/api_admin_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/integration/api_admin_test.go b/tests/integration/api_admin_test.go index a861ca8e8c329..22ea06955c8cf 100644 --- a/tests/integration/api_admin_test.go +++ b/tests/integration/api_admin_test.go @@ -75,10 +75,10 @@ func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) { DecodeJSON(t, resp, &newPublicKey) session = loginUser(t, normalUsername) - token = getTokenForLoggedInUser(t, session, "sudo") + token = getTokenForLoggedInUser(t, session) req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d?token=%s", adminUsername, newPublicKey.ID, token) - session.MakeRequest(t, req, http.StatusForbidden) + session.MakeRequest(t, req, http.StatusUnauthorized) } func TestAPISudoUser(t *testing.T) { @@ -143,9 +143,9 @@ func TestAPIListUsersNonAdmin(t *testing.T) { defer tests.PrepareTestEnv(t)() nonAdminUsername := "user2" session := loginUser(t, nonAdminUsername) - token := getTokenForLoggedInUser(t, session, "sudo") + token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/admin/users?token=%s", token) - session.MakeRequest(t, req, http.StatusForbidden) + session.MakeRequest(t, req, http.StatusUnauthorized) } func TestAPICreateUserInvalidEmail(t *testing.T) { From 9b662fe69acf2ea4e96c74a8d458334714771cc3 Mon Sep 17 00:00:00 2001 From: Chongyi Zheng Date: Tue, 8 Nov 2022 02:49:55 -0500 Subject: [PATCH 081/118] Update routers/api/v1/api.go Co-authored-by: Lunny Xiao --- routers/api/v1/api.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 38ff8e4ec2843..ef7f4a3a4a494 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -230,7 +230,7 @@ func reqToken(requiredScope string) func(ctx *context.APIContext) { // if requires 'repo' scope, but only has 'public_repo' scope, allow it only if the repo is public if requiredScope == auth_model.AccessTokenScopeRepo { - if allowPublicRepo, err := scope.HasScope(auth_model.AccessTokenScopeUser); err == nil && allowPublicRepo { + if allowPublicRepo, err := scope.HasScope(auth_model.AccessTokenScopePublicRepo); err == nil && allowPublicRepo { if ctx.Repo.Repository != nil && !ctx.Repo.Repository.IsPrivate { return } From e755747ebaacbe375a8db06733bf66475020ed09 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 8 Nov 2022 23:02:35 -0500 Subject: [PATCH 082/118] Add admin:application scope --- models/auth/token_scope.go | 14 +++++++++++++- models/auth/token_scope_test.go | 5 +++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/models/auth/token_scope.go b/models/auth/token_scope.go index 467c67d223cf4..c82c64bd99307 100644 --- a/models/auth/token_scope.go +++ b/models/auth/token_scope.go @@ -53,6 +53,10 @@ const ( AccessTokenScopeWriteGPGKey = "write:gpg_key" AccessTokenScopeReadGPGKey = "read:gpg_key" + AccessTokenScopeAdminApplication = "admin:application" + AccessTokenScopeWriteApplication = "write:application" + AccessTokenScopeReadApplication = "read:application" + AccessTokenScopeSudo = "sudo" ) @@ -69,6 +73,7 @@ var AllAccessTokenScopes = []string{ AccessTokenScopeDeleteRepo, AccessTokenScopePackage, AccessTokenScopeWritePackage, AccessTokenScopeReadPackage, AccessTokenScopeDeletePackage, AccessTokenScopeAdminGPGKey, AccessTokenScopeWriteGPGKey, AccessTokenScopeReadGPGKey, + AccessTokenScopeAdminApplication, AccessTokenScopeWriteApplication, AccessTokenScopeReadApplication, AccessTokenScopeSudo, } @@ -127,6 +132,9 @@ func (s AccessTokenScope) Parse() (AccessTokenScopeBitmap, error) { case AccessTokenScopeAdminGPGKey: bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeWriteGPGKey, AllAccessTokenScopes)) bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeReadGPGKey, AllAccessTokenScopes)) + case AccessTokenScopeAdminApplication: + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeWriteApplication, AllAccessTokenScopes)) + bitmap |= 1 << uint(util.FindStringInSlice(AccessTokenScopeReadApplication, AllAccessTokenScopes)) } } return bitmap, nil @@ -207,6 +215,10 @@ func (bitmap AccessTokenScopeBitmap) ToScope() AccessTokenScope { if _, ok := groupedScope[AccessTokenScopeAdminGPGKey]; ok { continue } + case AccessTokenScopeWriteApplication, AccessTokenScopeReadApplication: + if _, ok := groupedScope[AccessTokenScopeAdminApplication]; ok { + continue + } } scopes = append(scopes, v) } @@ -215,7 +227,7 @@ func (bitmap AccessTokenScopeBitmap) ToScope() AccessTokenScope { scope := AccessTokenScope(strings.Join(scopes, ",")) scope = AccessTokenScope(strings.ReplaceAll( string(scope), - "repo,admin:org,admin:public_key,admin:org_hook,notification,user,delete_repo,package,admin:gpg_key", + "repo,admin:org,admin:public_key,admin:org_hook,notification,user,delete_repo,package,admin:gpg_key,admin:application", "all", )) return scope diff --git a/models/auth/token_scope_test.go b/models/auth/token_scope_test.go index add839ecbd1b9..7ffd7f8e8d08c 100644 --- a/models/auth/token_scope_test.go +++ b/models/auth/token_scope_test.go @@ -36,9 +36,10 @@ func TestAccessTokenScope_Normalize(t *testing.T) { {"admin:gpg_key", "admin:gpg_key", nil}, {"admin:gpg_key,write:gpg_key", "admin:gpg_key", nil}, {"admin:gpg_key,write:gpg_key,user", "user,admin:gpg_key", nil}, + {"admin:application,write:application,user", "user,admin:application", nil}, {"all", "all", nil}, - {"repo,admin:org,admin:public_key,admin:repo_hook,admin:org_hook,notification,user,delete_repo,package,admin:gpg_key", "all", nil}, - {"repo,admin:org,admin:public_key,admin:repo_hook,admin:org_hook,notification,user,delete_repo,package,admin:gpg_key,sudo", "all,sudo", nil}, + {"repo,admin:org,admin:public_key,admin:repo_hook,admin:org_hook,notification,user,delete_repo,package,admin:gpg_key,admin:application", "all", nil}, + {"repo,admin:org,admin:public_key,admin:repo_hook,admin:org_hook,notification,user,delete_repo,package,admin:gpg_key,admin:application,sudo", "all,sudo", nil}, } for _, test := range tests { From 143c85124d2a7322f9d5be8c65e85fac2b7b51d5 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Wed, 9 Nov 2022 00:39:49 -0500 Subject: [PATCH 083/118] Fix unit testing --- models/auth/token_scope.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/models/auth/token_scope.go b/models/auth/token_scope.go index c82c64bd99307..728ca55540f50 100644 --- a/models/auth/token_scope.go +++ b/models/auth/token_scope.go @@ -175,7 +175,7 @@ func (bitmap AccessTokenScopeBitmap) ToScope() AccessTokenScope { switch v { // Parse scopes that contains multiple sub-scopes case AccessTokenScopeRepo, AccessTokenScopeAdminOrg, AccessTokenScopeAdminPublicKey, - AccessTokenScopeUser, AccessTokenScopePackage, AccessTokenScopeAdminGPGKey: + AccessTokenScopeUser, AccessTokenScopePackage, AccessTokenScopeAdminGPGKey, AccessTokenScopeAdminApplication: groupedScope[v] = struct{}{} case AccessTokenScopeAdminRepoHook: groupedScope[v] = struct{}{} From be8466957fbfe0b003c637b108a99c01e4af51fc Mon Sep 17 00:00:00 2001 From: harryzcy Date: Wed, 9 Nov 2022 01:23:17 -0500 Subject: [PATCH 084/118] Update token scope of `/api/v1/user/applications` --- routers/api/v1/api.go | 12 ++++++------ tests/integration/api_oauth2_apps_test.go | 6 +++--- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index ef7f4a3a4a494..7062b5994641e 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -772,13 +772,13 @@ func Routes(ctx gocontext.Context) *web.Route { // (repo scope) m.Group("/applications", func() { m.Combo("/oauth2"). - Get(user.ListOauth2Applications). - Post(bind(api.CreateOAuth2ApplicationOptions{}), user.CreateOauth2Application) + Get(reqToken(auth_model.AccessTokenScopeReadApplication), user.ListOauth2Applications). + Post(reqToken(auth_model.AccessTokenScopeWriteApplication), bind(api.CreateOAuth2ApplicationOptions{}), user.CreateOauth2Application) m.Combo("/oauth2/{id}"). - Delete(user.DeleteOauth2Application). - Patch(bind(api.CreateOAuth2ApplicationOptions{}), user.UpdateOauth2Application). - Get(user.GetOauth2Application) - }, reqToken(auth_model.AccessTokenScopeRepo)) + Delete(reqToken(auth_model.AccessTokenScopeWriteApplication), user.DeleteOauth2Application). + Patch(reqToken(auth_model.AccessTokenScopeWriteApplication), bind(api.CreateOAuth2ApplicationOptions{}), user.UpdateOauth2Application). + Get(reqToken(auth_model.AccessTokenScopeReadApplication), user.GetOauth2Application) + }) // (admin:gpg_key scope) m.Group("/gpg_keys", func() { diff --git a/tests/integration/api_oauth2_apps_test.go b/tests/integration/api_oauth2_apps_test.go index 0ab97843a96a0..fb52f72e0e67d 100644 --- a/tests/integration/api_oauth2_apps_test.go +++ b/tests/integration/api_oauth2_apps_test.go @@ -56,7 +56,7 @@ func testAPICreateOAuth2Application(t *testing.T) { func testAPIListOAuth2Applications(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, "read_application") existApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ UID: user.ID, @@ -87,7 +87,7 @@ func testAPIListOAuth2Applications(t *testing.T) { func testAPIDeleteOAuth2Application(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, "write_application") oldApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ UID: user.ID, @@ -108,7 +108,7 @@ func testAPIDeleteOAuth2Application(t *testing.T) { func testAPIGetOAuth2Application(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, "read_application") existApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ UID: user.ID, From cd1e422011a019cbd106675eed1b45dcce4664f2 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Wed, 9 Nov 2022 01:24:28 -0500 Subject: [PATCH 085/118] Update comment --- routers/api/v1/api.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 7062b5994641e..737888136b47b 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -769,7 +769,7 @@ func Routes(ctx gocontext.Context) *web.Route { Delete(reqToken(auth_model.AccessTokenScopeWritePublicKey), user.DeletePublicKey) }) - // (repo scope) + // (admin:application scope) m.Group("/applications", func() { m.Combo("/oauth2"). Get(reqToken(auth_model.AccessTokenScopeReadApplication), user.ListOauth2Applications). From 28b1326642deeca79942e5125c92998a85aba75c Mon Sep 17 00:00:00 2001 From: harryzcy Date: Wed, 9 Nov 2022 01:49:43 -0500 Subject: [PATCH 086/118] Update frontend to add the new scope --- services/forms/user_form.go | 112 ++++++++++++---------- templates/user/settings/applications.tmpl | 20 ++++ 2 files changed, 79 insertions(+), 53 deletions(-) diff --git a/services/forms/user_form.go b/services/forms/user_form.go index 8cb2ee6bba0c1..211d3e26ef82a 100644 --- a/services/forms/user_form.go +++ b/services/forms/user_form.go @@ -371,33 +371,36 @@ func (f *AddKeyForm) Validate(req *http.Request, errs binding.Errors) binding.Er // NewAccessTokenForm form for creating access token type NewAccessTokenForm struct { - Name string `binding:"Required;MaxSize(255)"` - ScopeRepo bool - ScopeRepoStatus bool - ScopePublicRepo bool - ScopeAdminOrg bool - ScopeWriteOrg bool - ScopeReadOrg bool - ScopeAdminPublicKey bool - ScopeWritePublicKey bool - ScopeReadPublicKey bool - ScopeAdminRepoHook bool - ScopeWriteRepoHook bool - ScopeReadRepoHook bool - ScopeNotification bool - ScopeUser bool - ScopeReadUser bool - ScopeUserEmail bool - ScopeUserFollow bool - ScopeDeleteRepo bool - ScopePackage bool - ScopeWritePackage bool - ScopeReadPackage bool - ScopeDeletePackage bool - ScopeAdminGPGKey bool - ScopeWriteGPGKey bool - ScopeReadGPGKey bool - ScopeSudo bool + Name string `binding:"Required;MaxSize(255)"` + ScopeRepo bool + ScopeRepoStatus bool + ScopePublicRepo bool + ScopeAdminOrg bool + ScopeWriteOrg bool + ScopeReadOrg bool + ScopeAdminPublicKey bool + ScopeWritePublicKey bool + ScopeReadPublicKey bool + ScopeAdminRepoHook bool + ScopeWriteRepoHook bool + ScopeReadRepoHook bool + ScopeNotification bool + ScopeUser bool + ScopeReadUser bool + ScopeUserEmail bool + ScopeUserFollow bool + ScopeDeleteRepo bool + ScopePackage bool + ScopeWritePackage bool + ScopeReadPackage bool + ScopeDeletePackage bool + ScopeAdminGPGKey bool + ScopeWriteGPGKey bool + ScopeReadGPGKey bool + ScopeAdminApplication bool + ScopeWriteApplication bool + ScopeReadApplication bool + ScopeSudo bool } // Validate validates the fields @@ -408,32 +411,35 @@ func (f *NewAccessTokenForm) Validate(req *http.Request, errs binding.Errors) bi func (f *NewAccessTokenForm) GetScope() auth_model.AccessTokenScope { scopesMapping := map[string]string{ - "Repo": auth_model.AccessTokenScopeRepo, - "RepoStatus": auth_model.AccessTokenScopeRepoStatus, - "PublicRepo": auth_model.AccessTokenScopePublicRepo, - "AdminOrg": auth_model.AccessTokenScopeAdminOrg, - "WriteOrg": auth_model.AccessTokenScopeWriteOrg, - "ReadOrg": auth_model.AccessTokenScopeReadOrg, - "AdminPublicKey": auth_model.AccessTokenScopeAdminPublicKey, - "WritePublicKey": auth_model.AccessTokenScopeWritePublicKey, - "ReadPublicKey": auth_model.AccessTokenScopeReadPublicKey, - "AdminRepoHook": auth_model.AccessTokenScopeAdminRepoHook, - "WriteRepoHook": auth_model.AccessTokenScopeWriteRepoHook, - "ReadRepoHook": auth_model.AccessTokenScopeReadRepoHook, - "Notification": auth_model.AccessTokenScopeNotification, - "User": auth_model.AccessTokenScopeUser, - "ReadUser": auth_model.AccessTokenScopeReadUser, - "UserEmail": auth_model.AccessTokenScopeUserEmail, - "UserFollow": auth_model.AccessTokenScopeUserFollow, - "DeleteRepo": auth_model.AccessTokenScopeDeleteRepo, - "Package": auth_model.AccessTokenScopePackage, - "WritePackage": auth_model.AccessTokenScopeWritePackage, - "ReadPackage": auth_model.AccessTokenScopeReadPackage, - "DeletePackage": auth_model.AccessTokenScopeDeletePackage, - "AdminGPGKey": auth_model.AccessTokenScopeAdminGPGKey, - "WriteGPGKey": auth_model.AccessTokenScopeWriteGPGKey, - "ReadGPGKey": auth_model.AccessTokenScopeReadGPGKey, - "Sudo": auth_model.AccessTokenScopeSudo, + "Repo": auth_model.AccessTokenScopeRepo, + "RepoStatus": auth_model.AccessTokenScopeRepoStatus, + "PublicRepo": auth_model.AccessTokenScopePublicRepo, + "AdminOrg": auth_model.AccessTokenScopeAdminOrg, + "WriteOrg": auth_model.AccessTokenScopeWriteOrg, + "ReadOrg": auth_model.AccessTokenScopeReadOrg, + "AdminPublicKey": auth_model.AccessTokenScopeAdminPublicKey, + "WritePublicKey": auth_model.AccessTokenScopeWritePublicKey, + "ReadPublicKey": auth_model.AccessTokenScopeReadPublicKey, + "AdminRepoHook": auth_model.AccessTokenScopeAdminRepoHook, + "WriteRepoHook": auth_model.AccessTokenScopeWriteRepoHook, + "ReadRepoHook": auth_model.AccessTokenScopeReadRepoHook, + "Notification": auth_model.AccessTokenScopeNotification, + "User": auth_model.AccessTokenScopeUser, + "ReadUser": auth_model.AccessTokenScopeReadUser, + "UserEmail": auth_model.AccessTokenScopeUserEmail, + "UserFollow": auth_model.AccessTokenScopeUserFollow, + "DeleteRepo": auth_model.AccessTokenScopeDeleteRepo, + "Package": auth_model.AccessTokenScopePackage, + "WritePackage": auth_model.AccessTokenScopeWritePackage, + "ReadPackage": auth_model.AccessTokenScopeReadPackage, + "DeletePackage": auth_model.AccessTokenScopeDeletePackage, + "AdminGPGKey": auth_model.AccessTokenScopeAdminGPGKey, + "WriteGPGKey": auth_model.AccessTokenScopeWriteGPGKey, + "ReadGPGKey": auth_model.AccessTokenScopeReadGPGKey, + "AdminApplication": auth_model.AccessTokenScopeAdminApplication, + "WriteApplication": auth_model.AccessTokenScopeWriteApplication, + "ReadApplication": auth_model.AccessTokenScopeReadApplication, + "Sudo": auth_model.AccessTokenScopeSudo, } scope := "" diff --git a/templates/user/settings/applications.tmpl b/templates/user/settings/applications.tmpl index fd32d2cb5723c..fe4535eb7b2cd 100644 --- a/templates/user/settings/applications.tmpl +++ b/templates/user/settings/applications.tmpl @@ -215,6 +215,26 @@
+
+
+ + +
+
+
+
+
+ + +
+
+
+
+ + +
+
+
From 4f38d449e30e7e51f6bbaa04b61ea5a7e2b5d646 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Wed, 9 Nov 2022 02:38:45 -0500 Subject: [PATCH 087/118] Fix auth functions to allow either token or sigs --- routers/api/v1/api.go | 27 ++++++++++++--------------- services/auth/basic.go | 6 ++---- services/auth/httpsign.go | 4 +--- 3 files changed, 15 insertions(+), 22 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 737888136b47b..e4dfd66513175 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -211,7 +211,7 @@ func reqPackageAccess(accessMode perm.AccessMode) func(ctx *context.APIContext) // Contexter middleware already checks token for user sign in process. func reqToken(requiredScope string) func(ctx *context.APIContext) { return func(ctx *context.APIContext) { - if true == ctx.Data["IsApiToken"] { + if ctx.Data["IsApiToken"] == true { // no scope required if requiredScope == "" { return @@ -251,19 +251,6 @@ func reqToken(requiredScope string) func(ctx *context.APIContext) { } } -// reqSiteAdminOrToken user should be the site admin, or the token should have 'sudo' scope. -func reqSiteAdminOrToken() func(ctx *context.APIContext) { - return func(ctx *context.APIContext) { - // if is site admin, allow it - if ctx.IsUserSiteAdmin() { - return - } - - // otherwise, check token - reqToken("sudo")(ctx) - } -} - func reqExploreSignIn() func(ctx *context.APIContext) { return func(ctx *context.APIContext) { if setting.Service.Explore.RequireSigninView && !ctx.IsSigned { @@ -285,6 +272,16 @@ func reqBasicOrRevProxyAuth() func(ctx *context.APIContext) { } } +// reqSiteAdmin user should be the site admin +func reqSiteAdmin() func(ctx *context.APIContext) { + return func(ctx *context.APIContext) { + if !ctx.IsUserSiteAdmin() { + ctx.Error(http.StatusForbidden, "reqSiteAdmin", "user should be the site admin") + return + } + } +} + // reqOwner user should be the owner of the repo or site admin. func reqOwner() func(ctx *context.APIContext) { return func(ctx *context.APIContext) { @@ -1209,7 +1206,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Post("/{username}/{reponame}", admin.AdoptRepository) m.Delete("/{username}/{reponame}", admin.DeleteUnadoptedRepository) }) - }, reqSiteAdminOrToken()) + }, reqToken("sudo"), reqSiteAdmin()) m.Group("/topics", func() { m.Get("/search", repo.TopicSearch) diff --git a/services/auth/basic.go b/services/auth/basic.go index 5011a64e02af7..ae0ded33e6578 100644 --- a/services/auth/basic.go +++ b/services/auth/basic.go @@ -81,8 +81,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore return nil } - store.GetData()["IsApiToken"] = true - store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScope(auth_model.AccessTokenScopeAll) + store.GetData()["IsApiToken"] = false return u } @@ -100,8 +99,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore log.Error("UpdateAccessToken: %v", err) } - store.GetData()["IsApiToken"] = true - store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScope(auth_model.AccessTokenScopeAll) + store.GetData()["IsApiToken"] = false return u } else if !auth_model.IsErrAccessTokenNotExist(err) && !auth_model.IsErrAccessTokenEmpty(err) { log.Error("GetAccessTokenBySha: %v", err) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index f800a509d941d..8d0b543d6ee0a 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -13,7 +13,6 @@ import ( "strings" asymkey_model "code.gitea.io/gitea/models/asymkey" - auth_model "code.gitea.io/gitea/models/auth" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -80,8 +79,7 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt return nil } - store.GetData()["IsApiToken"] = true - store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScope(auth_model.AccessTokenScopeAll) + store.GetData()["IsApiToken"] = false log.Trace("HTTP Sign: Logged in user %-v", u) From 9abd5ab2051fc1850eed1f1406ad2d0c61ed8c59 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Fri, 11 Nov 2022 01:49:09 -0500 Subject: [PATCH 088/118] [doc] Add token scopes doc --- .../doc/developers/oauth2-provider.en-us.md | 36 ++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/docs/content/doc/developers/oauth2-provider.en-us.md b/docs/content/doc/developers/oauth2-provider.en-us.md index c6765f19e7aab..e75727d4d10a0 100644 --- a/docs/content/doc/developers/oauth2-provider.en-us.md +++ b/docs/content/doc/developers/oauth2-provider.en-us.md @@ -42,7 +42,41 @@ To use the Authorization Code Grant as a third party application it is required ## Scopes -Currently Gitea does not support scopes (see [#4300](https://github.com/go-gitea/gitea/issues/4300)) and all third party applications will be granted access to all resources of the user and their organizations. +Gitea supports the following scopes for tokens: + +| Name | Description | +| ---- | ----------- | +| **(no scope)** | Grants read-only access to public user profile and public repositories. | +| **repo** | Full control over all repositories. | +|     **repo:status** | Grants read/write access to commit status in all repositories. | +|     **public_repo** | Grants read/write access to public repositories only. | +| **admin:repo_hook** | Grants access to repository hooks of all repositories. This is included in the `repo` scope. | +|     **write:repo_hook** | | +|     **read:repo_hook** | | +| **admin:org** | | +|     **write:org** | | +|     **read:org** | | +| **admin:public_key** | | +|     **write:public_key** | | +|     **read:public_key** | | +| **admin:org_hook** | | +| **notification** | | +| **user** | | +|     **read:user** | | +|     **user:email** | | +|     **user:follow** | | +| **delete_repo** | | +| **package** | | +|     **write:package** | | +|     **read:package** | | +|     **delete:package** | | +| **admin:gpg_key** | | +|     **write:gpg_key** | | +|     **read:gpg_key** | | +| **admin:application** | | +|     **write:application** | | +|     **read:application** | | +| **sudo** | Allows to perform actions as the site admin. | ## Client types From 0ddab2894c008135c630a412bf30742efe6a8fa1 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Fri, 11 Nov 2022 02:31:00 -0500 Subject: [PATCH 089/118] Fix `repo:status` token --- routers/api/v1/api.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index e4dfd66513175..821f3ea0b01fb 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -1061,7 +1061,7 @@ func Routes(ctx gocontext.Context) *web.Route { }, mustAllowPulls, reqRepoReader(unit.TypeCode), context.ReferencesGitRepo()) m.Group("/statuses", func() { m.Combo("/{sha}").Get(repo.GetCommitStatuses). - Post(reqToken(auth_model.AccessTokenScopeRepo), reqRepoWriter(unit.TypeCode), bind(api.CreateStatusOption{}), repo.NewCommitStatus) + Post(reqToken(auth_model.AccessTokenScopeRepoStatus), reqRepoWriter(unit.TypeCode), bind(api.CreateStatusOption{}), repo.NewCommitStatus) }, reqRepoReader(unit.TypeCode)) m.Group("/commits", func() { m.Get("", context.ReferencesGitRepo(), repo.GetAllCommits) From 08836037b5f1a1f2781cde01cd273e5199395a71 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sat, 12 Nov 2022 02:18:42 -0500 Subject: [PATCH 090/118] Rewrite scope logic to let write:* contain read:* --- models/auth/token_scope.go | 190 ++++++++++++++++---------------- models/auth/token_scope_test.go | 3 + 2 files changed, 98 insertions(+), 95 deletions(-) diff --git a/models/auth/token_scope.go b/models/auth/token_scope.go index 728ca55540f50..dca69aa2a26cd 100644 --- a/models/auth/token_scope.go +++ b/models/auth/token_scope.go @@ -60,6 +60,60 @@ const ( AccessTokenScopeSudo = "sudo" ) +// AccessTokenScopeBitmap represents a bitmap of access token scopes. +type AccessTokenScopeBitmap uint64 + +// Bitmap of each scope, including the child scopes. +const ( + // AccessTokenScopeAllBits is the bitmap of all access token scopes. + AccessTokenScopeAllBits = AccessTokenScopeRepoBits | + AccessTokenScopeAdminOrgBits | AccessTokenScopeAdminPublicKeyBits | AccessTokenScopeAdminOrgHookBits | + AccessTokenScopeNotificationBits | AccessTokenScopeUserBits | AccessTokenScopeDeleteRepoBits | + AccessTokenScopePackageBits | AccessTokenScopeAdminGPGKeyBits | AccessTokenScopeAdminApplicationBits + + AccessTokenScopeRepoBits = 1< Date: Wed, 16 Nov 2022 22:31:25 -0500 Subject: [PATCH 091/118] Use constant `AccessTokenScopeSudo` in api.go Co-authored-by: KN4CK3R --- routers/api/v1/api.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index df247d68f43a2..5fc4d4576085b 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -1206,7 +1206,7 @@ func Routes(ctx gocontext.Context) *web.Route { m.Post("/{username}/{reponame}", admin.AdoptRepository) m.Delete("/{username}/{reponame}", admin.DeleteUnadoptedRepository) }) - }, reqToken("sudo"), reqSiteAdmin()) + }, reqToken(auth_model.AccessTokenScopeSudo), reqSiteAdmin()) m.Group("/topics", func() { m.Get("/search", repo.TopicSearch) From 50a3c5f0d0cabd7298e73abf6cf2aa10bfae8b2e Mon Sep 17 00:00:00 2001 From: harryzcy Date: Thu, 17 Nov 2022 23:47:54 -0500 Subject: [PATCH 092/118] Update access token form and update tests to use constants --- routers/web/user/setting/applications.go | 7 +- services/forms/user_form.go | 81 ++----------------- services/forms/user_form_test.go | 13 +-- templates/user/settings/applications.tmpl | 60 +++++++------- tests/integration/api_admin_org_test.go | 5 +- tests/integration/api_admin_test.go | 19 ++--- tests/integration/api_branch_test.go | 17 ++-- tests/integration/api_gpg_keys_test.go | 5 +- tests/integration/api_httpsig_test.go | 3 +- tests/integration/api_issue_label_test.go | 9 ++- tests/integration/api_issue_milestone_test.go | 3 +- tests/integration/api_issue_reaction_test.go | 5 +- tests/integration/api_issue_stopwatch_test.go | 9 ++- .../api_issue_subscription_test.go | 3 +- tests/integration/api_issue_test.go | 7 +- .../api_issue_tracked_time_test.go | 7 +- tests/integration/api_keys_test.go | 9 ++- tests/integration/api_notification_test.go | 5 +- tests/integration/api_oauth2_apps_test.go | 7 +- tests/integration/api_org_test.go | 9 ++- .../api_packages_container_test.go | 3 +- tests/integration/api_packages_test.go | 5 +- tests/integration/api_pull_review_test.go | 7 +- tests/integration/api_pull_test.go | 13 +-- tests/integration/api_releases_test.go | 11 +-- tests/integration/api_repo_archive_test.go | 3 +- .../integration/api_repo_collaborator_test.go | 9 ++- tests/integration/api_repo_edit_test.go | 5 +- .../integration/api_repo_file_create_test.go | 7 +- .../integration/api_repo_file_delete_test.go | 5 +- tests/integration/api_repo_file_get_test.go | 3 +- .../integration/api_repo_file_update_test.go | 5 +- tests/integration/api_repo_git_hook_test.go | 19 ++--- tests/integration/api_repo_git_tags_test.go | 3 +- tests/integration/api_repo_hook_test.go | 3 +- .../integration/api_repo_lfs_migrate_test.go | 3 +- tests/integration/api_repo_lfs_test.go | 3 +- tests/integration/api_repo_raw_test.go | 3 +- tests/integration/api_repo_tags_test.go | 3 +- tests/integration/api_repo_teams_test.go | 5 +- tests/integration/api_repo_test.go | 35 ++++---- tests/integration/api_repo_topic_test.go | 5 +- tests/integration/api_team_test.go | 15 ++-- tests/integration/api_team_user_test.go | 3 +- tests/integration/api_user_email_test.go | 7 +- tests/integration/api_user_follow_test.go | 3 +- tests/integration/api_user_org_perm_test.go | 7 +- tests/integration/api_user_orgs_test.go | 5 +- tests/integration/api_user_star_test.go | 3 +- tests/integration/api_user_watch_test.go | 3 +- tests/integration/api_wiki_test.go | 5 +- tests/integration/dump_restore_test.go | 3 +- tests/integration/eventsource_test.go | 3 +- tests/integration/git_test.go | 9 ++- tests/integration/gpg_git_test.go | 25 +++--- tests/integration/integration_test.go | 16 ++-- tests/integration/migrate_test.go | 3 +- tests/integration/org_count_test.go | 3 +- tests/integration/org_test.go | 3 +- tests/integration/privateactivity_test.go | 3 +- tests/integration/pull_merge_test.go | 5 +- tests/integration/pull_status_test.go | 3 +- tests/integration/pull_update_test.go | 5 +- tests/integration/repo_commits_test.go | 3 +- tests/integration/ssh_key_test.go | 9 ++- tests/integration/user_test.go | 3 +- 66 files changed, 296 insertions(+), 292 deletions(-) diff --git a/routers/web/user/setting/applications.go b/routers/web/user/setting/applications.go index c36436e8934c9..53795b008e90a 100644 --- a/routers/web/user/setting/applications.go +++ b/routers/web/user/setting/applications.go @@ -43,10 +43,15 @@ func ApplicationsPost(ctx *context.Context) { return } + scope, err := form.GetScope() + if err != nil { + ctx.ServerError("GetScope", err) + return + } t := &auth_model.AccessToken{ UID: ctx.Doer.ID, Name: form.Name, - Scope: form.GetScope(), + Scope: scope, } exist, err := auth_model.AccessTokenByNameExists(t) diff --git a/services/forms/user_form.go b/services/forms/user_form.go index 211d3e26ef82a..2c9c251381ec9 100644 --- a/services/forms/user_form.go +++ b/services/forms/user_form.go @@ -8,7 +8,6 @@ package forms import ( "mime/multipart" "net/http" - "reflect" "strings" auth_model "code.gitea.io/gitea/models/auth" @@ -371,36 +370,8 @@ func (f *AddKeyForm) Validate(req *http.Request, errs binding.Errors) binding.Er // NewAccessTokenForm form for creating access token type NewAccessTokenForm struct { - Name string `binding:"Required;MaxSize(255)"` - ScopeRepo bool - ScopeRepoStatus bool - ScopePublicRepo bool - ScopeAdminOrg bool - ScopeWriteOrg bool - ScopeReadOrg bool - ScopeAdminPublicKey bool - ScopeWritePublicKey bool - ScopeReadPublicKey bool - ScopeAdminRepoHook bool - ScopeWriteRepoHook bool - ScopeReadRepoHook bool - ScopeNotification bool - ScopeUser bool - ScopeReadUser bool - ScopeUserEmail bool - ScopeUserFollow bool - ScopeDeleteRepo bool - ScopePackage bool - ScopeWritePackage bool - ScopeReadPackage bool - ScopeDeletePackage bool - ScopeAdminGPGKey bool - ScopeWriteGPGKey bool - ScopeReadGPGKey bool - ScopeAdminApplication bool - ScopeWriteApplication bool - ScopeReadApplication bool - ScopeSudo bool + Name string `binding:"Required;MaxSize(255)"` + Scope []string } // Validate validates the fields @@ -409,50 +380,10 @@ func (f *NewAccessTokenForm) Validate(req *http.Request, errs binding.Errors) bi return middleware.Validate(errs, ctx.Data, f, ctx.Locale) } -func (f *NewAccessTokenForm) GetScope() auth_model.AccessTokenScope { - scopesMapping := map[string]string{ - "Repo": auth_model.AccessTokenScopeRepo, - "RepoStatus": auth_model.AccessTokenScopeRepoStatus, - "PublicRepo": auth_model.AccessTokenScopePublicRepo, - "AdminOrg": auth_model.AccessTokenScopeAdminOrg, - "WriteOrg": auth_model.AccessTokenScopeWriteOrg, - "ReadOrg": auth_model.AccessTokenScopeReadOrg, - "AdminPublicKey": auth_model.AccessTokenScopeAdminPublicKey, - "WritePublicKey": auth_model.AccessTokenScopeWritePublicKey, - "ReadPublicKey": auth_model.AccessTokenScopeReadPublicKey, - "AdminRepoHook": auth_model.AccessTokenScopeAdminRepoHook, - "WriteRepoHook": auth_model.AccessTokenScopeWriteRepoHook, - "ReadRepoHook": auth_model.AccessTokenScopeReadRepoHook, - "Notification": auth_model.AccessTokenScopeNotification, - "User": auth_model.AccessTokenScopeUser, - "ReadUser": auth_model.AccessTokenScopeReadUser, - "UserEmail": auth_model.AccessTokenScopeUserEmail, - "UserFollow": auth_model.AccessTokenScopeUserFollow, - "DeleteRepo": auth_model.AccessTokenScopeDeleteRepo, - "Package": auth_model.AccessTokenScopePackage, - "WritePackage": auth_model.AccessTokenScopeWritePackage, - "ReadPackage": auth_model.AccessTokenScopeReadPackage, - "DeletePackage": auth_model.AccessTokenScopeDeletePackage, - "AdminGPGKey": auth_model.AccessTokenScopeAdminGPGKey, - "WriteGPGKey": auth_model.AccessTokenScopeWriteGPGKey, - "ReadGPGKey": auth_model.AccessTokenScopeReadGPGKey, - "AdminApplication": auth_model.AccessTokenScopeAdminApplication, - "WriteApplication": auth_model.AccessTokenScopeWriteApplication, - "ReadApplication": auth_model.AccessTokenScopeReadApplication, - "Sudo": auth_model.AccessTokenScopeSudo, - } - - scope := "" - v := reflect.ValueOf(*f) - for i := 0; i < v.NumField(); i++ { - if strings.HasPrefix(v.Type().Field(i).Name, "Scope") && v.Field(i).Bool() { - singleScope := strings.TrimPrefix(v.Type().Field(i).Name, "Scope") - scope += scopesMapping[singleScope] + "," - } - } - scope = strings.TrimSuffix(scope, ",") - s, _ := auth_model.AccessTokenScope(scope).Normalize() // error should not happen, since fields are valid scopes - return s +func (f *NewAccessTokenForm) GetScope() (auth_model.AccessTokenScope, error) { + scope := strings.Join(f.Scope, ",") + s, err := auth_model.AccessTokenScope(scope).Normalize() + return s, err } // EditOAuth2ApplicationForm form for editing oauth2 applications diff --git a/services/forms/user_form_test.go b/services/forms/user_form_test.go index 8603694de5fd3..03895ce9ae081 100644 --- a/services/forms/user_form_test.go +++ b/services/forms/user_form_test.go @@ -89,22 +89,25 @@ func TestRegisterForm_IsDomainAllowed_BlocklistedEmail(t *testing.T) { func TestNewAccessTokenForm_GetScope(t *testing.T) { tests := []struct { - form NewAccessTokenForm - scope auth_model.AccessTokenScope + form NewAccessTokenForm + scope auth_model.AccessTokenScope + expectedErr error }{ { - form: NewAccessTokenForm{Name: "test", ScopeRepo: true}, + form: NewAccessTokenForm{Name: "test", Scope: []string{"repo"}}, scope: "repo", }, { - form: NewAccessTokenForm{Name: "test", ScopeRepo: true, ScopeUser: true}, + form: NewAccessTokenForm{Name: "test", Scope: []string{"repo", "user"}}, scope: "repo,user", }, } for i, test := range tests { t.Run(strconv.Itoa(i), func(t *testing.T) { - assert.Equal(t, test.scope, test.form.GetScope()) + scope, err := test.form.GetScope() + assert.Equal(t, test.expectedErr, err) + assert.Equal(t, test.scope, scope) }) } } diff --git a/templates/user/settings/applications.tmpl b/templates/user/settings/applications.tmpl index fe4535eb7b2cd..c108f20b5b32c 100644 --- a/templates/user/settings/applications.tmpl +++ b/templates/user/settings/applications.tmpl @@ -47,197 +47,197 @@
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
- +
diff --git a/tests/integration/api_admin_org_test.go b/tests/integration/api_admin_org_test.go index aaa27517496ba..c52a6ec7497dc 100644 --- a/tests/integration/api_admin_org_test.go +++ b/tests/integration/api_admin_org_test.go @@ -10,6 +10,7 @@ import ( "strings" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" api "code.gitea.io/gitea/modules/structs" @@ -21,7 +22,7 @@ import ( func TestAPIAdminOrgCreate(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "sudo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeSudo) org := api.CreateOrgOption{ UserName: "user2_org", @@ -55,7 +56,7 @@ func TestAPIAdminOrgCreate(t *testing.T) { func TestAPIAdminOrgCreateBadVisibility(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "sudo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeSudo) org := api.CreateOrgOption{ UserName: "user2_org", diff --git a/tests/integration/api_admin_test.go b/tests/integration/api_admin_test.go index 22ea06955c8cf..181c2d4507d99 100644 --- a/tests/integration/api_admin_test.go +++ b/tests/integration/api_admin_test.go @@ -10,6 +10,7 @@ import ( "testing" asymkey_model "code.gitea.io/gitea/models/asymkey" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/json" @@ -53,7 +54,7 @@ func TestAPIAdminDeleteMissingSSHKey(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "sudo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeSudo) req := NewRequestf(t, "DELETE", "/api/v1/admin/users/user1/keys/%d?token=%s", unittest.NonexistentID, token) session.MakeRequest(t, req, http.StatusNotFound) } @@ -64,7 +65,7 @@ func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) { normalUsername := "user2" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session, "sudo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeSudo) urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys?token=%s", adminUsername, token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n", @@ -86,7 +87,7 @@ func TestAPISudoUser(t *testing.T) { adminUsername := "user1" normalUsername := "user2" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session, "sudo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeSudo) urlStr := fmt.Sprintf("/api/v1/user?sudo=%s&token=%s", normalUsername, token) req := NewRequest(t, "GET", urlStr) @@ -103,7 +104,7 @@ func TestAPISudoUserForbidden(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session, "sudo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeSudo) urlStr := fmt.Sprintf("/api/v1/user?sudo=%s&token=%s", adminUsername, token) req := NewRequest(t, "GET", urlStr) @@ -114,7 +115,7 @@ func TestAPIListUsers(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session, "sudo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeSudo) urlStr := fmt.Sprintf("/api/v1/admin/users?token=%s", token) req := NewRequest(t, "GET", urlStr) @@ -152,7 +153,7 @@ func TestAPICreateUserInvalidEmail(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session, "sudo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeSudo) urlStr := fmt.Sprintf("/api/v1/admin/users?token=%s", token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "email": "invalid_email@domain.com\r\n", @@ -171,7 +172,7 @@ func TestAPICreateAndDeleteUser(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session, "sudo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeSudo) req := NewRequestWithValues( t, @@ -198,7 +199,7 @@ func TestAPIEditUser(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session, "sudo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeSudo) urlStr := fmt.Sprintf("/api/v1/admin/users/%s?token=%s", "user2", token) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ @@ -241,7 +242,7 @@ func TestAPICreateRepoForUser(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" session := loginUser(t, adminUsername) - token := getTokenForLoggedInUser(t, session, "sudo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeSudo) req := NewRequestWithJSON( t, diff --git a/tests/integration/api_branch_test.go b/tests/integration/api_branch_test.go index 7614aee117ec0..966cfbe3ba9e4 100644 --- a/tests/integration/api_branch_test.go +++ b/tests/integration/api_branch_test.go @@ -9,6 +9,7 @@ import ( "net/url" "testing" + auth_model "code.gitea.io/gitea/models/auth" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/tests" @@ -17,7 +18,7 @@ import ( func testAPIGetBranch(t *testing.T, branchName string, exists bool) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branches/%s?token=%s", branchName, token) resp := session.MakeRequest(t, req, NoExpectedStatus) if !exists { @@ -34,7 +35,7 @@ func testAPIGetBranch(t *testing.T, branchName string, exists bool) { func testAPIGetBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branch_protections/%s?token=%s", branchName, token) resp := session.MakeRequest(t, req, expectedHTTPStatus) @@ -47,7 +48,7 @@ func testAPIGetBranchProtection(t *testing.T, branchName string, expectedHTTPSta func testAPICreateBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/branch_protections?token="+token, &api.BranchProtection{ BranchName: branchName, }) @@ -62,7 +63,7 @@ func testAPICreateBranchProtection(t *testing.T, branchName string, expectedHTTP func testAPIEditBranchProtection(t *testing.T, branchName string, body *api.BranchProtection, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestWithJSON(t, "PATCH", "/api/v1/repos/user2/repo1/branch_protections/"+branchName+"?token="+token, body) resp := session.MakeRequest(t, req, expectedHTTPStatus) @@ -75,14 +76,14 @@ func testAPIEditBranchProtection(t *testing.T, branchName string, body *api.Bran func testAPIDeleteBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branch_protections/%s?token=%s", branchName, token) session.MakeRequest(t, req, expectedHTTPStatus) } func testAPIDeleteBranch(t *testing.T, branchName string, expectedHTTPStatus int) { session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branches/%s?token=%s", branchName, token) session.MakeRequest(t, req, expectedHTTPStatus) } @@ -108,7 +109,7 @@ func TestAPICreateBranch(t *testing.T) { func testAPICreateBranches(t *testing.T, giteaURL *url.URL) { username := "user2" - ctx := NewAPITestContext(t, username, "my-noo-repo", "repo") + ctx := NewAPITestContext(t, username, "my-noo-repo", auth_model.AccessTokenScopeRepo) giteaURL.Path = ctx.GitPath() t.Run("CreateRepo", doAPICreateRepository(ctx, false)) @@ -156,7 +157,7 @@ func testAPICreateBranches(t *testing.T, giteaURL *url.URL) { } func testAPICreateBranch(t testing.TB, session *TestSession, user, repo, oldBranch, newBranch string, status int) bool { - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestWithJSON(t, "POST", "/api/v1/repos/"+user+"/"+repo+"/branches?token="+token, &api.CreateBranchRepoOption{ BranchName: newBranch, OldBranchName: oldBranch, diff --git a/tests/integration/api_gpg_keys_test.go b/tests/integration/api_gpg_keys_test.go index 46a7e8d702d9d..c80f64f648e68 100644 --- a/tests/integration/api_gpg_keys_test.go +++ b/tests/integration/api_gpg_keys_test.go @@ -10,6 +10,7 @@ import ( "strconv" "testing" + auth_model "code.gitea.io/gitea/models/auth" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/tests" @@ -21,8 +22,8 @@ type makeRequestFunc func(testing.TB, *http.Request, int) *httptest.ResponseReco func TestGPGKeys(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") - tokenWithGPGKeyScope := getTokenForLoggedInUser(t, session, "admin_gpg_key", "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) + tokenWithGPGKeyScope := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeAdminGPGKey, auth_model.AccessTokenScopeRepo) tt := []struct { name string diff --git a/tests/integration/api_httpsig_test.go b/tests/integration/api_httpsig_test.go index e8af69dcf7028..f611c8838ca54 100644 --- a/tests/integration/api_httpsig_test.go +++ b/tests/integration/api_httpsig_test.go @@ -11,6 +11,7 @@ import ( "net/url" "testing" + auth_model "code.gitea.io/gitea/models/auth" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/tests" @@ -53,7 +54,7 @@ func TestHTTPSigPubKey(t *testing.T) { // Add our public key to user1 defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") - token := url.QueryEscape(getTokenForLoggedInUser(t, session, "admin_public_key", "sudo")) + token := url.QueryEscape(getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeAdminPublicKey, auth_model.AccessTokenScopeSudo)) keysURL := fmt.Sprintf("/api/v1/user/keys?token=%s", token) keyType := "ssh-rsa" keyContent := "AAAAB3NzaC1yc2EAAAADAQABAAABAQCqOZB5vkRvXFXups1/0StDRdG8plbNSwsWEnNnP4Bvurxa0+z3W9B8GLKnDiLw5MbpbMNyBlpXw13GfuIeciy10DWTz0xUbiy3J3KabCaT36asIw2y7k6Z0jL0UBnrVENwq5/lUbZYqSZ4rRU744wkhh8TULpzM14npQCZwg6aEbG+MwjzddQ72fR+3BPBrKn5dTmmu8rH99O+U+Nuto81Tg7PA+NUupcHOmhdiEGq49plgVFXK98Vks5tiybL4GuzFyWgyX73Dg/QBMn2eMHt1EMv5Gs3i6GFhKKGo4rjDi9qI6PX5oDR4LTNe6cR8td8YhVD8WFZwLLl/vaYyIqd" diff --git a/tests/integration/api_issue_label_test.go b/tests/integration/api_issue_label_test.go index b4c96e3838463..64ca7791c0d05 100644 --- a/tests/integration/api_issue_label_test.go +++ b/tests/integration/api_issue_label_test.go @@ -10,6 +10,7 @@ import ( "strings" "testing" + auth_model "code.gitea.io/gitea/models/auth" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -25,7 +26,7 @@ func TestAPIModifyLabels(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels?token=%s", owner.Name, repo.Name, token) // CreateLabel @@ -97,7 +98,7 @@ func TestAPIAddIssueLabels(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels?token=%s", repo.OwnerName, repo.Name, issue.Index, token) req := NewRequestWithJSON(t, "POST", urlStr, &api.IssueLabelsOption{ @@ -120,7 +121,7 @@ func TestAPIReplaceIssueLabels(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels?token=%s", owner.Name, repo.Name, issue.Index, token) req := NewRequestWithJSON(t, "PUT", urlStr, &api.IssueLabelsOption{ @@ -144,7 +145,7 @@ func TestAPIModifyOrgLabels(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) user := "user1" session := loginUser(t, user) - token := getTokenForLoggedInUser(t, session, "repo", "admin_org") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo, auth_model.AccessTokenScopeAdminOrg) urlStr := fmt.Sprintf("/api/v1/orgs/%s/labels?token=%s", owner.Name, token) // CreateLabel diff --git a/tests/integration/api_issue_milestone_test.go b/tests/integration/api_issue_milestone_test.go index 949a99b5460f0..704d225719611 100644 --- a/tests/integration/api_issue_milestone_test.go +++ b/tests/integration/api_issue_milestone_test.go @@ -9,6 +9,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -29,7 +30,7 @@ func TestAPIIssuesMilestone(t *testing.T) { assert.Equal(t, structs.StateOpen, milestone.State()) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) // update values of issue milestoneState := "closed" diff --git a/tests/integration/api_issue_reaction_test.go b/tests/integration/api_issue_reaction_test.go index 30f9d08df3cf8..73c0260714a86 100644 --- a/tests/integration/api_issue_reaction_test.go +++ b/tests/integration/api_issue_reaction_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" "code.gitea.io/gitea/models/unittest" @@ -29,7 +30,7 @@ func TestAPIIssuesReactions(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue.Repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/reactions?token=%s", @@ -88,7 +89,7 @@ func TestAPICommentReactions(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue.Repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) diff --git a/tests/integration/api_issue_stopwatch_test.go b/tests/integration/api_issue_stopwatch_test.go index 5d2e6cdd434f0..228c2a793a875 100644 --- a/tests/integration/api_issue_stopwatch_test.go +++ b/tests/integration/api_issue_stopwatch_test.go @@ -8,6 +8,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" @@ -26,7 +27,7 @@ func TestAPIListStopWatches(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "GET", "/api/v1/user/stopwatches?token=%s", token) resp := session.MakeRequest(t, req, http.StatusOK) var apiWatches []*api.StopWatch @@ -52,7 +53,7 @@ func TestAPIStopStopWatches(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/issues/%d/stopwatch/stop?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) session.MakeRequest(t, req, http.StatusCreated) @@ -68,7 +69,7 @@ func TestAPICancelStopWatches(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/stopwatch/delete?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) session.MakeRequest(t, req, http.StatusNoContent) @@ -84,7 +85,7 @@ func TestAPIStartStopWatches(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/issues/%d/stopwatch/start?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) session.MakeRequest(t, req, http.StatusCreated) diff --git a/tests/integration/api_issue_subscription_test.go b/tests/integration/api_issue_subscription_test.go index 60256f63a9fe3..5938b2846a896 100644 --- a/tests/integration/api_issue_subscription_test.go +++ b/tests/integration/api_issue_subscription_test.go @@ -9,6 +9,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -31,7 +32,7 @@ func TestAPIIssueSubscriptions(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue1.PosterID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) testSubscription := func(issue *issues_model.Issue, isWatching bool) { issueRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}) diff --git a/tests/integration/api_issue_test.go b/tests/integration/api_issue_test.go index 16293f35ff272..540b8ea1a33f7 100644 --- a/tests/integration/api_issue_test.go +++ b/tests/integration/api_issue_test.go @@ -11,6 +11,7 @@ import ( "testing" "time" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" @@ -30,7 +31,7 @@ func TestAPIListIssues(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/issues", owner.Name, repo.Name)) link.RawQuery = url.Values{"token": {token}, "state": {"all"}}.Encode() @@ -81,7 +82,7 @@ func TestAPICreateIssue(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all&token=%s", owner.Name, repoBefore.Name, token) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateIssueOption{ Body: body, @@ -117,7 +118,7 @@ func TestAPIEditIssue(t *testing.T) { assert.Equal(t, api.StateOpen, issueBefore.State()) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) // update values of issue issueState := "closed" diff --git a/tests/integration/api_issue_tracked_time_test.go b/tests/integration/api_issue_tracked_time_test.go index fdb604c754075..332b52cb06793 100644 --- a/tests/integration/api_issue_tracked_time_test.go +++ b/tests/integration/api_issue_tracked_time_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" "code.gitea.io/gitea/models/unittest" @@ -28,7 +29,7 @@ func TestAPIGetTrackedTimes(t *testing.T) { assert.NoError(t, issue2.LoadRepo(db.DefaultContext)) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/times?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, token) resp := session.MakeRequest(t, req, http.StatusOK) @@ -71,7 +72,7 @@ func TestAPIDeleteTrackedTime(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) // Deletion not allowed req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time6.ID, token) @@ -106,7 +107,7 @@ func TestAPIAddTrackedTimes(t *testing.T) { admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, admin.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/times?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, token) diff --git a/tests/integration/api_keys_test.go b/tests/integration/api_keys_test.go index efb12edd013ec..749801a9e82e2 100644 --- a/tests/integration/api_keys_test.go +++ b/tests/integration/api_keys_test.go @@ -11,6 +11,7 @@ import ( "testing" asymkey_model "code.gitea.io/gitea/models/asymkey" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/perm" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -54,7 +55,7 @@ func TestCreateReadOnlyDeployKey(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", repoOwner.Name, repo.Name, token) rawKeyBody := api.CreateKeyOption{ Title: "read-only", @@ -80,7 +81,7 @@ func TestCreateReadWriteDeployKey(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", repoOwner.Name, repo.Name, token) rawKeyBody := api.CreateKeyOption{ Title: "read-write", @@ -104,7 +105,7 @@ func TestCreateUserKey(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user1"}) session := loginUser(t, "user1") - token := url.QueryEscape(getTokenForLoggedInUser(t, session, "admin_public_key")) + token := url.QueryEscape(getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeAdminPublicKey)) keysURL := fmt.Sprintf("/api/v1/user/keys?token=%s", token) keyType := "ssh-rsa" keyContent := "AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM=" @@ -168,7 +169,7 @@ func TestCreateUserKey(t *testing.T) { // Now login as user 2 session2 := loginUser(t, "user2") - token2 := url.QueryEscape(getTokenForLoggedInUser(t, session2, "admin_public_key")) + token2 := url.QueryEscape(getTokenForLoggedInUser(t, session2, auth_model.AccessTokenScopeAdminPublicKey)) // Should find key even though not ours, but we shouldn't know whose it is fingerprintURL = fmt.Sprintf("/api/v1/user/keys?token=%s&fingerprint=%s", token2, newPublicKey.Fingerprint) diff --git a/tests/integration/api_notification_test.go b/tests/integration/api_notification_test.go index 75dd8a288c84a..4b9268e4c7e64 100644 --- a/tests/integration/api_notification_test.go +++ b/tests/integration/api_notification_test.go @@ -10,6 +10,7 @@ import ( "testing" activities_model "code.gitea.io/gitea/models/activities" + auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -27,7 +28,7 @@ func TestAPINotification(t *testing.T) { thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) assert.NoError(t, thread5.LoadAttributes()) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session, "notification") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeNotification) // -- GET /notifications -- // test filter @@ -145,7 +146,7 @@ func TestAPINotificationPUT(t *testing.T) { thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) assert.NoError(t, thread5.LoadAttributes()) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session, "notification") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeNotification) // Check notifications are as expected req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?all=true&token=%s", token)) diff --git a/tests/integration/api_oauth2_apps_test.go b/tests/integration/api_oauth2_apps_test.go index fb52f72e0e67d..9f7d515dacbb0 100644 --- a/tests/integration/api_oauth2_apps_test.go +++ b/tests/integration/api_oauth2_apps_test.go @@ -10,6 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models/auth" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" api "code.gitea.io/gitea/modules/structs" @@ -56,7 +57,7 @@ func testAPICreateOAuth2Application(t *testing.T) { func testAPIListOAuth2Applications(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "read_application") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadApplication) existApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ UID: user.ID, @@ -87,7 +88,7 @@ func testAPIListOAuth2Applications(t *testing.T) { func testAPIDeleteOAuth2Application(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "write_application") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteApplication) oldApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ UID: user.ID, @@ -108,7 +109,7 @@ func testAPIDeleteOAuth2Application(t *testing.T) { func testAPIGetOAuth2Application(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "read_application") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadApplication) existApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ UID: user.ID, diff --git a/tests/integration/api_org_test.go b/tests/integration/api_org_test.go index 98807af5684e4..58739db644598 100644 --- a/tests/integration/api_org_test.go +++ b/tests/integration/api_org_test.go @@ -11,6 +11,7 @@ import ( "strings" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/setting" @@ -22,7 +23,7 @@ import ( func TestAPIOrgCreate(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { - token := getUserToken(t, "user1", "write_org", "read_org") + token := getUserToken(t, "user1", auth_model.AccessTokenScopeWriteOrg) org := api.CreateOrgOption{ UserName: "user1_org", @@ -80,7 +81,7 @@ func TestAPIOrgEdit(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "write_org") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteOrg) org := api.EditOrgOption{ FullName: "User3 organization new full name", Description: "A new description", @@ -107,7 +108,7 @@ func TestAPIOrgEditBadVisibility(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "write_org") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteOrg) org := api.EditOrgOption{ FullName: "User3 organization new full name", Description: "A new description", @@ -160,7 +161,7 @@ func TestAPIGetAll(t *testing.T) { func TestAPIOrgSearchEmptyTeam(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { - token := getUserToken(t, "user1", "admin_org") + token := getUserToken(t, "user1", auth_model.AccessTokenScopeAdminOrg) orgName := "org_with_empty_team" // create org diff --git a/tests/integration/api_packages_container_test.go b/tests/integration/api_packages_container_test.go index 5ba47dbd11cd4..5d120e8e8bbf4 100644 --- a/tests/integration/api_packages_container_test.go +++ b/tests/integration/api_packages_container_test.go @@ -12,6 +12,7 @@ import ( "strings" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" packages_model "code.gitea.io/gitea/models/packages" container_model "code.gitea.io/gitea/models/packages/container" @@ -31,7 +32,7 @@ func TestPackageContainer(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "read_package") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadPackage) has := func(l packages_model.PackagePropertyList, name string) bool { for _, pp := range l { diff --git a/tests/integration/api_packages_test.go b/tests/integration/api_packages_test.go index 75603d39c2563..f4dbe2875a2f5 100644 --- a/tests/integration/api_packages_test.go +++ b/tests/integration/api_packages_test.go @@ -11,6 +11,7 @@ import ( "testing" "time" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" packages_model "code.gitea.io/gitea/models/packages" container_model "code.gitea.io/gitea/models/packages/container" @@ -29,8 +30,8 @@ func TestPackageAPI(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) session := loginUser(t, user.Name) - tokenReadPackage := getTokenForLoggedInUser(t, session, "read_package") - tokenDeletePackage := getTokenForLoggedInUser(t, session, "delete_package") + tokenReadPackage := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadPackage) + tokenDeletePackage := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeDeletePackage) packageName := "test-package" packageVersion := "1.0.3" diff --git a/tests/integration/api_pull_review_test.go b/tests/integration/api_pull_review_test.go index dc4f2d3d97ff5..097d2a42964f7 100644 --- a/tests/integration/api_pull_review_test.go +++ b/tests/integration/api_pull_review_test.go @@ -9,6 +9,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" @@ -28,7 +29,7 @@ func TestAPIPullReview(t *testing.T) { // test ListPullReviews session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token) resp := session.MakeRequest(t, req, http.StatusOK) @@ -231,7 +232,7 @@ func TestAPIPullReviewRequest(t *testing.T) { // Test add Review Request session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.PullReviewRequestOptions{ Reviewers: []string{"user4@example.com", "user8"}, }) @@ -251,7 +252,7 @@ func TestAPIPullReviewRequest(t *testing.T) { // Test Remove Review Request session2 := loginUser(t, "user4") - token2 := getTokenForLoggedInUser(t, session2, "repo") + token2 := getTokenForLoggedInUser(t, session2, auth_model.AccessTokenScopeRepo) req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token2), &api.PullReviewRequestOptions{ Reviewers: []string{"user4"}, diff --git a/tests/integration/api_pull_test.go b/tests/integration/api_pull_test.go index 68625f56c34f5..80d575b7d993b 100644 --- a/tests/integration/api_pull_test.go +++ b/tests/integration/api_pull_test.go @@ -10,6 +10,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -28,7 +29,7 @@ func TestAPIViewPulls(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) - ctx := NewAPITestContext(t, "user2", repo.Name, "repo") + ctx := NewAPITestContext(t, "user2", repo.Name, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/pulls?state=all&token="+ctx.Token, owner.Name, repo.Name) resp := ctx.Session.MakeRequest(t, req, http.StatusOK) @@ -74,7 +75,7 @@ func TestAPIMergePullWIP(t *testing.T) { assert.Contains(t, pr.Issue.Title, setting.Repository.PullRequest.WorkInProgressPrefixes[0]) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", owner.Name, repo.Name, pr.Index, token), &forms.MergePullRequestForm{ MergeMessageField: pr.Issue.Title, Do: string(repo_model.MergeStyleMerge), @@ -93,7 +94,7 @@ func TestAPICreatePullSuccess(t *testing.T) { owner11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo11.OwnerID}) session := loginUser(t, owner11.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", owner10.Name, repo10.Name, token), &api.CreatePullRequestOption{ Head: fmt.Sprintf("%s:master", owner11.Name), Base: "master", @@ -113,7 +114,7 @@ func TestAPICreatePullWithFieldsSuccess(t *testing.T) { owner11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo11.OwnerID}) session := loginUser(t, owner11.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) opts := &api.CreatePullRequestOption{ Head: fmt.Sprintf("%s:master", owner11.Name), @@ -150,7 +151,7 @@ func TestAPICreatePullWithFieldsFailure(t *testing.T) { owner11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo11.OwnerID}) session := loginUser(t, owner11.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) opts := &api.CreatePullRequestOption{ Head: fmt.Sprintf("%s:master", owner11.Name), @@ -180,7 +181,7 @@ func TestAPIEditPull(t *testing.T) { owner10 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo10.OwnerID}) session := loginUser(t, owner10.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", owner10.Name, repo10.Name, token), &api.CreatePullRequestOption{ Head: "develop", Base: "master", diff --git a/tests/integration/api_releases_test.go b/tests/integration/api_releases_test.go index 10a52a1b295b0..614b471b1bb9c 100644 --- a/tests/integration/api_releases_test.go +++ b/tests/integration/api_releases_test.go @@ -10,6 +10,7 @@ import ( "net/url" "testing" + auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -25,7 +26,7 @@ func TestAPIListReleases(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - token := getUserToken(t, user2.LowerName, "repo") + token := getUserToken(t, user2.LowerName, auth_model.AccessTokenScopeRepo) link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/releases", user2.Name, repo.Name)) link.RawQuery = url.Values{"token": {token}}.Encode() @@ -101,7 +102,7 @@ func TestAPICreateAndUpdateRelease(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) gitRepo, err := git.OpenRepository(git.DefaultContext, repo.RepoPath()) assert.NoError(t, err) @@ -153,7 +154,7 @@ func TestAPICreateReleaseToDefaultBranch(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) createNewReleaseUsingAPI(t, session, token, owner, repo, "v0.0.1", "", "v0.0.1", "test") } @@ -164,7 +165,7 @@ func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) gitRepo, err := git.OpenRepository(git.DefaultContext, repo.RepoPath()) assert.NoError(t, err) @@ -215,7 +216,7 @@ func TestAPIDeleteReleaseByTagName(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) createNewReleaseUsingAPI(t, session, token, owner, repo, "release-tag", "", "Release Tag", "test") diff --git a/tests/integration/api_repo_archive_test.go b/tests/integration/api_repo_archive_test.go index fb60d3f509f2a..69cfe9299a065 100644 --- a/tests/integration/api_repo_archive_test.go +++ b/tests/integration/api_repo_archive_test.go @@ -11,6 +11,7 @@ import ( "net/url" "testing" + auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -25,7 +26,7 @@ func TestAPIDownloadArchive(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user2.LowerName) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/archive/master.zip", user2.Name, repo.Name)) link.RawQuery = url.Values{"token": {token}}.Encode() diff --git a/tests/integration/api_repo_collaborator_test.go b/tests/integration/api_repo_collaborator_test.go index c680b27748e37..fb4b5d3df3588 100644 --- a/tests/integration/api_repo_collaborator_test.go +++ b/tests/integration/api_repo_collaborator_test.go @@ -9,6 +9,7 @@ import ( "net/url" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/perm" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -29,7 +30,7 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { user11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 11}) session := loginUser(t, repo2Owner.Name) - testCtx := NewAPITestContext(t, repo2Owner.Name, repo2.Name, "repo") + testCtx := NewAPITestContext(t, repo2Owner.Name, repo2.Name, auth_model.AccessTokenScopeRepo) t.Run("RepoOwnerShouldBeOwner", func(t *testing.T) { req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, repo2Owner.Name, testCtx.Token) @@ -86,7 +87,7 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { t.Run("AddUserAsCollaboratorWithReadAccess", doAPIAddCollaborator(testCtx, user5.Name, perm.AccessModeRead)) _session := loginUser(t, user5.Name) - _testCtx := NewAPITestContext(t, user5.Name, repo2.Name, "repo") + _testCtx := NewAPITestContext(t, user5.Name, repo2.Name, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user5.Name, _testCtx.Token) resp := _session.MakeRequest(t, req, http.StatusOK) @@ -101,7 +102,7 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { t.Run("AddUserAsCollaboratorWithReadAccess", doAPIAddCollaborator(testCtx, user5.Name, perm.AccessModeRead)) _session := loginUser(t, user5.Name) - _testCtx := NewAPITestContext(t, user5.Name, repo2.Name, "repo") + _testCtx := NewAPITestContext(t, user5.Name, repo2.Name, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user5.Name, _testCtx.Token) resp := _session.MakeRequest(t, req, http.StatusOK) @@ -117,7 +118,7 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { t.Run("AddUserAsCollaboratorWithReadAccess", doAPIAddCollaborator(testCtx, user11.Name, perm.AccessModeRead)) _session := loginUser(t, user10.Name) - _testCtx := NewAPITestContext(t, user10.Name, repo2.Name, "repo") + _testCtx := NewAPITestContext(t, user10.Name, repo2.Name, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user11.Name, _testCtx.Token) resp := _session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/api_repo_edit_test.go b/tests/integration/api_repo_edit_test.go index eec7c0bb0d31b..844756db0c825 100644 --- a/tests/integration/api_repo_edit_test.go +++ b/tests/integration/api_repo_edit_test.go @@ -10,6 +10,7 @@ import ( "net/url" "testing" + auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" unit_model "code.gitea.io/gitea/models/unit" "code.gitea.io/gitea/models/unittest" @@ -146,10 +147,10 @@ func TestAPIRepoEdit(t *testing.T) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session, "repo") + token2 := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session, "repo") + token4 := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) session = emptyTestSession(t) // Test editing a repo1 which user2 owns, changing name and many properties diff --git a/tests/integration/api_repo_file_create_test.go b/tests/integration/api_repo_file_create_test.go index 6810526a64a4d..e0f03884241f6 100644 --- a/tests/integration/api_repo_file_create_test.go +++ b/tests/integration/api_repo_file_create_test.go @@ -14,6 +14,7 @@ import ( "testing" "time" + auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -151,10 +152,10 @@ func TestAPICreateFile(t *testing.T) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session, "repo") + token2 := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session, "repo") + token4 := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) session = emptyTestSession(t) // Test creating a file in repo1 which user2 owns, try both with branch and empty branch @@ -281,7 +282,7 @@ func TestAPICreateFile(t *testing.T) { session.MakeRequest(t, req, http.StatusForbidden) // Test creating a file in an empty repository - doAPICreateRepository(NewAPITestContext(t, "user2", "empty-repo", "repo"), true)(t) + doAPICreateRepository(NewAPITestContext(t, "user2", "empty-repo", auth_model.AccessTokenScopeRepo), true)(t) createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) diff --git a/tests/integration/api_repo_file_delete_test.go b/tests/integration/api_repo_file_delete_test.go index 9a548c652c983..909f234710446 100644 --- a/tests/integration/api_repo_file_delete_test.go +++ b/tests/integration/api_repo_file_delete_test.go @@ -10,6 +10,7 @@ import ( "net/url" "testing" + auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -49,10 +50,10 @@ func TestAPIDeleteFile(t *testing.T) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session, "repo") + token2 := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session, "repo") + token4 := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) session = emptyTestSession(t) // Test deleting a file in repo1 which user2 owns, try both with branch and empty branch diff --git a/tests/integration/api_repo_file_get_test.go b/tests/integration/api_repo_file_get_test.go index 9ce88bd913b99..75114d16163f3 100644 --- a/tests/integration/api_repo_file_get_test.go +++ b/tests/integration/api_repo_file_get_test.go @@ -9,6 +9,7 @@ import ( "net/url" "testing" + auth_model "code.gitea.io/gitea/models/auth" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/tests" @@ -25,7 +26,7 @@ func TestAPIGetRawFileOrLFS(t *testing.T) { // Test with LFS onGiteaRun(t, func(t *testing.T, u *url.URL) { - httpContext := NewAPITestContext(t, "user2", "repo-lfs-test", "repo", "delete_repo") + httpContext := NewAPITestContext(t, "user2", "repo-lfs-test", auth_model.AccessTokenScopeRepo, auth_model.AccessTokenScopeDeleteRepo) doAPICreateRepository(httpContext, false, func(t *testing.T, repository api.Repository) { u.Path = httpContext.GitPath() dstPath := t.TempDir() diff --git a/tests/integration/api_repo_file_update_test.go b/tests/integration/api_repo_file_update_test.go index 910410b5fd60d..d1657b70f82dc 100644 --- a/tests/integration/api_repo_file_update_test.go +++ b/tests/integration/api_repo_file_update_test.go @@ -13,6 +13,7 @@ import ( "path/filepath" "testing" + auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -117,10 +118,10 @@ func TestAPIUpdateFile(t *testing.T) { // Get user2's token session := loginUser(t, user2.Name) - token2 := getTokenForLoggedInUser(t, session, "repo") + token2 := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) // Get user4's token session = loginUser(t, user4.Name) - token4 := getTokenForLoggedInUser(t, session, "repo") + token4 := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) session = emptyTestSession(t) // Test updating a file in repo1 which user2 owns, try both with branch and empty branch diff --git a/tests/integration/api_repo_git_hook_test.go b/tests/integration/api_repo_git_hook_test.go index 8c195753ffaf3..96639a04e35c4 100644 --- a/tests/integration/api_repo_git_hook_test.go +++ b/tests/integration/api_repo_git_hook_test.go @@ -9,6 +9,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -31,7 +32,7 @@ func TestAPIListGitHooks(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "read_repo_hook") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepoHook) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", owner.Name, repo.Name, token) resp := MakeRequest(t, req, http.StatusOK) @@ -57,7 +58,7 @@ func TestAPIListGitHooksNoHooks(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "read_repo_hook") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepoHook) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", owner.Name, repo.Name, token) resp := MakeRequest(t, req, http.StatusOK) @@ -77,7 +78,7 @@ func TestAPIListGitHooksNoAccess(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "read_repo_hook") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepoHook) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", owner.Name, repo.Name, token) MakeRequest(t, req, http.StatusForbidden) @@ -91,7 +92,7 @@ func TestAPIGetGitHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "read_repo_hook") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepoHook) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) resp := MakeRequest(t, req, http.StatusOK) @@ -108,7 +109,7 @@ func TestAPIGetGitHookNoAccess(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "read_repo_hook") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepoHook) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) MakeRequest(t, req, http.StatusForbidden) @@ -122,7 +123,7 @@ func TestAPIEditGitHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "admin_repo_hook") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeAdminRepoHook) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) @@ -151,7 +152,7 @@ func TestAPIEditGitHookNoAccess(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "write_repo_hook") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepoHook) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) req := NewRequestWithJSON(t, "PATCH", urlStr, &api.EditGitHookOption{ @@ -168,7 +169,7 @@ func TestAPIDeleteGitHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "admin_repo_hook") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeAdminRepoHook) req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) @@ -190,7 +191,7 @@ func TestAPIDeleteGitHookNoAccess(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - token := getTokenForLoggedInUser(t, session, "write_repo_hook") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepoHook) req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", owner.Name, repo.Name, token) MakeRequest(t, req, http.StatusForbidden) diff --git a/tests/integration/api_repo_git_tags_test.go b/tests/integration/api_repo_git_tags_test.go index 36bee8abd7163..e1e61db9159b2 100644 --- a/tests/integration/api_repo_git_tags_test.go +++ b/tests/integration/api_repo_git_tags_test.go @@ -9,6 +9,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -70,7 +71,7 @@ func TestAPIDeleteTagByName(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.LowerName) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/tags/delete-tag?token=%s", owner.Name, repo.Name, token) diff --git a/tests/integration/api_repo_hook_test.go b/tests/integration/api_repo_hook_test.go index 7ad3f4f42caab..ddf1f45cb6628 100644 --- a/tests/integration/api_repo_hook_test.go +++ b/tests/integration/api_repo_hook_test.go @@ -9,6 +9,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -26,7 +27,7 @@ func TestAPICreateHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "write_repo_hook") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepoHook) completeURL := func(lastSegment string) string { return fmt.Sprintf("/api/v1/repos/%s/%s/%s?token=%s", owner.Name, repo.Name, lastSegment, token) } diff --git a/tests/integration/api_repo_lfs_migrate_test.go b/tests/integration/api_repo_lfs_migrate_test.go index 66fdb8b921fe6..5ed366cfbd497 100644 --- a/tests/integration/api_repo_lfs_migrate_test.go +++ b/tests/integration/api_repo_lfs_migrate_test.go @@ -9,6 +9,7 @@ import ( "path" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/lfs" @@ -31,7 +32,7 @@ func TestAPIRepoLFSMigrateLocal(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+token, &api.MigrateRepoOptions{ CloneAddr: path.Join(setting.RepoRootPath, "migration/lfs-test.git"), diff --git a/tests/integration/api_repo_lfs_test.go b/tests/integration/api_repo_lfs_test.go index 76f79fcad7904..ee859a29c997c 100644 --- a/tests/integration/api_repo_lfs_test.go +++ b/tests/integration/api_repo_lfs_test.go @@ -12,6 +12,7 @@ import ( "strings" "testing" + auth_model "code.gitea.io/gitea/models/auth" git_model "code.gitea.io/gitea/models/git" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -59,7 +60,7 @@ func TestAPILFSMediaType(t *testing.T) { } func createLFSTestRepository(t *testing.T, name string) *repo_model.Repository { - ctx := NewAPITestContext(t, "user2", "lfs-"+name+"-repo", "repo") + ctx := NewAPITestContext(t, "user2", "lfs-"+name+"-repo", auth_model.AccessTokenScopeRepo) t.Run("CreateRepo", doAPICreateRepository(ctx, false)) repo, err := repo_model.GetRepositoryByOwnerAndName("user2", "lfs-"+name+"-repo") diff --git a/tests/integration/api_repo_raw_test.go b/tests/integration/api_repo_raw_test.go index f892a9236d3ed..92469b035434e 100644 --- a/tests/integration/api_repo_raw_test.go +++ b/tests/integration/api_repo_raw_test.go @@ -8,6 +8,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/tests" @@ -20,7 +21,7 @@ func TestAPIReposRaw(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) for _, ref := range [...]string{ "master", // Branch diff --git a/tests/integration/api_repo_tags_test.go b/tests/integration/api_repo_tags_test.go index 5c6f4a6a3eec9..951669c3dfa2e 100644 --- a/tests/integration/api_repo_tags_test.go +++ b/tests/integration/api_repo_tags_test.go @@ -9,6 +9,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/setting" @@ -23,7 +24,7 @@ func TestAPIRepoTags(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Login as User2. session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) repoName := "repo1" diff --git a/tests/integration/api_repo_teams_test.go b/tests/integration/api_repo_teams_test.go index f39a06c31aa0b..633a1a8c600b2 100644 --- a/tests/integration/api_repo_teams_test.go +++ b/tests/integration/api_repo_teams_test.go @@ -9,6 +9,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" "code.gitea.io/gitea/models/unittest" @@ -28,7 +29,7 @@ func TestAPIRepoTeams(t *testing.T) { // user4 user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) // ListTeams url := fmt.Sprintf("/api/v1/repos/%s/teams?token=%s", publicOrgRepo.FullName(), token) @@ -68,7 +69,7 @@ func TestAPIRepoTeams(t *testing.T) { // AddTeam with user2 user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session = loginUser(t, user.Name) - token = getTokenForLoggedInUser(t, session, "repo") + token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "team1", token) req = NewRequest(t, "PUT", url) session.MakeRequest(t, req, http.StatusNoContent) diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index 0c165c085752c..ac6583fbc123a 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -11,6 +11,7 @@ import ( "testing" "code.gitea.io/gitea/models" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" access_model "code.gitea.io/gitea/models/perm/access" repo_model "code.gitea.io/gitea/models/repo" @@ -296,7 +297,7 @@ func TestAPIOrgRepos(t *testing.T) { for userToLogin, expected := range expectedResults { testName := fmt.Sprintf("LoggedUser%d", userToLogin.ID) session := loginUser(t, userToLogin.Name) - token := getTokenForLoggedInUser(t, session, "read_org") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrg) t.Run(testName, func(t *testing.T) { req := NewRequestf(t, "GET", "/api/v1/orgs/%s/repos?token="+token, sourceOrg.Name) @@ -318,7 +319,7 @@ func TestAPIGetRepoByIDUnauthorized(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "GET", "/api/v1/repositories/2?token="+token) session.MakeRequest(t, req, http.StatusNotFound) } @@ -342,7 +343,7 @@ func TestAPIRepoMigrate(t *testing.T) { for _, testCase := range testCases { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+token, &api.MigrateRepoOptions{ CloneAddr: testCase.cloneURL, RepoOwnerID: testCase.userID, @@ -372,7 +373,7 @@ func TestAPIRepoMigrateConflict(t *testing.T) { func testAPIRepoMigrateConflict(t *testing.T, u *url.URL) { username := "user2" - baseAPITestContext := NewAPITestContext(t, username, "repo1", "repo") + baseAPITestContext := NewAPITestContext(t, username, "repo1", auth_model.AccessTokenScopeRepo) u.Path = baseAPITestContext.GitPath() @@ -407,7 +408,7 @@ func TestAPIMirrorSyncNonMirrorRepo(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) var repo api.Repository req := NewRequest(t, "GET", "/api/v1/repos/user2/repo1") @@ -439,7 +440,7 @@ func TestAPIOrgRepoCreate(t *testing.T) { for _, testCase := range testCases { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "admin_org") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeAdminOrg) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/org/%s/repos?token="+token, testCase.orgName), &api.CreateRepoOption{ Name: testCase.repoName, }) @@ -453,7 +454,7 @@ func TestAPIRepoCreateConflict(t *testing.T) { func testAPIRepoCreateConflict(t *testing.T, u *url.URL) { username := "user2" - baseAPITestContext := NewAPITestContext(t, username, "repo1", "repo") + baseAPITestContext := NewAPITestContext(t, username, "repo1", auth_model.AccessTokenScopeRepo) u.Path = baseAPITestContext.GitPath() @@ -503,7 +504,7 @@ func TestAPIRepoTransfer(t *testing.T) { // create repo to move user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) repoName := "moveME" apiRepo := new(api.Repository) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/user/repos?token=%s", token), &api.CreateRepoOption{ @@ -521,7 +522,7 @@ func TestAPIRepoTransfer(t *testing.T) { user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}) session = loginUser(t, user.Name) - token = getTokenForLoggedInUser(t, session, "repo") + token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer?token=%s", repo.OwnerName, repo.Name, token), &api.TransferRepoOption{ NewOwner: testCase.newOwner, TeamIDs: testCase.teams, @@ -538,7 +539,7 @@ func transfer(t *testing.T) *repo_model.Repository { // create repo to move user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) repoName := "moveME" apiRepo := new(api.Repository) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/user/repos?token=%s", token), &api.CreateRepoOption{ @@ -568,7 +569,7 @@ func TestAPIAcceptTransfer(t *testing.T) { // try to accept with not authorized user session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) session.MakeRequest(t, req, http.StatusForbidden) @@ -578,7 +579,7 @@ func TestAPIAcceptTransfer(t *testing.T) { // accept transfer session = loginUser(t, "user4") - token = getTokenForLoggedInUser(t, session, "repo") + token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/accept?token=%s", repo.OwnerName, repo.Name, token)) resp := session.MakeRequest(t, req, http.StatusAccepted) @@ -594,7 +595,7 @@ func TestAPIRejectTransfer(t *testing.T) { // try to reject with not authorized user session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) session.MakeRequest(t, req, http.StatusForbidden) @@ -604,7 +605,7 @@ func TestAPIRejectTransfer(t *testing.T) { // reject transfer session = loginUser(t, "user4") - token = getTokenForLoggedInUser(t, session, "repo") + token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) resp := session.MakeRequest(t, req, http.StatusOK) @@ -618,7 +619,7 @@ func TestAPIGenerateRepo(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) templateRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 44}) @@ -654,7 +655,7 @@ func TestAPIRepoGetReviewers(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/reviewers?token=%s", user.Name, repo.Name, token) @@ -668,7 +669,7 @@ func TestAPIRepoGetAssignees(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/assignees?token=%s", user.Name, repo.Name, token) diff --git a/tests/integration/api_repo_topic_test.go b/tests/integration/api_repo_topic_test.go index bd789e49a1ebb..60231bc8b5b3c 100644 --- a/tests/integration/api_repo_topic_test.go +++ b/tests/integration/api_repo_topic_test.go @@ -10,6 +10,7 @@ import ( "net/url" "testing" + auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -60,7 +61,7 @@ func TestAPIRepoTopic(t *testing.T) { repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) // Get user2's token - token2 := getUserToken(t, user2.Name, "repo") + token2 := getUserToken(t, user2.Name, auth_model.AccessTokenScopeRepo) // Test read topics using login url := fmt.Sprintf("/api/v1/repos/%s/%s/topics", user2.Name, repo2.Name) @@ -140,7 +141,7 @@ func TestAPIRepoTopic(t *testing.T) { MakeRequest(t, req, http.StatusNotFound) // Get user4's token - token4 := getUserToken(t, user4.Name, "repo") + token4 := getUserToken(t, user4.Name, auth_model.AccessTokenScopeRepo) // Test read topics with write access url = fmt.Sprintf("/api/v1/repos/%s/%s/topics?token=%s", user3.Name, repo3.Name, token4) diff --git a/tests/integration/api_team_test.go b/tests/integration/api_team_test.go index 07bdfb4376c3e..7432c7210b4c6 100644 --- a/tests/integration/api_team_test.go +++ b/tests/integration/api_team_test.go @@ -10,6 +10,7 @@ import ( "sort" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" @@ -30,7 +31,7 @@ func TestAPITeam(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: teamUser.UID}) session := loginUser(t, user.Name) - token := getTokenForLoggedInUser(t, session, "admin_org") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeAdminOrg) req := NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamUser.TeamID) resp := session.MakeRequest(t, req, http.StatusOK) @@ -44,7 +45,7 @@ func TestAPITeam(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: teamUser2.UID}) session = loginUser(t, user2.Name) - token = getTokenForLoggedInUser(t, session, "read_org") + token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrg) req = NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamUser.TeamID) _ = session.MakeRequest(t, req, http.StatusForbidden) @@ -54,7 +55,7 @@ func TestAPITeam(t *testing.T) { // Get an admin user able to create, update and delete teams. user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session = loginUser(t, user.Name) - token = getTokenForLoggedInUser(t, session, "admin_org") + token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeAdminOrg) org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 6}) @@ -228,7 +229,7 @@ func TestAPITeamSearch(t *testing.T) { var results TeamSearchResults - token := getUserToken(t, user.Name, "read_org") + token := getUserToken(t, user.Name, auth_model.AccessTokenScopeReadOrg) req := NewRequestf(t, "GET", "/api/v1/orgs/%s/teams/search?q=%s&token=%s", org.Name, "_team", token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &results) @@ -238,7 +239,7 @@ func TestAPITeamSearch(t *testing.T) { // no access if not organization member user5 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) - token5 := getUserToken(t, user5.Name, "read_org") + token5 := getUserToken(t, user5.Name, auth_model.AccessTokenScopeReadOrg) req = NewRequestf(t, "GET", "/api/v1/orgs/%s/teams/search?q=%s&token=%s", org.Name, "team", token5) MakeRequest(t, req, http.StatusForbidden) @@ -253,7 +254,7 @@ func TestAPIGetTeamRepo(t *testing.T) { var results api.Repository - token := getUserToken(t, user.Name, "read_org") + token := getUserToken(t, user.Name, auth_model.AccessTokenScopeReadOrg) req := NewRequestf(t, "GET", "/api/v1/teams/%d/repos/%s/?token=%s", team.ID, teamRepo.FullName(), token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &results) @@ -261,7 +262,7 @@ func TestAPIGetTeamRepo(t *testing.T) { // no access if not organization member user5 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) - token5 := getUserToken(t, user5.Name, "read_org") + token5 := getUserToken(t, user5.Name, auth_model.AccessTokenScopeReadOrg) req = NewRequestf(t, "GET", "/api/v1/teams/%d/repos/%s/?token=%s", team.ID, teamRepo.FullName(), token5) MakeRequest(t, req, http.StatusNotFound) diff --git a/tests/integration/api_team_user_test.go b/tests/integration/api_team_user_test.go index de66454822756..09603bf54d296 100644 --- a/tests/integration/api_team_user_test.go +++ b/tests/integration/api_team_user_test.go @@ -9,6 +9,7 @@ import ( "testing" "time" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/convert" @@ -23,7 +24,7 @@ func TestAPITeamUser(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session, "read_org") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrg) req := NewRequest(t, "GET", "/api/v1/teams/1/members/user1?token="+token) session.MakeRequest(t, req, http.StatusNotFound) diff --git a/tests/integration/api_user_email_test.go b/tests/integration/api_user_email_test.go index 62c66014693e0..8c1e08e351af3 100644 --- a/tests/integration/api_user_email_test.go +++ b/tests/integration/api_user_email_test.go @@ -8,6 +8,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/tests" @@ -19,7 +20,7 @@ func TestAPIListEmails(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session, "read_user") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadUser) req := NewRequest(t, "GET", "/api/v1/user/emails?token="+token) resp := session.MakeRequest(t, req, http.StatusOK) @@ -46,7 +47,7 @@ func TestAPIAddEmail(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session, "user") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeUser) opts := api.CreateEmailOption{ Emails: []string{"user101@example.com"}, @@ -83,7 +84,7 @@ func TestAPIDeleteEmail(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session, "user") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeUser) opts := api.DeleteEmailOption{ Emails: []string{"user2-3@example.com"}, diff --git a/tests/integration/api_user_follow_test.go b/tests/integration/api_user_follow_test.go index e87791761fde3..721b3b50ab554 100644 --- a/tests/integration/api_user_follow_test.go +++ b/tests/integration/api_user_follow_test.go @@ -9,6 +9,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/tests" @@ -25,7 +26,7 @@ func TestAPIFollow(t *testing.T) { token1 := getTokenForLoggedInUser(t, session1) session2 := loginUser(t, user2) - token2 := getTokenForLoggedInUser(t, session2, "user_follow") + token2 := getTokenForLoggedInUser(t, session2, auth_model.AccessTokenScopeUserFollow) t.Run("Follow", func(t *testing.T) { defer tests.PrintCurrentTest(t)() diff --git a/tests/integration/api_user_org_perm_test.go b/tests/integration/api_user_org_perm_test.go index e083cce7d34dd..3e7bb4d107885 100644 --- a/tests/integration/api_user_org_perm_test.go +++ b/tests/integration/api_user_org_perm_test.go @@ -9,6 +9,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/tests" @@ -34,7 +35,7 @@ func sampleTest(t *testing.T, auoptc apiUserOrgPermTestCase) { defer tests.PrepareTestEnv(t)() session := loginUser(t, auoptc.LoginUser) - token := getTokenForLoggedInUser(t, session, "read_org") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrg) req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/orgs/%s/permissions?token=%s", auoptc.User, auoptc.Organization, token)) resp := session.MakeRequest(t, req, http.StatusOK) @@ -127,7 +128,7 @@ func TestUnknowUser(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "read_org") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrg) req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/unknow/orgs/org25/permissions?token=%s", token)) resp := session.MakeRequest(t, req, http.StatusNotFound) @@ -141,7 +142,7 @@ func TestUnknowOrganization(t *testing.T) { defer tests.PrepareTestEnv(t)() session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "read_org") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrg) req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/user1/orgs/unknow/permissions?token=%s", token)) resp := session.MakeRequest(t, req, http.StatusNotFound) diff --git a/tests/integration/api_user_orgs_test.go b/tests/integration/api_user_orgs_test.go index 6b0a03ff83ee4..1079436209f3e 100644 --- a/tests/integration/api_user_orgs_test.go +++ b/tests/integration/api_user_orgs_test.go @@ -9,6 +9,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" api "code.gitea.io/gitea/modules/structs" @@ -68,7 +69,7 @@ func TestUserOrgs(t *testing.T) { func getUserOrgs(t *testing.T, userDoer, userCheck string) (orgs []*api.Organization) { session := loginUser(t, userDoer) - token := getTokenForLoggedInUser(t, session, "read_org") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrg) urlStr := fmt.Sprintf("/api/v1/users/%s/orgs?token=%s", userCheck, token) req := NewRequest(t, "GET", urlStr) resp := session.MakeRequest(t, req, http.StatusOK) @@ -91,7 +92,7 @@ func TestMyOrgs(t *testing.T) { normalUsername := "user2" session = loginUser(t, normalUsername) - token := getTokenForLoggedInUser(t, session, "read_org") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrg) req = NewRequest(t, "GET", "/api/v1/user/orgs?token="+token) resp := session.MakeRequest(t, req, http.StatusOK) var orgs []*api.Organization diff --git a/tests/integration/api_user_star_test.go b/tests/integration/api_user_star_test.go index 3395b399cfbcb..c9e87fa8522fd 100644 --- a/tests/integration/api_user_star_test.go +++ b/tests/integration/api_user_star_test.go @@ -9,6 +9,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/tests" @@ -23,7 +24,7 @@ func TestAPIStar(t *testing.T) { session := loginUser(t, user) token := getTokenForLoggedInUser(t, session) - tokenWithRepoScope := getTokenForLoggedInUser(t, session, "repo") + tokenWithRepoScope := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) t.Run("Star", func(t *testing.T) { defer tests.PrintCurrentTest(t)() diff --git a/tests/integration/api_user_watch_test.go b/tests/integration/api_user_watch_test.go index 36c0f8030a3d0..452462f6e9fe2 100644 --- a/tests/integration/api_user_watch_test.go +++ b/tests/integration/api_user_watch_test.go @@ -9,6 +9,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/tests" @@ -23,7 +24,7 @@ func TestAPIWatch(t *testing.T) { session := loginUser(t, user) token := getTokenForLoggedInUser(t, session) - tokenWithRepoScope := getTokenForLoggedInUser(t, session, "repo") + tokenWithRepoScope := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) t.Run("Watch", func(t *testing.T) { defer tests.PrintCurrentTest(t)() diff --git a/tests/integration/api_wiki_test.go b/tests/integration/api_wiki_test.go index e154c1c438705..2d446b2aa2221 100644 --- a/tests/integration/api_wiki_test.go +++ b/tests/integration/api_wiki_test.go @@ -10,6 +10,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/tests" @@ -182,7 +183,7 @@ func TestAPINewWikiPage(t *testing.T) { defer tests.PrepareTestEnv(t)() username := "user2" session := loginUser(t, username) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/new?token=%s", username, "repo1", token) @@ -199,7 +200,7 @@ func TestAPIEditWikiPage(t *testing.T) { defer tests.PrepareTestEnv(t)() username := "user2" session := loginUser(t, username) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/page/Page-With-Spaced-Name?token=%s", username, "repo1", token) diff --git a/tests/integration/dump_restore_test.go b/tests/integration/dump_restore_test.go index 9004a65d426a9..381365dee1849 100644 --- a/tests/integration/dump_restore_test.go +++ b/tests/integration/dump_restore_test.go @@ -15,6 +15,7 @@ import ( "strings" "testing" + auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -51,7 +52,7 @@ func TestDumpRestore(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) // // Phase 1: dump repo1 from the Gitea instance to the filesystem diff --git a/tests/integration/eventsource_test.go b/tests/integration/eventsource_test.go index f43f48b33880f..a40c82397e184 100644 --- a/tests/integration/eventsource_test.go +++ b/tests/integration/eventsource_test.go @@ -11,6 +11,7 @@ import ( "time" activities_model "code.gitea.io/gitea/models/activities" + auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -59,7 +60,7 @@ func TestEventSourceManagerRun(t *testing.T) { thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) assert.NoError(t, thread5.LoadAttributes()) session := loginUser(t, user2.Name) - token := getTokenForLoggedInUser(t, session, "notification") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeNotification) var apiNL []api.NotificationThread diff --git a/tests/integration/git_test.go b/tests/integration/git_test.go index 73fe63a3cea10..dd9141aa66735 100644 --- a/tests/integration/git_test.go +++ b/tests/integration/git_test.go @@ -17,6 +17,7 @@ import ( "testing" "time" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" "code.gitea.io/gitea/models/perm" @@ -43,11 +44,11 @@ func TestGit(t *testing.T) { func testGit(t *testing.T, u *url.URL) { username := "user2" - baseAPITestContext := NewAPITestContext(t, username, "repo1", "repo", "write_public_key", "delete_repo") + baseAPITestContext := NewAPITestContext(t, username, "repo1", auth_model.AccessTokenScopeRepo, auth_model.AccessTokenScopeWritePublicKey, auth_model.AccessTokenScopeDeleteRepo) u.Path = baseAPITestContext.GitPath() - forkedUserCtx := NewAPITestContext(t, "user4", "repo1", "repo") + forkedUserCtx := NewAPITestContext(t, "user4", "repo1", auth_model.AccessTokenScopeRepo) t.Run("HTTP", func(t *testing.T) { defer tests.PrintCurrentTest(t)() @@ -358,7 +359,7 @@ func doBranchProtectPRMerge(baseCtx *APITestContext, dstPath string) func(t *tes t.Run("CreateBranchProtected", doGitCreateBranch(dstPath, "protected")) t.Run("PushProtectedBranch", doGitPushTestRepository(dstPath, "origin", "protected")) - ctx := NewAPITestContext(t, baseCtx.Username, baseCtx.Reponame, "repo") + ctx := NewAPITestContext(t, baseCtx.Username, baseCtx.Reponame, auth_model.AccessTokenScopeRepo) t.Run("ProtectProtectedBranchNoWhitelist", doProtectBranch(ctx, "protected", "", "")) t.Run("GenerateCommit", func(t *testing.T) { _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-") @@ -602,7 +603,7 @@ func doAutoPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) { return func(t *testing.T) { defer tests.PrintCurrentTest(t)() - ctx := NewAPITestContext(t, baseCtx.Username, baseCtx.Reponame, "repo") + ctx := NewAPITestContext(t, baseCtx.Username, baseCtx.Reponame, auth_model.AccessTokenScopeRepo) t.Run("CheckoutProtected", doGitCheckoutBranch(dstPath, "protected")) t.Run("PullProtected", doGitPull(dstPath, "origin", "protected")) diff --git a/tests/integration/gpg_git_test.go b/tests/integration/gpg_git_test.go index 4a224bf881421..f7d14634b8871 100644 --- a/tests/integration/gpg_git_test.go +++ b/tests/integration/gpg_git_test.go @@ -11,6 +11,7 @@ import ( "os" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/process" @@ -70,7 +71,7 @@ func TestGPGGit(t *testing.T) { t.Run("Unsigned-Initial", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-unsigned", "repo") + testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeRepo) t.Run("CreateRepository", doAPICreateRepository(testCtx, false)) t.Run("CheckMasterBranchUnsigned", doAPIGetBranch(testCtx, "master", func(t *testing.T, branch api.Branch) { assert.NotNil(t, branch.Commit) @@ -94,7 +95,7 @@ func TestGPGGit(t *testing.T) { t.Run("Unsigned-Initial-CRUD-ParentSigned", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-unsigned", "repo") + testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeRepo) t.Run("CreateCRUDFile-ParentSigned", crudActionCreateFile( t, testCtx, user, "master", "parentsigned", "signed-parent.txt", func(t *testing.T, response api.FileResponse) { assert.False(t, response.Verification.Verified) @@ -111,7 +112,7 @@ func TestGPGGit(t *testing.T) { t.Run("Unsigned-Initial-CRUD-Never", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-unsigned", "repo") + testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeRepo) t.Run("CreateCRUDFile-Never", crudActionCreateFile( t, testCtx, user, "parentsigned", "parentsigned-never", "unsigned-never2.txt", func(t *testing.T, response api.FileResponse) { assert.False(t, response.Verification.Verified) @@ -124,7 +125,7 @@ func TestGPGGit(t *testing.T) { t.Run("Unsigned-Initial-CRUD-Always", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-unsigned", "repo") + testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeRepo) t.Run("CreateCRUDFile-Always", crudActionCreateFile( t, testCtx, user, "master", "always", "signed-always.txt", func(t *testing.T, response api.FileResponse) { assert.NotNil(t, response.Verification) @@ -161,7 +162,7 @@ func TestGPGGit(t *testing.T) { t.Run("Unsigned-Initial-CRUD-ParentSigned", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-unsigned", "repo") + testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeRepo) t.Run("CreateCRUDFile-Always-ParentSigned", crudActionCreateFile( t, testCtx, user, "always", "always-parentsigned", "signed-always-parentsigned.txt", func(t *testing.T, response api.FileResponse) { assert.NotNil(t, response.Verification) @@ -184,7 +185,7 @@ func TestGPGGit(t *testing.T) { t.Run("AlwaysSign-Initial", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-always", "repo") + testCtx := NewAPITestContext(t, username, "initial-always", auth_model.AccessTokenScopeRepo) t.Run("CreateRepository", doAPICreateRepository(testCtx, false)) t.Run("CheckMasterBranchSigned", doAPIGetBranch(testCtx, "master", func(t *testing.T, branch api.Branch) { assert.NotNil(t, branch.Commit) @@ -212,7 +213,7 @@ func TestGPGGit(t *testing.T) { t.Run("AlwaysSign-Initial-CRUD-Never", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-always-never", "repo") + testCtx := NewAPITestContext(t, username, "initial-always-never", auth_model.AccessTokenScopeRepo) t.Run("CreateRepository", doAPICreateRepository(testCtx, false)) t.Run("CreateCRUDFile-Never", crudActionCreateFile( t, testCtx, user, "master", "never", "unsigned-never.txt", func(t *testing.T, response api.FileResponse) { @@ -225,7 +226,7 @@ func TestGPGGit(t *testing.T) { u.Path = baseAPITestContext.GitPath() t.Run("AlwaysSign-Initial-CRUD-ParentSigned-On-Always", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-always-parent", "repo") + testCtx := NewAPITestContext(t, username, "initial-always-parent", auth_model.AccessTokenScopeRepo) t.Run("CreateRepository", doAPICreateRepository(testCtx, false)) t.Run("CreateCRUDFile-ParentSigned", crudActionCreateFile( t, testCtx, user, "master", "parentsigned", "signed-parent.txt", func(t *testing.T, response api.FileResponse) { @@ -244,7 +245,7 @@ func TestGPGGit(t *testing.T) { t.Run("AlwaysSign-Initial-CRUD-Always", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-always-always", "repo") + testCtx := NewAPITestContext(t, username, "initial-always-always", auth_model.AccessTokenScopeRepo) t.Run("CreateRepository", doAPICreateRepository(testCtx, false)) t.Run("CreateCRUDFile-Always", crudActionCreateFile( t, testCtx, user, "master", "always", "signed-always.txt", func(t *testing.T, response api.FileResponse) { @@ -264,7 +265,7 @@ func TestGPGGit(t *testing.T) { t.Run("UnsignedMerging", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-unsigned", "repo") + testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeRepo) var err error t.Run("CreatePullRequest", func(t *testing.T) { pr, err = doAPICreatePullRequest(testCtx, testCtx.Username, testCtx.Reponame, "master", "never2")(t) @@ -285,7 +286,7 @@ func TestGPGGit(t *testing.T) { t.Run("BaseSignedMerging", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-unsigned", "repo") + testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeRepo) var err error t.Run("CreatePullRequest", func(t *testing.T) { pr, err = doAPICreatePullRequest(testCtx, testCtx.Username, testCtx.Reponame, "master", "parentsigned2")(t) @@ -306,7 +307,7 @@ func TestGPGGit(t *testing.T) { t.Run("CommitsSignedMerging", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - testCtx := NewAPITestContext(t, username, "initial-unsigned", "repo") + testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeRepo) var err error t.Run("CreatePullRequest", func(t *testing.T) { pr, err = doAPICreatePullRequest(testCtx, testCtx.Username, testCtx.Reponame, "master", "always-parentsigned")(t) diff --git a/tests/integration/integration_test.go b/tests/integration/integration_test.go index 7affd41e7b56d..0a75c75493838 100644 --- a/tests/integration/integration_test.go +++ b/tests/integration/integration_test.go @@ -270,14 +270,13 @@ func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...strin req := NewRequest(t, "GET", "/user/settings/applications") resp := session.MakeRequest(t, req, http.StatusOK) doc := NewHTMLParser(t, resp.Body) - values := map[string]string{ - "_csrf": doc.GetCSRF(), - "name": fmt.Sprintf("api-testing-token-%d", tokenCounter), - } + urlValues := url.Values{} + urlValues.Add("_csrf", doc.GetCSRF()) + urlValues.Add("name", fmt.Sprintf("api-testing-token-%d", tokenCounter)) for _, scope := range scopes { - values[fmt.Sprintf("scope_%s", scope)] = "on" + urlValues.Add("scope", scope) } - req = NewRequestWithValues(t, "POST", "/user/settings/applications", values) + req = NewRequestWithURLValues(t, "POST", "/user/settings/applications", urlValues) session.MakeRequest(t, req, http.StatusSeeOther) req = NewRequest(t, "GET", "/user/settings/applications") resp = session.MakeRequest(t, req, http.StatusOK) @@ -303,6 +302,11 @@ func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string for key, value := range values { urlValues[key] = []string{value} } + return NewRequestWithURLValues(t, method, urlStr, urlValues) +} + +func NewRequestWithURLValues(t testing.TB, method, urlStr string, urlValues url.Values) *http.Request { + t.Helper() req := NewRequestWithBody(t, method, urlStr, bytes.NewBufferString(urlValues.Encode())) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") return req diff --git a/tests/integration/migrate_test.go b/tests/integration/migrate_test.go index 7b2412cabd042..05c5f1e7da770 100644 --- a/tests/integration/migrate_test.go +++ b/tests/integration/migrate_test.go @@ -12,6 +12,7 @@ import ( "path/filepath" "testing" + auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -67,7 +68,7 @@ func TestMigrateGiteaForm(t *testing.T) { repoName := "repo1" repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: ownerName}) session := loginUser(t, ownerName) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) // Step 0: verify the repo is available req := NewRequestf(t, "GET", fmt.Sprintf("/%s/%s", ownerName, repoName)) diff --git a/tests/integration/org_count_test.go b/tests/integration/org_count_test.go index 6c15ec79b79e2..5ce1032ea9e17 100644 --- a/tests/integration/org_count_test.go +++ b/tests/integration/org_count_test.go @@ -9,6 +9,7 @@ import ( "strings" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -25,7 +26,7 @@ func testOrgCounts(t *testing.T, u *url.URL) { orgOwner := "user2" orgName := "testOrg" orgCollaborator := "user4" - ctx := NewAPITestContext(t, orgOwner, "repo1", "admin_org") + ctx := NewAPITestContext(t, orgOwner, "repo1", auth_model.AccessTokenScopeAdminOrg) var ownerCountRepos map[string]int var collabCountRepos map[string]int diff --git a/tests/integration/org_test.go b/tests/integration/org_test.go index 91cab00e4737f..41611040b1407 100644 --- a/tests/integration/org_test.go +++ b/tests/integration/org_test.go @@ -10,6 +10,7 @@ import ( "strings" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" api "code.gitea.io/gitea/modules/structs" @@ -159,7 +160,7 @@ func TestOrgRestrictedUser(t *testing.T) { // Therefore create a read-only team adminSession := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, adminSession, "admin_org") + token := getTokenForLoggedInUser(t, adminSession, auth_model.AccessTokenScopeAdminOrg) teamToCreate := &api.CreateTeamOption{ Name: "codereader", diff --git a/tests/integration/privateactivity_test.go b/tests/integration/privateactivity_test.go index b29418ef95bfa..e2fee7a507c30 100644 --- a/tests/integration/privateactivity_test.go +++ b/tests/integration/privateactivity_test.go @@ -10,6 +10,7 @@ import ( "testing" activities_model "code.gitea.io/gitea/models/activities" + auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -34,7 +35,7 @@ func testPrivateActivityDoSomethingForActionEntries(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}) session := loginUser(t, privateActivityTestUser) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all&token=%s", owner.Name, repoBefore.Name, token) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateIssueOption{ Body: "test", diff --git a/tests/integration/pull_merge_test.go b/tests/integration/pull_merge_test.go index 9a521e2a934d8..b5091f8f7f9e8 100644 --- a/tests/integration/pull_merge_test.go +++ b/tests/integration/pull_merge_test.go @@ -18,6 +18,7 @@ import ( "time" "code.gitea.io/gitea/models" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" @@ -218,7 +219,7 @@ func TestCantMergeConflict(t *testing.T) { testEditFileToNewBranch(t, session, "user1", "repo1", "master", "base", "README.md", "Hello, World (Edited Twice)\n") // Use API to create a conflicting pr - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", "user1", "repo1", token), &api.CreatePullRequestOption{ Head: "conflict", Base: "base", @@ -326,7 +327,7 @@ func TestCantMergeUnrelated(t *testing.T) { testEditFileToNewBranch(t, session, "user1", "repo1", "master", "conflict", "README.md", "Hello, World (Edited Once)\n") // Use API to create a conflicting pr - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", "user1", "repo1", token), &api.CreatePullRequestOption{ Head: "unrelated", Base: "base", diff --git a/tests/integration/pull_status_test.go b/tests/integration/pull_status_test.go index cb34b188db607..6b9aab9509158 100644 --- a/tests/integration/pull_status_test.go +++ b/tests/integration/pull_status_test.go @@ -11,6 +11,7 @@ import ( "strings" "testing" + auth_model "code.gitea.io/gitea/models/auth" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -63,7 +64,7 @@ func TestPullCreate_CommitStatus(t *testing.T) { api.CommitStatusWarning: "gitea-exclamation", } - testCtx := NewAPITestContext(t, "user1", "repo1", "repo") + testCtx := NewAPITestContext(t, "user1", "repo1", auth_model.AccessTokenScopeRepo) // Update commit status, and check if icon is updated as well for _, status := range statusList { diff --git a/tests/integration/pull_update_test.go b/tests/integration/pull_update_test.go index 4c869c3dc2e4e..7ccae652b2b4d 100644 --- a/tests/integration/pull_update_test.go +++ b/tests/integration/pull_update_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" "code.gitea.io/gitea/models/unittest" @@ -39,7 +40,7 @@ func TestAPIPullUpdate(t *testing.T) { assert.NoError(t, pr.LoadIssue()) session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index) session.MakeRequest(t, req, http.StatusOK) @@ -67,7 +68,7 @@ func TestAPIPullUpdateByRebase(t *testing.T) { assert.NoError(t, pr.LoadIssue()) session := loginUser(t, "user2") - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase&token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index) session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/repo_commits_test.go b/tests/integration/repo_commits_test.go index dfcf5bf17ddd5..eb9d9dfb89d19 100644 --- a/tests/integration/repo_commits_test.go +++ b/tests/integration/repo_commits_test.go @@ -10,6 +10,7 @@ import ( "path" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" @@ -49,7 +50,7 @@ func doTestRepoCommitWithStatus(t *testing.T, state string, classes ...string) { assert.NotEmpty(t, commitURL) // Call API to add status for commit - ctx := NewAPITestContext(t, "user2", "repo1", "repo") + ctx := NewAPITestContext(t, "user2", "repo1", auth_model.AccessTokenScopeRepo) t.Run("CreateStatus", doAPICreateCommitStatus(ctx, path.Base(commitURL), api.CommitStatusState(state))) req = NewRequest(t, "GET", "/user2/repo1/commits/branch/master") diff --git a/tests/integration/ssh_key_test.go b/tests/integration/ssh_key_test.go index 43d20c86060ef..af19f406f8319 100644 --- a/tests/integration/ssh_key_test.go +++ b/tests/integration/ssh_key_test.go @@ -13,6 +13,7 @@ import ( "testing" "time" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/modules/git" api "code.gitea.io/gitea/modules/structs" @@ -48,8 +49,8 @@ func TestPushDeployKeyOnEmptyRepo(t *testing.T) { func testPushDeployKeyOnEmptyRepo(t *testing.T, u *url.URL) { // OK login - ctx := NewAPITestContext(t, "user2", "deploy-key-empty-repo-1", "repo") - ctxWithDeleteRepo := NewAPITestContext(t, "user2", "deploy-key-empty-repo-1", "repo", "delete_repo") + ctx := NewAPITestContext(t, "user2", "deploy-key-empty-repo-1", auth_model.AccessTokenScopeRepo) + ctxWithDeleteRepo := NewAPITestContext(t, "user2", "deploy-key-empty-repo-1", auth_model.AccessTokenScopeRepo, auth_model.AccessTokenScopeDeleteRepo) keyname := fmt.Sprintf("%s-push", ctx.Reponame) u.Path = ctx.GitPath() @@ -92,8 +93,8 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) { keyname := fmt.Sprintf("%s-push", reponame) // OK login - ctx := NewAPITestContext(t, username, reponame, "repo", "admin_public_key") - ctxWithDeleteRepo := NewAPITestContext(t, username, reponame, "repo", "admin_public_key", "delete_repo") + ctx := NewAPITestContext(t, username, reponame, auth_model.AccessTokenScopeRepo, auth_model.AccessTokenScopeAdminPublicKey) + ctxWithDeleteRepo := NewAPITestContext(t, username, reponame, auth_model.AccessTokenScopeRepo, auth_model.AccessTokenScopeAdminPublicKey, auth_model.AccessTokenScopeDeleteRepo) otherCtx := ctx otherCtx.Reponame = "ssh-key-test-repo-2" diff --git a/tests/integration/user_test.go b/tests/integration/user_test.go index baadb2c94769d..0ca2781ab43b7 100644 --- a/tests/integration/user_test.go +++ b/tests/integration/user_test.go @@ -8,6 +8,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -166,7 +167,7 @@ Note: This user hasn't uploaded any GPG keys. // Import key // User1 session := loginUser(t, "user1") - token := getTokenForLoggedInUser(t, session, "write_gpg_key") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteGPGKey) testCreateGPGKey(t, session.MakeRequest, token, http.StatusCreated, `-----BEGIN PGP PUBLIC KEY BLOCK----- mQENBFyy/VUBCADJ7zbM20Z1RWmFoVgp5WkQfI2rU1Vj9cQHes9i42wVLLtcbPeo From 7c4ecf4771cd0bd1551f3193304112712585a22d Mon Sep 17 00:00:00 2001 From: harryzcy Date: Thu, 17 Nov 2022 23:55:22 -0500 Subject: [PATCH 093/118] Fix lint issue --- tests/integration/api_oauth2_apps_test.go | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/tests/integration/api_oauth2_apps_test.go b/tests/integration/api_oauth2_apps_test.go index 9f7d515dacbb0..ed137ff521fb4 100644 --- a/tests/integration/api_oauth2_apps_test.go +++ b/tests/integration/api_oauth2_apps_test.go @@ -9,7 +9,6 @@ import ( "net/http" "testing" - "code.gitea.io/gitea/models/auth" auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -51,7 +50,7 @@ func testAPICreateOAuth2Application(t *testing.T) { assert.True(t, createdApp.ConfidentialClient) assert.NotEmpty(t, createdApp.Created) assert.EqualValues(t, appBody.RedirectURIs[0], createdApp.RedirectURIs[0]) - unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{UID: user.ID, Name: createdApp.Name}) + unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{UID: user.ID, Name: createdApp.Name}) } func testAPIListOAuth2Applications(t *testing.T) { @@ -59,7 +58,7 @@ func testAPIListOAuth2Applications(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadApplication) - existApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ + existApp := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ UID: user.ID, Name: "test-app-1", RedirectURIs: []string{ @@ -82,7 +81,7 @@ func testAPIListOAuth2Applications(t *testing.T) { assert.Len(t, expectedApp.ClientID, 36) assert.Empty(t, expectedApp.ClientSecret) assert.EqualValues(t, existApp.RedirectURIs[0], expectedApp.RedirectURIs[0]) - unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name}) + unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name}) } func testAPIDeleteOAuth2Application(t *testing.T) { @@ -90,7 +89,7 @@ func testAPIDeleteOAuth2Application(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteApplication) - oldApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ + oldApp := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ UID: user.ID, Name: "test-app-1", }) @@ -99,7 +98,7 @@ func testAPIDeleteOAuth2Application(t *testing.T) { req := NewRequest(t, "DELETE", urlStr) session.MakeRequest(t, req, http.StatusNoContent) - unittest.AssertNotExistsBean(t, &auth.OAuth2Application{UID: oldApp.UID, Name: oldApp.Name}) + unittest.AssertNotExistsBean(t, &auth_model.OAuth2Application{UID: oldApp.UID, Name: oldApp.Name}) // Delete again will return not found req = NewRequest(t, "DELETE", urlStr) @@ -111,7 +110,7 @@ func testAPIGetOAuth2Application(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadApplication) - existApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ + existApp := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ UID: user.ID, Name: "test-app-1", RedirectURIs: []string{ @@ -135,13 +134,13 @@ func testAPIGetOAuth2Application(t *testing.T) { assert.Empty(t, expectedApp.ClientSecret) assert.Len(t, expectedApp.RedirectURIs, 1) assert.EqualValues(t, existApp.RedirectURIs[0], expectedApp.RedirectURIs[0]) - unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name}) + unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name}) } func testAPIUpdateOAuth2Application(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - existApp := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ + existApp := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ UID: user.ID, Name: "test-app-1", RedirectURIs: []string{ @@ -171,5 +170,5 @@ func testAPIUpdateOAuth2Application(t *testing.T) { assert.EqualValues(t, expectedApp.RedirectURIs[0], appBody.RedirectURIs[0]) assert.EqualValues(t, expectedApp.RedirectURIs[1], appBody.RedirectURIs[1]) assert.Equal(t, expectedApp.ConfidentialClient, appBody.ConfidentialClient) - unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name}) + unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name}) } From dc1a717d1a82a68433e4bb7edb480eb24965c23f Mon Sep 17 00:00:00 2001 From: harryzcy Date: Fri, 18 Nov 2022 00:09:38 -0500 Subject: [PATCH 094/118] Fix TestAPIOrgDeny --- tests/integration/api_org_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/integration/api_org_test.go b/tests/integration/api_org_test.go index 58739db644598..d3817ed7c1957 100644 --- a/tests/integration/api_org_test.go +++ b/tests/integration/api_org_test.go @@ -128,7 +128,7 @@ func TestAPIOrgDeny(t *testing.T) { setting.Service.RequireSignInView = false }() - token := getUserToken(t, "user1", "read_org") + token := getUserToken(t, "user1", auth_model.AccessTokenScopeReadOrg) orgName := "user1_org" req := NewRequestf(t, "GET", "/api/v1/orgs/%s?token=%s", orgName, token) @@ -145,7 +145,7 @@ func TestAPIOrgDeny(t *testing.T) { func TestAPIGetAll(t *testing.T) { defer tests.PrepareTestEnv(t)() - token := getUserToken(t, "user1", "read_org") + token := getUserToken(t, "user1", auth_model.AccessTokenScopeReadOrg) req := NewRequestf(t, "GET", "/api/v1/orgs?token=%s", token) resp := MakeRequest(t, req, http.StatusOK) From 240656a320d8c032af3aeef1840941f786ff9711 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Fri, 18 Nov 2022 01:30:12 -0500 Subject: [PATCH 095/118] Catch missed constants --- tests/integration/api_admin_test.go | 2 +- tests/integration/api_comment_test.go | 11 ++++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/tests/integration/api_admin_test.go b/tests/integration/api_admin_test.go index 181c2d4507d99..7403634dd2d05 100644 --- a/tests/integration/api_admin_test.go +++ b/tests/integration/api_admin_test.go @@ -26,7 +26,7 @@ func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) { session := loginUser(t, "user1") keyOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user2"}) - token := getTokenForLoggedInUser(t, session, "sudo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeSudo) urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys?token=%s", keyOwner.Name, token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n", diff --git a/tests/integration/api_comment_test.go b/tests/integration/api_comment_test.go index 0025c58b11e28..063e8d6060128 100644 --- a/tests/integration/api_comment_test.go +++ b/tests/integration/api_comment_test.go @@ -10,6 +10,7 @@ import ( "net/url" "testing" + auth_model "code.gitea.io/gitea/models/auth" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -77,7 +78,7 @@ func TestAPIListIssueComments(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/comments?token=%s", repoOwner.Name, repo.Name, issue.Index, token) resp := session.MakeRequest(t, req, http.StatusOK) @@ -98,7 +99,7 @@ func TestAPICreateComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/comments?token=%s", repoOwner.Name, repo.Name, issue.Index, token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ @@ -123,7 +124,7 @@ func TestAPIGetComment(t *testing.T) { session := loginUser(t, repoOwner.Name) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID) session.MakeRequest(t, req, http.StatusOK) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) resp := session.MakeRequest(t, req, http.StatusOK) @@ -150,7 +151,7 @@ func TestAPIEditComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ @@ -175,7 +176,7 @@ func TestAPIDeleteComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session, "repo") + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) session.MakeRequest(t, req, http.StatusNoContent) From b1ddfeabcf29f589ffa8922a954ca9c63f99fe1c Mon Sep 17 00:00:00 2001 From: Chongyi Zheng Date: Wed, 30 Nov 2022 22:28:03 +0000 Subject: [PATCH 096/118] Document current implementation limitation --- models/auth/token_scope.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/models/auth/token_scope.go b/models/auth/token_scope.go index dca69aa2a26cd..6d323185df133 100644 --- a/models/auth/token_scope.go +++ b/models/auth/token_scope.go @@ -112,6 +112,10 @@ const ( AccessTokenScopeReadApplicationBits = 1 << iota AccessTokenScopeSudoBits = 1 << iota + + // The current implementation only supports up to 64 token scopes. + // If we need to support > 64 scopes, + // refactoring the whole implementation in this file (and only this file) is needed. ) // AllAccessTokenScopes contains all access token scopes. From 826b1600226516f6f0a5c56ec6754d5e42825916 Mon Sep 17 00:00:00 2001 From: Chongyi Zheng Date: Wed, 30 Nov 2022 22:30:28 +0000 Subject: [PATCH 097/118] Update copyright style --- models/auth/token_scope.go | 3 +-- models/auth/token_scope_test.go | 3 +-- models/migrations/v1_19/v236.go | 3 +-- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/models/auth/token_scope.go b/models/auth/token_scope.go index 6d323185df133..c2d4abfab695c 100644 --- a/models/auth/token_scope.go +++ b/models/auth/token_scope.go @@ -1,6 +1,5 @@ // Copyright 2022 The Gitea Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package auth diff --git a/models/auth/token_scope_test.go b/models/auth/token_scope_test.go index f564e9112cdc7..dd53716b516e2 100644 --- a/models/auth/token_scope_test.go +++ b/models/auth/token_scope_test.go @@ -1,6 +1,5 @@ // Copyright 2022 The Gitea Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package auth diff --git a/models/migrations/v1_19/v236.go b/models/migrations/v1_19/v236.go index c17caff734ab8..69b9a44a16a2c 100644 --- a/models/migrations/v1_19/v236.go +++ b/models/migrations/v1_19/v236.go @@ -1,6 +1,5 @@ // Copyright 2022 The Gitea Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package v1_19 //nolint From 0e0c4ddbaca36d1d4f246e050637b88573bab0d6 Mon Sep 17 00:00:00 2001 From: Chongyi Zheng Date: Thu, 1 Dec 2022 03:40:04 +0000 Subject: [PATCH 098/118] Ensure migration is safe --- models/migrations/v1_19/v236.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/models/migrations/v1_19/v236.go b/models/migrations/v1_19/v236.go index 69b9a44a16a2c..633800f8c7317 100644 --- a/models/migrations/v1_19/v236.go +++ b/models/migrations/v1_19/v236.go @@ -18,6 +18,6 @@ func AddScopeForAccessTokens(x *xorm.Engine) error { return err } - _, err := x.Exec("UPDATE access_token SET scope = ?", auth_models.AccessTokenScopeAll) + _, err := x.Exec("UPDATE access_token SET scope = ? WHERE scope IS NULL OR scope = ''", auth_models.AccessTokenScopeAll) return err } From 3b93df8b6c445631e3dd7bfb69789b351cf94833 Mon Sep 17 00:00:00 2001 From: Chongyi Zheng Date: Thu, 1 Dec 2022 03:50:00 +0000 Subject: [PATCH 099/118] Fix integration tests after merge --- tests/integration/repo_commits_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/integration/repo_commits_test.go b/tests/integration/repo_commits_test.go index 5a244c247ea12..c38e4e0a8fa2f 100644 --- a/tests/integration/repo_commits_test.go +++ b/tests/integration/repo_commits_test.go @@ -139,7 +139,8 @@ func TestRepoCommitsStatusParallel(t *testing.T) { wg.Add(1) go func(t *testing.T, i int) { t.Run(fmt.Sprintf("ParallelCreateStatus_%d", i), func(t *testing.T) { - runBody := doAPICreateCommitStatus(NewAPITestContext(t, "user2", "repo1"), path.Base(commitURL), api.CommitStatusState("pending")) + ctx := NewAPITestContext(t, "user2", "repo1", auth_model.AccessTokenScopeRepoStatus) + runBody := doAPICreateCommitStatus(ctx, path.Base(commitURL), api.CommitStatusState("pending")) runBody(t) wg.Done() }) From 16b13a7f68f51a32ea85ba257e16ac0db5de88e7 Mon Sep 17 00:00:00 2001 From: Chongyi Zheng Date: Fri, 2 Dec 2022 06:15:00 +0000 Subject: [PATCH 100/118] Use Forbidden for tokens without required scope --- routers/api/v1/api.go | 4 ++-- tests/integration/api_admin_test.go | 4 ++-- tests/integration/api_gpg_keys_test.go | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 3c87103b5bf60..32a47c3f55311 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -220,7 +220,7 @@ func reqToken(requiredScope string) func(ctx *context.APIContext) { scope := ctx.Data["ApiTokenScope"].(auth_model.AccessTokenScope) allow, err := scope.HasScope(requiredScope) if err != nil { - ctx.Error(http.StatusUnauthorized, "reqToken", "parsing token failed: "+err.Error()) + ctx.Error(http.StatusForbidden, "reqToken", "parsing token failed: "+err.Error()) return } if allow { @@ -236,7 +236,7 @@ func reqToken(requiredScope string) func(ctx *context.APIContext) { } } - ctx.Error(http.StatusUnauthorized, "reqToken", "token does not have required scope: "+requiredScope) + ctx.Error(http.StatusForbidden, "reqToken", "token does not have required scope: "+requiredScope) return } if ctx.Context.IsBasicAuth { diff --git a/tests/integration/api_admin_test.go b/tests/integration/api_admin_test.go index d2facf10091c4..e21b1187b78f2 100644 --- a/tests/integration/api_admin_test.go +++ b/tests/integration/api_admin_test.go @@ -78,7 +78,7 @@ func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) { token = getTokenForLoggedInUser(t, session) req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d?token=%s", adminUsername, newPublicKey.ID, token) - session.MakeRequest(t, req, http.StatusUnauthorized) + session.MakeRequest(t, req, http.StatusForbidden) } func TestAPISudoUser(t *testing.T) { @@ -145,7 +145,7 @@ func TestAPIListUsersNonAdmin(t *testing.T) { session := loginUser(t, nonAdminUsername) token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/admin/users?token=%s", token) - session.MakeRequest(t, req, http.StatusUnauthorized) + session.MakeRequest(t, req, http.StatusForbidden) } func TestAPICreateUserInvalidEmail(t *testing.T) { diff --git a/tests/integration/api_gpg_keys_test.go b/tests/integration/api_gpg_keys_test.go index b50ce0b27edfd..de0256b347b0e 100644 --- a/tests/integration/api_gpg_keys_test.go +++ b/tests/integration/api_gpg_keys_test.go @@ -36,7 +36,7 @@ func TestGPGKeys(t *testing.T) { }, { name: "LoggedAsUser2", makeRequest: session.MakeRequest, token: token, - results: []int{http.StatusUnauthorized, http.StatusOK, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized}, + results: []int{http.StatusForbidden, http.StatusOK, http.StatusForbidden, http.StatusForbidden, http.StatusForbidden, http.StatusForbidden, http.StatusForbidden, http.StatusForbidden, http.StatusForbidden}, }, { name: "LoggedAsUser2WithScope", makeRequest: session.MakeRequest, token: tokenWithGPGKeyScope, From 5f70625caf020d93dbb2ec0dac1f1ccc9a8811f6 Mon Sep 17 00:00:00 2001 From: Chongyi Zheng Date: Fri, 2 Dec 2022 06:33:48 +0000 Subject: [PATCH 101/118] Fix indentation issue --- tests/integration/api_comment_test.go | 2 +- tests/integration/repo_commits_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/integration/api_comment_test.go b/tests/integration/api_comment_test.go index 090c623504b77..b58c1069d25d8 100644 --- a/tests/integration/api_comment_test.go +++ b/tests/integration/api_comment_test.go @@ -146,7 +146,7 @@ func TestAPIEditComment(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) - token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeRepo) + token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ diff --git a/tests/integration/repo_commits_test.go b/tests/integration/repo_commits_test.go index 519cfcfa8df94..3ceeb3fa43b1f 100644 --- a/tests/integration/repo_commits_test.go +++ b/tests/integration/repo_commits_test.go @@ -139,7 +139,7 @@ func TestRepoCommitsStatusParallel(t *testing.T) { wg.Add(1) go func(parentT *testing.T, i int) { parentT.Run(fmt.Sprintf("ParallelCreateStatus_%d", i), func(t *testing.T) { - ctx := NewAPITestContext(t, "user2", "repo1", auth_model.AccessTokenScopeRepoStatus) + ctx := NewAPITestContext(t, "user2", "repo1", auth_model.AccessTokenScopeRepoStatus) runBody := doAPICreateCommitStatus(ctx, path.Base(commitURL), api.CommitStatusState("pending")) runBody(t) wg.Done() From 5f0076cc65437de34d5c65eed37c8962aefa6f44 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 11 Dec 2022 16:09:15 -0500 Subject: [PATCH 102/118] Fix data race in integration tests --- tests/integration/integration_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/integration/integration_test.go b/tests/integration/integration_test.go index 856368656f80b..d65dedffc4b5b 100644 --- a/tests/integration/integration_test.go +++ b/tests/integration/integration_test.go @@ -17,6 +17,7 @@ import ( "os" "path/filepath" "strings" + "sync/atomic" "testing" "time" @@ -265,7 +266,7 @@ var tokenCounter int64 // but without the "scope_" prefix. func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...string) string { t.Helper() - tokenCounter++ + atomic.AddInt64(&tokenCounter, 1) req := NewRequest(t, "GET", "/user/settings/applications") resp := session.MakeRequest(t, req, http.StatusOK) doc := NewHTMLParser(t, resp.Body) From 5fecbd1e2a4d61643ca42f906ddcf0efb562999e Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 11 Dec 2022 16:27:19 -0500 Subject: [PATCH 103/118] Fix License header issue --- modules/util/compare_test.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/modules/util/compare_test.go b/modules/util/compare_test.go index f8972f4da548c..4fbea27349096 100644 --- a/modules/util/compare_test.go +++ b/modules/util/compare_test.go @@ -1,6 +1,5 @@ // Copyright 2022 The Gitea Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package util From 3c8be2e5604a830865370d2c82640446a750e0be Mon Sep 17 00:00:00 2001 From: harryzcy Date: Sun, 11 Dec 2022 21:17:42 -0500 Subject: [PATCH 104/118] Fix tests errors caused by merge --- tests/integration/api_comment_attachment_test.go | 7 ++++--- tests/integration/api_issue_attachment_test.go | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/tests/integration/api_comment_attachment_test.go b/tests/integration/api_comment_attachment_test.go index 22bf502ef6d0d..12e08865ed3a1 100644 --- a/tests/integration/api_comment_attachment_test.go +++ b/tests/integration/api_comment_attachment_test.go @@ -12,6 +12,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" @@ -81,7 +82,7 @@ func TestAPICreateCommentAttachment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets?token=%s", repoOwner.Name, repo.Name, comment.ID, token) @@ -120,7 +121,7 @@ func TestAPIEditCommentAttachment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, attachment.ID, token) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ @@ -143,7 +144,7 @@ func TestAPIDeleteCommentAttachment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, attachment.ID, token) diff --git a/tests/integration/api_issue_attachment_test.go b/tests/integration/api_issue_attachment_test.go index 0558dda56a14d..b4d6dab42a184 100644 --- a/tests/integration/api_issue_attachment_test.go +++ b/tests/integration/api_issue_attachment_test.go @@ -12,6 +12,7 @@ import ( "net/http" "testing" + auth_model "code.gitea.io/gitea/models/auth" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -72,7 +73,7 @@ func TestAPICreateIssueAttachment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets?token=%s", repoOwner.Name, repo.Name, issue.Index, token) @@ -110,7 +111,7 @@ func TestAPIEditIssueAttachment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets/%d?token=%s", repoOwner.Name, repo.Name, issue.Index, attachment.ID, token) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ @@ -132,7 +133,7 @@ func TestAPIDeleteIssueAttachment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, repoOwner.Name) - token := getTokenForLoggedInUser(t, session) + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeRepo) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets/%d?token=%s", repoOwner.Name, repo.Name, issue.Index, attachment.ID, token) From a7340b81526e09b2f779bb610acdf4e4629341a1 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Thu, 29 Dec 2022 20:33:45 -0500 Subject: [PATCH 105/118] Prevent `IsApiToken` change --- routers/api/v1/api.go | 3 ++- services/auth/basic.go | 4 ++-- services/auth/httpsign.go | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 9dfa5e7096d9d..368aa263b5dad 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -209,7 +209,8 @@ func reqPackageAccess(accessMode perm.AccessMode) func(ctx *context.APIContext) // Contexter middleware already checks token for user sign in process. func reqToken(requiredScope string) func(ctx *context.APIContext) { return func(ctx *context.APIContext) { - if ctx.Data["IsApiToken"] == true { + // If OAuth2 token is present + if _, ok := ctx.Data["ApiTokenScope"]; ctx.Data["IsApiToken"] == true && ok { // no scope required if requiredScope == "" { return diff --git a/services/auth/basic.go b/services/auth/basic.go index 76e4e64c07b7e..5fb80703ab5a4 100644 --- a/services/auth/basic.go +++ b/services/auth/basic.go @@ -80,7 +80,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore return nil, err } - store.GetData()["IsApiToken"] = false + store.GetData()["IsApiToken"] = true return u, nil } @@ -98,7 +98,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore log.Error("UpdateAccessToken: %v", err) } - store.GetData()["IsApiToken"] = false + store.GetData()["IsApiToken"] = true return u, nil } else if !auth_model.IsErrAccessTokenNotExist(err) && !auth_model.IsErrAccessTokenEmpty(err) { log.Error("GetAccessTokenBySha: %v", err) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index b7c0a407f5ed2..4d52315381c32 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -78,7 +78,7 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt return nil, err } - store.GetData()["IsApiToken"] = false + store.GetData()["IsApiToken"] = true log.Trace("HTTP Sign: Logged in user %-v", u) From 6796f66a6ef3e7aa2ba738488e9a79fbef162b03 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Thu, 29 Dec 2022 20:37:06 -0500 Subject: [PATCH 106/118] Fix integration tests after merging from upstream --- tests/integration/integration_test.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/tests/integration/integration_test.go b/tests/integration/integration_test.go index 814393d0559d7..38e4f43a94c68 100644 --- a/tests/integration/integration_test.go +++ b/tests/integration/integration_test.go @@ -283,10 +283,7 @@ func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...strin for _, scope := range scopes { urlValues.Add("scope", scope) } - req = NewRequestWithValues(t, "POST", "/user/settings/applications", map[string]string{ - "_csrf": csrf, - "name": fmt.Sprintf("api-testing-token-%d", atomic.AddInt64(&tokenCounter, 1)), - }) + req = NewRequestWithURLValues(t, "POST", "/user/settings/applications", urlValues) resp = session.MakeRequest(t, req, http.StatusSeeOther) // Log the flash values on failure From a1b52e45be4ac1f423c10a79f98700567f2f99e9 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Tue, 3 Jan 2023 23:19:05 -0500 Subject: [PATCH 107/118] Document all token scopes --- .../doc/developers/oauth2-provider.en-us.md | 50 +++++++++---------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/docs/content/doc/developers/oauth2-provider.en-us.md b/docs/content/doc/developers/oauth2-provider.en-us.md index e75727d4d10a0..d8c397bf300f3 100644 --- a/docs/content/doc/developers/oauth2-provider.en-us.md +++ b/docs/content/doc/developers/oauth2-provider.en-us.md @@ -51,31 +51,31 @@ Gitea supports the following scopes for tokens: |     **repo:status** | Grants read/write access to commit status in all repositories. | |     **public_repo** | Grants read/write access to public repositories only. | | **admin:repo_hook** | Grants access to repository hooks of all repositories. This is included in the `repo` scope. | -|     **write:repo_hook** | | -|     **read:repo_hook** | | -| **admin:org** | | -|     **write:org** | | -|     **read:org** | | -| **admin:public_key** | | -|     **write:public_key** | | -|     **read:public_key** | | -| **admin:org_hook** | | -| **notification** | | -| **user** | | -|     **read:user** | | -|     **user:email** | | -|     **user:follow** | | -| **delete_repo** | | -| **package** | | -|     **write:package** | | -|     **read:package** | | -|     **delete:package** | | -| **admin:gpg_key** | | -|     **write:gpg_key** | | -|     **read:gpg_key** | | -| **admin:application** | | -|     **write:application** | | -|     **read:application** | | +|     **write:repo_hook** | Grants read/write access to repository hooks | +|     **read:repo_hook** | Grants read-only access to repository hooks | +| **admin:org** | Grants full access to organization settings | +|     **write:org** | Grants read/write access to organization settings | +|     **read:org** | Grants read-only access to organization settings | +| **admin:public_key** | Grants full access for managing public keys | +|     **write:public_key** | Grant read/write access to public keys | +|     **read:public_key** | Grant read-only access to public keys | +| **admin:org_hook** | Grants full access to organizational-level hooks | +| **notification** | Grants full access to notifications | +| **user** | Grants full access to user profile info | +|     **read:user** | Grants read access to user's profile | +|     **user:email** | Grants read access to user's email addresses | +|     **user:follow** | Grants access to follow/un-follow a user | +| **delete_repo** | Grants access to delete repositories as an admin | +| **package** | Grants full access to hosted packages | +|     **write:package** | Grants read/write access to packages | +|     **read:package** | Grants read access to packages | +|     **delete:package** | Grants delete access to packages | +| **admin:gpg_key** | Grants full access for managing GPG keys | +|     **write:gpg_key** | Grants read/write access to GPG keys | +|     **read:gpg_key** | Grants read-only access to GPG keys | +| **admin:application** | Grants full access to manage applications | +|     **write:application** | Grants read/write access for managing applications | +|     **read:application** | Grants read access for managing applications | | **sudo** | Allows to perform actions as the site admin. | ## Client types From e3114bbc16bbd1f6d21abf322f3e710d0673b701 Mon Sep 17 00:00:00 2001 From: Chongyi Zheng Date: Wed, 4 Jan 2023 14:32:24 -0500 Subject: [PATCH 108/118] Update docs/content/doc/developers/oauth2-provider.en-us.md Co-authored-by: KN4CK3R --- .../doc/developers/oauth2-provider.en-us.md | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/docs/content/doc/developers/oauth2-provider.en-us.md b/docs/content/doc/developers/oauth2-provider.en-us.md index d8c397bf300f3..17c12d22f2423 100644 --- a/docs/content/doc/developers/oauth2-provider.en-us.md +++ b/docs/content/doc/developers/oauth2-provider.en-us.md @@ -48,34 +48,34 @@ Gitea supports the following scopes for tokens: | ---- | ----------- | | **(no scope)** | Grants read-only access to public user profile and public repositories. | | **repo** | Full control over all repositories. | -|     **repo:status** | Grants read/write access to commit status in all repositories. | -|     **public_repo** | Grants read/write access to public repositories only. | +|     **repo:status** | Grants read/write access to commit status in all repositories. | +|     **public_repo** | Grants read/write access to public repositories only. | | **admin:repo_hook** | Grants access to repository hooks of all repositories. This is included in the `repo` scope. | -|     **write:repo_hook** | Grants read/write access to repository hooks | -|     **read:repo_hook** | Grants read-only access to repository hooks | +|     **write:repo_hook** | Grants read/write access to repository hooks | +|     **read:repo_hook** | Grants read-only access to repository hooks | | **admin:org** | Grants full access to organization settings | -|     **write:org** | Grants read/write access to organization settings | -|     **read:org** | Grants read-only access to organization settings | +|     **write:org** | Grants read/write access to organization settings | +|     **read:org** | Grants read-only access to organization settings | | **admin:public_key** | Grants full access for managing public keys | -|     **write:public_key** | Grant read/write access to public keys | -|     **read:public_key** | Grant read-only access to public keys | +|     **write:public_key** | Grant read/write access to public keys | +|     **read:public_key** | Grant read-only access to public keys | | **admin:org_hook** | Grants full access to organizational-level hooks | | **notification** | Grants full access to notifications | | **user** | Grants full access to user profile info | -|     **read:user** | Grants read access to user's profile | -|     **user:email** | Grants read access to user's email addresses | -|     **user:follow** | Grants access to follow/un-follow a user | +|     **read:user** | Grants read access to user's profile | +|     **user:email** | Grants read access to user's email addresses | +|     **user:follow** | Grants access to follow/un-follow a user | | **delete_repo** | Grants access to delete repositories as an admin | | **package** | Grants full access to hosted packages | -|     **write:package** | Grants read/write access to packages | -|     **read:package** | Grants read access to packages | -|     **delete:package** | Grants delete access to packages | +|     **write:package** | Grants read/write access to packages | +|     **read:package** | Grants read access to packages | +|     **delete:package** | Grants delete access to packages | | **admin:gpg_key** | Grants full access for managing GPG keys | -|     **write:gpg_key** | Grants read/write access to GPG keys | -|     **read:gpg_key** | Grants read-only access to GPG keys | +|     **write:gpg_key** | Grants read/write access to GPG keys | +|     **read:gpg_key** | Grants read-only access to GPG keys | | **admin:application** | Grants full access to manage applications | -|     **write:application** | Grants read/write access for managing applications | -|     **read:application** | Grants read access for managing applications | +|     **write:application** | Grants read/write access for managing applications | +|     **read:application** | Grants read access for managing applications | | **sudo** | Allows to perform actions as the site admin. | ## Client types From cd836c76e1e76479f7656bd3d6f833752278f4ac Mon Sep 17 00:00:00 2001 From: harryzcy Date: Mon, 16 Jan 2023 13:39:52 -0500 Subject: [PATCH 109/118] Use map to store token scope bits --- models/auth/token_scope.go | 79 ++++++++++++++++++++++---------------- modules/util/slice.go | 23 ----------- modules/util/slice_test.go | 7 ---- 3 files changed, 46 insertions(+), 63 deletions(-) diff --git a/models/auth/token_scope.go b/models/auth/token_scope.go index 9b03b8d9c9d2d..4f03ffa65b642 100644 --- a/models/auth/token_scope.go +++ b/models/auth/token_scope.go @@ -6,8 +6,6 @@ package auth import ( "fmt" "strings" - - "code.gitea.io/gitea/modules/util" ) // AccessTokenScope represents the scope for an access token. @@ -119,7 +117,7 @@ const ( // AllAccessTokenScopes contains all access token scopes. // The order is important: parent scope must precedes child scopes. -var AllAccessTokenScopes = []string{ +var allAccessTokenScopes = []string{ AccessTokenScopeRepo, AccessTokenScopeRepoStatus, AccessTokenScopePublicRepo, AccessTokenScopeAdminOrg, AccessTokenScopeWriteOrg, AccessTokenScopeReadOrg, AccessTokenScopeAdminPublicKey, AccessTokenScopeWritePublicKey, AccessTokenScopeReadPublicKey, @@ -135,20 +133,37 @@ var AllAccessTokenScopes = []string{ } // AllAccessTokenScopeBits contains all access token scopes. -// The order must be the same as AllAccessTokenScopeBits. -var AllAccessTokenScopeBits = []AccessTokenScopeBitmap{ - AccessTokenScopeRepoBits, AccessTokenScopeRepoStatusBits, AccessTokenScopePublicRepoBits, - AccessTokenScopeAdminOrgBits, AccessTokenScopeWriteOrgBits, AccessTokenScopeReadOrgBits, - AccessTokenScopeAdminPublicKeyBits, AccessTokenScopeWritePublicKeyBits, AccessTokenScopeReadPublicKeyBits, - AccessTokenScopeAdminRepoHookBits, AccessTokenScopeWriteRepoHookBits, AccessTokenScopeReadRepoHookBits, - AccessTokenScopeAdminOrgHookBits, - AccessTokenScopeNotificationBits, - AccessTokenScopeUserBits, AccessTokenScopeReadUserBits, AccessTokenScopeUserEmailBits, AccessTokenScopeUserFollowBits, - AccessTokenScopeDeleteRepoBits, - AccessTokenScopePackageBits, AccessTokenScopeWritePackageBits, AccessTokenScopeReadPackageBits, AccessTokenScopeDeletePackageBits, - AccessTokenScopeAdminGPGKeyBits, AccessTokenScopeWriteGPGKeyBits, AccessTokenScopeReadGPGKeyBits, - AccessTokenScopeAdminApplicationBits, AccessTokenScopeWriteApplicationBits, AccessTokenScopeReadApplicationBits, - AccessTokenScopeSudoBits, +var allAccessTokenScopeBits = map[string]AccessTokenScopeBitmap{ + AccessTokenScopeRepo: AccessTokenScopeRepoBits, + AccessTokenScopeRepoStatus: AccessTokenScopeRepoStatusBits, + AccessTokenScopePublicRepo: AccessTokenScopePublicRepoBits, + AccessTokenScopeAdminOrg: AccessTokenScopeAdminOrgBits, + AccessTokenScopeWriteOrg: AccessTokenScopeWriteOrgBits, + AccessTokenScopeReadOrg: AccessTokenScopeReadOrgBits, + AccessTokenScopeAdminPublicKey: AccessTokenScopeAdminPublicKeyBits, + AccessTokenScopeWritePublicKey: AccessTokenScopeWritePublicKeyBits, + AccessTokenScopeReadPublicKey: AccessTokenScopeReadPublicKeyBits, + AccessTokenScopeAdminRepoHook: AccessTokenScopeAdminRepoHookBits, + AccessTokenScopeWriteRepoHook: AccessTokenScopeWriteRepoHookBits, + AccessTokenScopeReadRepoHook: AccessTokenScopeReadRepoHookBits, + AccessTokenScopeAdminOrgHook: AccessTokenScopeAdminOrgHookBits, + AccessTokenScopeNotification: AccessTokenScopeNotificationBits, + AccessTokenScopeUser: AccessTokenScopeUserBits, + AccessTokenScopeReadUser: AccessTokenScopeReadUserBits, + AccessTokenScopeUserEmail: AccessTokenScopeUserEmailBits, + AccessTokenScopeUserFollow: AccessTokenScopeUserFollowBits, + AccessTokenScopeDeleteRepo: AccessTokenScopeDeleteRepoBits, + AccessTokenScopePackage: AccessTokenScopePackageBits, + AccessTokenScopeWritePackage: AccessTokenScopeWritePackageBits, + AccessTokenScopeReadPackage: AccessTokenScopeReadPackageBits, + AccessTokenScopeDeletePackage: AccessTokenScopeDeletePackageBits, + AccessTokenScopeAdminGPGKey: AccessTokenScopeAdminGPGKeyBits, + AccessTokenScopeWriteGPGKey: AccessTokenScopeWriteGPGKeyBits, + AccessTokenScopeReadGPGKey: AccessTokenScopeReadGPGKeyBits, + AccessTokenScopeAdminApplication: AccessTokenScopeAdminApplicationBits, + AccessTokenScopeWriteApplication: AccessTokenScopeWriteApplicationBits, + AccessTokenScopeReadApplication: AccessTokenScopeReadApplicationBits, + AccessTokenScopeSudo: AccessTokenScopeSudoBits, } // Parse parses the scope string into a bitmap, thus removing possible duplicates. @@ -156,20 +171,20 @@ func (s AccessTokenScope) Parse() (AccessTokenScopeBitmap, error) { list := strings.Split(string(s), ",") var bitmap AccessTokenScopeBitmap - for _, v := range list { - if v == "" { + for _, singleScope := range list { + if singleScope == "" { continue } - if v == AccessTokenScopeAll { + if singleScope == AccessTokenScopeAll { bitmap |= AccessTokenScopeAllBits continue } - idx := util.SliceFindString(v, AllAccessTokenScopes) - if idx < 0 { - return 0, fmt.Errorf("invalid access token scope: %s", v) + if bits, ok := allAccessTokenScopeBits[singleScope]; !ok { + return 0, fmt.Errorf("invalid access token scope: %s", singleScope) + } else { + bitmap |= bits } - bitmap |= AllAccessTokenScopeBits[idx] } return bitmap, nil } @@ -196,14 +211,12 @@ func (s AccessTokenScope) HasScope(scope string) (bool, error) { // HasScope returns true if the string has the given scope func (bitmap AccessTokenScopeBitmap) HasScope(scope string) (bool, error) { - index := util.SliceFindString(scope, AllAccessTokenScopes) - if index == -1 { + expectedBits, ok := allAccessTokenScopeBits[scope] + if !ok { return false, fmt.Errorf("invalid access token scope: %s", scope) } - expectedBitmap := AllAccessTokenScopeBits[index] - - return bitmap&expectedBitmap == expectedBitmap, nil + return bitmap&expectedBits == expectedBits, nil } // ToScope returns a normalized scope string without any duplicates. @@ -214,16 +227,16 @@ func (bitmap AccessTokenScopeBitmap) ToScope() AccessTokenScope { // if the reconstructed bitmap doesn't change, then the scope is already included var reconstruct AccessTokenScopeBitmap - for i, v := range AllAccessTokenScopes { + for _, singleScope := range allAccessTokenScopes { // no need for error checking here, since we know the scope is valid - if ok, _ := bitmap.HasScope(v); ok { - current := reconstruct | AllAccessTokenScopeBits[i] + if ok, _ := bitmap.HasScope(singleScope); ok { + current := reconstruct | allAccessTokenScopeBits[singleScope] if current == reconstruct { continue } reconstruct = current - scopes = append(scopes, v) + scopes = append(scopes, singleScope) } } diff --git a/modules/util/slice.go b/modules/util/slice.go index 7e39ef36a8011..74356f5496205 100644 --- a/modules/util/slice.go +++ b/modules/util/slice.go @@ -34,29 +34,6 @@ func SliceContainsString(slice []string, target string, insensitive ...bool) boo return SliceContains(slice, target) } -// SliceFindString returns the index of the first occurrence of target in slice. -// If target is not present in slice, -1 is returned. -func SliceFindString(target string, slice []string, insensitive ...bool) int { - caseInsensitive := false - if len(insensitive) != 0 && insensitive[0] { - caseInsensitive = true - target = strings.ToLower(target) - } - - for i, s := range slice { - if caseInsensitive { - if strings.ToLower(s) == target { - return i - } - } else { - if s == target { - return i - } - } - } - return -1 -} - // SliceSortedEqual returns true if the two slices will be equal when they get sorted. // It doesn't require that the slices have been sorted, and it doesn't sort them either. func SliceSortedEqual[T comparable](s1, s2 []T) bool { diff --git a/modules/util/slice_test.go b/modules/util/slice_test.go index f62e34216c7c2..b0b771a79a8fd 100644 --- a/modules/util/slice_test.go +++ b/modules/util/slice_test.go @@ -35,13 +35,6 @@ func TestSliceContainsString(t *testing.T) { assert.False(t, SliceContainsString(nil, "a")) } -func TestSliceFindString(t *testing.T) { - assert.Equal(t, 0, SliceFindString("a", []string{"a", "b", "c"})) - assert.Equal(t, 2, SliceFindString("c", []string{"a", "b", "c"})) - assert.Equal(t, -1, SliceFindString("d", []string{"a", "b", "c"})) - assert.Equal(t, 2, SliceFindString("C", []string{"a", "b", "c"}, true)) -} - func TestSliceSortedEqual(t *testing.T) { assert.True(t, SliceSortedEqual([]int{2, 0, 2, 3}, []int{2, 0, 2, 3})) assert.True(t, SliceSortedEqual([]int{3, 0, 2, 2}, []int{2, 0, 2, 3})) From 70d0c836874f77a2e10243045b5ccceca1075c61 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Mon, 16 Jan 2023 13:45:45 -0500 Subject: [PATCH 110/118] Use custom type for all scope variables --- models/auth/token_scope.go | 82 +++++++++++++++++---------------- models/auth/token_scope_test.go | 2 +- 2 files changed, 43 insertions(+), 41 deletions(-) diff --git a/models/auth/token_scope.go b/models/auth/token_scope.go index 4f03ffa65b642..badd8ed36957e 100644 --- a/models/auth/token_scope.go +++ b/models/auth/token_scope.go @@ -12,49 +12,49 @@ import ( type AccessTokenScope string const ( - AccessTokenScopeAll = "all" + AccessTokenScopeAll AccessTokenScope = "all" - AccessTokenScopeRepo = "repo" - AccessTokenScopeRepoStatus = "repo:status" - AccessTokenScopePublicRepo = "public_repo" + AccessTokenScopeRepo AccessTokenScope = "repo" + AccessTokenScopeRepoStatus AccessTokenScope = "repo:status" + AccessTokenScopePublicRepo AccessTokenScope = "public_repo" - AccessTokenScopeAdminOrg = "admin:org" - AccessTokenScopeWriteOrg = "write:org" - AccessTokenScopeReadOrg = "read:org" + AccessTokenScopeAdminOrg AccessTokenScope = "admin:org" + AccessTokenScopeWriteOrg AccessTokenScope = "write:org" + AccessTokenScopeReadOrg AccessTokenScope = "read:org" - AccessTokenScopeAdminPublicKey = "admin:public_key" - AccessTokenScopeWritePublicKey = "write:public_key" - AccessTokenScopeReadPublicKey = "read:public_key" + AccessTokenScopeAdminPublicKey AccessTokenScope = "admin:public_key" + AccessTokenScopeWritePublicKey AccessTokenScope = "write:public_key" + AccessTokenScopeReadPublicKey AccessTokenScope = "read:public_key" - AccessTokenScopeAdminRepoHook = "admin:repo_hook" - AccessTokenScopeWriteRepoHook = "write:repo_hook" - AccessTokenScopeReadRepoHook = "read:repo_hook" + AccessTokenScopeAdminRepoHook AccessTokenScope = "admin:repo_hook" + AccessTokenScopeWriteRepoHook AccessTokenScope = "write:repo_hook" + AccessTokenScopeReadRepoHook AccessTokenScope = "read:repo_hook" - AccessTokenScopeAdminOrgHook = "admin:org_hook" + AccessTokenScopeAdminOrgHook AccessTokenScope = "admin:org_hook" - AccessTokenScopeNotification = "notification" + AccessTokenScopeNotification AccessTokenScope = "notification" - AccessTokenScopeUser = "user" - AccessTokenScopeReadUser = "read:user" - AccessTokenScopeUserEmail = "user:email" - AccessTokenScopeUserFollow = "user:follow" + AccessTokenScopeUser AccessTokenScope = "user" + AccessTokenScopeReadUser AccessTokenScope = "read:user" + AccessTokenScopeUserEmail AccessTokenScope = "user:email" + AccessTokenScopeUserFollow AccessTokenScope = "user:follow" - AccessTokenScopeDeleteRepo = "delete_repo" + AccessTokenScopeDeleteRepo AccessTokenScope = "delete_repo" - AccessTokenScopePackage = "package" - AccessTokenScopeWritePackage = "write:package" - AccessTokenScopeReadPackage = "read:package" - AccessTokenScopeDeletePackage = "delete:package" + AccessTokenScopePackage AccessTokenScope = "package" + AccessTokenScopeWritePackage AccessTokenScope = "write:package" + AccessTokenScopeReadPackage AccessTokenScope = "read:package" + AccessTokenScopeDeletePackage AccessTokenScope = "delete:package" - AccessTokenScopeAdminGPGKey = "admin:gpg_key" - AccessTokenScopeWriteGPGKey = "write:gpg_key" - AccessTokenScopeReadGPGKey = "read:gpg_key" + AccessTokenScopeAdminGPGKey AccessTokenScope = "admin:gpg_key" + AccessTokenScopeWriteGPGKey AccessTokenScope = "write:gpg_key" + AccessTokenScopeReadGPGKey AccessTokenScope = "read:gpg_key" - AccessTokenScopeAdminApplication = "admin:application" - AccessTokenScopeWriteApplication = "write:application" - AccessTokenScopeReadApplication = "read:application" + AccessTokenScopeAdminApplication AccessTokenScope = "admin:application" + AccessTokenScopeWriteApplication AccessTokenScope = "write:application" + AccessTokenScopeReadApplication AccessTokenScope = "read:application" - AccessTokenScopeSudo = "sudo" + AccessTokenScopeSudo AccessTokenScope = "sudo" ) // AccessTokenScopeBitmap represents a bitmap of access token scopes. @@ -115,9 +115,9 @@ const ( // refactoring the whole implementation in this file (and only this file) is needed. ) -// AllAccessTokenScopes contains all access token scopes. +// allAccessTokenScopes contains all access token scopes. // The order is important: parent scope must precedes child scopes. -var allAccessTokenScopes = []string{ +var allAccessTokenScopes = []AccessTokenScope{ AccessTokenScopeRepo, AccessTokenScopeRepoStatus, AccessTokenScopePublicRepo, AccessTokenScopeAdminOrg, AccessTokenScopeWriteOrg, AccessTokenScopeReadOrg, AccessTokenScopeAdminPublicKey, AccessTokenScopeWritePublicKey, AccessTokenScopeReadPublicKey, @@ -132,8 +132,8 @@ var allAccessTokenScopes = []string{ AccessTokenScopeSudo, } -// AllAccessTokenScopeBits contains all access token scopes. -var allAccessTokenScopeBits = map[string]AccessTokenScopeBitmap{ +// allAccessTokenScopeBits contains all access token scopes. +var allAccessTokenScopeBits = map[AccessTokenScope]AccessTokenScopeBitmap{ AccessTokenScopeRepo: AccessTokenScopeRepoBits, AccessTokenScopeRepoStatus: AccessTokenScopeRepoStatusBits, AccessTokenScopePublicRepo: AccessTokenScopePublicRepoBits, @@ -171,7 +171,8 @@ func (s AccessTokenScope) Parse() (AccessTokenScopeBitmap, error) { list := strings.Split(string(s), ",") var bitmap AccessTokenScopeBitmap - for _, singleScope := range list { + for _, v := range list { + singleScope := AccessTokenScope(v) if singleScope == "" { continue } @@ -200,7 +201,7 @@ func (s AccessTokenScope) Normalize() (AccessTokenScope, error) { } // HasScope returns true if the string has the given scope -func (s AccessTokenScope) HasScope(scope string) (bool, error) { +func (s AccessTokenScope) HasScope(scope AccessTokenScope) (bool, error) { bitmap, err := s.Parse() if err != nil { return false, err @@ -210,7 +211,7 @@ func (s AccessTokenScope) HasScope(scope string) (bool, error) { } // HasScope returns true if the string has the given scope -func (bitmap AccessTokenScopeBitmap) HasScope(scope string) (bool, error) { +func (bitmap AccessTokenScopeBitmap) HasScope(scope AccessTokenScope) (bool, error) { expectedBits, ok := allAccessTokenScopeBits[scope] if !ok { return false, fmt.Errorf("invalid access token scope: %s", scope) @@ -227,7 +228,8 @@ func (bitmap AccessTokenScopeBitmap) ToScope() AccessTokenScope { // if the reconstructed bitmap doesn't change, then the scope is already included var reconstruct AccessTokenScopeBitmap - for _, singleScope := range allAccessTokenScopes { + for _, v := range allAccessTokenScopes { + singleScope := AccessTokenScope(v) // no need for error checking here, since we know the scope is valid if ok, _ := bitmap.HasScope(singleScope); ok { current := reconstruct | allAccessTokenScopeBits[singleScope] @@ -236,7 +238,7 @@ func (bitmap AccessTokenScopeBitmap) ToScope() AccessTokenScope { } reconstruct = current - scopes = append(scopes, singleScope) + scopes = append(scopes, string(singleScope)) } } diff --git a/models/auth/token_scope_test.go b/models/auth/token_scope_test.go index dd53716b516e2..1d7f4794a477f 100644 --- a/models/auth/token_scope_test.go +++ b/models/auth/token_scope_test.go @@ -56,7 +56,7 @@ func TestAccessTokenScope_Normalize(t *testing.T) { func TestAccessTokenScope_HasScope(t *testing.T) { tests := []struct { in AccessTokenScope - scope string + scope AccessTokenScope out bool err error }{ From bce707f7bc1b285067c57d763954adb521a04fa5 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Mon, 16 Jan 2023 13:46:37 -0500 Subject: [PATCH 111/118] Fix backend lints --- models/auth/token_scope.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/models/auth/token_scope.go b/models/auth/token_scope.go index badd8ed36957e..09f9f7c1c4278 100644 --- a/models/auth/token_scope.go +++ b/models/auth/token_scope.go @@ -181,11 +181,11 @@ func (s AccessTokenScope) Parse() (AccessTokenScopeBitmap, error) { continue } - if bits, ok := allAccessTokenScopeBits[singleScope]; !ok { + bits, ok := allAccessTokenScopeBits[singleScope] + if !ok { return 0, fmt.Errorf("invalid access token scope: %s", singleScope) - } else { - bitmap |= bits } + bitmap |= bits } return bitmap, nil } From d0a27a68bbee864de0b56e10c9b17f5705712934 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Mon, 16 Jan 2023 13:48:35 -0500 Subject: [PATCH 112/118] Update types for bitmap constants as well --- models/auth/token_scope.go | 62 +++++++++++++++++++------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/models/auth/token_scope.go b/models/auth/token_scope.go index 09f9f7c1c4278..886fe29abf560 100644 --- a/models/auth/token_scope.go +++ b/models/auth/token_scope.go @@ -63,52 +63,52 @@ type AccessTokenScopeBitmap uint64 // Bitmap of each scope, including the child scopes. const ( // AccessTokenScopeAllBits is the bitmap of all access token scopes. - AccessTokenScopeAllBits = AccessTokenScopeRepoBits | + AccessTokenScopeAllBits AccessTokenScopeBitmap = AccessTokenScopeRepoBits | AccessTokenScopeAdminOrgBits | AccessTokenScopeAdminPublicKeyBits | AccessTokenScopeAdminOrgHookBits | AccessTokenScopeNotificationBits | AccessTokenScopeUserBits | AccessTokenScopeDeleteRepoBits | AccessTokenScopePackageBits | AccessTokenScopeAdminGPGKeyBits | AccessTokenScopeAdminApplicationBits - AccessTokenScopeRepoBits = 1< 64 scopes, From 64d52513a766f0bb23d9585226caedabd93b6737 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Mon, 16 Jan 2023 13:58:41 -0500 Subject: [PATCH 113/118] Fix typing issue in integration tests --- tests/integration/api_helper_for_declarative_test.go | 3 ++- tests/integration/integration_test.go | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/integration/api_helper_for_declarative_test.go b/tests/integration/api_helper_for_declarative_test.go index 7b9c7e136a319..3524ce9834add 100644 --- a/tests/integration/api_helper_for_declarative_test.go +++ b/tests/integration/api_helper_for_declarative_test.go @@ -13,6 +13,7 @@ import ( "testing" "time" + "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/perm" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/json" @@ -31,7 +32,7 @@ type APITestContext struct { ExpectedCode int } -func NewAPITestContext(t *testing.T, username, reponame string, scope ...string) APITestContext { +func NewAPITestContext(t *testing.T, username, reponame string, scope ...auth.AccessTokenScope) APITestContext { session := loginUser(t, username) token := getTokenForLoggedInUser(t, session, scope...) return APITestContext{ diff --git a/tests/integration/integration_test.go b/tests/integration/integration_test.go index 38e4f43a94c68..fbb6322785afd 100644 --- a/tests/integration/integration_test.go +++ b/tests/integration/integration_test.go @@ -21,6 +21,7 @@ import ( "testing" "time" + "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/json" @@ -217,7 +218,7 @@ func emptyTestSession(t testing.TB) *TestSession { return &TestSession{jar: jar} } -func getUserToken(t testing.TB, userName string, scope ...string) string { +func getUserToken(t testing.TB, userName string, scope ...auth.AccessTokenScope) string { return getTokenForLoggedInUser(t, loginUser(t, userName), scope...) } @@ -259,7 +260,7 @@ var tokenCounter int64 // getTokenForLoggedInUser returns a token for a logged in user. // The scope is an optional list of snake_case strings like the frontend form fields, // but without the "scope_" prefix. -func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...string) string { +func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...auth.AccessTokenScope) string { t.Helper() var token string req := NewRequest(t, "GET", "/user/settings/applications") @@ -281,7 +282,7 @@ func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...strin urlValues.Add("_csrf", csrf) urlValues.Add("name", fmt.Sprintf("api-testing-token-%d", atomic.AddInt64(&tokenCounter, 1))) for _, scope := range scopes { - urlValues.Add("scope", scope) + urlValues.Add("scope", string(scope)) } req = NewRequestWithURLValues(t, "POST", "/user/settings/applications", urlValues) resp = session.MakeRequest(t, req, http.StatusSeeOther) From 32fa0aa2230d185380fbe16259f0c1fc9beb357f Mon Sep 17 00:00:00 2001 From: harryzcy Date: Mon, 16 Jan 2023 14:28:16 -0500 Subject: [PATCH 114/118] Fix type in router APIs --- routers/api/v1/api.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 2aa5330dda29d..cd08aae4145c4 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -207,7 +207,7 @@ func reqPackageAccess(accessMode perm.AccessMode) func(ctx *context.APIContext) } // Contexter middleware already checks token for user sign in process. -func reqToken(requiredScope string) func(ctx *context.APIContext) { +func reqToken(requiredScope auth_model.AccessTokenScope) func(ctx *context.APIContext) { return func(ctx *context.APIContext) { // If OAuth2 token is present if _, ok := ctx.Data["ApiTokenScope"]; ctx.Data["IsApiToken"] == true && ok { From 0d9160b74414b1a8f623840abf7252feb050e6b9 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Mon, 16 Jan 2023 14:33:13 -0500 Subject: [PATCH 115/118] Avoid unnecessary type conversion --- models/auth/token_scope.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/models/auth/token_scope.go b/models/auth/token_scope.go index 886fe29abf560..c61c306496b49 100644 --- a/models/auth/token_scope.go +++ b/models/auth/token_scope.go @@ -62,7 +62,7 @@ type AccessTokenScopeBitmap uint64 // Bitmap of each scope, including the child scopes. const ( - // AccessTokenScopeAllBits is the bitmap of all access token scopes. + // AccessTokenScopeAllBits is the bitmap of all access token scopes, except `sudo`. AccessTokenScopeAllBits AccessTokenScopeBitmap = AccessTokenScopeRepoBits | AccessTokenScopeAdminOrgBits | AccessTokenScopeAdminPublicKeyBits | AccessTokenScopeAdminOrgHookBits | AccessTokenScopeNotificationBits | AccessTokenScopeUserBits | AccessTokenScopeDeleteRepoBits | @@ -228,8 +228,7 @@ func (bitmap AccessTokenScopeBitmap) ToScope() AccessTokenScope { // if the reconstructed bitmap doesn't change, then the scope is already included var reconstruct AccessTokenScopeBitmap - for _, v := range allAccessTokenScopes { - singleScope := AccessTokenScope(v) + for _, singleScope := range allAccessTokenScopes { // no need for error checking here, since we know the scope is valid if ok, _ := bitmap.HasScope(singleScope); ok { current := reconstruct | allAccessTokenScopeBits[singleScope] From 7d7344f0e3b9617beb27c522d08dfd7c88567d41 Mon Sep 17 00:00:00 2001 From: harryzcy Date: Mon, 16 Jan 2023 14:37:17 -0500 Subject: [PATCH 116/118] More unnecessary conversion --- services/auth/oauth2.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/auth/oauth2.go b/services/auth/oauth2.go index f1ee40e4f377c..1be78b85c5efa 100644 --- a/services/auth/oauth2.go +++ b/services/auth/oauth2.go @@ -88,7 +88,7 @@ func (o *OAuth2) userIDFromToken(req *http.Request, store DataStore) int64 { uid := CheckOAuthAccessToken(tokenSHA) if uid != 0 { store.GetData()["IsApiToken"] = true - store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScope(auth_model.AccessTokenScopeAll) // fallback to all + store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScopeAll // fallback to all } return uid } From 6f2974a2cfad88d05efc7ac1154d692006e59e9e Mon Sep 17 00:00:00 2001 From: harryzcy Date: Mon, 16 Jan 2023 15:54:30 -0500 Subject: [PATCH 117/118] Include sudo scope for old tokens during migration --- models/migrations/v1_19/v238.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/models/migrations/v1_19/v238.go b/models/migrations/v1_19/v238.go index 633800f8c7317..62e68c2159963 100644 --- a/models/migrations/v1_19/v238.go +++ b/models/migrations/v1_19/v238.go @@ -18,6 +18,7 @@ func AddScopeForAccessTokens(x *xorm.Engine) error { return err } - _, err := x.Exec("UPDATE access_token SET scope = ? WHERE scope IS NULL OR scope = ''", auth_models.AccessTokenScopeAll) + // all previous tokens have `all` and `sudo` scopes + _, err := x.Exec("UPDATE access_token SET scope = ? WHERE scope IS NULL OR scope = ''", auth_models.AccessTokenScopeAll+","+auth_models.AccessTokenScopeSudo) return err } From 1f596e7e1861dc59dfe521bfdd4b945759eca2be Mon Sep 17 00:00:00 2001 From: Chongyi Zheng Date: Mon, 16 Jan 2023 23:23:31 -0500 Subject: [PATCH 118/118] Use string type in migration Co-authored-by: Jason Song --- models/migrations/v1_19/v239.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/models/migrations/v1_19/v239.go b/models/migrations/v1_19/v239.go index 62e68c2159963..10076f2401696 100644 --- a/models/migrations/v1_19/v239.go +++ b/models/migrations/v1_19/v239.go @@ -4,14 +4,12 @@ package v1_19 //nolint import ( - auth_models "code.gitea.io/gitea/models/auth" - "xorm.io/xorm" ) func AddScopeForAccessTokens(x *xorm.Engine) error { type AccessToken struct { - Scope auth_models.AccessTokenScope + Scope string } if err := x.Sync(new(AccessToken)); err != nil { @@ -19,6 +17,6 @@ func AddScopeForAccessTokens(x *xorm.Engine) error { } // all previous tokens have `all` and `sudo` scopes - _, err := x.Exec("UPDATE access_token SET scope = ? WHERE scope IS NULL OR scope = ''", auth_models.AccessTokenScopeAll+","+auth_models.AccessTokenScopeSudo) + _, err := x.Exec("UPDATE access_token SET scope = ? WHERE scope IS NULL OR scope = ''", "all,sudo") return err }