Skip to content

Add opt-in upstream subject identifiers - #6908

Merged
jhrozek merged 2 commits into
mainfrom
sub-ns
Oct 22, 2026
Merged

jhrozek merged 2 commits into
mainfrom
sub-ns

Conversation

@jhrozek

@jhrozek jhrozek commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

Summary

Clients that host sessions for a user, such as Mecatl, need to know which person at the company identity provider an access token belongs to, so they can tie sessions and grants to that person. Until now the embedded auth server's access tokens only carried the auth server's own sub.

This PR adds two claims to access tokens. Both are off by default and enabled per audience:

  • sub_id, the RFC 9493 identifier: {"format":"iss_sub","iss":...,"sub":...}. It holds the exact iss and raw sub of the validated upstream OIDC ID token.
  • https://toolhive.dev/upstream_subject: {"iss":...,"claim":...,"value":...}. claim is the upstream's subject_claim (or "sub"), and value is that claim from the same ID token, the value ToolHive already keys its local user on. The raw sub is not stable on every IdP: Microsoft Entra ID issues a different sub per app registration. With subject_claim: oid this claim stays the same across app registrations. Consumers that need a stable key compare all three members.

What changed:

  • Opt-in: authserver.Config.SubjectIdentifierAudiences for authserver.New callers, and runner.WithSubjectIdentifierAudiences for runner callers. Every entry must be one of the allowed audiences. The claims are added only when every audience of the token is listed.
  • Which tokens: access tokens from authorization-code and device-flow logins and their refreshes. Token exchange, jwt-bearer and ID-JAG never carry the claims over from a subject token.
  • Where the identity comes from: only the validated ID token of the upstream login that establishes the user, never client input. Synthetic and pure OAuth2 identities never get either claim.
  • Storage: the identity is stored on pending authorizations, pending device confirmations, device requests and token sessions, even when disclosure is off. Every token request clears both claims and computes them again, so a policy change applies at the next refresh.
  • Go-only setting: it is not a RunConfig field, so it stays out of the published API schema, the SDK, config files and operator CRDs while the feature settles. The commit message describes how to move it to RunConfig later without breaking anything.
  • Storage interface: MarkDeviceRequestAuthorized now takes a DeviceAuthorization struct.
  • Docs: docs/arch/11-auth-server-storage.md describes both claims, the rules for consumers, IdP caveats and upgrade behavior.

Fixes #6900

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (task test)
  • E2E tests (task test-e2e)
  • Linting (task lint-fix)
  • Manual testing (describe below)

The new tests cover:

  • Disclosure on and off: audiences that do and don't match, and a mapped subject_claim.
  • Partial audience match: some audiences listed, some not.
  • Policy change between login and refresh, in both directions, with two servers sharing storage.
  • Multi-upstream chains: only the first upstream login supplies the identity.
  • Device flow: verified and synthetic identities.
  • Redis round-trips for every stored type.
  • Session clone isolation.
  • Token exchange clearing the claims.

Changes

File Change
pkg/authserver/config.go, server/audience.go New SubjectIdentifierAudiences setting and its validation against the allowed audiences
pkg/authserver/runner/embeddedauthserver.go WithSubjectIdentifierAudiences runner option
pkg/authserver/upstream/oidc.go, types.go Capture the verified issuer, subject and stable claim from the validated ID token
pkg/authserver/server/handlers/callback.go, device_verification.go Store the identity from the login that establishes the user
pkg/authserver/server/handlers/token.go Clear and recompute both claims on every token request
pkg/authserver/server/session/session.go UpstreamSubject type, claim keys, set and clear helpers, clone
pkg/authserver/storage/* Store the identity on pending, confirmation and device records; DeviceAuthorization struct
docs/arch/11-auth-server-storage.md, docs/redis-storage.md Claim reference, rules for consumers, upgrade behavior

Does this introduce a user-facing change?

Only for Go callers that opt in. For thv, vMCP and operator users nothing changes: the setting is not reachable from config files or CRDs, and it is off by default.

  • Before: access tokens carried only the auth server's own sub.
  • After: when a Go caller lists an audience in SubjectIdentifierAudiences, access tokens issued only to listed audiences also carry sub_id and https://toolhive.dev/upstream_subject.

Disclosing oid lets anyone who sees the token match the same user across apps in the tenant, so only first-party audiences should be listed.

Go API break: storage.Storage.MarkDeviceRequestAuthorized(ctx, deviceCode, DeviceAuthorization) replaces the earlier positional arguments. Storage decorators outside this repo that forward the method must be updated. Nothing in this repo forwards it.

Implementation plan

The plan covered the second claim, upstream_subject, which was added after the first sub_id draft. This is its design section.

Approved implementation plan

Problem

The commit adds an RFC 9493 sub_id claim to access tokens from the embedded auth server:
{"format":"iss_sub","iss":<upstream ID token iss>,"sub":<upstream ID token raw sub>}. It is opt-in per
audience from Go (runner.WithSubjectIdentifierAudiences, authserver.Config.SubjectIdentifierAudiences).

With Microsoft Entra ID as the upstream, the ID token sub is pairwise per (client ID, tenant, user).
It changes when ToolHive's upstream app is registered again, and a second Entra app (for example a
gateway's AS-2) sees a different sub for the same person. Microsoft recommends oid + tid as the
cross-app key. The consumer, Mecatl, keys session ownership on this identity and expects it to be stable,
and its AS-2 consistency check compares identities across two Entra apps.

Decision

  1. Keep sub_id exactly as it is: a bare iss_sub with the raw upstream iss and sub. Do not switch
    to RFC 9493 aliases (it would change sub_id's format depending on config and break consumers that
    check format == "iss_sub"), and do not put oid in the sub member (it is not the issuer's sub).

  2. Add one claim with a collision-resistant (public) claim name (RFC 7519 §4.2; same https://toolhive.dev/
    prefix as the existing NoUpstreamSessionClaimKey), emitted together with sub_id under the same opt-in:

    "https://toolhive.dev/upstream_subject": {
      "iss":   "https://login.microsoftonline.com/<tid>/v2.0",
      "claim": "oid",
      "value": "<oid>"
    }
    • iss is the same validated upstream issuer as in sub_id.
    • claim is the upstream's existing subject_claim setting, or "sub" when it is unset.
    • value is that claim's value from the validated ID token. This is exactly the value ToolHive already
      resolves to key its own local user (OIDCProviderImpl.resolveSubject), so no new config is needed.
    • It is emitted for every OIDC upstream, also when claim is "sub" and the value duplicates
      sub_id.sub (Okta, Google, Keycloak). Consumers always key on one claim, and the key does not
      silently change shape when an operator sets subject_claim later.
    • The tenant is scoped by iss: the upstream issuer check is strict (no SkipIssuerCheck), so an Entra
      upstream must use a tenant-specific issuer, and iss pins tid and the endpoint version. No tid
      member. A v1/v2 endpoint switch changes iss and therefore the identifier; this is documented.
  3. Policy: no new setting. The claim is cleared and recomputed with sub_id on every token request and
    only appears when sub_id does. Disclosing oid is a stronger cross-app correlator than a pairwise
    sub; the docs say so.

  4. Storage: replace the two provenance string fields (VerifiedUpstreamIssuer, VerifiedUpstreamSubject)
    on every type with one value-type struct that also stores the stable claim name and value. No released
    version has the old fields, so changing the shape now is free. Adding members later would make replicas
    running this version drop them on every rewrite and force re-logins.

  5. Capture rules are unchanged: only from a validated upstream OIDC ID token, only on the callback that
    establishes the local user (first leg), never from userInfo, OAuth2 identityFromToken, refresh
    responses, or client input. Synthetic and pure OAuth2 identities get neither claim.

  6. (claim, value) is fixed at login. A later subject_claim config change applies at the user's next
    login (it also re-keys ToolHive's own sub; the next upstream refresh under the new config already
    fails with ErrSubjectMismatch), never at refresh. Recomputing claim at refresh would pair a new
    claim name with an old value. The disclosure policy, by contrast, applies at the next refresh.

  7. The value is only a safe ownership key when the claim is an immutable, never-reassigned,
    IdP-controlled identifier (sub; Entra oid). email, preferred_username, upn and unique_name
    can be reassigned to another person (Entra email is not even verified). This is not new risk inside
    ToolHive (the same value already keys the local user) but consumers will treat an exported key as
    authoritative, so the docs tell them to allowlist (iss, claim) pairs and fail closed. No code change
    restricts subject_claim in this PR.

  8. Consumers compare the full (iss, claim, value) as exact strings, never value alone. iss must be
    identical on both sides: Entra v1 vs v2, Okta org vs custom authorization server, custom URL domains and
    B2C tfp issuers all give a different iss for the same person. Multi-tenant Entra authorities
    (common, organizations) cannot be used as an upstream at all, because the issuer check is strict.

Storage member names (stable_claim, stable_value) differ from the emitted ones (claim, value) on
purpose: the stored object also holds the raw sub, so value alone would be ambiguous there.

Why a value-type struct and omitzero

All four members are strings, so a value type copies safely with plain assignment (no pointer aliasing in
memory storage clones, no nil checks). go.mod is go 1.27, so encoding/json supports the omitzero
tag option, which omits a zero struct.

Special notes for reviewers

  • Size: this PR changes about 520 non-test lines across 15 non-test files, which is over the 400-line and 10-file limits. It is one feature: the claims are useless without the stored identity, and the stored identity is only there for the claims. Splitting them would leave a PR that stores data nothing reads. About 1,250 further lines are tests.
  • Rolling upgrade and rollback: replicas running an older version drop the stored identity. They also issue a sub_id already present in a stored refresh session again without checking the disclosure setting. The safe order is to roll out with disclosure off and enable it once no older replica is left. To roll back, turn disclosure off first. Details are in Storage and upgrades.
  • Sessions from before the upgrade have no stored identity, so they get neither claim until the user logs in again.
  • sub_id.sub is the raw ID-token sub even when subject_claim maps the local user to another claim. RFC 9493 iss_sub requires the issuer's own sub. The stable key is the job of upstream_subject.
  • Device flow: the token gets the client's full audience list, so device-flow tokens carry the claims only if every one of the client's audiences is listed.

@github-actions github-actions Bot added the size/XL Extra large PR: 1000+ lines changed label Oct 22, 2026
@codecov

codecov Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.73418% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.91%. Comparing base (76b09c0) to head (03d11af).

Files with missing lines Patch % Lines
pkg/authserver/config.go 83.33% 1 Missing ⚠️
pkg/authserver/server/provider.go 93.33% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6908      +/-   ##
==========================================
- Coverage   79.94%   79.91%   -0.04%     
==========================================
  Files         833      833              
  Lines       84977    85086     +109     
==========================================
+ Hits        67938    67999      +61     
- Misses      17034    17082      +48     
  Partials        5        5              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

ChrisJBurns
ChrisJBurns previously approved these changes Oct 22, 2026
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Oct 22, 2026
jhrozek and others added 2 commits October 22, 2026 21:40
Clients that host sessions for a user, such as Mecatl, need to know
which person at the company identity provider a token belongs to.
Access tokens only carried the auth server's own sub.

Add an RFC 9493 sub_id claim ({"format":"iss_sub"}) with the issuer and
subject of the validated upstream OIDC ID token to access tokens from
authorization-code and device-flow logins and their refreshes.
Disclosure is off by default and enabled per audience. Every entry
must be a member of the allowed audiences, and the claims are only
added when every audience of the token is listed.

The raw upstream sub is not stable everywhere: Microsoft Entra ID
issues a different sub per app registration. Alongside sub_id, add
https://toolhive.dev/upstream_subject = {iss, claim, value}, where
claim is the upstream's subject_claim (or "sub") and value is that
claim's value from the same ID token, the value ToolHive already keys
its local user on. With subject_claim: oid on Entra, it stays the same
across app registrations. Consumers that need a stable key should
compare all three members, not sub_id. claim and value are fixed at
login; the disclosure setting applies at every refresh. Both claims
use one opt-in, and since oid correlates a user across apps in a
tenant, only first-party audiences should be listed.

The setting is reachable from Go only: runner callers pass
runner.WithSubjectIdentifierAudiences, and authserver.New callers set
Config.SubjectIdentifierAudiences. It is deliberately not a RunConfig
field, so it stays out of the published API schema, the SDK, config
files and operator CRDs while the feature settles.

Promoting it to RunConfig later is additive: add an omitempty
subject_identifier_audiences field and its validation to RunConfig,
map it into Config in the runner, regenerate the API docs and SDK, and
fail construction if both the field and the option are set. Deprecate
the option, move Mecatl to the field, then remove the option. Older
binaries ignore the unknown field, so disclosure stays off until they
are upgraded. A CRD field can follow in a separate change.

The verified upstream identity comes only from the first upstream
login that establishes the user, never from client input. Synthetic
and pure OAuth2 identities never get either claim. The identity is
stored with the pending authorization, pending device confirmation,
device request and token session even when disclosure is off, and
every token request clears and recomputes both claims, so policy
changes apply at the next refresh. Token exchange never carries either
claim over from a subject token.

MarkDeviceRequestAuthorized now takes a DeviceAuthorization struct, so
storage decorators that forward it must be updated.

Fixes: #6900

Co-authored-by: Mecatl <[email protected]>
A SingleLeg authorization connects one backend and never establishes
the local user, so the upstream it authenticates against must not
supply the sub_id provenance carried into issued tokens.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Oct 22, 2026
@jhrozek
jhrozek merged commit 5c8427b into main Oct 22, 2026
57 of 58 checks passed
@jhrozek
jhrozek deleted the sub-ns branch October 22, 2026 20:40
rdimitrov pushed a commit that referenced this pull request Oct 27, 2026
Since #6908 the auth server stored the verified upstream identity
(issuer, subject, stable claim and value) at every login, even when
SubjectIdentifierAudiences was empty. Its only reader turns it into the
sub_id and upstream_subject claims, and only for listed audiences. With
the default empty list, every write was stored data nobody reads, and
deployments that keep upstream identity out of storage had to strip it
in their own storage layer.

Record the identity at login only when SubjectIdentifierAudiences is
not empty. Both login paths, the authorization-code callback and the
device verification flow, now ask one helper,
Handler.recordedUpstreamIdentity, so a future login path cannot forget
the check. Nothing downstream changes: a zero value already means "no
claim". Behaviour with disclosure on is unchanged.

This reverses a choice made in #6908, which stored the identity so that
a policy change applied at the next refresh. Now, going from an empty
list to a non-empty one adds the claims only to sessions whose login
happened while the list was non-empty. Other users get them from their
next login. Adding an audience to a list that is already non-empty
still applies at the next refresh, and emptying the list still stops
the claims at the next refresh.

Sessions created on v0.57.0 already hold the stored identity and keep
it until their refresh token expires. There is no cleanup step.

Update the SubjectIdentifierAudiences docs and the auth server storage
architecture page to describe both cases, tell consumers not to switch
a user's key based on whether sub_id is present, and note that a
rolling restart leaves some logins unrecorded.

Fixes #6955

Co-authored-by: Mecatl <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Extra large PR: 1000+ lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Emit sub_id (RFC 9493) with the user's upstream identity in access tokens

2 participants