From 01db50f0bf9fc0607337b1cf2e1970b3289097e3 Mon Sep 17 00:00:00 2001 From: Giteabot Date: Tue, 20 Oct 2026 22:58:07 -0700 Subject: [PATCH] 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 Co-authored-by: wxiaoguang Co-authored-by: bircni --- models/packages/package_blob.go | 7 ++++-- models/packages/package_blob_test.go | 8 +++++-- routers/api/packages/container/container.go | 2 +- routers/api/v1/api.go | 12 +++++++---- routers/api/v1/user/user.go | 3 ++- routers/web/auth/oauth2_provider.go | 11 +--------- routers/web/org/home.go | 2 +- routers/web/shared/user/header.go | 2 +- routers/web/user/home.go | 5 ++++- routers/web/user/profile.go | 6 +++--- tests/integration/api_public_only_test.go | 18 ++++++++++++++++ tests/integration/api_user_heatmap_test.go | 4 ++++ tests/integration/feed_user_test.go | 24 +++++++++++++++++++++ tests/integration/oauth_test.go | 6 ++++++ 14 files changed, 84 insertions(+), 26 deletions(-) diff --git a/models/packages/package_blob.go b/models/packages/package_blob.go index e3db4527609..07b0117f5e0 100644 --- a/models/packages/package_blob.go +++ b/models/packages/package_blob.go @@ -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"). diff --git a/models/packages/package_blob_test.go b/models/packages/package_blob_test.go index 55ae037c7e4..fb364bd41c1 100644 --- a/models/packages/package_blob_test.go +++ b/models/packages/package_blob_test.go @@ -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) } diff --git a/routers/api/packages/container/container.go b/routers/api/packages/container/container.go index 1e48375e504..ea527a9f12f 100644 --- a/routers/api/packages/container/container.go +++ b/routers/api/packages/container/container.go @@ -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 diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index aba8f5f33a2..0f558547f53 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -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) diff --git a/routers/api/v1/user/user.go b/routers/api/v1/user/user.go index 22bd2b9e494..5db314713d6 100644 --- a/routers/api/v1/user/user.go +++ b/routers/api/v1/user/user.go @@ -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 diff --git a/routers/web/auth/oauth2_provider.go b/routers/web/auth/oauth2_provider.go index 6a9b0b973cd..5810924e5ac 100644 --- a/routers/web/auth/oauth2_provider.go +++ b/routers/web/auth/oauth2_provider.go @@ -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) diff --git a/routers/web/org/home.go b/routers/web/org/home.go index dfb7da079fd..6469484cdb0 100644 --- a/routers/web/org/home.go +++ b/routers/web/org/home.go @@ -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, diff --git a/routers/web/shared/user/header.go b/routers/web/shared/user/header.go index 0114dc8ea7a..8393aed6370 100644 --- a/routers/web/shared/user/header.go +++ b/routers/web/shared/user/header.go @@ -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, }) diff --git a/routers/web/user/home.go b/routers/web/user/home.go index addb9caec9a..c401ed8cb1e 100644 --- a/routers/web/user/home.go +++ b/routers/web/user/home.go @@ -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) diff --git a/routers/web/user/profile.go b/routers/web/user/profile.go index a342e3b1631..362f64a91cc 100644 --- a/routers/web/user/profile.go +++ b/routers/web/user/profile.go @@ -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, diff --git a/tests/integration/api_public_only_test.go b/tests/integration/api_public_only_test.go index c6ff027875a..90285cd52ae 100644 --- a/tests/integration/api_public_only_test.go +++ b/tests/integration/api_public_only_test.go @@ -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)() diff --git a/tests/integration/api_user_heatmap_test.go b/tests/integration/api_user_heatmap_test.go index ebf6548a63f..c383b974372 100644 --- a/tests/integration/api_user_heatmap_test.go +++ b/tests/integration/api_user_heatmap_test.go @@ -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{})) } diff --git a/tests/integration/feed_user_test.go b/tests/integration/feed_user_test.go index 077cab79c0d..48a88c4ae06 100644 --- a/tests/integration/feed_user_test.go +++ b/tests/integration/feed_user_test.go @@ -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) + } +} diff --git a/tests/integration/oauth_test.go b/tests/integration/oauth_test.go index 7ce463b361b..a28a9f6696e 100644 --- a/tests/integration/oauth_test.go +++ b/tests/integration/oauth_test.go @@ -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",