fix: correct scope validation in token exchange (#12312)

## Which Problems Are Solved

The v4.15.3 token exchange hardening (`#12319`, `#12322`) introduced two
regressions:

1. **Logic bug**: scope validation used intersection (`!inSubject ||
!inActor`) instead of union, so any explicit `scope` on a `user_id`
subject always failed — even `openid` when present on the actor token.
2. **Design gap**: even with union logic, scope-less subjects
(`user_id`, `id_token`) cannot satisfy a rule that requires all
requested scopes to exist on input tokens. This breaks documented
impersonation flows (e.g. service account actor + `user_id` subject
requesting `email`).

## How the Problems Are Solved

- **Standard exchange** (no actor, or subject carries scopes): keep
union validation — requested scopes must be ⊆ subject ∪ actor. For plain
exchange this is effectively a subset of the subject token.
- **Scope-less subject impersonation** (`user_id`, `id_token` on actor
path): split validation:
- **Subject-data scopes** (`openid`, `profile`, `email`, …): client
allowlist only
- **Authorization scopes** (`offline_access`, `:aud`, `projects:roles`,
`role:*`): still ⊆ subject ∪ actor
- Restore subject → actor fallback when `scope` is omitted.

GHSA protections remain: cross-client token binding and
authorization-scope escalation are still rejected.

Closes #12319
Closes #12322

## Additional Changes

- Unit tests for scope validators (`token_exchange_test.go`)
- Integration tests covering `user_id`/`id_token` paths, union-path
rejection, and client-credentials actor → `user_id` exchange

## Additional Context

- Relates to https://github.com/zitadel/zitadel/releases/tag/v4.15.3
- Security fix: GHSA-vrh8-c9cm-wh8v

---------

Co-authored-by: Cursor <[email protected]>
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
This commit is contained in:
Livio Spring
2026-07-09 12:33:11 +00:00
committed by GitHub
co-authored by Cursor Copilot Autofix powered by AI
parent 9d60e83d6f
commit 39ad66bded
3 changed files with 378 additions and 9 deletions
+118 -9
View File
@@ -3,6 +3,7 @@ package oidc
import (
"context"
"slices"
"strings"
"time"
"github.com/zitadel/oidc/v3/pkg/oidc"
@@ -57,7 +58,12 @@ func (s *Server) tokenExchange(ctx context.Context, r *op.ClientRequest[oidc.Tok
}
actorToken := subjectToken // see [createExchangeTokens] comment.
// actorPath: a separate actor_token was verified (impersonation/delegation).
// Standard exchange leaves actorToken == subjectToken; this branch runs for
// user_id/JWT subjects or when the client sends actor_token explicitly.
actorPath := false
if subjectToken.tokenType == UserIDTokenType || subjectToken.tokenType == oidc.JWTTokenType || r.Data.ActorToken != "" {
actorPath = true
if !authz.GetInstance(ctx).EnableImpersonation() {
return nil, zerrors.ThrowPermissionDenied(nil, "OIDC-Fae5w", "Errors.TokenExchange.Impersonation.PolicyDisabled")
}
@@ -75,7 +81,13 @@ func (s *Server) tokenExchange(ctx context.Context, r *op.ClientRequest[oidc.Tok
if err != nil {
return nil, err
}
scopes, err := validateTokenExchangeScopes(client, r.Data.Scopes, subjectToken.scopes, actorToken.scopes)
// scopelessActorPath: actorPath with a subject that cannot carry scopes
// (user_id or id_token). Subject-data scopes (email, profile, …) are taken
// from the impersonated user at mint time; only authorization scopes must
// appear on subject_token ∪ actor_token. Access/JWT subjects always use
// union validation even when their scope claim is empty.
scopelessActorPath := actorPath && (subjectToken.tokenType == UserIDTokenType || subjectToken.tokenType == oidc.IDTokenType)
scopes, err := validateTokenExchangeScopes(client, r.Data.Scopes, subjectToken.scopes, actorToken.scopes, scopelessActorPath)
if err != nil {
return nil, err
}
@@ -178,25 +190,122 @@ func (s *Server) jwtProfileUserCheck(ctx context.Context, resourceOwner *string,
})
}
func validateTokenExchangeScopes(client *Client, requestedScopes, subjectScopes, actorScopes []string) ([]string, error) {
// Scope always has 1 empty string if the space delimited array was an empty string.
requestedScopes = slices.DeleteFunc(requestedScopes, func(s string) bool {
return s == ""
})
// validateTokenExchangeScopes picks the scope rule set for this exchange.
// scopelessActorPath selects impersonation rules (user_id/id_token subjects
// on the actor path); otherwise every requested scope must ⊆ subject ∪ actor.
func validateTokenExchangeScopes(
client *Client,
requestedScopes, subjectScopes, actorScopes []string,
scopelessActorPath bool,
) ([]string, error) {
requestedScopes = normalizeRequestedScopes(requestedScopes)
if scopelessActorPath {
return validateImpersonationTokenExchangeScopes(client, requestedScopes, subjectScopes, actorScopes)
}
return validateUnionTokenExchangeScopes(client, requestedScopes, subjectScopes, actorScopes)
}
// validateUnionTokenExchangeScopes applies when the requested scopes must be a subset
// of the scopes present on the subject and/or actor tokens (union).
// This covers standard exchange (actor == subject) and actor-path exchanges with
// access/JWT subject tokens. Actor-path exchanges with scope-less subjects
// (user_id, id_token) use validateImpersonationTokenExchangeScopes instead.
// Rule: every scope must be present on the subject or actor token (union).
// For standard exchange both lists are identical, so this is effectively
// "subset of subject token only".
func validateUnionTokenExchangeScopes(
client *Client,
requestedScopes, subjectScopes, actorScopes []string,
) ([]string, error) {
if len(requestedScopes) == 0 {
return op.ValidateAuthReqScopes(client, actorScopes)
requestedScopes = subjectScopes
}
if len(requestedScopes) == 0 {
requestedScopes = actorScopes
}
for _, scope := range requestedScopes {
if !slices.Contains(subjectScopes, scope) || !slices.Contains(actorScopes, scope) {
return nil, oidc.ErrInvalidScope().WithDescription("scope %q not found in subject or actor token", scope)
if !scopeInUnion(scope, subjectScopes, actorScopes) {
return nil, oidc.ErrInvalidScope().
WithDescription("scope %q not found in subject or actor token", scope)
}
}
return op.ValidateAuthReqScopes(client, requestedScopes)
}
// validateImpersonationTokenExchangeScopes applies when the subject token
// cannot carry scopes (user_id, id_token). The actor token authorizes the
// request; impersonation permission is checked later in CreateOIDCSession.
//
// Two scope classes:
// - authorization scopes: privilege/audience/roles — must be on input tokens
// - subject-data scopes: user claims (email, profile, …) — client allowlist only
func validateImpersonationTokenExchangeScopes(
client *Client,
requestedScopes, subjectScopes, actorScopes []string,
) ([]string, error) {
// Subject has no scopes to inherit; fall back to actor.
if len(requestedScopes) == 0 {
requestedScopes = actorScopes
}
for _, scope := range requestedScopes {
// Prevent privilege escalation: offline_access, audiences, roles, etc.
// must still come from subject or actor token.
if isTokenExchangeAuthorizationScope(scope) && !scopeInUnion(scope, subjectScopes, actorScopes) {
return nil, oidc.ErrInvalidScope().
WithDescription("scope %q not found in subject or actor token", scope)
}
// Subject-data scopes (openid, profile, email, urn:zitadel:iam:user:*, …)
// skip the union check — validated by client allowlist below.
}
return op.ValidateAuthReqScopes(client, requestedScopes)
}
func normalizeRequestedScopes(scopes []string) []string {
// Space-delimited empty scope produces a single "" entry.
return slices.DeleteFunc(scopes, func(s string) bool {
return s == ""
})
}
func scopeInUnion(scope string, subjectScopes, actorScopes []string) bool {
return slices.Contains(subjectScopes, scope) || slices.Contains(actorScopes, scope)
}
// isTokenExchangeAuthorizationScope identifies scopes that control what a token
// may do (audiences, refresh, roles), not which user claims to embed.
func isTokenExchangeAuthorizationScope(scope string) bool {
switch scope {
case oidc.ScopeOfflineAccess, ScopeProjectsRoles:
return true
}
if strings.HasPrefix(scope, ScopeProjectRolePrefix) {
return true // urn:zitadel:iam:org:project:role:*
}
if strings.HasPrefix(scope, domain.ProjectIDScope) {
return true // urn:zitadel:iam:org:project:id:*:aud
}
if strings.HasPrefix(scope, domain.OrgIDScope) {
return true
}
if strings.HasPrefix(scope, domain.OrgDomainPrimaryScope) {
return true
}
if strings.HasPrefix(scope, domain.OrgRoleIDScope) {
return true
}
if strings.HasPrefix(scope, domain.SelectIDPScope) {
return true
}
return false
}
func validateTokenExchangeAudience(requestedAudience, subjectAudience, actorAudience []string) ([]string, error) {
if len(requestedAudience) == 0 {
if len(subjectAudience) > 0 {