Skip to content

Add opt-in at+jwt typ for embedded AS access tokens - #6942

Merged
jhrozek merged 8 commits into
stacklok:mainfrom
jhrozek:jwt-plus-at
Oct 26, 2026
Merged

jhrozek merged 8 commits into
stacklok:mainfrom
jhrozek:jwt-plus-at

Conversation

@jhrozek

@jhrozek jhrozek commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Summary

RFC 9068 §2.1 says JWT access tokens must carry the JOSE header typ: at+jwt, and §4 says resource servers must check it. The type is what lets a resource server tell an access token apart from another JWT with the same issuer and audience. Access tokens from the embedded authorization server always carry fosite's default typ: JWT. Two things make this matter now:

  • Mecatl, which embeds this authorization server, refuses access tokens for its API that are not typed at+jwt, so sign-in fails.
  • The server is about to issue a second kind of JWT under the same issuer: ID-JAGs (ID-JAG issuance through token exchange #6898), typed oauth-id-jag+jwt.

This adds an opt-in, Go-only setting for the access-token typ. The default stays JWT.

  • authserver.Config.AccessTokenType and runner.WithAccessTokenType accept "" / "JWT" (the default) or "at+jwt". Any other value fails server construction. Following the subject identifier audiences setting (Add opt-in upstream subject identifiers #6908), it is deliberately not a RunConfig field yet, so config files, the CLI and operator CRDs can't set it.
  • When the setting is at+jwt, createProvider wraps fosite's access-token signer so every JWT access token is signed with typ: at+jwt. That covers the authorization code (+PKCE), refresh, device code, RFC 8693 token exchange, RFC 7523 JWT-bearer and ID-JAG redemption grants. With the default, the signer is not wrapped, and the code path is the one used today.
  • Tests decode the JOSE header for every grant in both configurations. They also check:
    • a change to the setting takes effect at the next refresh, with no typ stored in the session
    • an at+jwt access token is still refused as a JWT-bearer assertion
    • token exchange accepts an at+jwt subject token
    • the pkg/auth token validator, which the vMCP also uses, accepts JWT, at+jwt and no typ
  • Docs: a new "Access token type" section in docs/arch/11-auth-server-storage.md.

Fixes #6941

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)

Targeted go test runs of every new and changed test, all passing:

  • TestValidateAccessTokenType
  • TestNewAuthorizationServerConfig_AccessTokenType
  • TestATJWTAccessTokenSigner_Generate
  • TestConfigValidateAccessTokenType
  • the TestNewEmbeddedAuthServer subtests and TestWithAccessTokenTypeReplacesValue
  • TestIntegration_AccessTokenType
  • TestIntegration_AccessTokenTypeAppliesAtRefresh
  • TestIntegration_AccessTokenAtJWTRefusedAsJWTBearerAssertion
  • TestValidateAssertionType_Typ
  • TestTokenValidator

Plus the neighbouring integration tests whose helpers changed.

Mutation check: with the createProvider wiring disabled, every at+jwt integration case fails and the default cases still pass.

Changes

File Change
pkg/authserver/server/provider.go AccessTokenTypeJWT / AccessTokenTypeATJWT, ValidateAccessTokenType, the AccessTokenType field on params and config (normalized to JWT)
pkg/authserver/server/access_token_signer.go New: signer wrapper that sets typ: at+jwt on a copy of the header
pkg/authserver/server_impl.go Map the setting into params. Install the wrapper in createProvider when the setting is at+jwt
pkg/authserver/config.go Config.AccessTokenType and its validation
pkg/authserver/runner/embeddedauthserver.go WithAccessTokenType option
docs/arch/11-auth-server-storage.md, docs/arch/README.md "Access token type" section and index entry
tests Unit, integration and consumer tests listed above

Does this introduce a user-facing change?

For Go embedders only.

  • Before: every access token from the embedded authorization server has typ: JWT.
  • After: the same by default. An embedder that passes runner.WithAccessTokenType("at+jwt") (or sets Config.AccessTokenType) gets typ: at+jwt on access tokens from every grant.

Deployments through thv, the vMCP or the operator can't set it and see no change.

Special notes for reviewers

  • Why the signer and not the session. Redis stores each session's JWT header with the session. A typ set in session.New would therefore keep its old value across refreshes after the setting changes. It would also need all six call sites changed. The wrapper sets the type when the token is signed instead, on a copy of the header, so a stored session is never changed. TestIntegration_AccessTokenTypeAppliesAtRefresh checks both directions of a change and that the stored session has no typ.
  • Only access tokens go through this signer. Auth codes and refresh tokens use the HMAC strategy, and no ID-token strategy is registered. ID-JAG issuance (ID-JAG issuance through token exchange #6898) must sign with its own signer, or its tokens would be typed at+jwt. A comment in createProvider says so.
  • No client credentials grant. The issue lists it, but this server registers no client credentials grant.
  • Why the default stays JWT. Nimbus JOSE+JWT's default type verifier accepts only JWT or no typ. Spring Security's NimbusJwtDecoder used that default before 6.5, so Java resource servers on those versions reject at+jwt. 6.5 added validateType, which defaults to off. The setting is Go-only, so thv, vMCP and operator users couldn't opt out of an at+jwt default. Planned follow-up: make the setting a RunConfig field, then switch the default with a release note.
  • Validation runs twice. Both Config.Validate and validateParams validate the value. This matches how SubjectIdentifierAudiences is checked, and the second check covers direct callers of NewAuthorizationServerConfig.
  • Consumers are tested, not changed. Enforcing typ on the consuming side is out of scope, as the issue says.

Implementation plan

Approved implementation plan

Plan: optional typ: at+jwt on embedded AS access tokens (#6941)

Worktree: .worktrees/jwt-plus-at, branch jwt-plus-at. One PR. Fixes #6941, part of #6886.

Decisions

# Decision Why
D1 Default JWT; at+jwt is opt-in Nimbus's default type check (and so Spring Security before 6.5) accepts only JWT or no typ. A Go-only setting gives thv, vMCP and operator users no way to opt out, so the default must not change.
D2 Go-only setting: authserver.Config.AccessTokenType + runner.WithAccessTokenType Same pattern as WithSubjectIdentifierAudiences (#6908). Stays out of RunConfig, the API schema, the SDK and the CRDs while it settles. Adding a RunConfig field later only adds to the API.
D3 Set typ in a wrapper around the access-token signer, not in the session Redis stores the session's JWT header (storage/redis.go marshalRequester). A typ set per session would stay stale across refreshes after the setting changes, and would need all six session.New call sites.
D4 Install the wrapper only for at+jwt With the default, the code path is byte-for-byte what runs today.
D5 Allowed values: JWT, at+jwt. Empty means JWT. Anything else fails validation. Matches the issue. application/at+jwt is not offered: RFC 9068 allows it, but no consumer needs it.
D6 No change on the consuming side The issue puts enforcement out of scope. golang-jwt v5 ignores typ, so we only add tests.

Background (verified)

  • Fosite v0.49.0 Token.toJoseHeader writes typ: JWT first and then lets values from the header map replace it. A typ in the header handed to Signer.Generate therefore wins.
  • DefaultJWTStrategy.generate (handler/oauth2/strategy_jwt.go:131) is the only caller of Signer.Generate, and it runs only for access tokens. Refresh tokens and auth codes go through the HMAC strategy. ToolHive registers no OpenID Connect factory, so it issues no ID tokens.
  • Grants that issue access tokens through this strategy:
    • authorization code + PKCE
    • refresh
    • device code (deviceflow/handler.go:192)
    • RFC 8693 token exchange
    • RFC 7523 JWT-bearer
    • ID-JAG redemption (bound JWT-bearer)
  • ToolHive registers no client credentials grant, although the issue lists one. Say so in the PR body and on the issue.
  • validateAssertionType (tokenexchange/jwt_bearer_handler.go:376) accepts an empty typ, JWT or oauth-id-jag+jwt, so it already refuses an at+jwt access token presented as an assertion.
  • pkg/auth/token.go:1136 uses golang-jwt v5 jwt.Parse, which does not check typ. The vMCP's incoming auth uses the same validator (pkg/auth/utils.go:73). The token-exchange subject/actor token validator does not check typ either.

Implementation steps

Step 1: Config plumbing

  • pkg/authserver/server/provider.go
    • Add exported constants: AccessTokenTypeJWT = "JWT" and AccessTokenTypeATJWT = "at+jwt".
    • Add an AccessTokenType string field to AuthorizationServerParams and to AuthorizationServerConfig, with doc comments.
    • Add ValidateAccessTokenType(string) error (empty is OK) and call it from validateParams.
    • NewAuthorizationServerConfig copies the field, normalizing empty to JWT.
  • pkg/authserver/config.go
    • Add Config.AccessTokenType with a doc comment (default JWT; at+jwt per RFC 9068 §2.1; Go-only).
    • Validate it in Config.Validate, using the same validator.
  • pkg/authserver/server_impl.go newServer: map cfg.AccessTokenType into oauthParams.
  • pkg/authserver/runner/embeddedauthserver.go
    • Add accessTokenType to embeddedAuthServerOptions.
    • Add WithAccessTokenType(typ string) EmbeddedAuthServerOption. The godoc says:
      • what each value does and that JWT is the default
      • the Spring/Nimbus risk
      • that it is deliberately not a RunConfig field
      • that repeated options replace each other
    • Map it into Config in newEmbeddedAuthServerWithStorage.

Step 2: Signer wrapper

  • New file pkg/authserver/server/access_token_signer.go, with the SPDX header:
    // typedAccessTokenSigner sets the JOSE "typ" header on every token signed by
    // the access-token strategy. It writes into a copy of the header, so the
    // session (which storage persists) is never changed.
    type typedAccessTokenSigner struct {
        jwt.Signer
        typ string
    }
    
    func (s *typedAccessTokenSigner) Generate(ctx context.Context, claims jwt.MapClaims, header jwt.Mapper) (string, string, error) {
        hdr := map[string]any{}
        if header != nil {
            hdr = header.ToMap() // ToMap returns a new map
        }
        hdr[string(jwt.JWTHeaderType)] = s.typ
        return s.Signer.Generate(ctx, claims, &jwt.Headers{Extra: hdr})
    }
    Export a constructor (NewTypedAccessTokenSigner, or a helper WrapAccessTokenSigner(strategy *oauth2.DefaultJWTStrategy, typ string)) so createProvider in package authserver can use it. Validate, Decode and the other methods pass straight through to the embedded signer.
  • pkg/authserver/server_impl.go createProvider: after compose.NewOAuth2JWTStrategy(...), wrap the signer when the setting is at+jwt:
    if authServerConfig.AccessTokenType == oauthserver.AccessTokenTypeATJWT {
        jwtStrategy.Signer = oauthserver.NewTypedAccessTokenSigner(jwtStrategy.Signer, authServerConfig.AccessTokenType)
    }
    Add a comment at this spot:

Step 3: Tests (all of them decode the JOSE header)

  • Shared test helper: jwtHeaderTyp(t, token) string. It splits the token, base64url-decodes the first segment, unmarshals it and returns typ. It fails the test if typ is missing, unless a variant asserts that it's absent.

  • Unit tests, pkg/authserver/server/access_token_signer_test.go:

    • typ gets set to at+jwt.
    • kid and any other header entries are kept.
    • The caller's jwt.Headers.Extra is not changed.
    • A nil header still produces a token.
    • Validate on a token from the wrapper succeeds.
  • Config tests in provider_test.go, config_test.go and runner/embeddedauthserver_test.go:

    • Empty, JWT and at+jwt are valid. at+JWT, application/at+jwt and foo are rejected.
    • The runner option reaches Config, and a repeated option replaces the earlier one.
  • Integration tests in pkg/authserver/integration_test.go. Run the table twice, once with the default and once with at+jwt, and check the header typ for each grant:

    1. authorization code + PKCE
    2. refresh
    3. device code
    4. RFC 8693 token exchange (the subject token is itself an at+jwt access token, so this also checks that an at+jwt subject is accepted)
    5. RFC 7523 JWT-bearer
    6. ID-JAG redemption

    The default run expects JWT, the at+jwt run expects at+jwt.

  • Setting changed while sessions exist:

    • Issue a token with the default, against storage that both servers share (memory works; add a miniredis variant if the existing tests already have one).
    • Build a second server on the same storage with at+jwt and refresh with it.
    • The new access token must have typ: at+jwt.
    • The session reloaded from storage still has no typ in its JWT header.
  • Assertion refusal: an access token this AS issued with at+jwt, presented as a jwt-bearer assertion, gets invalid_grant. Add a table case to the existing validateAssertionType tests and one integration-level case.

  • Consumers:

    • pkg/auth TokenValidator accepts RS256 tokens with typ: JWT, typ: at+jwt and no typ (a table case next to the existing validator tests).
    • The vMCP uses this same validator, so the pkg/auth test covers it. Add a vMCP-level test only if one already exercises incoming auth against an AS-issued token cheaply.

Step 4: Docs

  • Add a short "Access token format" section to the auth server architecture doc. If no such section exists, put it in docs/arch/17-token-exchange-delegation.md or the auth server part of docs/arch/11-auth-server-storage.md, wherever the access-token claims (tsid, sub_id) are already described. It covers:
    • typ is JWT by default, or at+jwt with WithAccessTokenType
    • which grants are affected
    • that ID-JAGs keep oauth-id-jag+jwt
    • that ToolHive's own consumers accept both values
  • Godoc on WithAccessTokenType and Config.AccessTokenType (step 1).
  • No task docs run is needed: no CLI or API change.

PR

  • Title: Add opt-in at+jwt typ for embedded AS access tokens
  • Body, following .github/pull_request_template.md:
    • Summary:
    • Type of change: New feature.
    • User-facing change: Before, every access token has typ: JWT. After, the same by default; Go embedders that set WithAccessTokenType("at+jwt") get typ: at+jwt from every grant.
    • Special notes:
      • The signer wrapper instead of per-session typing, and why (D3).
      • Client credentials isn't registered.
      • The ID-JAG signer must stay separate (ID-JAG issuance through token exchange #6898).
      • Why the default stays JWT and the setting stays Go-only, and the Spring/Nimbus research.
      • The follow-up: promote to a RunConfig field, then flip the default with a release note.
    • Implementation plan: this file, in a <details> block.
  • Size: about 100 to 150 lines of non-test code in about 6 files, within the limits.

Work breakdown

Steps 1–4 above are split into work items. Small items go to a Haiku worker and large items to a Sonnet worker (go-expert-developer with a model override). An Opus reviewer checks every result.

Item Size / worker Content (refers to the steps above) Files Depends on
W1 Small / Haiku Step 1, server part: the two constants, ValidateAccessTokenType, the fields on AuthorizationServerParams / AuthorizationServerConfig, the call in validateParams, normalizing empty to JWT in NewAuthorizationServerConfig. Validator table test in provider_test.go. server/provider.go, server/provider_test.go none
W2 Small / Haiku Step 1, embedder part: Config.AccessTokenType + validation in Config.Validate, the mapping in newServer, runner.WithAccessTokenType + its mapping. Tests in config_test.go and runner/embeddedauthserver_test.go. Copy the WithSubjectIdentifierAudiences shape from commit 5c8427b. config.go, server_impl.go (newServer only), runner/embeddedauthserver.go, matching _test.go files W1
W3 Small / Haiku Step 2, the wrapper type and constructor only (access_token_signer.go) and its unit tests (typ set, kid kept, caller header not changed, nil header, Validate passes). Nothing gets wired in. server/access_token_signer.go, server/access_token_signer_test.go W1 (the constants)
W4 Large / Sonnet Step 2, wiring in createProvider, with the comment about ID-JAG and stale headers. Step 3 integration tests: the shared jwtHeaderTyp helper; the grant table (auth code+PKCE, refresh, device code, token exchange with an at+jwt subject token, JWT-bearer, ID-JAG redemption), run once with the default and once with at+jwt; the test where the setting changes between issue and refresh; the integration-level assertion refusal. Needs to learn the existing integration harness. server_impl.go (createProvider), integration_test.go W2, W3
W5 Small / Haiku Step 3 unit-level checks: a validateAssertionType table case for typ: at+jwt (refused); a pkg/auth TokenValidator table case accepting JWT, at+jwt and no typ. server/tokenexchange/jwt_bearer_handler_test.go, pkg/auth/token_test.go none (test-only)
W6 Small / Haiku Step 4: the "Access token format" docs section. The worker first finds where tsid/sub_id are documented and puts the section next to them. docs/arch/… W4 (so the docs describe the code as it landed)

Order: W1 → W2 → W3 → W4 → W5 → W6. Every worker shares this worktree and commits there. Running them one at a time keeps the index from racing and leaves one commit per item. W5 has no code dependencies, so it could run in its own worktree alongside W2–W4 if speed matters.

Per-item loop

  1. Brief the worker. The brief includes:
    • the item row, plus the relevant step text and the "Background (verified)" facts from this plan
    • "stay inside the listed files"
    • "do not run task lint-fix or task test unless told to; report the commands you ran and their output"
    • the exact commit message to use: imperative subject of at most 50 characters, no Conventional Commit prefix, ending with the Co-Authored-By: Claude Opus 5.5 trailer and nothing else
  2. Check the commit. Confirm the files it touched match the item, and that the commit message and trailers are exactly what was asked.
  3. Opus review. A code-reviewer on Opus reads that commit's diff and the plan section for the item, without seeing the worker's summary. W4 also gets oauth-expert on Opus to check that the grant coverage and the stale-header test actually prove what they claim.
  4. Fix the findings. The same worker fixes every obvious in-scope finding, then Opus re-checks. Anything that is a judgment call or outside the plan goes to the user.
  5. Gate. Report the item result and the review outcome to the user, and stop before starting the next item.

Final pass

  • Once W6 is done, an Opus go-security-reviewer + code-reviewer do one blind review of the whole branch diff against main. This catches problems that span items, such as the wrapper being wired in but the default path changing anyway.
  • Run task lint-fix / task test only when the user asks.
  • Draft the PR body (see the PR section). Stop for user review before pushing or opening the PR.

Out of scope

  • Enforcing typ in ToolHive's consumers.
  • A RunConfig field, a CRD field, or flipping the default (all follow-ups).
  • Client credentials grant support.
  • ID-JAG issuance itself (ID-JAG issuance through token exchange #6898). This PR only leaves the note above.

🤖 Generated with Claude Code

@codecov

codecov Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.08%. Comparing base (9726b3f) to head (d8e1e68).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6942      +/-   ##
==========================================
- Coverage   80.09%   80.08%   -0.02%     
==========================================
  Files         839      840       +1     
  Lines       85339    85365      +26     
==========================================
+ Hits        68351    68363      +12     
- Misses      16983    16997      +14     
  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 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See the inline comments.

Comment thread pkg/authserver/server_impl.go Resolved
ChrisJBurns
ChrisJBurns previously approved these changes Oct 26, 2026
jhrozek and others added 8 commits October 26, 2026 19:12
The embedded authorization server will optionally type its JWT
access tokens as at+jwt (RFC 9068). Add the setting and its
validation to the server parameters; the default stays JWT.

Co-authored-by: Mecatl <[email protected]>
Add Config.AccessTokenType and runner.WithAccessTokenType so an
embedder can type access tokens as at+jwt. The setting is Go-only,
like the subject identifier audiences, and defaults to JWT.

Co-authored-by: Mecatl <[email protected]>
Wrap fosite's JWT signer so every access token it signs carries
the JOSE header typ: at+jwt (RFC 9068). The header is copied first,
so the stored session header is never changed.

Co-authored-by: Mecatl <[email protected]>
Install the at+jwt signer in the provider when AccessTokenType is
at+jwt. Integration tests decode the JOSE header for every grant
that issues access tokens, check that a configuration change takes
effect at the next refresh, and check that an access token is still
refused as a JWT-bearer assertion.

Co-authored-by: Mecatl <[email protected]>
Test that the JWT-bearer grant refuses an at+jwt access token as an
assertion, and that the pkg/auth token validator, which the vMCP
also uses, accepts access tokens typed JWT, at+jwt, or untyped.

Co-authored-by: Mecatl <[email protected]>
Describe the opt-in at+jwt access token type in the auth server
architecture docs: which tokens it affects, when a change takes
effect, how ToolHive's consumers handle it, and the risk of
resource servers that only accept typ JWT.

Co-authored-by: Mecatl <[email protected]>
Correct the docs on why the server's own access tokens are never
JWT-bearer assertions, make the signer's header copy explicit, and
drop redundant or non-proving test cases.

Co-authored-by: Mecatl <[email protected]>
The access-token signer added in the previous commits set typ
at+jwt on every JWT it signed, so any future JWT routed through
the same signer, such as an ID-JAG, would be mistyped. The signer
now sets at+jwt only when the header has no typ. Access tokens
are unchanged because sessions never store a typ.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Set typ: at+jwt on access tokens issued by the embedded authorization server (RFC 9068)

2 participants