fix: enforce public-only token scope on more routes (#39690) (#39853)

Partial backport of https://github.com/go-gitea/gitea/pull/39690 with
only its public-only token checks, without the refactor.

1. Admin, org owner and repo or org creation APIs reject public-only
tokens.
1. Profile and org pages hide private repos and limited owners from
public-only tokens.
1. Heatmap API, OIDC userinfo and OCI blob mounts respect public-only
tokens.

Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: bircni <bircni@icloud.com>
This commit is contained in:
Giteabot
2026-10-21 05:58:07 +00:00
committed by GitHub
co-authored by silverwind wxiaoguang bircni
parent 4b743d2e8c
commit 01db50f0bf
14 changed files with 84 additions and 26 deletions
+5 -2
View File
@@ -122,8 +122,8 @@ func GetTotalUnreferencedBlobSize(ctx context.Context) (int64, error) {
}
// IsBlobAccessibleForUser tests if the user has access to the blob
func IsBlobAccessibleForUser(ctx context.Context, blobID int64, user *user_model.User) (bool, error) {
if user.IsAdmin {
func IsBlobAccessibleForUser(ctx context.Context, blobID int64, user *user_model.User, publicOnly bool) (bool, error) {
if user.IsAdmin && !publicOnly {
return true, nil
}
ownerVisibilities := []structs.VisibleType{structs.VisibleTypePublic}
@@ -153,6 +153,9 @@ func IsBlobAccessibleForUser(ctx context.Context, blobID int64, user *user_model
Or(builder.Eq{"`user`.type": user_model.UserTypeOrganization}.
And(builder.Lte{strconv.Itoa(int(perm.AccessModeRead)): maxTeamAuthorize}.Or(builder.Lte{strconv.Itoa(int(perm.AccessModeRead)): maxTeamUnitAccessMode}))),
)
if publicOnly {
cond = cond.And(builder.Eq{"`user`.visibility": structs.VisibleTypePublic})
}
return db.GetEngine(ctx).
Table("package_blob").
+6 -2
View File
@@ -64,11 +64,15 @@ func TestIsBlobAccessibleForRestrictedUser(t *testing.T) {
_, err = TryInsertFile(t.Context(), &PackageFile{VersionID: version.ID, BlobID: blob.ID, Name: "blob", LowerName: "blob"})
require.NoError(t, err)
accessible, err := IsBlobAccessibleForUser(t.Context(), blob.ID, unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}))
accessible, err := IsBlobAccessibleForUser(t.Context(), blob.ID, unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}), false)
require.NoError(t, err)
assert.True(t, accessible)
accessible, err = IsBlobAccessibleForUser(t.Context(), blob.ID, unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 29}))
accessible, err = IsBlobAccessibleForUser(t.Context(), blob.ID, unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 29}), false)
require.NoError(t, err)
assert.False(t, accessible)
accessible, err = IsBlobAccessibleForUser(t.Context(), blob.ID, unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}), true)
require.NoError(t, err)
assert.False(t, accessible)
}
+1 -1
View File
@@ -244,7 +244,7 @@ func PostBlobsUploads(ctx *context.Context) {
Digest: mount,
})
if blob != nil {
accessible, err := packages_model.IsBlobAccessibleForUser(ctx, blob.Blob.ID, ctx.Doer)
accessible, err := packages_model.IsBlobAccessibleForUser(ctx, blob.Blob.ID, ctx.Doer, context.TokenIsPublicOnly(ctx))
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
+8 -4
View File
@@ -492,6 +492,9 @@ func reqAnyRepoReader() func(ctx *context.APIContext) {
// reqOrgOwnership user should be an organization owner, or a site admin
func reqOrgOwnership() func(ctx *context.APIContext) {
return func(ctx *context.APIContext) {
if rejectPublicOnly()(ctx); ctx.Written() { // org ownership reaches the org's private repos (hooks, teams, secrets)
return
}
if ctx.IsUserSiteAdmin() {
return
}
@@ -1283,6 +1286,7 @@ func Routes() *web.Router {
// FIXME: we need org in context
tokenRequiresScopes(auth_model.AccessTokenScopeCategoryOrganization, auth_model.AccessTokenScopeCategoryRepository),
reqToken(),
rejectPublicOnly(),
bind(api.CreateRepoOption{}),
repo.CreateOrgRepoDeprecated)
@@ -1303,7 +1307,7 @@ func Routes() *web.Router {
m.Combo("").Get(reqAnyRepoReader(), repo.Get).
Delete(reqToken(), reqRepoDangerZone(), repo.Delete).
Patch(reqToken(), reqAdmin(), bind(api.EditRepoOption{}), repo.Edit)
m.Post("/generate", reqToken(), reqRepoReader(unit.TypeCode), bind(api.GenerateRepoOption{}), repo.Generate)
m.Post("/generate", reqToken(), rejectPublicOnly(), reqRepoReader(unit.TypeCode), bind(api.GenerateRepoOption{}), repo.Generate)
m.Group("/transfer", func() {
m.Post("", reqRepoDangerZone(), bind(api.TransferRepoOption{}), repo.Transfer)
m.Post("/accept", repo.AcceptTransfer)
@@ -1777,7 +1781,7 @@ func Routes() *web.Router {
m.Get("", reqToken(), org.ListUserOrgs)
m.Get("/{org}/permissions", reqToken(), org.GetUserOrgsPermissions)
}, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryUser, auth_model.AccessTokenScopeCategoryOrganization), context.UserAssignmentAPI(), checkTokenPublicOnly(), individualPermsChecker)
m.Post("/orgs", tokenRequiresScopes(auth_model.AccessTokenScopeCategoryOrganization), reqToken(), bind(api.CreateOrgOption{}), org.Create)
m.Post("/orgs", tokenRequiresScopes(auth_model.AccessTokenScopeCategoryOrganization), reqToken(), rejectPublicOnly(), bind(api.CreateOrgOption{}), org.Create)
m.Get("/orgs", tokenRequiresScopes(auth_model.AccessTokenScopeCategoryOrganization), org.GetAll)
m.Group("/orgs/{org}", func() {
m.Combo("").Get(org.Get).
@@ -1785,7 +1789,7 @@ func Routes() *web.Router {
Delete(reqToken(), reqOrgOwnership(), org.Delete)
m.Post("/rename", reqToken(), reqOrgOwnership(), bind(api.RenameOrgOption{}), org.Rename)
m.Combo("/repos").Get(user.ListOrgRepos).
Post(reqToken(), tokenRequiresScopes(auth_model.AccessTokenScopeCategoryRepository), bind(api.CreateRepoOption{}), repo.CreateOrgRepo).
Post(reqToken(), tokenRequiresScopes(auth_model.AccessTokenScopeCategoryRepository), rejectPublicOnly(), bind(api.CreateRepoOption{}), repo.CreateOrgRepo).
Delete(reqToken(), reqOrgOwnership(), tokenRequiresScopes(auth_model.AccessTokenScopeCategoryRepository), org.DeleteOrgRepos)
m.Group("/members", func() {
m.Get("", reqToken(), org.ListMembers)
@@ -1921,7 +1925,7 @@ func Routes() *web.Router {
m.Get("/runs", admin.ListWorkflowRuns)
m.Get("/jobs", admin.ListWorkflowJobs)
})
}, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryAdmin), reqToken(), reqSiteAdmin())
}, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryAdmin), reqToken(), reqSiteAdmin(), rejectPublicOnly())
m.Group("/topics", func() {
m.Get("/search", repo.TopicSearch)
+2 -1
View File
@@ -9,6 +9,7 @@ import (
activities_model "gitea.dev/models/activities"
user_model "gitea.dev/models/user"
"gitea.dev/modules/util"
"gitea.dev/routers/api/v1/utils"
"gitea.dev/services/context"
"gitea.dev/services/convert"
@@ -154,7 +155,7 @@ func GetUserHeatmapData(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
heatmap, err := activities_model.GetUserHeatmapDataByUser(ctx, ctx.ContextUser, ctx.Doer)
heatmap, err := activities_model.GetUserHeatmapDataByUser(ctx, ctx.ContextUser, util.Iif(ctx.PublicOnly, nil, ctx.Doer))
if err != nil {
ctx.APIErrorInternal(err)
return
+1 -10
View File
@@ -121,16 +121,7 @@ func InfoOAuth(ctx *context.Context) {
Picture: ctx.Doer.AvatarLink(ctx),
}
var accessTokenScope auth.AccessTokenScope
if auHead := ctx.Req.Header.Get("Authorization"); auHead != "" {
if parsed, ok := httpauth.ParseAuthorizationHeader(auHead); ok && parsed.BearerToken != nil {
accessTokenScope, _, _ = auth_service.GetOAuthAccessTokenScopeAndUserID(ctx, parsed.BearerToken.Token)
}
}
// since version 1.22 does not verify if groups should be public-only,
// onlyPublicGroups will be set only if 'public-only' is included in a valid scope
onlyPublicGroups, _ := accessTokenScope.PublicOnly()
onlyPublicGroups, _ := tokenScope.PublicOnly()
groups, err := oauth2_provider.GetOAuthGroupsForUser(ctx, ctx.Doer, onlyPublicGroups)
if err != nil {
ctx.ServerError("Oauth groups for user", err)
+1 -1
View File
@@ -148,7 +148,7 @@ func orgHome(ctx *context.Context, viewRepositories bool) {
Keyword: keyword,
OwnerID: org.ID,
OrderBy: orderBy,
Private: ctx.IsSigned,
Private: ctx.IsSigned && !context.TokenIsPublicOnly(ctx),
Actor: ctx.Doer,
Language: language,
IncludeDescription: setting.UI.SearchRepoDescription,
+1 -1
View File
@@ -166,7 +166,7 @@ func loadHeaderCount(ctx *context.Context) error {
repoCount, err := repo_model.CountRepository(ctx, repo_model.SearchRepoOptions{
Actor: ctx.Doer,
OwnerID: ctx.ContextUser.ID,
Private: ctx.IsSigned,
Private: ctx.IsSigned && !context.TokenIsPublicOnly(ctx),
Collaborate: optional.Some(false),
IncludeDescription: setting.UI.SearchRepoDescription,
})
+4 -1
View File
@@ -714,7 +714,7 @@ func UsernameSubRoute(ctx *context.Context) {
}
// check view permissions
if !user_model.IsUserVisibleToViewer(ctx, ctx.ContextUser, ctx.Doer) {
if !user_model.IsUserVisibleToViewer(ctx, ctx.ContextUser, ctx.Doer) || (context.TokenIsPublicOnly(ctx) && !ctx.ContextUser.Visibility.IsPublic()) {
ctx.NotFound(fmt.Errorf("%s", ctx.ContextUser.Name))
return false
}
@@ -743,6 +743,9 @@ func UsernameSubRoute(ctx *context.Context) {
}
default:
context.UserAssignmentWeb()(ctx)
if !ctx.Written() && context.TokenIsPublicOnly(ctx) && !ctx.ContextUser.Visibility.IsPublic() {
ctx.NotFound(nil)
}
if !ctx.Written() {
ctx.Data["EnableFeed"] = setting.Other.EnableFeed
OwnerProfile(ctx)
+3 -3
View File
@@ -203,7 +203,7 @@ func prepareUserProfileTabData(ctx *context.Context, profileDbRepo *repo_model.R
Actor: ctx.Doer,
Keyword: keyword,
OrderBy: orderBy,
Private: ctx.IsSigned,
Private: ctx.IsSigned && !context.TokenIsPublicOnly(ctx),
StarredByID: ctx.ContextUser.ID,
Collaborate: optional.Some(false),
TopicOnly: topicOnly,
@@ -230,7 +230,7 @@ func prepareUserProfileTabData(ctx *context.Context, profileDbRepo *repo_model.R
Actor: ctx.Doer,
Keyword: keyword,
OrderBy: orderBy,
Private: ctx.IsSigned,
Private: ctx.IsSigned && !context.TokenIsPublicOnly(ctx),
WatchedByID: ctx.ContextUser.ID,
Collaborate: optional.Some(false),
TopicOnly: topicOnly,
@@ -290,7 +290,7 @@ func prepareUserProfileTabData(ctx *context.Context, profileDbRepo *repo_model.R
Keyword: keyword,
OwnerID: ctx.ContextUser.ID,
OrderBy: orderBy,
Private: ctx.IsSigned,
Private: ctx.IsSigned && !context.TokenIsPublicOnly(ctx),
Collaborate: optional.Some(false),
TopicOnly: topicOnly,
Language: language,
+18
View File
@@ -117,6 +117,24 @@ func TestAPIOrgPermissionsPublicOnly(t *testing.T) {
MakeRequest(t, req, http.StatusNotFound)
}
func TestAPIPublicOnlyRejectedRoutes(t *testing.T) {
defer tests.PrepareTestEnv(t)()
token := getUserToken(t, "user1", auth_model.AccessTokenScopeWriteAdmin, auth_model.AccessTokenScopeWriteOrganization,
auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopePublicOnly)
for _, route := range []struct{ method, url string }{
{"GET", "/api/v1/admin/orgs"},
{"POST", "/api/v1/orgs"},
{"POST", "/api/v1/org/org3/repos"},
{"POST", "/api/v1/orgs/org3/repos"},
{"DELETE", "/api/v1/orgs/org3/repos"},
{"POST", "/api/v1/orgs/org3/actions/runners/registration-token"},
{"POST", "/api/v1/repos/user2/repo1/generate"},
} {
MakeRequest(t, NewRequest(t, route.method, route.url).AddTokenAuth(token), http.StatusForbidden)
}
}
func TestAPITeamReposPublicOnly(t *testing.T) {
defer tests.PrepareTestEnv(t)()
@@ -35,4 +35,8 @@ func TestUserHeatmap(t *testing.T) {
dummyheatmap = append(dummyheatmap, &activities_model.UserHeatmapData{Timestamp: 1603227600, Contributions: 1})
assert.Equal(t, dummyheatmap, heatmap)
publicOnlyToken := getUserToken(t, normalUsername, auth_model.AccessTokenScopeReadUser, auth_model.AccessTokenScopePublicOnly)
req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/heatmap", normalUsername)).AddTokenAuth(publicOnlyToken)
assert.Empty(t, DecodeJSON(t, MakeRequest(t, req, http.StatusOK), []*activities_model.UserHeatmapData{}))
}
+24
View File
@@ -107,3 +107,27 @@ func TestProfileActivityPublicOnlyToken(t *testing.T) {
respPublicOnly := MakeRequest(t, reqPublicOnly, http.StatusOK)
assert.NotContains(t, respPublicOnly.Body.String(), privateMarker)
}
func TestProfileReposAndLimitedOwnersPublicOnlyToken(t *testing.T) {
defer tests.PrepareTestEnv(t)()
fullToken := getUserToken(t, "user2", auth_model.AccessTokenScopeReadUser)
publicOnlyToken := getUserToken(t, "user2", auth_model.AccessTokenScopeReadUser, auth_model.AccessTokenScopePublicOnly)
for link, privateRepoLink := range map[string]string{
"/user2?tab=repositories&q=repo2": `"/user2/repo2"`,
"/user2?tab=stars": `"/user2/repo2"`,
"/org3": `"/org3/repo3"`,
} {
reqFull := NewRequest(t, "GET", link)
reqFull.SetBasicAuth("user2", fullToken)
assert.Contains(t, MakeRequest(t, reqFull, http.StatusOK).Body.String(), privateRepoLink, link)
reqPublicOnly := NewRequest(t, "GET", link)
reqPublicOnly.SetBasicAuth("user2", publicOnlyToken)
assert.NotContains(t, MakeRequest(t, reqPublicOnly, http.StatusOK).Body.String(), privateRepoLink, link)
}
for _, limitedLink := range []string{"/user33", "/user33.rss", "/limited_org"} {
assertBasicAuthStatus(t, limitedLink, fullToken, http.StatusOK)
assertBasicAuthStatus(t, limitedLink, publicOnlyToken, http.StatusNotFound)
}
}
+6
View File
@@ -1123,6 +1123,12 @@ func testOAuthGrantScopesClaimPublicOnlyGroups(t *testing.T) {
require.NoError(t, json.Unmarshal(userinfoResp.Body.Bytes(), userinfoParsed))
assert.Contains(t, userinfoParsed.Email, "user2@example.com")
defer test.MockVariableValue(&setting.DisableQueryAuthToken, false)()
queryUserinfoResp := MakeRequest(t, NewRequest(t, "GET", "/login/oauth/userinfo?access_token="+parsed.AccessToken), http.StatusOK)
queryUserinfoParsed := new(userinfoResponse)
require.NoError(t, json.Unmarshal(queryUserinfoResp.Body.Bytes(), queryUserinfoParsed))
assert.Equal(t, userinfoParsed.Groups, queryUserinfoParsed.Groups)
// test both id_token and call to /login/oauth/userinfo
for _, publicGroup := range []string{
"org17",