diff --git a/cmd/admin_user.go b/cmd/admin_user.go index f4f6fb49af..ea62bd3a45 100644 --- a/cmd/admin_user.go +++ b/cmd/admin_user.go @@ -17,6 +17,7 @@ func subcmdUser() *cli.Command { microcmdUserChangePassword(), microcmdUserDelete(), microcmdUserGenerateAccessToken(), + microcmdUserCreateAuthorizedIntegration(), microcmdUserMustChangePassword(), microcmdUserResetMFA(), }, diff --git a/cmd/admin_user_generate_authorized_integration.go b/cmd/admin_user_generate_authorized_integration.go new file mode 100644 index 0000000000..5f3e13a48e --- /dev/null +++ b/cmd/admin_user_generate_authorized_integration.go @@ -0,0 +1,204 @@ +// Copyright 2026 The Forgejo Authors. All rights reserved. +// SPDX-License-Identifier: GPL-3.0-or-later + +package cmd + +import ( + "bytes" + "context" + "errors" + "fmt" + "os" + "strings" + + auth_model "forgejo.org/models/auth" + "forgejo.org/models/db" + "forgejo.org/models/repo" + user_model "forgejo.org/models/user" + "forgejo.org/modules/json" + "forgejo.org/services/authz" + + "github.com/urfave/cli/v3" +) + +func microcmdUserCreateAuthorizedIntegration() *cli.Command { + return &cli.Command{ + Name: "create-authorized-integration", + Usage: "Create an authorized integration for a specific user", + Flags: []cli.Flag{ + &cli.StringFlag{ + Name: "username", + Aliases: []string{"u"}, + Usage: "Username", + Required: true, + }, + + // JWT validation: + &cli.StringFlag{ + Name: "issuer", + Usage: `JWT issuer ('iss' claim), example: https://forgejo.example.org/api/actions`, + Required: true, + }, + &cli.StringMapFlag{ + Name: "claim-eq", + Value: map[string]string{}, + Usage: `Zero-or-more claim equality checks, formatted as claim=value, example: "actor=someuser"`, + }, + &cli.StringMapFlag{ + Name: "claim-glob", + Value: map[string]string{}, + Usage: `Zero-or-more claim glob checks, formatted as claim=value, example: "sub=repo:forgejo/*:pull_request"`, + }, + // nested claim support omitted for now -- pretty complex for a CLI + + // Permissions available on successful auth: + &cli.StringSliceFlag{ + Name: "scope", + Value: []string{"all"}, + Usage: `One-or-more scopes to apply to access token, examples: "all", "read:issue", "write:repository"`, + }, + &cli.StringSliceFlag{ + Name: "repo", + Value: []string{"all"}, + Usage: `Zero-or-more specific repositories that can be accessed, or "all" to allow access to all repositories, example: "owner1/repo1"`, + }, + }, + Before: noDanglingArgs, + Action: runCreateAuthorizedIntegration, + } +} + +func runCreateAuthorizedIntegration(ctx context.Context, c *cli.Command) error { + if !c.IsSet("username") { + return errors.New("you must provide a username to generate a token for") + } + + ctx, cancel := installSignals(ctx) + defer cancel() + + if err := initDB(ctx); err != nil { + return err + } + + user, err := user_model.GetUserByName(ctx, c.String("username")) + if err != nil { + return err + } + + ai := &auth_model.AuthorizedIntegration{ + UserID: user.ID, + } + + var rules []auth_model.ClaimRule + ai.Issuer = c.String("issuer") + for claim, value := range c.StringMap("claim-eq") { + rules = append(rules, auth_model.ClaimRule{ + Claim: claim, + Comparison: auth_model.ClaimEqual, + Value: value, + }) + } + for claim, value := range c.StringMap("claim-glob") { + rules = append(rules, auth_model.ClaimRule{ + Claim: claim, + Comparison: auth_model.ClaimGlob, + Value: value, + }) + } + ai.ClaimRules = &auth_model.ClaimRules{Rules: rules} + + scopes := strings.Join(c.StringSlice("scope"), ",") + accessTokenScope, err := auth_model.AccessTokenScope(scopes).Normalize() + if err != nil { + return fmt.Errorf("invalid access token scope provided: %w", err) + } + ai.Scope = accessTokenScope + + allRepos := false + repos := []*repo.Repository{} + for _, repoName := range c.StringSlice("repo") { + if repoName == "all" { + allRepos = true + } else { + split := strings.Split(repoName, "/") + if len(split) != 2 { + return fmt.Errorf("invalid repo name: %q", split) + } + owner := split[0] + name := split[1] + repo, err := repo.GetRepositoryByOwnerAndName(ctx, owner, name) + if err != nil { + return err + } + repos = append(repos, repo) + } + } + ai.ResourceAllRepos = allRepos + + rr := make([]*auth_model.AuthorizedIntegResourceRepo, len(repos)) + for i := range repos { + rr[i] = &auth_model.AuthorizedIntegResourceRepo{RepoID: repos[i].ID} + } + if err := authz.ValidateAuthorizedIntegration(ai, rr); err != nil { + return err + } + + err = db.WithTx(ctx, func(ctx context.Context) error { + if err := auth_model.InsertAuthorizedIntegration(ctx, ai); err != nil { + return err + } + if !allRepos { + if err := auth_model.InsertAuthorizedIntegrationResourceRepos(ctx, ai.ID, rr); err != nil { + return err + } + } + return nil + }) + if err != nil { + return err + } + + type ClaimRuleDescription struct { + Description string `json:"description"` + Claim string `json:"claim"` + Comparison auth_model.ClaimComparison `json:"compare"` + Value string `json:"value"` + } + output := struct { + Message string `json:"message"` + Issuer string `json:"issuer"` + Audience string `json:"audience"` + ClaimRules []ClaimRuleDescription `json:"claim_rules"` + }{ + Message: "Authorized integration was successfully created.", + Issuer: ai.Issuer, + Audience: ai.Audience, + } + for _, cr := range ai.ClaimRules.Rules { + var description string + switch cr.Comparison { + case auth_model.ClaimEqual: + description = fmt.Sprintf("%q = %q", cr.Claim, cr.Value) + case auth_model.ClaimGlob: + description = fmt.Sprintf("%q matches %q", cr.Claim, cr.Value) + } + output.ClaimRules = append(output.ClaimRules, ClaimRuleDescription{ + Description: description, + Claim: cr.Claim, + Comparison: cr.Comparison, + Value: cr.Value, + }) + } + + raw, err := json.Marshal(output) + if err != nil { + return err + } + var indent bytes.Buffer + if err := json.Indent(&indent, raw, "", " "); err != nil { + return err + } + os.Stdout.Write(indent.Bytes()) + + return nil +} diff --git a/models/auth/authorized_integration.go b/models/auth/authorized_integration.go index a8641d44ca..e4cc8cedb0 100644 --- a/models/auth/authorized_integration.go +++ b/models/auth/authorized_integration.go @@ -5,12 +5,15 @@ package auth import ( "context" + "errors" + "fmt" "time" "forgejo.org/models/db" "forgejo.org/modules/timeutil" "forgejo.org/modules/util" + gouuid "github.com/google/uuid" "xorm.io/builder" ) @@ -128,6 +131,16 @@ func GetAuthorizedIntegration(ctx context.Context, issuer, audience string) (*Au return &ai, nil } +func InsertAuthorizedIntegration(ctx context.Context, ai *AuthorizedIntegration) error { + if ai.Audience != "" { + return errors.New("audience cannot be provided, and must be generated by NewAuthorizedIntegration") + } else if err := ai.generateAudience(); err != nil { + return err + } + _, err := db.GetEngine(ctx).Insert(ai) + return err +} + // Bump the UpdatedUnix field of this authorized integration to now, tracking when it was last used for authentication. // To reduce database write workload, this is only tracked by one-minute intervals -- the UPDATE statement conditionally // avoids writes. @@ -144,3 +157,25 @@ func (ai *AuthorizedIntegration) UpdateLastUsed(ctx context.Context) error { } return err } + +// Generates the `aud` claim that the remote JWT generator must use to match this authorized integration. The `aud` +// claim is an arbitrary value in a JWT claim, but Forgejo is faced with a few hard and soft requirements: +// +// - Hard requirement: each authorized integration must have a unique `aud`, as it is used to find the DB record that +// authenticates a request. +// - If authentication is failing, being able to inspect the `aud` claim can be useful to identify the intent. +// - Inspection should have a stable meaning -- eg. if it included the username, and the user was renamed, the `aud` +// value which can't be changed would continue to reference the old username causing confusion when inspecting it. +// - Forgejo & GitHub Actions uses a URL $ACTIONS_ID_TOKEN_REQUEST_URL&audience=... to generate a JWT for the running +// action, so it should only consist of safe characters for URL encoding. +// - It should be relatively short, as it's encoded into the JWT and increases its size. +// +// Meeting these requirements decently well is a combination of the owner's ID, a guid, and a "u:" prefix that makes the +// fact that it's an `aud` claim value a little bit identifiable. +func (ai *AuthorizedIntegration) generateAudience() error { + if ai.UserID == 0 { + return errors.New("UserID must be initialized") + } + ai.Audience = fmt.Sprintf("u:%d:%s", ai.UserID, gouuid.New().String()) + return nil +} diff --git a/models/auth/authorized_integration_resource_repo.go b/models/auth/authorized_integration_resource_repo.go index 9c48d16f98..77445b60ae 100644 --- a/models/auth/authorized_integration_resource_repo.go +++ b/models/auth/authorized_integration_resource_repo.go @@ -42,3 +42,15 @@ func GetRepositoriesAccessibleWithIntegration(ctx context.Context, aiID int64) ( } return resources, nil } + +func InsertAuthorizedIntegrationResourceRepos(ctx context.Context, aiID int64, resources []*AuthorizedIntegResourceRepo) error { + return db.WithTx(ctx, func(ctx context.Context) error { + for _, resourceRepo := range resources { + resourceRepo.IntegID = aiID + if err := db.Insert(ctx, resourceRepo); err != nil { + return err + } + } + return nil + }) +} diff --git a/models/auth/authorized_integration_resource_repo_test.go b/models/auth/authorized_integration_resource_repo_test.go index 853cddb828..15c5b4854f 100644 --- a/models/auth/authorized_integration_resource_repo_test.go +++ b/models/auth/authorized_integration_resource_repo_test.go @@ -38,3 +38,54 @@ func TestGetRepositoriesAccessibleWithIntegration(t *testing.T) { assert.Contains(t, repoIDs, int64(3)) }) } + +func TestInsertAuthorizedIntegration(t *testing.T) { + require.NoError(t, unittest.PrepareTestDatabase()) + + ai1 := makeAuthorizedIntegration(t) + ai2 := makeAuthorizedIntegration(t) + ai3 := makeAuthorizedIntegration(t) + + t.Run("blank insert", func(t *testing.T) { + err := auth_model.InsertAuthorizedIntegrationResourceRepos(t.Context(), ai1.ID, nil) + require.NoError(t, err) + }) + + t.Run("multiple insert", func(t *testing.T) { + resRepo1 := &auth_model.AuthorizedIntegResourceRepo{ + IntegID: ai2.ID, + RepoID: 1, + } + resRepo3 := &auth_model.AuthorizedIntegResourceRepo{ + IntegID: ai2.ID, + RepoID: 3, + } + err := auth_model.InsertAuthorizedIntegrationResourceRepos(t.Context(), ai2.ID, + []*auth_model.AuthorizedIntegResourceRepo{resRepo1, resRepo3}) + require.NoError(t, err) + + unittest.AssertCount(t, &auth_model.AuthorizedIntegResourceRepo{IntegID: ai2.ID}, 2) + }) + + t.Run("in tx", func(t *testing.T) { + // Pre-condition: count is 0. + unittest.AssertCount(t, &auth_model.AuthorizedIntegResourceRepo{IntegID: ai3.ID}, 0) + + // Verify that InsertAuthorizedIntegrationResourceRepos performs inserts in a TX by having a second one with an invalid + // RepoID, causing a foreign key violation + resRepo1 := &auth_model.AuthorizedIntegResourceRepo{ + IntegID: ai3.ID, + RepoID: 1, + } + resRepo3 := &auth_model.AuthorizedIntegResourceRepo{ + IntegID: ai3.ID, + RepoID: 30000, // invalid + } + err := auth_model.InsertAuthorizedIntegrationResourceRepos(t.Context(), ai3.ID, + []*auth_model.AuthorizedIntegResourceRepo{resRepo1, resRepo3}) + require.ErrorContains(t, err, "foreign key") + + // Count remains 0; the first record was not inserted. + unittest.AssertCount(t, &auth_model.AuthorizedIntegResourceRepo{IntegID: ai3.ID}, 0) + }) +} diff --git a/models/auth/authorized_integration_test.go b/models/auth/authorized_integration_test.go index 54cf97fcb5..d705f1a144 100644 --- a/models/auth/authorized_integration_test.go +++ b/models/auth/authorized_integration_test.go @@ -4,7 +4,6 @@ package auth_test import ( - "fmt" "testing" "time" @@ -14,25 +13,20 @@ import ( "forgejo.org/modules/timeutil" "forgejo.org/modules/util" - gouuid "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func makeAuthorizedIntegration(t *testing.T) *auth_model.AuthorizedIntegration { t.Helper() - ai := &auth_model.AuthorizedIntegration{ UserID: 2, Scope: auth_model.AccessTokenScopeAll, ResourceAllRepos: true, Issuer: "https://example.org/", - Audience: fmt.Sprintf("https://forgejo.example.org/api/actions/%s", gouuid.New().String()), ClaimRules: &auth_model.ClaimRules{}, } - _, err := db.GetEngine(t.Context()).Insert(ai) - require.NoError(t, err) - + require.NoError(t, auth_model.InsertAuthorizedIntegration(t.Context(), ai)) return ai } @@ -79,3 +73,34 @@ func TestAuthorizedIntegrationUpdateLastUsed(t *testing.T) { assert.EqualValues(t, 1777131139, ai.UpdatedUnix) // object field updated assert.EqualValues(t, 1777131139, unittest.AssertExistsAndLoadBean(t, &auth_model.AuthorizedIntegration{ID: ai.ID}).UpdatedUnix) // database field updated } + +func TestNewAuthorizedIntegration(t *testing.T) { + ai := &auth_model.AuthorizedIntegration{ + UserID: 2, + Scope: auth_model.AccessTokenScopeAll, + ResourceAllRepos: true, + Issuer: "https://example.org/", + ClaimRules: &auth_model.ClaimRules{}, + } + require.NoError(t, auth_model.InsertAuthorizedIntegration(t.Context(), ai)) + assert.Contains(t, ai.Audience, "u:2:") + + ai = &auth_model.AuthorizedIntegration{ + UserID: 2, + Scope: auth_model.AccessTokenScopeAll, + ResourceAllRepos: true, + Issuer: "https://example.org/", + Audience: "I made my own audience", + ClaimRules: &auth_model.ClaimRules{}, + } + require.ErrorContains(t, auth_model.InsertAuthorizedIntegration(t.Context(), ai), "audience cannot be provided") + + ai = &auth_model.AuthorizedIntegration{ + // Forgot to set UserID + Scope: auth_model.AccessTokenScopeAll, + ResourceAllRepos: true, + Issuer: "https://example.org/", + ClaimRules: &auth_model.ClaimRules{}, + } + require.ErrorContains(t, auth_model.InsertAuthorizedIntegration(t.Context(), ai), "UserID must be initialized") +} diff --git a/services/authz/access_token.go b/services/authz/access_token.go index 1660881dab..5a6d876cf6 100644 --- a/services/authz/access_token.go +++ b/services/authz/access_token.go @@ -33,14 +33,11 @@ func GetAuthorizationReducerForAccessToken(ctx context.Context, token *auth_mode return &SpecificReposAuthorizationReducer{resourceRepos: iface}, nil } -// A locale lookup string for the error -- eg. `access_token.error.invalid_something` -type AccessTokenValidationFailure string - // Validate that an access token's state is valid for creation. For example, that it doesn't have a conflicting set of // resources (public-only and specific repositories), and other similar checks. func ValidateAccessToken(token *auth_model.AccessToken, repoResources []*auth_model.AccessTokenResourceRepo) error { // Other validations may be added here in the future. - return validateRepositoryResource(token, repoResources) + return validateRepositoryResource(token.ResourceAllRepos, token.Scope, len(repoResources)) } var ( @@ -49,19 +46,19 @@ var ( ErrSpecifiedReposInvalidScope = errors.New("specified repository access token: invalid scope") ) -func validateRepositoryResource(token *auth_model.AccessToken, repoResources []*auth_model.AccessTokenResourceRepo) error { +func validateRepositoryResource(resourceAllRepos bool, scope auth_model.AccessTokenScope, numRepoResources int) error { // Access tokens with broad access to all resources don't have any relevant validation rules to apply. - if token.ResourceAllRepos { + if resourceAllRepos { return nil } // Repo-specific access token must have at least one repository. - if len(repoResources) == 0 { + if numRepoResources == 0 { return ErrSpecifiedReposNone } // Can't have public-only and specified repos -- that's a combination that doesn't make sense. - if publicOnly, err := token.Scope.PublicOnly(); err != nil { + if publicOnly, err := scope.PublicOnly(); err != nil { return err } else if publicOnly { return ErrSpecifiedReposNoPublicOnly @@ -71,7 +68,7 @@ func validateRepositoryResource(token *auth_model.AccessToken, repoResources []* // support repositories as a resource. For example, if you had a repo-specific token but then gave it // `write:organization`, it would be able to do operations like delete an organization -- permission checks on the // repository resources wouldn't be applicable to the organization resources. - for _, scope := range token.Scope.StringSlice() { + for _, scope := range scope.StringSlice() { switch auth_model.AccessTokenScope(scope) { case auth_model.AccessTokenScopeReadIssue, auth_model.AccessTokenScopeWriteIssue, diff --git a/services/authz/authorized_integration.go b/services/authz/authorized_integration.go index c463c0aeca..33099c7401 100644 --- a/services/authz/authorized_integration.go +++ b/services/authz/authorized_integration.go @@ -31,3 +31,10 @@ func GetAuthorizationReducerForAuthorizedIntegration(ctx context.Context, ai *au } return &SpecificReposAuthorizationReducer{resourceRepos: iface}, nil } + +// Validate that an authorized integration's state is valid for creation. For example, that it doesn't have a +// conflicting set of resources (public-only and specific repositories), and other similar checks. +func ValidateAuthorizedIntegration(ai *auth_model.AuthorizedIntegration, repoResources []*auth_model.AuthorizedIntegResourceRepo) error { + // Other validations may be added here in the future. + return validateRepositoryResource(ai.ResourceAllRepos, ai.Scope, len(repoResources)) +} diff --git a/services/authz/authorized_integration_test.go b/services/authz/authorized_integration_test.go index fe3ec697a4..cb46a2479f 100644 --- a/services/authz/authorized_integration_test.go +++ b/services/authz/authorized_integration_test.go @@ -4,6 +4,7 @@ package authz import ( + "strings" "testing" "forgejo.org/models/auth" @@ -44,3 +45,55 @@ func TestGetAuthorizationReducerForAuthorizedIntegration(t *testing.T) { assert.EqualValues(t, 1, specific.resourceRepos[0].GetTargetRepoID()) }) } + +func TestValidateAuthorizedIntegration(t *testing.T) { + t.Run("valid - all access", func(t *testing.T) { + ai := &auth.AuthorizedIntegration{ + ResourceAllRepos: true, + Scope: auth.AccessTokenScopeReadRepository, + } + err := ValidateAuthorizedIntegration(ai, nil) + require.NoError(t, err) + }) + + t.Run("valid - specified repos", func(t *testing.T) { + ai := &auth.AuthorizedIntegration{ + ResourceAllRepos: false, + Scope: auth.AccessTokenScopeReadRepository, + } + resources := []*auth.AuthorizedIntegResourceRepo{{RepoID: 12}} + err := ValidateAuthorizedIntegration(ai, resources) + require.NoError(t, err) + }) + + t.Run("invalid - no specified repos", func(t *testing.T) { + ai := &auth.AuthorizedIntegration{ + ResourceAllRepos: false, + Scope: auth.AccessTokenScopeReadRepository, + } + resources := []*auth.AuthorizedIntegResourceRepo{} + err := ValidateAuthorizedIntegration(ai, resources) + require.ErrorIs(t, err, ErrSpecifiedReposNone) + }) + + t.Run("invalid - specified repos & public-only", func(t *testing.T) { + ai := &auth.AuthorizedIntegration{ + ResourceAllRepos: false, + Scope: auth.AccessTokenScope(strings.Join([]string{string(auth.AccessTokenScopePublicOnly), string(auth.AccessTokenScopeReadRepository)}, ",")), + } + resources := []*auth.AuthorizedIntegResourceRepo{{RepoID: 12}} + err := ValidateAuthorizedIntegration(ai, resources) + require.ErrorIs(t, err, ErrSpecifiedReposNoPublicOnly) + }) + + t.Run("invalid - specified repos unsupported scopes", func(t *testing.T) { + ai := &auth.AuthorizedIntegration{ + ResourceAllRepos: false, + Scope: auth.AccessTokenScopeReadAdmin, + } + resources := []*auth.AuthorizedIntegResourceRepo{{RepoID: 12}} + err := ValidateAuthorizedIntegration(ai, resources) + require.ErrorIs(t, err, ErrSpecifiedReposInvalidScope) + require.ErrorContains(t, err, string(auth.AccessTokenScopeReadAdmin)) + }) +}