jojo/services/actions/auth.go
Mathieu Fenniak 9b88e77c19 feat: expose immutable identifiers in Forgejo Actions JWTs (#12355)
Protect OIDC tokens generated by Forgejo Actions from threats arising when users or repositories are renamed or deleted, freeing their names up for reuse by another user.  In this threat environment, relying on the name of users and repositories in validating JWT claims is unsafe because they can change.

Adds three new claims to Actions' OIDC tokens:
- `actor_id` -- the immutable identifier of the actor who triggered an Action run
- `repository_id` -- the immutable identifier of the repository on which the Action is running
- `repository_owner_id` -- the immutable identifier of the owner of the repository on which the Action is running

Repositories will change their subject (`sub`) OIDC claims to include these immutable identifiers.  Existing repositories will not change, in order to maintain compatibility with existing JWT usage.  The new format will be applied to new repositories, or can be applied by disabling and enabling the Actions unit.  The new format embeds the identifiers:
- **Existing repos:** `repo:my-org/my-repo:ref:refs/heads/main`
- **New repos:** `repo:my-org-123456/my-repo-456789:ref:refs/heads/main`

Fixes #12244.

## Checklist

The [contributor guide](https://forgejo.org/docs/next/contributor/) contains information that will be helpful to first time contributors. All work and communication must conform to Forgejo's [AI Agreement](https://codeberg.org/forgejo/governance/src/branch/main/AIAgreement.md). 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

- I added test coverage for Go changes...
  - [x] in their respective `*_test.go` for unit tests.
  - [ ] in the `tests/integration` directory if it involves interactions with a live Forgejo server.
- I ran...
  - [x] `make pr-go` before pushing

### Documentation

- [x] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change.
    - New fields will be added to documentation soon.
- [ ] 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.
- [ ] 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/12355
Reviewed-by: Andreas Ahlenstorf <aahlenst@noreply.codeberg.org>
2026-05-03 15:46:58 +02:00

263 lines
7 KiB
Go

// Copyright 2024 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package actions
import (
"errors"
"fmt"
"net/http"
"strings"
"time"
actions_model "forgejo.org/models/actions"
repo_model "forgejo.org/models/repo"
"forgejo.org/modules/json"
"forgejo.org/modules/log"
"forgejo.org/modules/setting"
"github.com/golang-jwt/jwt/v5"
)
type AuthorizationTokenClaims struct {
jwt.RegisteredClaims
Scp string `json:"scp"`
TaskID int64
RunID int64
JobID int64
Ac string `json:"ac"`
OIDCExtra string `json:"oidc_extra,omitempty"`
OIDCSub string `json:"oidc_sub,omitempty"`
}
type IDTokenCustomClaims struct {
Actor string `json:"actor"`
ActorID string `json:"actor_id"`
BaseRef string `json:"base_ref"`
EventName string `json:"event_name"`
HeadRef string `json:"head_ref"`
Ref string `json:"ref"`
RefProtected string `json:"ref_protected"`
RefType string `json:"ref_type"`
Repository string `json:"repository"`
RepositoryID string `json:"repository_id"`
RepositoryOwner string `json:"repository_owner"`
RepositoryOwnerID string `json:"repository_owner_id"`
RunAttempt string `json:"run_attempt"`
RunID string `json:"run_id"`
RunNumber string `json:"run_number"`
Sha string `json:"sha"`
Workflow string `json:"workflow"`
WorkflowRef string `json:"workflow_ref"`
}
type actionsCacheScope struct {
Scope string
Permission actionsCachePermission
}
type actionsCachePermission int
const (
actionsCachePermissionRead = 1 << iota
actionsCachePermissionWrite
)
func CreateAuthorizationToken(task *actions_model.ActionTask, gitGtx map[string]any, enableOpenIDConnect bool, actionsConfig *repo_model.ActionsConfig) (string, error) {
now := time.Now()
taskID := task.ID
runID := task.Job.RunID
jobID := task.Job.ID
ac, err := json.Marshal(&[]actionsCacheScope{
{
Scope: "",
Permission: actionsCachePermissionWrite,
},
})
if err != nil {
return "", err
}
runIDJobID := fmt.Sprintf("%d:%d", runID, jobID)
claims := AuthorizationTokenClaims{
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now.Add(24 * time.Hour)),
NotBefore: jwt.NewNumericDate(now),
},
Scp: fmt.Sprintf("Actions.Results:%s", runIDJobID),
Ac: string(ac),
TaskID: taskID,
RunID: runID,
JobID: jobID,
}
// Only populate OIDC information if the task has OIDC enabled.
if enableOpenIDConnect {
oidcExtra, err := generateOIDCExtra(gitGtx)
if err != nil {
return "", err
}
claims.OIDCExtra = oidcExtra
switch actionsConfig.OIDCSubjectFormat {
case repo_model.OIDCSubjectFormatDefault:
claims.OIDCSub = generateOIDCSub(gitGtx)
case repo_model.OIDCSubjectFormatLegacyForgejo15:
claims.OIDCSub = legacyGenerateOIDCSub(gitGtx)
default:
return "", fmt.Errorf("unexpected oidc subject format: %q", actionsConfig.OIDCSubjectFormat)
}
claims.Scp = fmt.Sprintf("%s generate_id_token:%s", claims.Scp, runIDJobID)
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(setting.GetGeneralTokenSigningSecret())
if err != nil {
return "", err
}
return tokenString, nil
}
func generateOIDCExtra(gitCtx map[string]any) (string, error) {
ctxVal := func(key string) string {
val, ok := gitCtx[key]
if !ok {
return ""
}
return fmt.Sprint(val)
}
claims := IDTokenCustomClaims{
Actor: ctxVal("actor"),
ActorID: ctxVal("actor_id"),
BaseRef: ctxVal("base_ref"),
EventName: ctxVal("event_name"),
HeadRef: ctxVal("head_ref"),
Ref: ctxVal("ref"),
RefProtected: ctxVal("ref_protected"),
RefType: ctxVal("ref_type"),
Repository: ctxVal("repository"),
RepositoryID: ctxVal("repository_id"),
RepositoryOwner: ctxVal("repository_owner"),
RepositoryOwnerID: ctxVal("repository_owner_id"),
RunAttempt: ctxVal("run_attempt"),
RunID: ctxVal("run_id"),
RunNumber: ctxVal("run_number"),
Sha: ctxVal("sha"),
Workflow: ctxVal("workflow"),
WorkflowRef: ctxVal("workflow_ref"),
}
ret, err := json.Marshal(claims)
if err != nil {
return "", err
}
return string(ret), nil
}
func generateOIDCSub(gitCtx map[string]any) string {
nameParts := strings.SplitN(gitCtx["repository"].(string), "/", 2)
repoName := nameParts[1]
switch gitCtx["event_name"] {
case "pull_request":
return fmt.Sprintf("repo:%s-%s/%s-%s:pull_request", gitCtx["repository_owner"], gitCtx["repository_owner_id"], repoName, gitCtx["repository_id"])
default:
return fmt.Sprintf("repo:%s-%s/%s-%s:ref:%s", gitCtx["repository_owner"], gitCtx["repository_owner_id"], repoName, gitCtx["repository_id"], gitCtx["ref"])
}
}
func legacyGenerateOIDCSub(gitCtx map[string]any) string {
switch gitCtx["event_name"] {
case "pull_request":
return fmt.Sprintf("repo:%s:pull_request", gitCtx["repository"])
default:
return fmt.Sprintf("repo:%s:ref:%s", gitCtx["repository"], gitCtx["ref"])
}
}
func ParseAuthorizationToken(req *http.Request) (int64, error) {
token, err := parseTokenFromHeader(req)
if err != nil {
return 0, err
}
if token == "" {
return 0, nil
}
return TokenToTaskID(token)
}
// TokenToTaskID returns the TaskID associated with the provided JWT token
func TokenToTaskID(token string) (int64, error) {
parsedToken, err := jwt.ParseWithClaims(token, &AuthorizationTokenClaims{}, func(t *jwt.Token) (any, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return setting.GetGeneralTokenSigningSecret(), nil
})
if err != nil {
return 0, err
}
c, ok := parsedToken.Claims.(*AuthorizationTokenClaims)
if !parsedToken.Valid || !ok {
return 0, errors.New("invalid token claim")
}
return c.TaskID, nil
}
func ParseAuthorizationTokenClaims(req *http.Request) (*AuthorizationTokenClaims, error) {
token, err := parseTokenFromHeader(req)
if err != nil {
return nil, err
}
claims, err := decodeTokenClaims(token)
if err != nil {
return nil, err
}
return claims, nil
}
func parseTokenFromHeader(req *http.Request) (string, error) {
h := req.Header.Get("Authorization")
if h == "" {
return "", nil
}
parts := strings.SplitN(h, " ", 2)
if len(parts) != 2 {
log.Error("split token failed: %s", h)
return "", errors.New("split token failed")
}
return parts[1], nil
}
func decodeTokenClaims(token string) (*AuthorizationTokenClaims, error) {
parsedToken, err := jwt.ParseWithClaims(token, &AuthorizationTokenClaims{}, func(t *jwt.Token) (any, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return setting.GetGeneralTokenSigningSecret(), nil
})
if err != nil {
return nil, err
}
c, ok := parsedToken.Claims.(*AuthorizationTokenClaims)
if !parsedToken.Valid || !ok {
return nil, errors.New("invalid token claim")
}
return c, nil
}