mirror of
https://codeberg.org/forgejo/forgejo.git
synced 2026-03-25 15:43:04 -04:00
This PR is part of a series (#11311). If the user authenticating to an API call is a Forgejo site administrator, or a Forgejo repo administrator, a wide variety of permission and ownership checks in the API are either bypassed, or are bypassable. If a user has created an access token with restricted resources, I understand the intent of the user is to create a token which has a layer of risk reduction in the event that the token is lost/leaked to an attacker. For this reason, it makes sense to me that restricted scope access tokens shouldn't inherit the owner's administrator access. My intent is that repo-specific access tokens [will only be able to access specific authorization scopes](https://codeberg.org/forgejo/design/issues/50#issuecomment-11093951), probably: `repository:read`, `repository:write`, `issue:read`, `issue:write`, (`organization:read` / `user:read` maybe). This means that *most* admin access is not intended to be affected by this because repo-specific access tokens won't have, for example, `admin:write` scope. However, administrative access still grants elevated permissions in some areas that are relevant to these scopes, and need to be restricted: - The `?sudo=otheruser` query parameter allows site administrators to impersonate other users in the API. - Repository management rules are different for a site administrator, allowing them to create repos for another user, create repos in another organization, migrate a repository to an arbitrary owner, and transfer a repository to a prviate organization. - Administrators have access to extra data through some APIs which would be in scope: the detailed configuration of branch protection rules, the some details of repository deploy keys (which repo, and which scope -- seems odd), (user:read -- user SSH keys, activity feeds of private users, user profiles of private users, user webhook configurations). - Pull request reviews have additional perms for repo administrators, including the ability to dismiss PR reviews, delete PR reviews, and view draft PR reviews. - Repo admins and site admins can comment on locked issues, and related to comments can edit or delete other user's comments and attachments. - Repo admins can manage and view logged time on behalf of other users. A handful of these permissions may make sense for repo-specific access tokens, but most of them clearly exceed the risk that would be expected from creating a limited scope access token. I'd generally prefer to take a restrictive approach, and we can relax it if real-world use-cases come in -- users will have a workaround of creating an access token without repo-specific restrictions if they are blocked from needed access. **Breaking:** The administration restrictions introduced in this PR affect both repo-specific access tokens, and existing public-only access tokens. ## Checklist The [contributor guide](https://forgejo.org/docs/next/contributor/) contains information that will be helpful to first time contributors. There also are a few [conditions for merging Pull Requests in Forgejo repositories](https://codeberg.org/forgejo/governance/src/branch/main/PullRequestsAgreement.md). You are also welcome to join the [Forgejo development chatroom](https://matrix.to/#/#forgejo-development:matrix.org). ### Tests for Go changes (can be removed for JavaScript changes) - I added test coverage for Go changes... - [x] in their respective `*_test.go` for unit tests. - [x] in the `tests/integration` directory if it involves interactions with a live Forgejo server. - I ran... - [x] `make pr-go` before pushing ### Documentation - [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change. - [x] I did not document these changes and I do not expect someone else to do it. ### Release notes - [x] This change will be noticed by a Forgejo user or admin (feature, bug fix, performance, etc.). I suggest to include a release note for this change. - Although repo-specific access tokens are not yet exposed to end users, the breaking changes to public-only tokens will be visible to users and require release notes. - [ ] This change is not visible to a Forgejo user or admin (refactor, dependency upgrade, etc.). I think there is no need to add a release note for this change. Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/11468 Reviewed-by: Andreas Ahlenstorf <aahlenst@noreply.codeberg.org> Co-authored-by: Mathieu Fenniak <mathieu@fenniak.net> Co-committed-by: Mathieu Fenniak <mathieu@fenniak.net>
265 lines
8.6 KiB
Go
265 lines
8.6 KiB
Go
// Copyright 2026 The Forgejo Authors. All rights reserved.
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
package shared
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
auth_model "forgejo.org/models/auth"
|
|
"forgejo.org/models/db"
|
|
"forgejo.org/models/unittest"
|
|
"forgejo.org/modules/json"
|
|
"forgejo.org/modules/jwtx"
|
|
"forgejo.org/modules/test"
|
|
"forgejo.org/modules/web"
|
|
"forgejo.org/routers/common"
|
|
"forgejo.org/services/auth/source/oauth2"
|
|
"forgejo.org/services/authz"
|
|
"forgejo.org/services/context"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestReducer(t *testing.T) {
|
|
defer unittest.OverrideFixtures("routers/api/shared/TestReducer")()
|
|
require.NoError(t, unittest.PrepareTestDatabase())
|
|
|
|
makeRecorder := func() *httptest.ResponseRecorder {
|
|
buff := bytes.NewBufferString("")
|
|
recorder := httptest.NewRecorder()
|
|
recorder.Body = buff
|
|
return recorder
|
|
}
|
|
|
|
r := web.NewRoute()
|
|
r.Use(common.ProtocolMiddlewares()...)
|
|
r.Use(Middlewares()...)
|
|
|
|
type ReducerInfo struct {
|
|
IsSigned bool
|
|
IsNil bool
|
|
IsAllAccess bool
|
|
IsPublicAccess bool
|
|
IsSpecificAccess bool
|
|
}
|
|
|
|
r.Get("/api/test", func(ctx *context.APIContext) {
|
|
retval := ReducerInfo{
|
|
IsSigned: ctx.IsSigned,
|
|
IsNil: ctx.Reducer == nil,
|
|
}
|
|
|
|
_, isAllAccess := ctx.Reducer.(*authz.AllAccessAuthorizationReducer)
|
|
retval.IsAllAccess = isAllAccess
|
|
|
|
_, isPublicAccess := ctx.Reducer.(*authz.PublicReposAuthorizationReducer)
|
|
retval.IsPublicAccess = isPublicAccess
|
|
|
|
_, isSpecificAccess := ctx.Reducer.(*authz.SpecificReposAuthorizationReducer)
|
|
retval.IsSpecificAccess = isSpecificAccess
|
|
|
|
ctx.JSON(http.StatusOK, retval)
|
|
})
|
|
|
|
t.Run("Basic Auth w/ PAT", func(t *testing.T) {
|
|
t.Run("unrestricted access token", func(t *testing.T) {
|
|
recorder := makeRecorder()
|
|
req, err := http.NewRequest("GET", "http://localhost:8000/api/test", nil)
|
|
req.SetBasicAuth("token", "4a0c970da8bf58408a8c22264b2ac1ff47dadcce")
|
|
require.NoError(t, err)
|
|
r.ServeHTTP(recorder, req)
|
|
assert.Equal(t, http.StatusOK, recorder.Code)
|
|
|
|
var reducerInfo ReducerInfo
|
|
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &reducerInfo))
|
|
|
|
assert.True(t, reducerInfo.IsSigned)
|
|
assert.False(t, reducerInfo.IsNil)
|
|
assert.True(t, reducerInfo.IsAllAccess)
|
|
assert.False(t, reducerInfo.IsPublicAccess)
|
|
assert.False(t, reducerInfo.IsSpecificAccess)
|
|
})
|
|
|
|
t.Run("public-only access token", func(t *testing.T) {
|
|
recorder := makeRecorder()
|
|
req, err := http.NewRequest("GET", "http://localhost:8000/api/test", nil)
|
|
req.SetBasicAuth("token", "83909b5b978acc5620ae0c7b0e55b548da2e26b5")
|
|
require.NoError(t, err)
|
|
r.ServeHTTP(recorder, req)
|
|
assert.Equal(t, http.StatusOK, recorder.Code)
|
|
|
|
var reducerInfo ReducerInfo
|
|
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &reducerInfo))
|
|
|
|
assert.True(t, reducerInfo.IsSigned)
|
|
assert.False(t, reducerInfo.IsNil)
|
|
assert.False(t, reducerInfo.IsAllAccess)
|
|
assert.True(t, reducerInfo.IsPublicAccess)
|
|
assert.False(t, reducerInfo.IsSpecificAccess)
|
|
})
|
|
|
|
t.Run("specific-repo access token", func(t *testing.T) {
|
|
recorder := makeRecorder()
|
|
req, err := http.NewRequest("GET", "http://localhost:8000/api/test", nil)
|
|
req.SetBasicAuth("token", "46088605ec804b43ebd15cef1b3f210c31b066dd")
|
|
require.NoError(t, err)
|
|
r.ServeHTTP(recorder, req)
|
|
assert.Equal(t, http.StatusOK, recorder.Code)
|
|
|
|
var reducerInfo ReducerInfo
|
|
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &reducerInfo))
|
|
|
|
assert.True(t, reducerInfo.IsSigned)
|
|
assert.False(t, reducerInfo.IsNil)
|
|
assert.False(t, reducerInfo.IsAllAccess)
|
|
assert.False(t, reducerInfo.IsPublicAccess)
|
|
assert.True(t, reducerInfo.IsSpecificAccess)
|
|
})
|
|
})
|
|
|
|
t.Run("Token Auth", func(t *testing.T) {
|
|
t.Run("unrestricted access token", func(t *testing.T) {
|
|
recorder := makeRecorder()
|
|
req, err := http.NewRequest("GET", "http://localhost:8000/api/test", nil)
|
|
req.Header.Set("Authorization", "token 4a0c970da8bf58408a8c22264b2ac1ff47dadcce")
|
|
require.NoError(t, err)
|
|
r.ServeHTTP(recorder, req)
|
|
assert.Equal(t, http.StatusOK, recorder.Code)
|
|
|
|
var reducerInfo ReducerInfo
|
|
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &reducerInfo))
|
|
|
|
assert.True(t, reducerInfo.IsSigned)
|
|
assert.False(t, reducerInfo.IsNil)
|
|
assert.True(t, reducerInfo.IsAllAccess)
|
|
assert.False(t, reducerInfo.IsPublicAccess)
|
|
assert.False(t, reducerInfo.IsSpecificAccess)
|
|
})
|
|
|
|
t.Run("public-only access token", func(t *testing.T) {
|
|
recorder := makeRecorder()
|
|
req, err := http.NewRequest("GET", "http://localhost:8000/api/test", nil)
|
|
req.Header.Set("Authorization", "token 83909b5b978acc5620ae0c7b0e55b548da2e26b5")
|
|
require.NoError(t, err)
|
|
r.ServeHTTP(recorder, req)
|
|
assert.Equal(t, http.StatusOK, recorder.Code)
|
|
|
|
var reducerInfo ReducerInfo
|
|
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &reducerInfo))
|
|
|
|
assert.True(t, reducerInfo.IsSigned)
|
|
assert.False(t, reducerInfo.IsNil)
|
|
assert.False(t, reducerInfo.IsAllAccess)
|
|
assert.True(t, reducerInfo.IsPublicAccess)
|
|
assert.False(t, reducerInfo.IsSpecificAccess)
|
|
})
|
|
|
|
t.Run("specific-repo access token", func(t *testing.T) {
|
|
recorder := makeRecorder()
|
|
req, err := http.NewRequest("GET", "http://localhost:8000/api/test", nil)
|
|
req.Header.Set("Authorization", "token 46088605ec804b43ebd15cef1b3f210c31b066dd")
|
|
require.NoError(t, err)
|
|
r.ServeHTTP(recorder, req)
|
|
assert.Equal(t, http.StatusOK, recorder.Code)
|
|
|
|
var reducerInfo ReducerInfo
|
|
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &reducerInfo))
|
|
|
|
assert.True(t, reducerInfo.IsSigned)
|
|
assert.False(t, reducerInfo.IsNil)
|
|
assert.False(t, reducerInfo.IsAllAccess)
|
|
assert.False(t, reducerInfo.IsPublicAccess)
|
|
assert.True(t, reducerInfo.IsSpecificAccess)
|
|
})
|
|
})
|
|
|
|
t.Run("OAuth", func(t *testing.T) {
|
|
signingKey, err := jwtx.CreateSigningKey("HS256", make([]byte, 32))
|
|
require.NoError(t, err)
|
|
defer test.MockVariableValue(&oauth2.DefaultSigningKey, signingKey)()
|
|
|
|
t.Run("unrestricted grant", func(t *testing.T) {
|
|
grant := &auth_model.OAuth2Grant{
|
|
UserID: 2,
|
|
ApplicationID: 100, // fake, but required here for unique constraint
|
|
Scope: "write:repository",
|
|
}
|
|
_, err = db.GetEngine(t.Context()).Insert(grant)
|
|
require.NoError(t, err)
|
|
|
|
token := oauth2.Token{
|
|
GrantID: grant.ID,
|
|
Type: oauth2.TypeAccessToken,
|
|
Counter: 100,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
IssuedAt: jwt.NewNumericDate(time.Now().Add(-1 * time.Hour)),
|
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(1 * time.Hour)),
|
|
},
|
|
}
|
|
signed, err := token.SignToken(oauth2.DefaultSigningKey)
|
|
require.NoError(t, err)
|
|
|
|
recorder := makeRecorder()
|
|
req, err := http.NewRequest("GET", "http://localhost:8000/api/test", nil)
|
|
req.Header.Set("Authorization", fmt.Sprintf("bearer %s", signed))
|
|
require.NoError(t, err)
|
|
r.ServeHTTP(recorder, req)
|
|
assert.Equal(t, http.StatusOK, recorder.Code)
|
|
|
|
var reducerInfo ReducerInfo
|
|
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &reducerInfo))
|
|
|
|
assert.True(t, reducerInfo.IsSigned)
|
|
assert.False(t, reducerInfo.IsNil)
|
|
assert.True(t, reducerInfo.IsAllAccess)
|
|
assert.False(t, reducerInfo.IsPublicAccess)
|
|
assert.False(t, reducerInfo.IsSpecificAccess)
|
|
})
|
|
|
|
t.Run("public-only grant", func(t *testing.T) {
|
|
grant := &auth_model.OAuth2Grant{
|
|
UserID: 2,
|
|
ApplicationID: 101, // fake, but required here for unique constraint
|
|
Scope: "write:repository public-only",
|
|
}
|
|
_, err = db.GetEngine(t.Context()).Insert(grant)
|
|
require.NoError(t, err)
|
|
|
|
token := oauth2.Token{
|
|
GrantID: grant.ID,
|
|
Type: oauth2.TypeAccessToken,
|
|
Counter: 100,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
IssuedAt: jwt.NewNumericDate(time.Now().Add(-1 * time.Hour)),
|
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(1 * time.Hour)),
|
|
},
|
|
}
|
|
signed, err := token.SignToken(oauth2.DefaultSigningKey)
|
|
require.NoError(t, err)
|
|
|
|
recorder := makeRecorder()
|
|
req, err := http.NewRequest("GET", "http://localhost:8000/api/test", nil)
|
|
req.Header.Set("Authorization", fmt.Sprintf("bearer %s", signed))
|
|
require.NoError(t, err)
|
|
r.ServeHTTP(recorder, req)
|
|
assert.Equal(t, http.StatusOK, recorder.Code)
|
|
|
|
var reducerInfo ReducerInfo
|
|
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &reducerInfo))
|
|
|
|
assert.True(t, reducerInfo.IsSigned)
|
|
assert.False(t, reducerInfo.IsNil)
|
|
assert.False(t, reducerInfo.IsAllAccess)
|
|
assert.True(t, reducerInfo.IsPublicAccess)
|
|
assert.False(t, reducerInfo.IsSpecificAccess)
|
|
})
|
|
})
|
|
}
|