diff --git a/docs/arch/17-token-exchange-delegation.md b/docs/arch/17-token-exchange-delegation.md index 1999132e3f..5efc094162 100644 --- a/docs/arch/17-token-exchange-delegation.md +++ b/docs/arch/17-token-exchange-delegation.md @@ -568,9 +568,12 @@ grant; see [Actor-token validation at ID-JAG issuance](#actor-token-validation-a `actor_token_type` only accepts `access_token` or `jwt`; `id_token` is rejected outright. Similarly, `subject_token_type` accepts `access_token` or -`jwt`, but not `id_token`: this embedded authorization-server endpoint does -not implement the XAA/ID-JAG profile in the token-exchange slot (an ID-JAG is -accepted as a JWT-bearer *grant* assertion instead — see [Bound ID-JAG +`jwt`, but not `id_token`. A client with `exchange_refresh_tokens` may also +present a refresh-token subject (see [Refresh tokens through token +exchange](#refresh-tokens-through-token-exchange) and [Minting ID-JAGs from a +grant](#minting-id-jags-from-a-grant)). Because ID tokens are not accepted as +subjects, this endpoint is not the XAA/ID-JAG profile in the token-exchange +slot (an ID-JAG is accepted as a JWT-bearer *grant* assertion instead — see [Bound ID-JAG assertions](#bound-id-jag-assertions)) and applies exactly one validation profile to a subject or actor token (the self-issued/access-token one — see `rejectIDTokenClaims`'s doc comment in `validator.go`), so accepting a @@ -955,9 +958,9 @@ and the mode. ### ID-JAG targets A delegate client that holds ID-JAG grants can list the authorization servers it -may later get an ID-JAG for. Set `token_exchange.id_jag.targets` on the client. -Nothing issues an ID-JAG yet. At startup the block only builds the runtime -policy. The policy is keyed by the issuer exactly as configured. At request time +may get an ID-JAG for. Set `token_exchange.id_jag.targets` on the client. +Requests for an ID-JAG are described in [Minting ID-JAGs from a +grant](#minting-id-jags-from-a-grant). The policy is keyed by the issuer exactly as configured. At request time the client's `audience` parameter must equal it exactly. These settings are RunConfig-only: no CRD exposes `id_jag`. Each target has these fields: @@ -997,8 +1000,7 @@ Each target has these fields: A client with `exchange_refresh_tokens.id_jag_max_lifetime` and no `id_jag.targets` logs one DEBUG line at startup. It says the client can hold -ID-JAG grants but cannot mint ID-JAGs. The line is DEBUG until ID-JAG issuance -exists. +ID-JAG grants but cannot mint ID-JAGs. ### Worked example @@ -1490,6 +1492,24 @@ them: A strict mode would have to refuse these two as well as the four logged findings. +**Keeping AS-2 ID-JAG-only.** Trusting AS-1 as a JWT-bearer issuer at AS-2 +also lets AS-2's plain handler (`typ` `JWT`, empty or absent) accept AS-1's +access tokens. That handler needs no client authentication, applies none of the +ID-JAG checks, and issues a token with a synthetic `client_id`. It accepts the +token when its `aud` is a value AS-2 accepts (a value in `accepted_audiences`, +or AS-2's token endpoint when that list is empty) and AS-2's +`max_assertion_age` covers the token's lifetime. The subject binding and +resource checks still apply. Mitigations: + +- Set AS-1's `AccessTokenType` to `at+jwt` (Go code only). The plain handler + refuses that `typ`. Some resource servers reject `at+jwt`. +- Set AS-2's `accepted_audiences` to exactly AS-2's issuer, and keep that value + out of AS-2's `allowed_audiences`. Make sure no AS-1 client, trusted-issuer or + DCR audience equals that value or is a path prefix of it. After removing a + value from AS-1's `allowed_audiences`, remove the DCR clients and refresh + tokens granted it. +- Keep AS-2's `max_assertion_age` short. + ## Operational notes - **Audience.** The requested audience is bounded by the subject token's own @@ -1653,8 +1673,8 @@ A configured confidential client can exchange a user's login access token for an opaque refresh token. The token is not redeemable at `grant_type=refresh_token`; only token exchange accepts it. What the token may be used for is fixed when it is issued. This section describes issuing it from an access token and deriving a -child token from it. Revoking it is not covered here yet, and issuing an ID-JAG -from a grant is not implemented yet. +child token from it. Revoking it is not covered here yet. Exchanging a grant for +an ID-JAG is described in "Minting ID-JAGs from a grant". **Enabling.** Set `token_exchange.exchange_refresh_tokens` on the client, with `id_jag_max_lifetime` or both `id_jag_max_lifetime` and `refresh_token_max_lifetime` @@ -1764,9 +1784,13 @@ handler (`RefreshTokenHandler`); every other token-exchange request is handled b the access-token handler. Both use one predicate, `isRefreshTokenExchange`, so a request goes to exactly one. A refresh-token `subject_token_type` is a derive request (see "Deriving a child token") when `requested_token_type` is also the -refresh-token URN. With any other `requested_token_type`, or from a client without -`exchange_refresh_tokens`, it is refused with the unsupported `subject_token_type` -text in the error table. +refresh-token URN, and an ID-JAG request (see "Minting ID-JAGs from a grant") +when `requested_token_type` is the ID-JAG URN. Each needs its own entry in the +client's `exchange_refresh_tokens`. With any other `requested_token_type`, without +the matching entry, or from a client without `exchange_refresh_tokens`, it is +refused with the unsupported `subject_token_type` text in the error table. A +client that has the ID-JAG entry but no `id_jag.targets` and asks for an ID-JAG +gets the unsupported `requested_token_type` text instead. **Errors.** Each `error_description` is one of two kinds. The reason-code rows, the `authorization_details` rows and the internal-failure row are exact: the @@ -1780,8 +1804,9 @@ client receives them. | --- | --- | --- | | Client is public | `invalid_grant` | generic text, then a fixed hint | | Client lacks the token-exchange grant | `unauthorized_client` | generic text, then a fixed hint | -| `subject_token_type` is the refresh-token URN, and the client has no `exchange_refresh_tokens` or `requested_token_type` is not the refresh-token URN | `invalid_request` | generic text, then `The 'subject_token_type' value '' is not supported. Use '' or ''.` (unchanged from before) | +| `subject_token_type` is the refresh-token URN, and the client has no `exchange_refresh_tokens`, or `requested_token_type` is neither the refresh-token nor the ID-JAG URN, or the client lacks the `exchange_refresh_tokens` entry for the requested type | `invalid_request` | generic text, then `The 'subject_token_type' value '' is not supported. Use '' or ''.` (unchanged from before) | | `requested_token_type` is the refresh-token URN and the client has no `exchange_refresh_tokens` | `invalid_request` | generic text, then the unsupported `requested_token_type` hint (see below) | +| `subject_token_type` is the refresh-token URN, `requested_token_type` is the ID-JAG URN, and the client has the ID-JAG entry but no `id_jag.targets` | `invalid_request` | generic text, then the unsupported `requested_token_type` hint (see below) | | Missing `subject_token` | `invalid_request` | generic text, then a fixed hint | | For an access-token subject: `subject_token_type` is not the access-token URN. For any subject: `actor_token` or `actor_token_type` is present | `invalid_request` | generic text, then a fixed hint | | `scope` | `invalid_scope` | generic text, then a fixed hint | @@ -1843,7 +1868,11 @@ code is still `invalid_request`. A request whose `subject_token_type` is the refresh-token URN now goes to the refresh-token handler. A request with the refresh-token URN as both `subject_token_type` and `requested_token_type`, from a client with `exchange_refresh_tokens`, was refused before and is now a derive request (see -"Deriving a child token"). For every other client or `requested_token_type`, the +"Deriving a child token"). With the ID-JAG URN as `requested_token_type`, from a +client with the ID-JAG entry, it is now an ID-JAG request (see "Minting ID-JAGs +from a grant"), and from a client with that entry but no `id_jag.targets` it now +gets the unsupported `requested_token_type` text instead of the unsupported +`subject_token_type` text. For every other client or `requested_token_type`, the refusal text is unchanged. Check precedence changed for a refresh-token subject in one way: the `subject_token_type` refusal now comes before a missing `subject_token`. For `requested_token_type` set to the refresh-token URN from a @@ -1857,7 +1886,8 @@ longer reported first. at debug level when it issues a token, and "Exchange grant refused" at warn level for refusals after the public-client and grant checks. The public-client and missing-grant refusals are not logged this way. Each line carries `client_id`, -plus `sub`, `source_jti`, `sub_id`, `has_parent`, `issuable_token_type` and +plus `sub`, `source_jti`, `sub_id` (top-level grants only; derive lines never +carry it), `has_parent`, `issuable_token_type` and `expires_at` once they are known, and a stable `reason` on a refusal. The refresh token, its signature and the subject token are never logged. @@ -1931,8 +1961,11 @@ first that fails: 7. If the grant has a parent, the parent exists and is live. A parent that is missing, revoked or expired gives `parent_revoked`. An expired parent always means the child has expired too, because a child's `expires_at` is never later - than its parent's. So the child fails at step 3 or 5 with `grant_invalid`. -8. The grant allows `refresh_token`, else `not_issuable`. A child fails here. + than its parent's. So a child of an expired parent fails earlier, at step 5, + with `grant_invalid`. (The stores report an expired grant as not found, so it + can already fail at step 3 with the same error.) +8. The grant allows `refresh_token` and is top-level, else `not_issuable`. A + child fails here. 9. The child entry passes the rules above. Nothing about the token is revealed until step 4 has passed. A forged token, an @@ -1986,8 +2019,9 @@ without config validation. A parent can be derived from many times; each call creates an independent child. If the response is lost, the child stays until its parent ends (revoked or expired). This is accepted. Today the derive path checks the parent on every -use. The ID-JAG issuance path is not built yet, and it must check the parent's -liveness too, because a child is usable only while its parent is live. +use. The ID-JAG path (see "Minting ID-JAGs from a grant") checks the grant's and +the parent's liveness on every use as well, because a child is usable only while +its parent is live. **Logging.** A derive logs "Exchange grant derived" at debug level with `has_parent=true`. Every refusal after the public-client and grant checks is @@ -1996,6 +2030,224 @@ logged as "Exchange grant refused", including a failed HMAC check `grant_invalid` error (`not_found_or_other_client` or `token_invalid`) is internal and is never sent to the client. +## Minting ID-JAGs from a grant + +A client that holds an exchange grant (see "Refresh tokens through token +exchange") can exchange the grant's refresh token for an Identity Assertion JWT +Authorization Grant (ID-JAG): a short-lived signed JWT that another +authorization server redeems at its own token endpoint. "The draft" below is +draft-ietf-oauth-identity-assertion-authz-grant, revision 06. + +### Roles and limits + +The embedded authorization server issues ID-JAGs through RFC 8693 token +exchange. It is a partial *IdP Authorization Server* (draft section 2.1). Its +only subject token is the refresh token of an exchange grant. The `iss` and +`sub` of an ID-JAG are its own, so AS-2 must trust ToolHive's issuer directly. + +| Role | Who | +| --- | --- | +| AS-1 | The embedded authorization server that holds the grant and issues the ID-JAG | +| AS-2 | The authorization server that redeems the ID-JAG | +| Client | The confidential delegate client at AS-1 (the "broker") that holds the grant | + +It does not meet draft section 4.3 in full and is not a Cross App Access +identity provider. Not supported: + +- ID tokens, or an ordinary login refresh token, as the subject. +- `scope`. Exchange grants record no scopes, so every `scope` is refused. +- Metadata. Discovery does not advertise the ID-JAG token type (draft section + 7.1), and targets are not discovered. + +### Request and response + +`POST /oauth/token` from a confidential client with the token-exchange grant, +`exchange_refresh_tokens` and `id_jag.targets`: + +```http +POST /oauth/token HTTP/1.1 +Host: as1.example.com +Content-Type: application/x-www-form-urlencoded + +grant_type=urn:ietf:params:oauth:grant-type:token-exchange +&subject_token= +&subject_token_type=urn:ietf:params:oauth:token-type:refresh_token +&requested_token_type=urn:ietf:params:oauth:token-type:id-jag +&audience=https://as2.example.com +&resource=https://gw.example.com/mcp +&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer +&client_assertion= +``` + +`audience` must be exactly one target `issuer` and `resource` exactly one of +that target's `resources`, both as written. `scope`, `authorization_details` +and `actor_token` are refused. Unknown parameters, including `sub`, are +ignored. The response is `200` with `Cache-Control: no-store`: + +```json +{ + "access_token": "", + "issued_token_type": "urn:ietf:params:oauth:token-type:id-jag", + "token_type": "N_A", + "expires_in": 60 +} +``` + +There is no `refresh_token` and no `scope`. The ID-JAG's header `typ` is +`oauth-id-jag+jwt`, and it is signed with AS-1's access-token key. Its claims +are listed in "Claims and subject". + +### Checks and errors + +The server stops at the first check that fails: + +1. The client: confidential, with the token-exchange grant, and with both + `exchange_refresh_tokens` and `id_jag.targets`. A client with an actor + profile then gets `400 unauthorized_client` before anything else is + checked (see [Fail-closed guard](#fail-closed-guard)). +2. The request shape, then a target of this client that lists the `resource`. + Nothing is read from the store yet. +3. The grant: an unknown, forged, foreign, login or expired token all get + `grant_invalid`. Then revoked, parent revoked, and `not_issuable` when the + grant does not list the ID-JAG output. +4. The claims the target requires must have been recorded at login. + +An `error_description` is either a *stable reason*, the whole text, which is +safe to match on, or a *hint* that can change (match on `error`). Grant problems +use `invalid_request`, as RFC 8693 section 2.2.2 requires. The stable reasons +are `grant_invalid`, `revoked`, `parent_revoked`, `not_issuable`, +`upstream_subject_missing`, `sub_id_missing` and `dpop_not_supported`. Store and +signing failures give `server_error` with no detail. An ID token as the subject +is refused with the unsupported `subject_token_type` hint. + +A missing `resource` gives `invalid_target`, as draft section 4.3.3 requires +when the IdP requires `resource`. More than one `audience` gives +`invalid_request`, as section 4.3.3 requires. + +ToolHive departs from the draft in these places: + +- Another client's target gets `invalid_target`, not the draft's + `access_denied`, so it looks like an unknown one. +- More than one `resource` is refused with `invalid_target`. The draft lets the + IdP grant a subset and put an array in the `resource` claim. +- A request with a `DPoP` header is refused with `400`, `invalid_request` and + the description `dpop_not_supported`, with no hint, after any other refusal. + Draft section 9.11.1.1 says the IdP MUST validate the proof and bind the + ID-JAG with `cnf`, which ToolHive cannot do yet, and silently issuing an + unbound token would be worse. AS-1 logs one Warn line with the `client_id`. + +### Targets + +Targets are configured on the delegate client that holds the grants. Each +target names AS-2 and the resources AS-2 protects. The fields and their +startup checks are in [ID-JAG targets](#id-jag-targets); startup also requires +the client to be `restricted` and to set `id_jag_max_lifetime`. + +```yaml +# AS-1: issuer https://as1.example.com +inbound_grants: + token_exchange: + delegate_clients: + - client_id: broker # auth settings omitted + token_exchange: + self_issued_subject_tokens: restricted + allowed_source_clients: [mcp-client] + subject_token_audiences: [https://broker.example.com/api] + exchange_refresh_tokens: + id_jag_max_lifetime: 12h # how long the GRANT may live + id_jag: + targets: + - issuer: https://as2.example.com # AS-2: the request's `audience`, the ID-JAG's `aud` + client_id: broker-at-as2 # the broker's client_id registered at AS-2 + resources: [https://gw.example.com/mcp] # behind AS-2: the request's `resource` + lifetime: 60s # how long each ID-JAG lives +``` + +**Two lifetimes.** `id_jag_max_lifetime` caps the grant (at most 720h). The +target's `lifetime` is each ID-JAG's life (60s by default). The ID-JAG's `exp` +is the earliest of now plus `lifetime`, the grant's expiry, and the grant's +creation plus the client's current `id_jag_max_lifetime`. Lowering the cap +therefore also limits grants already issued; a grant past the new cap is refused +like an expired one. + +**Why `SubjectIdentifierAudiences` matters.** A login records the upstream +identity on the grant only when the login token's audience is in +`SubjectIdentifierAudiences` (see the target fields). If an entry of the +broker's `subject_token_audiences` is missing there, a target that requires +`upstream_subject` or `sub_id` always fails with `_missing`. + +### Claims and subject + +| Claim | Type | Value | +| --- | --- | --- | +| `iss` | string | AS-1's access-token issuer | +| `sub` | string | AS-1's own ID for the grant's user. Never empty | +| `aud` | string | The target's `issuer` as configured. Always a string, never an array | +| `client_id` | string | The target's `client_id`: the client at AS-2 that may redeem the ID-JAG | +| `jti`, `iat`, `exp` | string, integers | A random UUID, then whole seconds | +| `resource` | string | The requested resource | +| `sub_id` | object | Only if the target requires it: `{"format": "iss_sub", "iss", "sub"}` (RFC 9493) | +| `https://toolhive.dev/upstream_subject` | object | Only if the target requires it: `{"iss", "claim", "value"}`. The config calls it `upstream_subject` | + +There is no `nbf`, `scope`, `cnf`, `authorization_details` or `act` claim. The +client in `client_id` acts for the user. + +`sub` is the same for every audience. AS-1 draws it as a random UUID at the +user's first login. With memory storage a restart gives every user a new `sub`, +and AS-2 subject bindings stop matching. It also changes if the upstream's +`subject_claim` is changed after users exist. + +`sub`, `sub_id` and `upstream_subject` come from what the grant recorded at +login. AS-1 does not read them again from the upstream when it mints, so an +upstream change shows up only in grants from a later login. + +### Grant reuse and revocation + +Minting writes nothing to the store. It does not use up the grant, so one grant +can mint many ID-JAGs, each with a new `jti`. AS-2 records each `jti` and +refuses a second use. A revocation stops the next mint; an ID-JAG already +issued stays valid until its `exp`. + +Minting also needs the ID-JAG entry in the client's *current* +`exchange_refresh_tokens` policy. Removing that entry stops minting from grants +the client already holds, the same way removing the `refresh_token` entry stops +derives. + +For an ID-JAG request the token endpoint does not check `resource` against +`allowed_audiences` or grant it as an audience: it names a resource behind +AS-2, and the target's `resources` list is the only check. + +### Keeping ID-JAGs apart from access tokens + +An ID-JAG is signed with AS-1's access-token key. Its `typ`, +`oauth-id-jag+jwt`, is kept even when `AccessTokenType` is `at+jwt`, and +ToolHive's access-token and subject-token validators refuse it. No target +issuer may be an audience AS-1 accepts, so an ID-JAG's `aud` never passes +AS-1's own audience checks. Always set `--oidc-audience` on resource servers: +with an empty audience `pkg/auth` skips the audience check. + +### Redemption and known gaps + +See [Bound ID-JAG assertions](#bound-id-jag-assertions) for how AS-2 redeems +the ID-JAG. A ToolHive AS-2 finds the user by an exact AS-1 `sub` in +`subject_bindings`, and its `max_assertion_age` must be at least the target's +`lifetime`. Known gaps: + +- AS-2 takes the resource from the request form when it is present, and only + logs `resource_not_covered` when the `resource` claim does not list it. So an + ID-JAG minted for one resource redeems for any other resource in the subject + binding's `allowed_resources` and the client's audiences. +- An AS-1 access token can redeem as a plain JWT-bearer assertion (see + "Keeping AS-2 ID-JAG-only"). + +### Logging + +Minting is not audited. A refusal logs "Exchange grant refused" at Warn with +the reason and without `sub_id`. A successful mint is one Debug line, +`ID-JAG minted`, with `client_id`, `sub`, `target`, `resource`, `has_parent`, +`jti` and, when recorded, `sub_id`. The subject token, the ID-JAG, any +assertion, the form, the DPoP proof and `upstream_subject` are never logged. + ### Actor-token validation at ID-JAG issuance An ID-JAG can name the acting agent in its `act` claim (ID-JAG draft -06, @@ -2120,9 +2372,9 @@ already done so. #### Fail-closed guard -`checkIDJAGRequest` returns `server_error` ("Actor-token validation is not -available.") for a client that has an actor profile, before it reads any request -parameter. A client the operator configured to require an actor check therefore gets no +`checkIDJAGRequest` returns `400 unauthorized_client` ("Actor-token validation +is not available.") for a client that has an actor profile, before it reads any +request parameter. A client the operator configured to require an actor check therefore gets no ID-JAG until the check is wired in. The change that adds the validator call to issuance replaces this guard. @@ -2135,9 +2387,11 @@ and it belongs in the embedder's validator. - `pkg/authserver/server/tokenexchange/actor_validator.go` — `ActorTokenValidator` and its contract, `ActorValidatorRegistration`, `ActIssuerProblem`, `ActorProfile` - `pkg/authserver/server/tokenexchange/handler.go` — `checkSourcePolicy`, `ConfiguredClientPolicy`, `checkDelegationConsent`, `grantScopes`, `grantAndBoundAudiences`, `externalOrigin`, `IDJAGTarget`, `ConfiguredClientPolicy.IDJAGTargets`, `ConfiguredClientPolicy.ActorProfile` -- `pkg/authserver/server/tokenexchange/id_jag_mint.go` — `checkIDJAGRequest`, including the fail-closed guard for a client with an actor profile - `pkg/authserver/server/tokenexchange/refresh_token_handler.go` — `RefreshTokenHandler`, `isRefreshTokenExchange`, `checkLoginToken`, `checkExchangeGrantSubject` - `pkg/authserver/server/tokenexchange/exchange_grant.go` — the exchange-grant entry type and its validation +- `pkg/authserver/server/tokenexchange/id_jag_mint.go` — the ID-JAG minting core: `checkIDJAGRequest` (including the fail-closed guard for a client with an actor profile), `selectSubjectClaims`, `respondWithIDJAG`, `mintIDJAG` +- `pkg/authserver/server/tokenexchange/refresh_token_id_jag.go` — `decideIDJAG`, `issueIDJAG`: the grant checks and the Debug line for an ID-JAG +- `pkg/authserver/server/id_jag_seam.go` — `OwnsResourceParameter`, `ReasonDPoPNotSupported`; the token endpoint calls them from `pkg/authserver/server/handlers/token.go` - `pkg/authserver/server/tokenexchange/multi_issuer_validator.go` — `MultiIssuerTokenValidator`, `TrustedIssuer`, `resolveActorAuthorization`, `ValidateJWKSURL` - `pkg/authserver/server/tokenexchange/validator.go` — `assignClaim`, `buildValidatedClaims`, `validateMayActShape`, `scpToScopeString` - `pkg/authserver/config.go` — `DelegateClientRunConfig`, delegate-client validation, `validateTrustedIssuerURL`, `validateJWKSEndpointURL`, `validateTrustedIssuers`, `warnTrustedIssuerAudiences`, `Config.ActorTokenValidators`, `DelegateClientTokenExchange.ActorProfile`, `validateActorTokenValidatorMap`, `validateActIssuer`, `validateActorProfilesRegistered`, `validateActorProfile`, `validateActorTokenType`, `ValidateActorProfilesForRunConfig`, `validateIDJAG`, `validateIDJAGTarget`, `claimIDJAGTargets`, `validateIDJAGSubjectClaims`, the exported `ValidateIDJAGSubjectClaimAudiences` (called by the runner before upstream registration), the issuer comparison used by the reserved check diff --git a/docs/arch/README.md b/docs/arch/README.md index 4e10078689..917de24760 100644 --- a/docs/arch/README.md +++ b/docs/arch/README.md @@ -140,6 +140,7 @@ Welcome to the ToolHive architecture documentation. This directory contains comp - RFC 7523 JWT-bearer assertions, audience configuration, and replay protection - Confused-deputy trust model and the `may_act` / allowlist consent signals - Accepted limitations: client-set equivalence, disjoint subject namespaces, partial provenance + - Minting ID-JAGs from exchange grants: roles and conformance, request and error contract, target configuration, claims, redeemer guidance, known gaps - Operational gotchas: audience/scope binding, discovery redirects, JWKS caching, diagnostics - RFC 9396 `authorization_details` on token exchange: Go-only type registry, validation and echo diff --git a/pkg/authserver/configured_client_runner_integration_test.go b/pkg/authserver/configured_client_runner_integration_test.go index 9cedea70c1..d6434e8459 100644 --- a/pkg/authserver/configured_client_runner_integration_test.go +++ b/pkg/authserver/configured_client_runner_integration_test.go @@ -140,6 +140,12 @@ func (r tokenResult) str(t *testing.T, key string) string { } func postToken(t *testing.T, serverURL string, auth clientAuth, values url.Values) tokenResult { + t.Helper() + return postTokenWithHeader(t, serverURL, auth, values, nil) +} + +// postTokenWithHeader is postToken with extra request headers. +func postTokenWithHeader(t *testing.T, serverURL string, auth clientAuth, values url.Values, header http.Header) tokenResult { t.Helper() form := url.Values{} for k, v := range values { @@ -163,6 +169,11 @@ func postToken(t *testing.T, serverURL string, auth clientAuth, values url.Value request, err := http.NewRequest(http.MethodPost, serverURL+"/oauth/token", strings.NewReader(form.Encode())) require.NoError(t, err) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for name, values := range header { + for _, value := range values { + request.Header.Add(name, value) + } + } if auth.secret != "" || auth.emptyBasic { request.SetBasicAuth(auth.clientID, auth.secret) } diff --git a/pkg/authserver/embedded_auth_server_helpers_test.go b/pkg/authserver/embedded_auth_server_helpers_test.go index d79937cacc..0f418b6f03 100644 --- a/pkg/authserver/embedded_auth_server_helpers_test.go +++ b/pkg/authserver/embedded_auth_server_helpers_test.go @@ -21,12 +21,7 @@ import ( ) // startEmbeddedAuthServer starts an embedded auth server on a loopback listener -// with a mock upstream. The issuer is derived from the listener address, so -// mutate receives it to wire clients, audiences and redirect URIs. The returned -// issuer is that listener address, not a cfg.Issuer that mutate may have -// overridden. A nil stor argument lets the server choose its storage from -// cfg.Storage. The returned stop func is idempotent and also registered with -// t.Cleanup, so a test can stop the server mid-way to model a restart. +// with a mock upstream. See startEmbeddedAuthServerOn. func startEmbeddedAuthServer( t *testing.T, mutate func(cfg *authserver.RunConfig, issuer string), @@ -34,10 +29,31 @@ func startEmbeddedAuthServer( opts ...authserverrunner.EmbeddedAuthServerOption, ) (server *httptest.Server, issuer string, embedded *authserverrunner.EmbeddedAuthServer, stop func()) { t.Helper() - - upstream := helpers.NewMockUpstreamIDP(t) listener, err := net.Listen("tcp", "127.0.0.1:0") require.NoError(t, err) + return startEmbeddedAuthServerOn(t, listener, mutate, stor, opts...) +} + +// startEmbeddedAuthServerOn starts an embedded auth server with a mock upstream +// on a listener the caller has already bound, so a second server can be +// configured with this server's issuer before this one starts. The issuer is +// derived from the listener address, so mutate receives it to wire clients, +// audiences and redirect URIs. The returned issuer is that listener address, +// not a cfg.Issuer that mutate may have overridden. A nil stor argument lets the +// server choose its storage from cfg.Storage. The server takes ownership of the +// listener. The returned stop func is idempotent and also registered with +// t.Cleanup, so a test can stop the server mid-way to model a restart. +func startEmbeddedAuthServerOn( + t *testing.T, + listener net.Listener, + mutate func(cfg *authserver.RunConfig, issuer string), + stor storage.Storage, + opts ...authserverrunner.EmbeddedAuthServerOption, +) (server *httptest.Server, issuer string, embedded *authserverrunner.EmbeddedAuthServer, stop func()) { + t.Helper() + + upstream := helpers.NewMockUpstreamIDP(t) + var err error issuer = "http://" + listener.Addr().String() cfg := helpers.NewTestAuthServerConfig(t, upstream.URL()) diff --git a/pkg/authserver/exchange_grant_id_jag_integration_test.go b/pkg/authserver/exchange_grant_id_jag_integration_test.go new file mode 100644 index 0000000000..17fbaca323 --- /dev/null +++ b/pkg/authserver/exchange_grant_id_jag_integration_test.go @@ -0,0 +1,301 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package authserver_test + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "maps" + "net/http" + "net/url" + "slices" + "strings" + "testing" + "time" + + "github.com/go-jose/go-jose/v4/jwt" + "github.com/oauth2-proxy/mockoidc" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/authserver" + "github.com/stacklok/toolhive/pkg/authserver/claimnames" + "github.com/stacklok/toolhive/pkg/authserver/server" + servercrypto "github.com/stacklok/toolhive/pkg/authserver/server/crypto" + "github.com/stacklok/toolhive/pkg/oauthproto" + "github.com/stacklok/toolhive/test/integration/authserver/helpers" +) + +// requestIDJAG presents a grant token and asks for an ID-JAG for target and +// xrtIDJAGResource. +func (e *xrtEnv) requestIDJAG(t *testing.T, auth clientAuth, grant, target string) tokenResult { + t.Helper() + return e.requestIDJAGWithHeader(t, auth, grant, target, nil) +} + +func (e *xrtEnv) requestIDJAGWithHeader( + t *testing.T, auth clientAuth, grant, target string, header http.Header, +) tokenResult { + t.Helper() + return postTokenWithHeader(t, e.srv.URL, auth, idJAGForm(grant, target), header) +} + +// requestIDJAGForm posts form as given, for requests that change or drop what +// requestIDJAG sets. +func (e *xrtEnv) requestIDJAGForm(t *testing.T, auth clientAuth, form url.Values) tokenResult { + t.Helper() + return postToken(t, e.srv.URL, auth, form) +} + +// idJAGForm is the form of a valid ID-JAG request for target and xrtIDJAGResource. +func idJAGForm(grant, target string) url.Values { + return url.Values{ + "grant_type": {oauthproto.GrantTypeTokenExchange}, + "subject_token": {grant}, + "subject_token_type": {oauthproto.TokenTypeRefreshToken}, + "requested_token_type": {oauthproto.TokenTypeIDJAG}, + "audience": {target}, + "resource": {xrtIDJAGResource}, + } +} + +// idJAGGrant returns a grant token owned by auth that allows ID-JAGs, from a +// login-shaped access token. +func (e *xrtEnv) idJAGGrant(t *testing.T, auth clientAuth) string { + t.Helper() + subject := e.mint(t, nil) + res := e.requestRefreshToken(t, auth, subject, func(f url.Values) { + f.Set("authorization_details", "["+xrtEntry(oauthproto.TokenTypeIDJAG, nil)+"]") + }) + require.Equal(t, http.StatusOK, res.status, res.body) + return res.str(t, "access_token") +} + +// decodeIDJAG returns the JOSE header and the claims of a compact JWT without +// verifying it. Numbers stay json.Number, so a fractional time shows. +func decodeIDJAG(t *testing.T, token string) (map[string]any, map[string]any) { + t.Helper() + parts := strings.Split(token, ".") + require.Len(t, parts, 3) + decode := func(segment string) map[string]any { + raw, err := base64.RawURLEncoding.DecodeString(segment) + require.NoError(t, err) + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() + var out map[string]any + require.NoError(t, decoder.Decode(&out)) + return out + } + return decode(parts[0]), decode(parts[1]) +} + +func intClaim(t *testing.T, claims map[string]any, name string) int64 { + t.Helper() + number, ok := claims[name].(json.Number) + require.True(t, ok, "%s is a JSON number: %v", name, claims[name]) + value, err := number.Int64() + require.NoError(t, err, "%s is an integer", name) + return value +} + +// assertMintedIDJAG checks a minted ID-JAG response and returns the token's +// claims. The token is for target and xrtIDJAGResource, for the user "user-1"; +// extraClaims names the claims the target adds to the base set. +func assertMintedIDJAG(t *testing.T, env *xrtEnv, res tokenResult, target string, extraClaims ...string) map[string]any { + t.Helper() + require.Equal(t, http.StatusOK, res.status, res.body) + assert.ElementsMatch(t, []string{"access_token", "issued_token_type", "token_type", "expires_in"}, + slices.Collect(maps.Keys(res.body)), "the response members are exactly these") + assert.Equal(t, oauthproto.TokenTypeIDJAG, res.body["issued_token_type"]) + assert.Equal(t, "N_A", res.body["token_type"]) + assert.Equal(t, "no-store", res.header.Get("Cache-Control")) + + header, claims := decodeIDJAG(t, res.str(t, "access_token")) + assert.Equal(t, oauthproto.JWTTypeIDJAG, header["typ"]) + assert.Equal(t, env.issuer, claims["iss"]) + assert.Equal(t, "user-1", claims["sub"]) + assert.Equal(t, target, claims["aud"]) + assert.Equal(t, xrtTargetClientID, claims["client_id"]) + assert.Equal(t, xrtIDJAGResource, claims["resource"]) + assert.EqualValues(t, xrtIDJAGLifetime, intClaim(t, claims, "exp")-intClaim(t, claims, "iat")) + base := []string{"iss", "sub", "aud", "client_id", "jti", "iat", "exp", "resource"} + assert.ElementsMatch(t, append(base, extraClaims...), slices.Collect(maps.Keys(claims)), "the claims are exactly these") + return claims +} + +// TestMintIDJAGFromExchangeGrant mints ID-JAGs from exchange grants over HTTP, +// on both storage backends. Subtests on one server run serially, because +// postToken derives the client assertion's jti from the clock. +func TestMintIDJAGFromExchangeGrant(t *testing.T) { + t.Parallel() + for _, backend := range []string{"memory", "redis"} { + t.Run(backend, func(t *testing.T) { + t.Parallel() + runIDJAGGrantFlows(t, startXRTServer(t, backend)) + }) + } +} + +func runIDJAGGrantFlows(t *testing.T, env *xrtEnv) { + t.Helper() + upstream := map[string]any{"iss": "https://idp.example", "claim": "oid", "value": "obj-1"} + + t.Run("a top-level grant mints an ID-JAG with the golden claims and response", func(t *testing.T) { + grant := env.idJAGGrant(t, env.broker) + res := env.requestIDJAG(t, env.broker, grant, xrtTargetPlain) + assertMintedIDJAG(t, env, res, xrtTargetPlain) + }) + + t.Run("a child grant mints with the claims it copied from its parent", func(t *testing.T) { + parent := env.mint(t, func(_ *jwt.Claims, x map[string]any) { x[claimnames.UpstreamSubjectKey] = upstream }) + parentGrant := env.requestRefreshToken(t, env.broker, parent, nil) + require.Equal(t, http.StatusOK, parentGrant.status, parentGrant.body) + child := env.derive(t, env.broker, parentGrant.str(t, "access_token"), oauthproto.TokenTypeIDJAG, nil) + require.Equal(t, http.StatusOK, child.status, child.body) + + res := env.requestIDJAG(t, env.broker, child.str(t, "access_token"), xrtTargetUpstream) + claims := assertMintedIDJAG(t, env, res, xrtTargetUpstream, claimnames.UpstreamSubjectKey) + assert.Equal(t, upstream, claims[claimnames.UpstreamSubjectKey]) + }) + + t.Run("a DPoP header on a valid request is refused", func(t *testing.T) { + grant := env.idJAGGrant(t, env.broker) + res := env.requestIDJAGWithHeader(t, env.broker, grant, xrtTargetPlain, http.Header{"Dpop": {"proof"}}) + requireError(t, res, "invalid_request", server.ReasonDPoPNotSupported) + assert.NotContains(t, res.body, "access_token") + }) + + targetRefusals := []struct { + name string + mutate func(url.Values) + code string + }{ + {name: "an unknown audience", code: "invalid_target", + mutate: func(f url.Values) { f.Set("audience", "https://unknown.example.net") }}, + {name: "a resource the target does not list", code: "invalid_target", + mutate: func(f url.Values) { f.Set("resource", "https://other.example.net/mcp") }}, + {name: "a missing resource", code: "invalid_target", + mutate: func(f url.Values) { f.Del("resource") }}, + {name: "a repeated audience", code: "invalid_request", + mutate: func(f url.Values) { f.Add("audience", xrtTargetPlain) }}, + } + for _, tt := range targetRefusals { + t.Run(tt.name+" is refused", func(t *testing.T) { + form := idJAGForm(env.idJAGGrant(t, env.broker), xrtTargetPlain) + tt.mutate(form) + res := env.requestIDJAGForm(t, env.broker, form) + require.Equal(t, http.StatusBadRequest, res.status, res.body) + assert.Equal(t, tt.code, res.body["error"]) + assert.NotContains(t, res.body, "access_token") + }) + } +} + +// TestMintIDJAGClaimsFromRealLogin proves that upstream_subject and sub_id in a +// minted ID-JAG come from a real login: an upstream OIDC login through +// /oauth/authorize and the callback, the source app's access token, a grant +// exchanged from it, and the ID-JAG minted from that grant. Nothing is written +// to storage by the test. The upstream is mockoidc, an OIDC provider, because +// only a verified OIDC identity is complete enough to be recorded. +func TestMintIDJAGClaimsFromRealLogin(t *testing.T) { + t.Parallel() + t.Run("memory", func(t *testing.T) { + t.Parallel() + oidc := startRealLoginUpstream(t) + env := startXRTServerWith(t, "memory", func(cfg *authserver.RunConfig, issuer string) { + cfg.Upstreams = []authserver.UpstreamRunConfig{{ + Name: "mockoidc", + Type: authserver.UpstreamProviderTypeOIDC, + OIDCConfig: &authserver.OIDCUpstreamRunConfig{ + IssuerURL: oidc.Issuer(), ClientID: oidc.Config().ClientID, + ClientSecretFile: writeSecretFile(t, oidc.Config().ClientSecret), + RedirectURI: issuer + "/oauth/callback", + Scopes: []string{"openid", "profile", "email"}, + InsecureAllowHTTP: true, AllowPrivateIPs: true, + }, + }} + }) + + login := realLoginAccessToken(t, env) + _, loginClaims := decodeIDJAG(t, login) + wantUpstream := map[string]any{"iss": oidc.Issuer(), "claim": "sub", "value": realLoginUpstreamSubject} + wantSubID := map[string]any{"format": "iss_sub", "iss": oidc.Issuer(), "sub": realLoginUpstreamSubject} + require.Equal(t, wantUpstream, loginClaims[claimnames.UpstreamSubjectKey], "the login recorded upstream_subject") + require.Equal(t, wantSubID, loginClaims["sub_id"], "the login recorded sub_id") + + grant := env.requestRefreshToken(t, env.broker, login, func(f url.Values) { + f.Set("authorization_details", "["+xrtEntry(oauthproto.TokenTypeIDJAG, nil)+"]") + }) + require.Equal(t, http.StatusOK, grant.status, grant.body) + res := env.requestIDJAG(t, env.broker, grant.str(t, "access_token"), xrtTargetBoth) + require.Equal(t, http.StatusOK, res.status, res.body) + + _, claims := decodeIDJAG(t, res.str(t, "access_token")) + assert.Equal(t, loginClaims["sub"], claims["sub"], "sub is the login's local subject") + assert.Equal(t, wantUpstream, claims[claimnames.UpstreamSubjectKey]) + assert.Equal(t, wantSubID, claims["sub_id"]) + }) +} + +// realLoginAccessToken logs a user in to the source app through the upstream +// and returns the access token for the broker's API audience. +func realLoginAccessToken(t *testing.T, env *xrtEnv) string { + t.Helper() + locationOf := func(response *http.Response, status int) *url.URL { + t.Helper() + defer func() { require.NoError(t, response.Body.Close()) }() + require.Equal(t, status, response.StatusCode) + location, err := response.Location() + require.NoError(t, err) + return location + } + browser := helpers.NewOAuthClient(env.srv.URL) + verifier := servercrypto.GeneratePKCEVerifier() + page, err := browser.StartAuthorization(url.Values{ + "client_id": {xrtSourceApp}, "redirect_uri": {cfgRedirectURI}, "response_type": {"code"}, + "scope": {"openid profile offline_access"}, "state": {"login-state"}, "resource": {cfgAudienceA}, + "code_challenge": {servercrypto.ComputePKCEChallenge(verifier)}, + "code_challenge_method": {"S256"}, + }) + require.NoError(t, err) + require.Equal(t, http.StatusOK, page.StatusCode) + approved, err := browser.ApproveConsent(page, env.srv.URL) + require.NoError(t, err) + require.NoError(t, page.Body.Close()) + upstreamAuthorize := locationOf(approved, http.StatusSeeOther) + + upstreamResponse, err := (&http.Client{ + Timeout: 10 * time.Second, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + }).Get(upstreamAuthorize.String()) + require.NoError(t, err) + upstreamCallback := locationOf(upstreamResponse, http.StatusFound) + + callback, err := browser.Callback(upstreamCallback.Query().Get("code"), upstreamCallback.Query().Get("state")) + require.NoError(t, err) + done := locationOf(callback, http.StatusSeeOther) + require.Equal(t, "login-state", done.Query().Get("state")) + + tokens := postToken(t, env.srv.URL, clientAuth{}, url.Values{ + "grant_type": {oauthproto.GrantTypeAuthorizationCode}, "code": {done.Query().Get("code")}, + "redirect_uri": {cfgRedirectURI}, "code_verifier": {verifier}, "client_id": {xrtSourceApp}, + "resource": {cfgAudienceA}, + }) + require.Equal(t, http.StatusOK, tokens.status, tokens.body) + return tokens.str(t, "access_token") +} + +// realLoginUpstreamSubject is the subject mockoidc asserts for the queued user. +const realLoginUpstreamSubject = "idjag-real-login-user" + +// startRealLoginUpstream starts mockoidc with one queued user. +func startRealLoginUpstream(t *testing.T) *mockoidc.MockOIDC { + t.Helper() + m, err := mockoidc.Run() + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, m.Shutdown()) }) + m.QueueUser(&mockoidc.MockUser{Subject: realLoginUpstreamSubject, Email: "idjag-user@example.com"}) + return m +} diff --git a/pkg/authserver/exchange_refresh_token_integration_test.go b/pkg/authserver/exchange_refresh_token_integration_test.go index 1e6b8c89c3..e96fd16b1b 100644 --- a/pkg/authserver/exchange_refresh_token_integration_test.go +++ b/pkg/authserver/exchange_refresh_token_integration_test.go @@ -10,6 +10,7 @@ import ( "encoding/hex" "encoding/json" "fmt" + "net" "net/http" "net/http/httptest" "net/url" @@ -44,8 +45,27 @@ const ( xrtOtherAudience = "https://other.test.local" xrtIDJAGCap = 12 * time.Hour xrtRefreshCap = 720 * time.Hour + xrtTargetsOther = "configured-targets-other" + + // The broker's ID-JAG targets. Each requires a different set of subject + // claims. xrtIDJAGResource is not one of the server's allowed audiences. + xrtTargetPlain = "https://as2.example.net" + xrtTargetUpstream = "https://as2-upstream.example.net" + xrtTargetBoth = "https://as2-both.example.net" + xrtIDJAGResource = "https://gw.example.net/mcp" + xrtTargetClientID = "broker-at-as2" + xrtIDJAGLifetime = 60 + xrtUpstreamSubject = "upstream_subject" ) +// xrtIDJAGTarget is a broker target for xrtIDJAGResource with the default lifetime. +func xrtIDJAGTarget(issuer string, required ...string) authserver.DelegateClientIDJAGTarget { + return authserver.DelegateClientIDJAGTarget{ + Issuer: issuer, ClientID: xrtTargetClientID, Resources: []string{xrtIDJAGResource}, + RequiredSubjectClaims: required, + } +} + // xrtEnv is an embedded auth server with a broker client that may exchange // login tokens for refresh tokens, plus clients that may not. type xrtEnv struct { @@ -75,6 +95,11 @@ func xrtClients(t *testing.T, jwksFile string) []authserver.DelegateClientRunCon ExchangeRefreshTokens: &authserver.DelegateClientExchangeRefreshTokens{ IDJAGMaxLifetime: xrtIDJAGCap.String(), RefreshTokenMaxLifetime: xrtRefreshCap.String(), }, + IDJAG: &authserver.DelegateClientIDJAG{Targets: []authserver.DelegateClientIDJAGTarget{ + xrtIDJAGTarget(xrtTargetPlain), + xrtIDJAGTarget(xrtTargetUpstream, xrtUpstreamSubject), + xrtIDJAGTarget(xrtTargetBoth, xrtUpstreamSubject, "sub_id"), + }}, } otherRefresh := secretClient(t, xrtOtherRefreshClient, []string{oauthproto.GrantTypeTokenExchange}) otherRefresh.Audiences = nil @@ -86,6 +111,16 @@ func xrtClients(t *testing.T, jwksFile string) []authserver.DelegateClientRunCon IDJAGMaxLifetime: xrtIDJAGCap.String(), RefreshTokenMaxLifetime: xrtRefreshCap.String(), }, } + targetsOther := secretClient(t, xrtTargetsOther, []string{oauthproto.GrantTypeTokenExchange}) + targetsOther.Audiences = nil + targetsOther.TokenExchange = &authserver.DelegateClientTokenExchange{ + SelfIssuedSubjectTokens: authserver.SelfIssuedSubjectTokensRestricted, + SubjectTokenAudiences: []string{cfgAudienceA}, + AllowedSourceClients: []string{xrtSourceApp}, + ExchangeRefreshTokens: &authserver.DelegateClientExchangeRefreshTokens{ + IDJAGMaxLifetime: xrtIDJAGCap.String(), + }, + } idJAGOnly := secretClient(t, xrtIDJAGOnlyClient, []string{oauthproto.GrantTypeTokenExchange}) idJAGOnly.Audiences = nil idJAGOnly.TokenExchange = &authserver.DelegateClientTokenExchange{ @@ -100,12 +135,34 @@ func xrtClients(t *testing.T, jwksFile string) []authserver.DelegateClientRunCon broker, otherRefresh, idJAGOnly, + targetsOther, secretClient(t, cfgExchangeOnly, []string{oauthproto.GrantTypeTokenExchange}), secretClient(t, cfgNoCodeID, []string{oauthproto.GrantTypeTokenExchange, oauthproto.GrantTypeJWTBearer}), } } func startXRTServer(t *testing.T, backend string) *xrtEnv { + t.Helper() + return startXRTServerWith(t, backend, nil) +} + +// startXRTServerWith starts the server like startXRTServer and applies mutate +// to the RunConfig last. The server records sub_id and upstream_subject for +// logins to the broker's API audience, which targets that require those +// claims need: the option is set the way an embedder sets it, because +// RunConfig has no field for it. +func startXRTServerWith(t *testing.T, backend string, mutate func(cfg *authserver.RunConfig, issuer string)) *xrtEnv { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + return startXRTServerOn(t, backend, listener, mutate) +} + +// startXRTServerOn is startXRTServerWith on a listener the caller has already +// bound, for a test that must know this server's issuer before it starts. +func startXRTServerOn( + t *testing.T, backend string, listener net.Listener, mutate func(cfg *authserver.RunConfig, issuer string), +) *xrtEnv { t.Helper() brokerKey := newAssertionKey(t, "broker-key") jwksFile := filepath.Join(t.TempDir(), "broker.jwks") @@ -122,7 +179,15 @@ func startXRTServer(t *testing.T, backend string) *xrtEnv { clients := configuredClients(xrtClients(t, jwksFile)...) stor := newStorageForBackend(t, backend) - srv, issuer, embedded, _ := startEmbeddedAuthServer(t, func(cfg *authserver.RunConfig, issuer string) { + // The source app is a user-facing client, as a DCR registration would be: + // it logs users in, and the broker exchanges its access tokens for grants. + require.NoError(t, stor.RegisterClient(t.Context(), &fosite.DefaultClient{ + ID: xrtSourceApp, Public: true, RedirectURIs: []string{cfgRedirectURI}, + ResponseTypes: []string{"code"}, + GrantTypes: []string{oauthproto.GrantTypeAuthorizationCode, oauthproto.GrantTypeRefreshToken}, + Scopes: []string{"openid", "profile", "offline_access"}, Audience: []string{cfgAudienceA}, + })) + srv, issuer, embedded, _ := startEmbeddedAuthServerOn(t, listener, func(cfg *authserver.RunConfig, issuer string) { clients(cfg) cfg.AllowedAudiences = []string{cfgAudienceA, xrtOtherAudience} cfg.InboundGrants.JWTBearer = &authserver.JWTBearerInboundGrantRunConfig{ @@ -138,7 +203,10 @@ func startXRTServer(t *testing.T, backend string) *xrtEnv { Name: "mock-idp", IssuerURL: cfgIDJAGIssuer, JWKSURL: jwksServer.URL, InsecureAllowHTTP: true, AllowPrivateIPs: true, }} - }, stor) + if mutate != nil { + mutate(cfg, issuer) + } + }, stor, authserverrunner.WithSubjectIdentifierAudiences([]string{cfgAudienceA})) return &xrtEnv{ srv: srv, issuer: issuer, embedded: embedded, store: stor, brokerKey: brokerKey, idpKey: idpKey, broker: clientAuth{clientID: cfgBrokerID, key: &brokerKey}, @@ -447,13 +515,28 @@ func runExchangeRefreshTokenGrantFlows(t *testing.T, env *xrtEnv) { func runExchangeRefreshTokenRefusals(t *testing.T, env *xrtEnv) { t.Helper() t.Run("routing", func(t *testing.T) { - // subject_token_type=refresh_token is claimed by the refresh-token handler, - // which refuses it unless the request asks for a refresh token. - res := env.requestRefreshToken(t, env.broker, "irrelevant", func(f url.Values) { + // subject_token_type=refresh_token with requested_token_type=id-jag is + // claimed by the refresh-token handler. A client with grants but no ID-JAG + // targets is refused with the unsupported requested-type text. + res := env.requestRefreshToken(t, env.secretIn, "irrelevant", func(f url.Values) { f.Set("subject_token_type", oauthproto.TokenTypeRefreshToken) f.Set("requested_token_type", oauthproto.TokenTypeIDJAG) f.Del("authorization_details") }) + requireError(t, res, "invalid_request", unsupportedTypeDescription("requested_token_type", oauthproto.TokenTypeIDJAG)) + + // A client with targets mints. + grant := env.grantToken(t, env.broker, oauthproto.TokenTypeIDJAG, nil).str(t, "access_token") + minted := env.requestIDJAG(t, env.broker, grant, xrtTargetPlain) + require.Equal(t, http.StatusOK, minted.status, minted.body) + assert.Equal(t, oauthproto.TokenTypeIDJAG, minted.body["issued_token_type"]) + + // A refresh-token subject asking for any other type keeps the subject text. + res = env.requestRefreshToken(t, env.broker, "irrelevant", func(f url.Values) { + f.Set("subject_token_type", oauthproto.TokenTypeRefreshToken) + f.Set("requested_token_type", oauthproto.TokenTypeAccessToken) + f.Del("authorization_details") + }) requireError(t, res, "invalid_request", hinted(fosite.ErrInvalidRequest, fmt.Sprintf( "The 'subject_token_type' value %q is not supported. Use %q or %q.", oauthproto.TokenTypeRefreshToken, oauthproto.TokenTypeAccessToken, oauthproto.TokenTypeJWT))) @@ -701,7 +784,8 @@ func TestExchangeRefreshTokensRequireTheStorageCapability(t *testing.T) { cfg.InsecureAllowConfidentialOverLoopbackHTTP = true configuredClients(clients...)(cfg) cfg.AllowedAudiences = []string{cfgAudienceA, xrtOtherAudience} - embedded, err := authserverrunner.NewEmbeddedAuthServerWithStorage(t.Context(), cfg, newHidden()) + embedded, err := authserverrunner.NewEmbeddedAuthServerWithStorage(t.Context(), cfg, newHidden(), + authserverrunner.WithSubjectIdentifierAudiences([]string{cfgAudienceA})) if err == nil { assert.NoError(t, embedded.Close()) } diff --git a/pkg/authserver/server/handlers/id_jag_seam_test.go b/pkg/authserver/server/handlers/id_jag_seam_test.go new file mode 100644 index 0000000000..1d55b3ad81 --- /dev/null +++ b/pkg/authserver/server/handlers/id_jag_seam_test.go @@ -0,0 +1,187 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package handlers + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/ory/fosite" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/authserver/server" + "github.com/stacklok/toolhive/pkg/oauthproto" +) + +const ( + seamForeignResource = "https://mcp.other-as.example.net/mcp" + seamDPoPValue = "seam-dpop-proof-value" +) + +// seamProvider answers the token endpoint with a prepared request and response +// and counts the calls that follow. Error writing goes through the embedded +// real provider. +type seamProvider struct { + fosite.OAuth2Provider + request *fosite.AccessRequest + response fosite.AccessResponder + + responses int + written int +} + +func (p *seamProvider) NewAccessRequest(context.Context, *http.Request, fosite.Session) (fosite.AccessRequester, error) { + return p.request, nil +} + +func (p *seamProvider) NewAccessResponse(context.Context, fosite.AccessRequester) (fosite.AccessResponder, error) { + p.responses++ + return p.response, nil +} + +func (p *seamProvider) WriteAccessResponse(_ context.Context, w http.ResponseWriter, _ fosite.AccessRequester, _ fosite.AccessResponder) { + p.written++ + w.WriteHeader(http.StatusOK) +} + +type seamCase struct { + grantType string + requestedType string + resource string + dpop []string + clientID string + granted []string + issuedType string +} + +func (c seamCase) request() *fosite.AccessRequest { + form := url.Values{} + if c.requestedType != "" { + form.Set("requested_token_type", c.requestedType) + } + if c.resource != "" { + form.Set("resource", c.resource) + } + req := fosite.NewAccessRequest(nil) + req.GrantTypes = fosite.Arguments{c.grantType} + req.Form = form + if c.clientID != "" { + req.Client = &fosite.DefaultClient{ID: c.clientID} + } + for _, aud := range c.granted { + req.GrantAudience(aud) + } + return req +} + +// run drives TokenHandler against a seamProvider built from c. +func (c seamCase) run(t *testing.T) (*seamProvider, *httptest.ResponseRecorder) { + t.Helper() + + handler, _, _ := handlerTestSetup(t) + response := fosite.NewAccessResponse() + if c.issuedType != "" { + response.SetExtra("issued_token_type", c.issuedType) + } + provider := &seamProvider{OAuth2Provider: handler.provider, request: c.request(), response: response} + handler.provider = provider + + req := httptest.NewRequest(http.MethodPost, "/oauth/token", strings.NewReader("")) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, value := range c.dpop { + req.Header.Add("DPoP", value) + } + rec := httptest.NewRecorder() + handler.TokenHandler(rec, req) + return provider, rec +} + +func TestTokenHandler_IDJAGRequests(t *testing.T) { + t.Parallel() + + idJAG := seamCase{ + grantType: oauthproto.GrantTypeTokenExchange, requestedType: oauthproto.TokenTypeIDJAG, + resource: seamForeignResource, issuedType: oauthproto.TokenTypeIDJAG, + } + plainExchange := seamCase{ + grantType: oauthproto.GrantTypeTokenExchange, resource: seamForeignResource, + issuedType: oauthproto.TokenTypeAccessToken, + } + with := func(base seamCase, mutate func(*seamCase)) seamCase { + mutate(&base) + return base + } + + tests := []struct { + name string + in seamCase + wantStatus int + wantCode string + wantBody string + wantResponses int + wantWritten int + }{ + { + name: "DPoP header on an ID-JAG request is refused with the exact reason", + in: with(idJAG, func(c *seamCase) { c.dpop = []string{seamDPoPValue} }), + wantStatus: http.StatusBadRequest, + wantBody: `{"error":"invalid_request","error_description":"` + server.ReasonDPoPNotSupported + `"}`, + }, + { + name: "DPoP header on a plain token exchange is unaffected", + in: with(plainExchange, func(c *seamCase) { c.dpop = []string{seamDPoPValue}; c.resource = "" }), + wantStatus: http.StatusOK, wantResponses: 1, wantWritten: 1, + }, + { + name: "ID-JAG resource outside AllowedAudiences is not refused by the resource check", + in: idJAG, + wantStatus: http.StatusOK, wantResponses: 1, wantWritten: 1, + }, + { + name: "plain token exchange with the same resource is still refused", + in: plainExchange, + wantStatus: http.StatusBadRequest, wantCode: "invalid_target", + }, + { + name: "ID-JAG request answered with another token type fails closed", + in: with(idJAG, func(c *seamCase) { c.issuedType = oauthproto.TokenTypeAccessToken }), + wantStatus: http.StatusInternalServerError, wantCode: "server_error", wantResponses: 1, + }, + { + name: "ID-JAG request answered without an issued_token_type fails closed", + in: with(idJAG, func(c *seamCase) { c.issuedType = "" }), + wantStatus: http.StatusInternalServerError, wantCode: "server_error", wantResponses: 1, + }, + { + name: "ID-JAG request with a granted audience fails closed", + in: with(idJAG, func(c *seamCase) { c.granted = []string{seamForeignResource} }), + wantStatus: http.StatusInternalServerError, wantCode: "server_error", wantResponses: 1, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + provider, rec := tt.in.run(t) + + assert.Equal(t, tt.wantStatus, rec.Code) + assert.Equal(t, tt.wantResponses, provider.responses, "NewAccessResponse calls") + assert.Equal(t, tt.wantWritten, provider.written, "WriteAccessResponse calls") + if tt.wantBody != "" { + assert.JSONEq(t, tt.wantBody, rec.Body.String()) + } + if tt.wantCode != "" { + var body map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body)) + assert.Equal(t, tt.wantCode, body["error"]) + } + }) + } +} diff --git a/pkg/authserver/server/handlers/token.go b/pkg/authserver/server/handlers/token.go index cf8e44b581..3674a52a3b 100644 --- a/pkg/authserver/server/handlers/token.go +++ b/pkg/authserver/server/handlers/token.go @@ -6,6 +6,7 @@ package handlers import ( "context" "errors" + "fmt" "log/slog" "net/http" "slices" @@ -75,7 +76,23 @@ func (h *Handler) TokenHandler(w http.ResponseWriter, req *http.Request) { return } - if h.applyResourceAudience(ctx, w, accessRequest) { + ownsResource := server.OwnsResourceParameter(accessRequest) + if ownsResource { + // DPoP-bound ID-JAGs are unsupported: the server cannot bind a cnf claim + // yet, and ignoring the proof would issue an unbound token. The handler's + // own phase-1 refusals come first, in NewAccessRequest. + if len(req.Header.Values("DPoP")) > 0 { + slog.Warn("DPoP-bound ID-JAGs are not supported; request refused", + "client_id", accessRequest.GetClient().GetID(), + ) + h.provider.WriteAccessError(ctx, w, accessRequest, &fosite.RFC6749Error{ + ErrorField: fosite.ErrInvalidRequest.ErrorField, + DescriptionField: server.ReasonDPoPNotSupported, + CodeField: http.StatusBadRequest, + }) + return + } + } else if h.applyResourceAudience(ctx, w, accessRequest) { return } h.applySubjectIdentifier(accessRequest) @@ -91,6 +108,20 @@ func (h *Handler) TokenHandler(w http.ResponseWriter, req *http.Request) { return } + // Only a server defect can reach this: a handler claimed the request without + // owning the resource. Its side effects are not undone, but nothing is sent. + if ownsResource && (response.GetExtra(oauthproto.ParamIssuedTokenType) != oauthproto.TokenTypeIDJAG || + len(accessRequest.GetGrantedAudience()) > 0) { + slog.Error("token response for an ID-JAG request is not a bare ID-JAG; request refused", + "client_id", accessRequest.GetClient().GetID(), + "issued_token_type", fmt.Sprint(response.GetExtra(oauthproto.ParamIssuedTokenType)), + "granted_audience_count", len(accessRequest.GetGrantedAudience()), + ) + h.provider.WriteAccessError(ctx, w, accessRequest, + fosite.ErrServerError.WithHint("The token could not be issued.")) + return + } + // Renew the registration TTL for DCR-issued clients (public or confidential) on a // successful token exchange/refresh. This is the proven-use signal — unlike the // unauthenticated /oauth/authorize client read — so an actively-used client does diff --git a/pkg/authserver/server/id_jag_seam.go b/pkg/authserver/server/id_jag_seam.go new file mode 100644 index 0000000000..2e3e95272b --- /dev/null +++ b/pkg/authserver/server/id_jag_seam.go @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package server + +import ( + "github.com/ory/fosite" + + "github.com/stacklok/toolhive/pkg/oauthproto" +) + +// ReasonDPoPNotSupported is the stable error_description the token endpoint +// sends when a request for an ID-JAG carries a DPoP header. It is the whole +// description, with no hint. +const ReasonDPoPNotSupported = "dpop_not_supported" + +// OwnsResourceParameter reports whether a token-exchange request asks for an +// ID-JAG, in which case the ID-JAG path owns the "resource" parameter and the +// token endpoint must not validate it against AllowedAudiences or grant it as +// the access token audience: the resource names an endpoint behind another +// authorization server. +// +// It keys only on the grant type and requested_token_type, never on +// subject_token_type, so every subject source (access token, ID token, SAML) +// shares the answer. A repeated requested_token_type is read as its first +// value, as fosite and the handlers' CanHandleTokenEndpointRequest read it. +// +// It lives in this package, not in tokenexchange, because package handlers +// calls it and must not import tokenexchange and its dependencies. +func OwnsResourceParameter(requester fosite.AccessRequester) bool { + return requester.GetGrantTypes().ExactOne(oauthproto.GrantTypeTokenExchange) && + requester.GetRequestForm().Get("requested_token_type") == oauthproto.TokenTypeIDJAG +} diff --git a/pkg/authserver/server/id_jag_seam_test.go b/pkg/authserver/server/id_jag_seam_test.go new file mode 100644 index 0000000000..f5c7847ef0 --- /dev/null +++ b/pkg/authserver/server/id_jag_seam_test.go @@ -0,0 +1,64 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package server + +import ( + "net/url" + "testing" + + "github.com/ory/fosite" + "github.com/stretchr/testify/assert" + + "github.com/stacklok/toolhive/pkg/oauthproto" +) + +func TestOwnsResourceParameter(t *testing.T) { + t.Parallel() + + exchange := fosite.Arguments{oauthproto.GrantTypeTokenExchange} + requestedIDJAG := url.Values{"requested_token_type": {oauthproto.TokenTypeIDJAG}} + + tests := []struct { + name string + grants fosite.Arguments + form url.Values + want bool + }{ + {name: "token exchange asking for an ID-JAG", grants: exchange, form: requestedIDJAG, want: true}, + { + name: "grant_type with two values", + grants: fosite.Arguments{oauthproto.GrantTypeTokenExchange, oauthproto.GrantTypeRefreshToken}, + form: requestedIDJAG, + }, + {name: "other grant type", grants: fosite.Arguments{oauthproto.GrantTypeAuthorizationCode}, form: requestedIDJAG}, + {name: "requested_token_type absent", grants: exchange, form: url.Values{}}, + { + name: "requested_token_type access token", + grants: exchange, + form: url.Values{"requested_token_type": {oauthproto.TokenTypeAccessToken}}, + }, + { + // url.Values.Get returns the first value, so a repeated parameter is read as its + // first value. A misread is safe: the token endpoint refuses any response that + // is not an ID-JAG or that carries a granted audience. + name: "repeated requested_token_type, ID-JAG first", + grants: exchange, + form: url.Values{"requested_token_type": {oauthproto.TokenTypeIDJAG, oauthproto.TokenTypeAccessToken}}, + want: true, + }, + { + name: "repeated requested_token_type, ID-JAG second", + grants: exchange, + form: url.Values{"requested_token_type": {oauthproto.TokenTypeAccessToken, oauthproto.TokenTypeIDJAG}}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + requester := &fosite.AccessRequest{GrantTypes: tt.grants, Request: fosite.Request{Form: tt.form}} + assert.Equal(t, tt.want, OwnsResourceParameter(requester)) + }) + } +} diff --git a/pkg/authserver/server/tokenexchange/id_jag_mint.go b/pkg/authserver/server/tokenexchange/id_jag_mint.go index 209ef9c1b6..7cf698e458 100644 --- a/pkg/authserver/server/tokenexchange/id_jag_mint.go +++ b/pkg/authserver/server/tokenexchange/id_jag_mint.go @@ -160,23 +160,26 @@ func allowAllIDJAGPolicy(context.Context, idJAGPolicyInput) error { return nil } // checked: an empty value counts as absent, and a refused parameter is refused // if any of its values is non-empty, since fosite reads only the first. // audience and resource are read from the raw form, so a value with spaces is -// one value. The audience must equal a configured target issuer exactly; it is -// not normalized. A target the client has not -// configured, whether unknown or configured for another client, and a resource -// the target does not list all get the same invalid_target error. Unknown -// parameters are ignored. +// one value. More than one audience is invalid_request, as section 4.3.3 of +// draft-ietf-oauth-identity-assertion-authz-grant requires. The audience must +// equal a configured target issuer exactly; it is not normalized. A target the +// client has not configured, whether unknown or configured for another client, +// and a resource the target does not list all get the same invalid_target +// error. Unknown parameters are ignored. // -// A client with an actor profile is refused with server_error before any -// parameter is read, because ID-JAG issuance does not check actor tokens yet -// and must not mint for a client the operator configured to require that +// A client with an actor profile is refused with unauthorized_client before +// any parameter is read, because ID-JAG issuance does not check actor tokens +// yet and must not mint for a client the operator configured to require that // check. Checking first means no request shape, valid or not, gets past it. // // Every refusal here carries a hint, never a stable reason, so it returns only // the error to send. func checkIDJAGRequest(form url.Values, policy ConfiguredClientPolicy) (idJAGRequestShape, error) { - // Issuance wiring must replace this guard with the validateActor call. + // The change that adds the validateActor call replaces this guard. It + // answers unauthorized_client (400), not server_error, so these refusals + // are not logged as server faults. if policy.ActorProfile != nil { - return idJAGRequestShape{}, errorsx.WithStack(fosite.ErrServerError.WithHint( + return idJAGRequestShape{}, errorsx.WithStack(fosite.ErrUnauthorizedClient.WithHint( "Actor-token validation is not available.")) } if form.Get("subject_token") == "" { @@ -189,7 +192,7 @@ func checkIDJAGRequest(form url.Values, policy ConfiguredClientPolicy) (idJAGReq "The 'audience' parameter is required when requesting an ID-JAG.")) } if len(audiences) > 1 { - return idJAGRequestShape{}, errorsx.WithStack(server.ErrInvalidTarget.WithHint( + return idJAGRequestShape{}, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint( "The 'audience' parameter must have exactly one value when requesting an ID-JAG.")) } resources := nonEmptyValues(form["resource"]) diff --git a/pkg/authserver/server/tokenexchange/id_jag_mint_test.go b/pkg/authserver/server/tokenexchange/id_jag_mint_test.go index 051b66399b..49c4319aae 100644 --- a/pkg/authserver/server/tokenexchange/id_jag_mint_test.go +++ b/pkg/authserver/server/tokenexchange/id_jag_mint_test.go @@ -301,10 +301,16 @@ func TestCheckIDJAGRequest(t *testing.T) { {name: "valid request", mutate: func(url.Values) {}}, {name: "valid request from a client with an actor profile fails closed", mutate: func(url.Values) {}, profiled: true, - wantCode: "server_error", wantParam: "Actor-token validation is not available"}, + wantCode: "unauthorized_client", wantParam: "Actor-token validation is not available"}, + {name: "actor profile is refused even when an actor token is sent", + mutate: func(f url.Values) { + f.Set("actor_token", "agent-token") + f.Set("actor_token_type", oauthproto.TokenTypeJWT) + }, profiled: true, + wantCode: "unauthorized_client", wantParam: "Actor-token validation is not available"}, {name: "actor profile is refused before the request is read", mutate: func(f url.Values) { f.Del("subject_token") }, profiled: true, - wantCode: "server_error", wantParam: "Actor-token validation is not available"}, + wantCode: "unauthorized_client", wantParam: "Actor-token validation is not available"}, {name: "empty first audience is a single audience", mutate: func(f url.Values) { f[mintTestAudienceParam] = []string{"", mintTestTargetIssuer} }}, {name: "empty first resource is a single resource", @@ -324,7 +330,7 @@ func TestCheckIDJAGRequest(t *testing.T) { wantCode: "invalid_request", wantParam: "'audience'"}, {name: "repeated audience", mutate: func(f url.Values) { f[mintTestAudienceParam] = []string{mintTestTargetIssuer, mintTestTargetIssuer} }, - wantCode: "invalid_target", wantParam: "'audience'"}, + wantCode: "invalid_request", wantParam: "'audience'"}, {name: "missing resource", mutate: func(f url.Values) { f.Del("resource") }, wantCode: "invalid_target", wantParam: "'resource'"}, {name: "only empty resource values", mutate: func(f url.Values) { f["resource"] = []string{"", ""} }, @@ -372,7 +378,7 @@ func TestCheckIDJAGRequest(t *testing.T) { f[mintTestAudienceParam] = []string{mintTestTargetIssuer, mintTestTargetIssuer} f["resource"] = []string{mintTestResource, "https://gw.example.com/other"} }, - wantCode: "invalid_target", wantParam: "'audience'"}, + wantCode: "invalid_request", wantParam: "'audience'"}, {name: "order: repeated resource wins over scope", mutate: func(f url.Values) { f["resource"] = []string{mintTestResource, "https://gw.example.com/other"} diff --git a/pkg/authserver/server/tokenexchange/refresh_token_handler.go b/pkg/authserver/server/tokenexchange/refresh_token_handler.go index 5512fa5d8c..0e6e5064b8 100644 --- a/pkg/authserver/server/tokenexchange/refresh_token_handler.go +++ b/pkg/authserver/server/tokenexchange/refresh_token_handler.go @@ -33,15 +33,16 @@ var _ fosite.TokenEndpointHandler = (*RefreshTokenHandler)(nil) // Reasons logged with a refusal. They are fixed strings; the // authorization_details reasons are the ones returned to the client. const ( - refuseUnsupportedType = "unsupported_token_type" - refuseSubjectToken = reasonSubjectInvalid - refuseRequestParam = "request_parameter_refused" - refuseDetailsInvalid = "authorization_details_invalid" - refuseReplay = "token_used" - refuseBadToken = "token_invalid" - refuseUnknownGrant = "not_found_or_other_client" - refuseInternal = "internal_error" - refuseStore = "store_failure" + refuseUnsupportedType = "unsupported_token_type" + refuseSubjectToken = reasonSubjectInvalid + refuseRequestParam = "request_parameter_refused" + refuseActorUnavailable = "actor_validation_unavailable" + refuseDetailsInvalid = "authorization_details_invalid" + refuseReplay = "token_used" + refuseBadToken = "token_invalid" + refuseUnknownGrant = "not_found_or_other_client" + refuseInternal = "internal_error" + refuseStore = "store_failure" ) // Reasons returned to the client as the whole error_description when a request @@ -99,16 +100,21 @@ func isRefreshTokenExchange(form url.Values) bool { // token_used. The check and the write are one atomic store call, made in // PopulateTokenEndpointResponse, so two concurrent exchanges produce one grant. // -// A refresh-token subject is exchanged for a child grant (decideChild). Two -// derives from one grant give two independent children, since a child has no -// replay marker. If the response of a derive is lost, the child stays until its -// parent ends; this is accepted. +// A refresh-token subject is exchanged for a child grant (decideChild), or for +// an ID-JAG (decideIDJAG) when the request asks for one. Two derives from one +// grant give two independent children, since a child has no replay marker. If +// the response of a derive is lost, the child stays until its parent ends; this +// is accepted. Minting an ID-JAG writes nothing, so one grant mints any number +// of them. // // A client without exchange_refresh_tokens is refused with the unsupported // requested_token_type text (unsupportedTokenType), or with the unsupported // subject_token_type text that validateFormParams returns when its subject is a -// refresh token. A refresh-token subject asking for any type but a refresh -// token is refused with the same subject text. All are invalid_request. +// refresh token. A refresh-token subject asking for a type whose cap +// the client lacks (a refresh token without the refresh_token cap, an ID-JAG +// without the ID-JAG cap) or for any other type is refused with the same +// subject text, and one asking for an ID-JAG from a client with the cap but no +// ID-JAG targets gets the unsupported requested_token_type text. All are invalid_request. // // The exchange grant is the only profile this handler issues today; a later // profile would be chosen where decide checks the client's exchange_refresh_tokens. @@ -119,8 +125,8 @@ type RefreshTokenHandler struct { registry *authorizationdetails.Registry clientPolicies map[string]ConfiguredClientPolicy refreshScopes fosite.RefreshTokenScopesProvider - signer *server.Signer // will sign ID-JAGs; nothing reads it yet - issuer string // the access-token issuer + signer idJAGSigner // signs ID-JAGs with typ oauth-id-jag+jwt; *server.Signer in production + issuer string // the access-token issuer } // RefreshTokenOption configures RefreshTokenFactory. Factory takes FactoryOption @@ -230,8 +236,9 @@ func (h *RefreshTokenHandler) HandleTokenEndpointRequest(ctx context.Context, re } // PopulateTokenEndpointResponse decides the request again and issues the refresh -// token. The second decision verifies the subject token right before it is -// consumed. The grant carries the subject token's (iss, jti), so a reused +// token or mints the ID-JAG. The second decision verifies the subject token +// right before it is consumed, and re-reads a presented grant right before an +// ID-JAG is signed. The grant carries the subject token's (iss, jti), so a reused // subject token fails in issue with token_used. A child grant has no (iss, jti) // marker, so token_used applies only to top-level grants. The response is the RFC 8693 // shape with token_type N_A and no refresh_token member; fosite writes @@ -242,11 +249,20 @@ func (h *RefreshTokenHandler) PopulateTokenEndpointResponse( if !h.CanHandleTokenEndpointRequest(ctx, requester) { return errorsx.WithStack(fosite.ErrUnknownRequest) } - decision, err := h.decide(ctx, requester, time.Now()) + decided, err := h.decide(ctx, requester, time.Now()) if err != nil { return err } - return h.issue(ctx, requester, decision, responder) + switch { + case decided.grant != nil: + return h.issue(ctx, requester, decided.grant, responder) + case decided.idJAG != nil: + return h.issueIDJAG(ctx, decided.idJAG, responder) + default: + // Unreachable: decide sets exactly one field or returns an error. Kept so a + // future decision kind fails closed instead of issuing nothing. + return errorsx.WithStack(fosite.ErrServerError.WithHint("The token could not be issued.")) + } } // refuse logs a refusal at warn level with a stable reason and returns the error @@ -271,6 +287,13 @@ type exchangeGrantDecision struct { log *slog.Logger } +// decision is the outcome of decide. Exactly one field is set: grant for a +// request that issues a grant, idJAG for one that mints an ID-JAG. +type decision struct { + grant *exchangeGrantDecision + idJAG *idJAGDecision +} + // decide validates the request, the subject token and the authorization_details // entry, and returns what to issue. It writes nothing to the store and consumes // nothing; its only effect is the refusal log line. It runs twice per request @@ -281,36 +304,41 @@ type exchangeGrantDecision struct { // branch (decideTopLevel for a login access token, decideChild for a refresh // token) that builds the same exchangeGrantDecision, which issue then writes. // That is a different axis from a new profile, which changes what the grant -// allows, not what it is derived from. +// allows, not what it is derived from. A refresh-token subject asking for an +// ID-JAG goes to decideIDJAG instead, whose decision issueIDJAG mints. func (h *RefreshTokenHandler) decide( ctx context.Context, requester fosite.AccessRequester, now time.Time, -) (*exchangeGrantDecision, error) { +) (decision, error) { client := requester.GetClient() form := requester.GetRequestForm() log := slog.With("client_id", client.GetID()) if client.IsPublic() { - return nil, errorsx.WithStack(fosite.ErrInvalidGrant.WithHint( + return decision{}, errorsx.WithStack(fosite.ErrInvalidGrant.WithHint( "The OAuth 2.0 Client is marked as public and is thus not allowed to use authorization grant 'token-exchange'.")) } if !client.GetGrantTypes().Has(oauthproto.GrantTypeTokenExchange) { - return nil, errorsx.WithStack(fosite.ErrUnauthorizedClient.WithHint( + return decision{}, errorsx.WithStack(fosite.ErrUnauthorizedClient.WithHint( "The OAuth 2.0 Client is not allowed to use authorization grant 'token-exchange'.")) } // The policy gate comes first: a client that has not enabled the feature gets // the unsupported-type text. A refresh-token subject is refused too when it - // does not ask for a refresh token, or when the client's policy no longer - // allows refresh tokens, so removing the cap stops derives from source grants the - // client already holds. The text is the one validateFormParams returns for an - // unsupported subject type. + // asks for neither a refresh token nor an ID-JAG, or when it asks for a + // type whose cap the client's policy no longer has, so removing a cap stops + // derives and ID-JAG mints from source grants the client already holds. + // The text is the one validateFormParams returns for an unsupported subject + // type. policy := h.clientPolicies[client.GetID()] subjectType := form.Get("subject_token_type") + requestedType := form.Get("requested_token_type") derive := subjectType == oauthproto.TokenTypeRefreshToken _, refreshAllowed := policy.ExchangeRefreshTokens[oauthproto.TokenTypeRefreshToken] - if derive && (!refreshAllowed || - form.Get("requested_token_type") != oauthproto.TokenTypeRefreshToken) { - return nil, refuse(ctx, log, refuseUnsupportedType, errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf( + deriveAllowed := requestedType == oauthproto.TokenTypeRefreshToken && refreshAllowed + _, idJAGCap := policy.ExchangeRefreshTokens[oauthproto.TokenTypeIDJAG] + idJAGAllowed := requestedType == oauthproto.TokenTypeIDJAG && idJAGCap + if derive && !deriveAllowed && !idJAGAllowed { + return decision{}, refuse(ctx, log, refuseUnsupportedType, errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf( "The 'subject_token_type' value %q is not supported. Use %q or %q.", subjectType, oauthproto.TokenTypeAccessToken, oauthproto.TokenTypeJWT))) } @@ -320,13 +348,34 @@ func (h *RefreshTokenHandler) decide( // and checked at startup, not by the shape of the request. A client with no // policy must keep meaning "nothing allowed". if len(policy.ExchangeRefreshTokens) == 0 { - return nil, refuse(ctx, log, refuseUnsupportedType, - errorsx.WithStack(unsupportedTokenType("requested_token_type", form.Get("requested_token_type")))) + return decision{}, refuse(ctx, log, refuseUnsupportedType, + errorsx.WithStack(unsupportedTokenType("requested_token_type", requestedType))) + } + if derive && requestedType == oauthproto.TokenTypeIDJAG { + // A client with no ID-JAG targets cannot mint at all, so it gets the + // unsupported-type text before any request parameter is checked or any + // grant is read. + if len(policy.IDJAGTargets) == 0 { + return decision{}, refuse(ctx, log, refuseUnsupportedType, + errorsx.WithStack(unsupportedTokenType("requested_token_type", requestedType))) + } + minting, err := h.decideIDJAG(ctx, requester, policy, log, now) + if err != nil { + return decision{}, err + } + return decision{idJAG: minting}, nil } + var grant *exchangeGrantDecision + var err error if derive { - return h.decideChild(ctx, requester, policy, log.With("has_parent", true), now) + grant, err = h.decideChild(ctx, requester, policy, log.With("has_parent", true), now) + } else { + grant, err = h.decideTopLevel(ctx, requester, policy, log, now) } - return h.decideTopLevel(ctx, requester, policy, log, now) + if err != nil { + return decision{}, err + } + return decision{grant: grant}, nil } // decideTopLevel decides a request that exchanges a login access token for a @@ -470,7 +519,7 @@ func (h *RefreshTokenHandler) decideChild( // whole-second check comes right after it: expires_at is whole seconds, so a // grant with no whole second left is refused like an expired one // (reasonGrantInvalid), whatever else is wrong with it. Which output the grant -// may produce is not checked here; the caller (decideChild) checks that after +// may produce is not checked here; each caller checks that after // this returns. func (h *RefreshTokenHandler) presentedGrant( ctx context.Context, clientID, token string, now time.Time, log *slog.Logger, @@ -488,9 +537,6 @@ func (h *RefreshTokenHandler) presentedGrant( } if grant != nil { log = log.With("sub", grant.Subject) - if grant.SubjectIdentifier != "" { - log = log.With("sub_id", grant.SubjectIdentifier) - } } if grant != nil && grant.ExpiresAt.Unix() <= now.Unix() { return nil, log, refuse(ctx, log, refuseUnknownGrant, errorsx.WithStack(errUnknownGrant)) @@ -870,6 +916,9 @@ func checkIDJAGTargetUsable(clientID, key string, target IDJAGTarget) error { case target.Lifetime <= 0: return fmt.Errorf("tokenexchange: client %q id_jag target %q lifetime must be positive, got %v", clientID, key, target.Lifetime) + case target.Lifetime%time.Second != 0: + return fmt.Errorf("tokenexchange: client %q id_jag target %q lifetime must be a whole number of seconds, got %v", + clientID, key, target.Lifetime) } seen := make(map[string]struct{}, len(target.RequiredSubjectClaims)) for _, token := range target.RequiredSubjectClaims { diff --git a/pkg/authserver/server/tokenexchange/refresh_token_handler_test.go b/pkg/authserver/server/tokenexchange/refresh_token_handler_test.go index 7cff4cb5c2..b82789d074 100644 --- a/pkg/authserver/server/tokenexchange/refresh_token_handler_test.go +++ b/pkg/authserver/server/tokenexchange/refresh_token_handler_test.go @@ -630,6 +630,8 @@ func TestRefreshTokenFactoryValidatesTargets(t *testing.T) { t.RequiredSubjectClaims = []string{IDJAGSubjectClaimSubID, IDJAGSubjectClaimSubID} }, wantErr: `lists required subject claim "sub_id" twice`}, + {name: "sub-second lifetime", key: key, + mutate: func(t *IDJAGTarget) { t.Lifetime = 500 * time.Millisecond }, wantErr: "lifetime must be a whole number of seconds"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/pkg/authserver/server/tokenexchange/refresh_token_id_jag.go b/pkg/authserver/server/tokenexchange/refresh_token_id_jag.go new file mode 100644 index 0000000000..3b3aad68b3 --- /dev/null +++ b/pkg/authserver/server/tokenexchange/refresh_token_id_jag.go @@ -0,0 +1,148 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package tokenexchange + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "slices" + "time" + + "github.com/ory/fosite" + "github.com/ory/x/errorsx" + + "github.com/stacklok/toolhive/pkg/authserver/claimnames" + "github.com/stacklok/toolhive/pkg/authserver/storage" + "github.com/stacklok/toolhive/pkg/oauthproto" +) + +// idJAGDecision is the outcome of deciding a request that mints an ID-JAG from +// an exchange grant, with nothing yet signed. now is the instant that checked +// the grant; the mint reuses it, so exp and expires_in agree with that check. +type idJAGDecision struct { + mint idJAGMint + // subID is the grant's recorded sub_id JSON; logged only on the Debug mint line. + subID string + // log carries what a refusal may log; nothing above Debug carries sub_id. + log *slog.Logger + now time.Time +} + +// decideIDJAG decides a request that exchanges an exchange grant's refresh +// token for an ID-JAG. The order is fixed. The request parameters and the +// target come first and read nothing from the store. presentedGrant then +// applies the grant checks in the order that reveals nothing before the client +// check. Then the grant must list the ID-JAG output. Then every subject claim +// the grant recorded is decoded, including ones the target does not require, so +// a stored value that is not JSON is an internal error for every target. Last, +// the claims the target requires must have been recorded on the grant. It +// writes nothing. +func (h *RefreshTokenHandler) decideIDJAG( + ctx context.Context, requester fosite.AccessRequester, policy ConfiguredClientPolicy, + log *slog.Logger, now time.Time, +) (*idJAGDecision, error) { + clientID := requester.GetClient().GetID() + form := requester.GetRequestForm() + shape, err := checkIDJAGRequest(form, policy) + if err != nil { + reason := refuseRequestParam + if policy.ActorProfile != nil { + reason = refuseActorUnavailable + } + return nil, refuse(ctx, log, reason, err) + } + log = log.With("target", shape.Target.Issuer, "resource", shape.Resource) + + grant, log, err := h.presentedGrant(ctx, clientID, form.Get("subject_token"), now, log) + if err != nil { + return nil, err + } + hasParent := grant.ParentSignature != "" + log = log.With("has_parent", hasParent) + if !slices.Contains(grant.IssuableTokenTypes, oauthproto.TokenTypeIDJAG) { + return nil, refuseWithReason(ctx, log, reasonNotIssuable) + } + + // The client's current cap bounds grants it already holds, as derive + // bounds new children, so lowering id_jag_max_lifetime limits old grants. + // A grant past the cap is refused like an expired one, so a client cannot + // tell the two apart. Every create path sets CreatedAt, so a zero value is + // a corrupt record; refusing it keeps the cap from being skipped. + if grant.CreatedAt.IsZero() { + return nil, refuse(ctx, log, refuseInternal, + serverFailure(hintMintFailed, errors.New("exchange grant has no creation time"))) + } + capped := grant.CreatedAt.Add(policy.ExchangeRefreshTokens[oauthproto.TokenTypeIDJAG]) + if capped.Unix() <= now.Unix() { + return nil, refuse(ctx, log, refuseUnknownGrant, errorsx.WithStack(errUnknownGrant)) + } + notAfter := []time.Time{grant.ExpiresAt, capped} + + available, err := grantSubjectClaims(grant) + if err != nil { + return nil, refuse(ctx, log, refuseInternal, serverFailure(hintMintFailed, err)) + } + // Selecting here refuses a missing required claim in the first decision. + // The mint gets every available claim and selects again, as its contract + // says; the result is the same. + if _, reason, err := selectSubjectClaims(shape.Target, available); err != nil { + return nil, refuse(ctx, log, reason, err) + } + + return &idJAGDecision{ + mint: idJAGMint{ + Issuer: h.issuer, + RequestingClientID: clientID, + Subject: idJAGSubject{Subject: grant.Subject, Claims: available}, + Target: shape.Target, + Resource: shape.Resource, + NotAfter: notAfter, + }, + subID: grant.SubjectIdentifier, + log: log, + now: now, + }, nil +} + +// issueIDJAG signs the ID-JAG of a decision made in PopulateTokenEndpointResponse +// and writes the response. It writes nothing to the store: the grant is neither +// consumed nor rotated, so the same grant may mint again with a new jti. +func (h *RefreshTokenHandler) issueIDJAG( + ctx context.Context, d *idJAGDecision, responder fosite.AccessResponder, +) error { + minted, reason, err := respondWithIDJAG(ctx, h.signer, allowAllIDJAGPolicy, d.mint, responder, d.now) + if err != nil { + return refuse(ctx, d.log, reason, err) + } + attrs := []any{"jti", minted.JTI} + if d.subID != "" { + attrs = append(attrs, "sub_id", d.subID) + } + d.log.DebugContext(ctx, "ID-JAG minted", attrs...) + return nil +} + +// grantSubjectClaims returns the subject claims a grant recorded at login, +// keyed by wire key. A claim the grant did not record is absent. A recorded +// value that is not JSON is an error; the message names the claim, not the +// value. +func grantSubjectClaims(grant *storage.ExchangeGrant) (map[string]json.RawMessage, error) { + available := make(map[string]json.RawMessage, 2) + for _, recorded := range []struct{ key, value string }{ + {claimnames.UpstreamSubjectKey, grant.UpstreamSubject}, + {claimnames.SubjectIdentifierKey, grant.SubjectIdentifier}, + } { + if recorded.value == "" { + continue + } + if !json.Valid([]byte(recorded.value)) { + return nil, fmt.Errorf("the grant's stored %s is not valid JSON", recorded.key) + } + available[recorded.key] = json.RawMessage(recorded.value) + } + return available, nil +} diff --git a/pkg/authserver/server/tokenexchange/refresh_token_id_jag_test.go b/pkg/authserver/server/tokenexchange/refresh_token_id_jag_test.go new file mode 100644 index 0000000000..174c5a4ac3 --- /dev/null +++ b/pkg/authserver/server/tokenexchange/refresh_token_id_jag_test.go @@ -0,0 +1,523 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package tokenexchange + +import ( + "encoding/json" + "errors" + "log" + "log/slog" + "net/url" + "strings" + "testing" + "time" + + "github.com/ory/fosite" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/authserver/claimnames" + "github.com/stacklok/toolhive/pkg/authserver/storage" + "github.com/stacklok/toolhive/pkg/oauthproto" +) + +const ( + grantMintTarget = "https://as2.example.com" + grantMintResource = "https://gw.example.com/mcp" + grantMintClientAt = "broker-at-as2" + // grantMintUpstream and grantMintSubID are what a grant records at login. + grantMintUpstream = `{"iss":"https://idp.example","claim":"oid","value":"unit-upstream-value"}` + grantMintSubID = `{"format":"iss_sub","iss":"https://idp.example","sub":"unit-sub-id"}` +) + +// idJAGHandler is deriveHandler with one ID-JAG target for the broker that +// requires the given subject claims, a real signer and an issuer. +func idJAGHandler(t *testing.T, store storage.ExchangeGrantStorage, required ...string) *RefreshTokenHandler { + t.Helper() + h := deriveHandler(t, store) + policy := h.clientPolicies[testRefreshClient] + policy.IDJAGTargets = map[string]IDJAGTarget{grantMintTarget: { + Issuer: grantMintTarget, ClientID: grantMintClientAt, Resources: []string{grantMintResource}, + Lifetime: time.Minute, RequiredSubjectClaims: required, + }} + h.clientPolicies[testRefreshClient] = policy + h.signer = newMintTestSigner(newTestJWKS(t)) + h.issuer = testIssuer + return h +} + +// idJAGRequest asks for an ID-JAG for the test target, presenting token. +func idJAGRequest(token string) *fosite.AccessRequest { + req := refreshRequestForTest(brokerClientForTest()) + req.Form = url.Values{ + "grant_type": {oauthproto.GrantTypeTokenExchange}, + "subject_token": {token}, + "subject_token_type": {oauthproto.TokenTypeRefreshToken}, + "requested_token_type": {oauthproto.TokenTypeIDJAG}, + "audience": {grantMintTarget}, + "resource": {grantMintResource}, + } + return req +} + +func idJAGRecord(sig, client, parent string, expires time.Time, types ...string) storage.ExchangeGrant { + return storage.ExchangeGrant{ + Signature: sig, ClientID: client, ParentSignature: parent, Subject: "user-1", + UpstreamSubject: grantMintUpstream, SubjectIdentifier: grantMintSubID, + IssuableTokenTypes: types, ExpiresAt: expires, CreatedAt: time.Now(), + } +} + +func idJAGRecords(records ...storage.ExchangeGrant) map[string]storage.ExchangeGrant { + out := make(map[string]storage.ExchangeGrant, len(records)) + for _, r := range records { + out[r.Signature] = r + } + return out +} + +// idJAGStore serves the given grants and records any grant written. +func idJAGStore(records ...storage.ExchangeGrant) *fakeGrantStoreWithRecords { + return &fakeGrantStoreWithRecords{recordStore: recordStore{grants: idJAGRecords(records...)}} +} + +func TestIDJAGCheckOrder(t *testing.T) { + t.Parallel() + + live := time.Now().Add(time.Hour) + idJAG := oauthproto.TokenTypeIDJAG + refresh := oauthproto.TokenTypeRefreshToken + revoked := idJAGRecord("revoked", testRefreshClient, "", live, idJAG) + revoked.RevokedAt = time.Now() + // A grant with under one whole second left is expired: the check compares + // whole seconds, so ExpiresAt in the current second is already past. + subSecond := time.Now().Truncate(time.Second).Add(500 * time.Millisecond) + records := []storage.ExchangeGrant{ + idJAGRecord("ok", testRefreshClient, "", live, idJAG), + idJAGRecord("stranger", "stranger", "", live, idJAG), + idJAGRecord("expired", testRefreshClient, "", time.Now().Add(-time.Hour), idJAG), + idJAGRecord("subsecond", testRefreshClient, "", subSecond, idJAG), + idJAGRecord("parent", testRefreshClient, "", live, refresh), + idJAGRecord("child", testRefreshClient, "parent", live, idJAG), + idJAGRecord("refresh-only", testRefreshClient, "", live, refresh), + revoked, + } + + tests := []struct { + name string + token string + want string // error_description; "" mints + }{ + {name: "a live top-level grant mints", token: "x.ok"}, + {name: "a live child grant mints", token: "x.child"}, + {name: "another client's grant", token: "x.stranger", want: reasonGrantInvalid}, + {name: "an unknown signature", token: "x.nothere", want: reasonGrantInvalid}, + {name: "an expired grant", token: "x.expired", want: reasonGrantInvalid}, + {name: "a grant with under one whole second left", token: "x.subsecond", want: reasonGrantInvalid}, + {name: "a revoked grant", token: "x.revoked", want: reasonRevoked}, + {name: "a grant that does not list the ID-JAG output", token: "x.refresh-only", want: reasonNotIssuable}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + store := idJAGStore(records...) + h := idJAGHandler(t, store) + req := idJAGRequest(tt.token) + resp := fosite.NewAccessResponse() + handleErr := h.HandleTokenEndpointRequest(t.Context(), req) + populateErr := h.PopulateTokenEndpointResponse(t.Context(), req, resp) + assert.Empty(t, store.created, "minting and refusing write nothing") + if tt.want == "" { + require.NoError(t, handleErr) + require.NoError(t, populateErr) + assert.NotEmpty(t, resp.GetAccessToken()) + return + } + for _, err := range []error{handleErr, populateErr} { + requireOAuthError(t, err, "invalid_request", tt.want) + } + assert.Empty(t, resp.GetAccessToken()) + }) + } + + t.Run("request parameters are checked before the store is read", func(t *testing.T) { + t.Parallel() + store := &recordStore{grants: idJAGRecords(records...)} + h := idJAGHandler(t, store) + req := idJAGRequest("x.ok") + req.Form.Del("resource") + requireOAuthError(t, h.HandleTokenEndpointRequest(t.Context(), req), "invalid_target", "") + req = idJAGRequest("bad.sig") + requireOAuthError(t, h.HandleTokenEndpointRequest(t.Context(), req), "invalid_request", reasonGrantInvalid) + assert.Zero(t, store.reads, "neither a request refusal nor a failed HMAC reads the store") + }) +} + +func TestIDJAGMintsFromTheGrantSnapshot(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + required []string + want map[string]string // signed subject claims; any other is absent + }{ + {name: "both claims required", required: []string{"upstream_subject", "sub_id"}, + want: map[string]string{claimnames.UpstreamSubjectKey: grantMintUpstream, "sub_id": grantMintSubID}}, + {name: "a claim the target does not require is not signed", required: []string{"upstream_subject"}, + want: map[string]string{claimnames.UpstreamSubjectKey: grantMintUpstream}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + store := idJAGStore(idJAGRecord("ok", testRefreshClient, "", time.Now().Add(time.Hour), oauthproto.TokenTypeIDJAG)) + h := idJAGHandler(t, store, tt.required...) + req := idJAGRequest("x.ok") + // The subject comes from the grant, never from the request. + req.Form.Set("sub", "attacker") + req.Form.Set("sub_id", `{"format":"opaque","id":"attacker"}`) + jtis := map[string]bool{} + for range 2 { + resp := fosite.NewAccessResponse() + require.NoError(t, h.HandleTokenEndpointRequest(t.Context(), req)) + require.NoError(t, h.PopulateTokenEndpointResponse(t.Context(), req, resp)) + + assert.Empty(t, req.GetGrantedAudience(), "the ID-JAG path never grants an audience") + claims := decodeJWTPart(t, resp.GetAccessToken(), 1) + assert.Equal(t, "user-1", claims["sub"]) + for _, key := range []string{claimnames.UpstreamSubjectKey, "sub_id"} { + want, ok := tt.want[key] + if !ok { + assert.NotContains(t, claims, key) + continue + } + got, err := json.Marshal(claims[key]) + require.NoError(t, err) + assert.JSONEq(t, want, string(got), key) + } + jti, _ := claims["jti"].(string) + jtis[jti] = true + } + assert.Len(t, jtis, 2, "each mint has its own jti") + assert.Empty(t, store.created, "minting writes nothing") + }) + } +} + +// TestIDJAGInternalFailuresAreGeneric covers internal failures on the ID-JAG +// path that the derive tests do not: each is a server_error whose description +// carries no cause. +func TestIDJAGInternalFailuresAreGeneric(t *testing.T) { + t.Parallel() + + good := idJAGRecord("ok", testRefreshClient, "", time.Now().Add(time.Hour), oauthproto.TokenTypeIDJAG) + badSubID := good + badSubID.SubjectIdentifier = "{not json" + tests := []struct { + name string + grant storage.ExchangeGrant + setup func(*RefreshTokenHandler) + leaks []string + }{ + {name: "signing failure", grant: good, setup: func(h *RefreshTokenHandler) { + h.signer = &recordingSigner{err: errors.New("signing key kid-42 is missing")} + }, leaks: []string{"kid-42"}}, + {name: "stored sub_id is not JSON although not required", grant: badSubID, leaks: []string{"not json", "sub_id"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + h := idJAGHandler(t, idJAGStore(tt.grant), "upstream_subject") + if tt.setup != nil { + tt.setup(h) + } + resp := fosite.NewAccessResponse() + err := h.PopulateTokenEndpointResponse(t.Context(), idJAGRequest("x.ok"), resp) + oauthErr := unwrapOAuth(t, err) + assert.Equal(t, "server_error", oauthErr.ErrorField) + for _, leak := range tt.leaks { + assert.NotContains(t, oauthErr.GetDescription(), leak) + } + assert.Empty(t, resp.GetAccessToken()) + }) + } +} + +func TestIDJAGDecidesAgainBeforeMinting(t *testing.T) { + t.Parallel() + + store := idJAGStore(idJAGRecord("ok", testRefreshClient, "", time.Now().Add(time.Hour), oauthproto.TokenTypeIDJAG)) + h := idJAGHandler(t, store) + req := idJAGRequest("x.ok") + require.NoError(t, h.HandleTokenEndpointRequest(t.Context(), req)) + + revoked := store.grants["ok"] + revoked.RevokedAt = time.Now() + store.grants["ok"] = revoked + resp := fosite.NewAccessResponse() + requireOAuthError(t, h.PopulateTokenEndpointResponse(t.Context(), req, resp), "invalid_request", reasonRevoked) + assert.Empty(t, resp.GetAccessToken(), "nothing is minted") +} + +// TestIDJAGMintUsesGrantExpiryAndDecisionTime sets the clock by value: decide +// takes now, so no wall clock is read. +func TestIDJAGMintUsesGrantExpiryAndDecisionTime(t *testing.T) { + t.Parallel() + + // exchangeGrantNow is a whole second; the offsets below rely on it. + base := exchangeGrantNow + record := idJAGRecord("ok", testRefreshClient, "", base.Add(1500*time.Millisecond), oauthproto.TokenTypeIDJAG) + record.CreatedAt = base + h := idJAGHandler(t, &recordStore{grants: idJAGRecords(record)}) + decided, err := h.decide(t.Context(), idJAGRequest("x.ok"), base.Add(200*time.Millisecond)) + require.NoError(t, err) + require.NotNil(t, decided.idJAG) + resp := fosite.NewAccessResponse() + require.NoError(t, h.issueIDJAG(t.Context(), decided.idJAG, resp)) + claims := decodeJWTPart(t, resp.GetAccessToken(), 1) + assert.Equal(t, json.Number("1800000001"), claims["exp"], "exp is the floor of the grant's expiry") + assert.Equal(t, json.Number("1800000000"), claims["iat"], "iat is the decision time") +} + +// TestIDJAGMintIsBoundedByTheCurrentCap sets the clock by value. The client's +// current id_jag_max_lifetime bounds a grant issued under a larger one. +func TestIDJAGMintIsBoundedByTheCurrentCap(t *testing.T) { + t.Parallel() + + base := exchangeGrantNow + tests := []struct { + name string + created time.Time + expires time.Time + cap time.Duration + wantExp json.Number // "" is refused as an invalid grant + corrupt bool // refused with server_error + }{ + {name: "a cap lowered below the remaining life bounds exp", + created: base.Add(-100 * time.Second), expires: base.Add(time.Hour), cap: 130 * time.Second, + wantExp: "1800000030"}, + {name: "a cap that does not bind leaves the target lifetime", + created: base.Add(-100 * time.Second), expires: base.Add(time.Hour), cap: time.Hour, + wantExp: "1800000060"}, + {name: "a grant already past the lowered cap is refused", + created: base.Add(-2 * time.Hour), expires: base.Add(time.Hour), cap: time.Hour}, + {name: "a grant whose cap ends in this second is refused", + created: base.Add(-time.Hour), expires: base.Add(time.Hour), cap: time.Hour}, + {name: "a zero creation time is a corrupt record and is refused", + expires: base.Add(30 * time.Second), cap: time.Hour, corrupt: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + record := idJAGRecord("ok", testRefreshClient, "", tt.expires, oauthproto.TokenTypeIDJAG) + record.CreatedAt = tt.created + store := idJAGStore(record) + h := idJAGHandler(t, store) + policy := h.clientPolicies[testRefreshClient] + policy.ExchangeRefreshTokens = map[string]time.Duration{oauthproto.TokenTypeIDJAG: tt.cap} + h.clientPolicies[testRefreshClient] = policy + + decided, err := h.decide(t.Context(), idJAGRequest("x.ok"), base) + if tt.corrupt { + requireOAuthError(t, err, "server_error", "") + return + } + if tt.wantExp == "" { + requireOAuthError(t, err, "invalid_request", reasonGrantInvalid) + assert.Empty(t, store.created, "nothing is minted") + return + } + require.NoError(t, err) + require.NotNil(t, decided.idJAG) + resp := fosite.NewAccessResponse() + require.NoError(t, h.issueIDJAG(t.Context(), decided.idJAG, resp)) + assert.Equal(t, tt.wantExp, decodeJWTPart(t, resp.GetAccessToken(), 1)["exp"]) + }) + } +} + +// TestRefreshTokenSubjectRequestGating covers a refresh-token subject under +// each set of exchange_refresh_tokens entries and ID-JAG targets a client's +// current policy may hold. Each requested type needs its own entry; without it +// the request is refused with the subject_token_type text, so removing an entry +// stops derives and mints from grants the client already holds. +func TestRefreshTokenSubjectRequestGating(t *testing.T) { + t.Parallel() + + const ( + subjectTxt = "'subject_token_type' value" + requestTxt = "'requested_token_type' value" + // deriveTxt is decideChild's refusal: the request carries the ID-JAG + // audience and resource, which a refresh-token derive does not accept. + deriveTxt = "parameters are not supported when requesting a refresh token" + mint = "mints" + ) + both := map[string]time.Duration{oauthproto.TokenTypeRefreshToken: time.Hour, oauthproto.TokenTypeIDJAG: time.Hour} + idJAGOnly := map[string]time.Duration{oauthproto.TokenTypeIDJAG: time.Hour} + refreshOnly := map[string]time.Duration{oauthproto.TokenTypeRefreshToken: time.Hour} + + tests := []struct { + name string + caps map[string]time.Duration + targets bool + // want is the substring of the refusal for each requested type, or mint. + refresh, idJAG, access string + }{ + {name: "both entries with targets", caps: both, targets: true, refresh: deriveTxt, idJAG: mint, access: subjectTxt}, + {name: "ID-JAG entry only with targets", caps: idJAGOnly, targets: true, refresh: subjectTxt, idJAG: mint, access: subjectTxt}, + {name: "refresh_token entry only with targets", caps: refreshOnly, targets: true, + refresh: deriveTxt, idJAG: subjectTxt, access: subjectTxt}, + {name: "ID-JAG entry without targets", caps: idJAGOnly, refresh: subjectTxt, idJAG: requestTxt, access: subjectTxt}, + {name: "no entries", targets: true, refresh: subjectTxt, idJAG: subjectTxt, access: subjectTxt}, + } + for _, tt := range tests { + for requested, want := range map[string]string{ + oauthproto.TokenTypeRefreshToken: tt.refresh, + oauthproto.TokenTypeIDJAG: tt.idJAG, + oauthproto.TokenTypeAccessToken: tt.access, + } { + t.Run(tt.name+" asking for "+requested, func(t *testing.T) { + t.Parallel() + store := idJAGStore(idJAGRecord("ok", testRefreshClient, "", time.Now().Add(time.Hour), oauthproto.TokenTypeIDJAG)) + h := idJAGHandler(t, store) + policy := h.clientPolicies[testRefreshClient] + policy.ExchangeRefreshTokens = tt.caps + if !tt.targets { + policy.IDJAGTargets = nil + } + h.clientPolicies[testRefreshClient] = policy + + req := idJAGRequest("x.ok") + req.Form.Set("requested_token_type", requested) + resp := fosite.NewAccessResponse() + handleErr := h.HandleTokenEndpointRequest(t.Context(), req) + if want == mint { + require.NoError(t, handleErr) + require.NoError(t, h.PopulateTokenEndpointResponse(t.Context(), req, resp)) + assert.Equal(t, oauthproto.TokenTypeIDJAG, resp.GetExtra("issued_token_type")) + assert.NotEmpty(t, resp.GetAccessToken()) + return + } + wantCode := "invalid_request" + if want == deriveTxt { + wantCode = "invalid_target" + } + requireOAuthError(t, handleErr, wantCode, "") + assert.Contains(t, unwrapOAuth(t, handleErr).GetDescription(), want) + assert.Empty(t, resp.GetAccessToken()) + }) + } + } +} + +// linesFor returns the lines of captured log output that name clientID. +func linesFor(logs, clientID string) []string { + var out []string + for _, line := range strings.Split(logs, "\n") { + if strings.Contains(line, "client_id="+clientID+" ") { + out = append(out, line) + } + } + return out +} + +// TestIDJAGLogs pins what the ID-JAG path logs on failure: one WARN line with +// the reason and without sub_id, the presented token or upstream_subject. A +// signing failure keeps its cause off the line, in the error's debug field, +// which the token endpoint logs at ERROR (serverFailure). A successful mint is +// one Debug line with the jti and sub_id. Each case uses a client_id no other +// test uses, because the default logger is process-wide. +// +//nolint:paralleltest // captures the process-global slog default +func TestIDJAGLogs(t *testing.T) { + logs := &syncBuffer{} + prev := slog.Default() + prevWriter, prevFlags := log.Writer(), log.Flags() + slog.SetDefault(slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug}))) + t.Cleanup(func() { + slog.SetDefault(prev) + // slog.SetDefault also redirects the log package's output and flags, + // and restoring the previous slog default does not undo that. + log.SetOutput(prevWriter) + log.SetFlags(prevFlags) + }) + + const token = "presented-token-value.ok" + tests := []struct { + name string + clientID string + required []string + mutate func(*storage.ExchangeGrant) + profiled bool // the client has an actor profile + signer *recordingSigner + code string // "" is a successful mint + reason string + debug string // cause carried in the error's debug field, not on the line + }{ + {name: "a successful mint", clientID: "idjag-log-unit-ok"}, + {name: "a revoked grant", clientID: "idjag-log-unit-revoked", + mutate: func(g *storage.ExchangeGrant) { g.RevokedAt = time.Now() }, + code: "invalid_request", reason: reasonRevoked}, + {name: "a missing claim", clientID: "idjag-log-unit-missing", required: []string{"upstream_subject"}, + mutate: func(g *storage.ExchangeGrant) { g.UpstreamSubject = "" }, + code: "invalid_request", reason: reasonUpstreamSubjectMissing}, + {name: "a client with an actor profile", clientID: "idjag-log-unit-profiled", profiled: true, + code: "unauthorized_client", reason: refuseActorUnavailable}, + {name: "a signing failure", clientID: "idjag-log-unit-sign", + signer: &recordingSigner{err: errors.New("signing key kid-42 is missing")}, + code: "server_error", reason: refuseInternal, debug: "kid-42"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + grant := idJAGRecord("ok", tt.clientID, "", time.Now().Add(time.Hour), oauthproto.TokenTypeIDJAG) + if tt.mutate != nil { + tt.mutate(&grant) + } + h := idJAGHandler(t, idJAGStore(grant), tt.required...) + policy := h.clientPolicies[testRefreshClient] + if tt.profiled { + policy.ActorProfile = &ActorProfile{Name: "broker", ActorTokenType: oauthproto.TokenTypeJWT} + } + h.clientPolicies[tt.clientID] = policy + if tt.signer != nil { + h.signer = tt.signer + } + req := idJAGRequest(token) + req.Client = &fosite.DefaultClient{ID: tt.clientID, GrantTypes: fosite.Arguments{oauthproto.GrantTypeTokenExchange}} + + resp := fosite.NewAccessResponse() + err := h.HandleTokenEndpointRequest(t.Context(), req) + if err == nil { + err = h.PopulateTokenEndpointResponse(t.Context(), req, resp) + } + if tt.code == "" { + require.NoError(t, err) + lines := linesFor(logs.String(), tt.clientID) + require.Len(t, lines, 1) + assert.Contains(t, lines[0], "level=DEBUG") + assert.Contains(t, lines[0], `msg="ID-JAG minted"`) + jti, _ := decodeJWTPart(t, resp.GetAccessToken(), 1)["jti"].(string) + for _, field := range []string{"jti=" + jti, "unit-sub-id", "target=", "resource=", "has_parent=false"} { + assert.Contains(t, lines[0], field) + } + for _, secret := range []string{token, resp.GetAccessToken(), "unit-upstream-value"} { + assert.NotContains(t, lines[0], secret) + } + return + } + requireOAuthError(t, err, tt.code, "") + if tt.debug != "" { + assert.Contains(t, unwrapOAuth(t, err).DebugField, tt.debug) + assert.NotContains(t, unwrapOAuth(t, err).GetDescription(), tt.debug) + } + + lines := linesFor(logs.String(), tt.clientID) + require.Len(t, lines, 1) + assert.Contains(t, lines[0], "level=WARN") + assert.Contains(t, lines[0], "reason="+tt.reason) + for _, secret := range []string{token, "unit-upstream-value", "unit-sub-id", "kid-42"} { + assert.NotContains(t, lines[0], secret) + } + }) + } +} diff --git a/pkg/authserver/server_impl.go b/pkg/authserver/server_impl.go index 78182affdc..301f23b9d5 100644 --- a/pkg/authserver/server_impl.go +++ b/pkg/authserver/server_impl.go @@ -718,10 +718,9 @@ func exchangeRefreshTokenCaps(block *DelegateClientExchangeRefreshTokens) (map[s // each restricted client's actor_profile to its registered validator. It relies // on Config.Validate having refused an unregistered or nil validator. // -// It also logs once, at DEBUG until ID-JAG issuance exists, for every client -// that can hold ID-JAG grants but has no id_jag.targets. It runs once per -// start, unlike config validation, which can run on both the RunConfig and the -// Config path. +// It also logs once, at DEBUG, for every client that can hold ID-JAG grants +// but has no id_jag.targets. It runs once per start, unlike config validation, +// which can run on both the RunConfig and the Config path. func configuredClientPolicies( clients []DelegateClient, validators map[string]tokenexchange.ActorValidatorRegistration, ) (map[string]tokenexchange.ConfiguredClientPolicy, error) { diff --git a/pkg/authserver/two_server_id_jag_integration_test.go b/pkg/authserver/two_server_id_jag_integration_test.go new file mode 100644 index 0000000000..ac8c1401b5 --- /dev/null +++ b/pkg/authserver/two_server_id_jag_integration_test.go @@ -0,0 +1,151 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package authserver_test + +import ( + "net" + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/authserver" + authserverrunner "github.com/stacklok/toolhive/pkg/authserver/runner" + "github.com/stacklok/toolhive/pkg/authserver/server/tokenexchange" + "github.com/stacklok/toolhive/pkg/oauthproto" +) + +// as2Env is an embedded auth server that redeems ID-JAGs minted by AS-1. +type as2Env struct { + srv *httptest.Server + issuer string + embedded *authserverrunner.EmbeddedAuthServer + // client is the ID-JAG's client_id at AS-2, authenticating with private_key_jwt. + client clientAuth +} + +// twoServerIDJAG is AS-1 plus an AS-2 that allows assertions to live two +// minutes. +type twoServerIDJAG struct { + as1 *xrtEnv + as2 *as2Env +} + +// redeem presents assertion at AS-2's token endpoint under the JWT-bearer +// grant, asking for resource. +func (e *as2Env) redeem(t *testing.T, auth clientAuth, assertion, resource string) tokenResult { + t.Helper() + return postToken(t, e.srv.URL, auth, url.Values{ + "grant_type": {oauthproto.GrantTypeJWTBearer}, + "assertion": {assertion}, + "resource": {resource}, + }) +} + +// startAS2 starts an AS-2 on listener that trusts the AS-1 at as1Issuer. AS-1's +// JWKS is fetched at the first redemption, so AS-1 may start later. user-1 is +// AS-1's sub for the grant's user, bound exactly. The server's own issuer is an +// accepted audience and is not an allowed audience; the resource is. +func startAS2(t *testing.T, listener net.Listener, as1Issuer string) *as2Env { + t.Helper() + key := newAssertionKey(t, "as2-client-key") + jwksFile := filepath.Join(t.TempDir(), "as2-client.jwks") + writeJWKS(t, jwksFile, key) + + resources := []string{xrtIDJAGResource} + // A delegate client must list token exchange; it is the jwt-bearer grant under test. + grants := []string{oauthproto.GrantTypeTokenExchange, oauthproto.GrantTypeJWTBearer} + client := authserver.DelegateClientRunConfig{ + ClientID: xrtTargetClientID, + TokenEndpointAuthMethod: oauthproto.TokenEndpointAuthMethodPrivateKeyJWT, + JWKSFile: jwksFile, + TokenEndpointAuthSigningAlg: "ES256", + GrantTypes: grants, + Scopes: []string{"openid", "profile"}, + Audiences: resources, + TokenExchange: anySelfIssuedSubjectTokens(), + } + + srv, issuer, embedded, _ := startEmbeddedAuthServerOn(t, listener, func(cfg *authserver.RunConfig, issuer string) { + configuredClients(client)(cfg) + cfg.AllowedAudiences = resources + cfg.TrustedIssuers = []tokenexchange.TrustedIssuer{{ + Name: "as1", IssuerURL: as1Issuer, JWKSURL: as1Issuer + "/.well-known/jwks.json", + InsecureAllowHTTP: true, AllowPrivateIPs: true, + }} + cfg.InboundGrants.JWTBearer = &authserver.JWTBearerInboundGrantRunConfig{ + IssuerPolicies: []authserver.JWTBearerIssuerPolicyRunConfig{{ + IssuerRef: "as1", MaxAssertionAge: "2m", + SubjectBindings: []tokenexchange.JWTBearerSubjectBinding{{ + Subject: "user-1", AllowedResources: resources, + }}, + AcceptedAudiences: []string{issuer}, + }}, + } + }, nil) + return &as2Env{ + srv: srv, issuer: issuer, embedded: embedded, + client: clientAuth{clientID: xrtTargetClientID, key: &key}, + } +} + +// startTwoServerIDJAG is the one two-server harness in this package: AS-1 +// mints ID-JAGs and AS-2 trusts AS-1 and redeems them, in one process, over +// HTTP, on memory storage. It binds both listeners first, so AS-2 can be given +// AS-1's issuer and AS-1 can be given AS-2's, then starts AS-2 and AS-1. AS-1's +// broker has one ID-JAG target: as2, with one resource. +func startTwoServerIDJAG(t *testing.T) *twoServerIDJAG { + t.Helper() + listen := func() net.Listener { + listener, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + // Closes a listener whose server never started. After a server has + // stopped, the second close fails harmlessly and the error is ignored. + t.Cleanup(func() { _ = listener.Close() }) + return listener + } + l1, l2 := listen(), listen() + as1Issuer := "http://" + l1.Addr().String() + + as2 := startAS2(t, l2, as1Issuer) + + as1 := startXRTServerOn(t, "memory", l1, func(cfg *authserver.RunConfig, _ string) { + for _, delegate := range cfg.InboundGrants.TokenExchange.DelegateClients { + if delegate.ClientID != cfgBrokerID { + continue + } + delegate.TokenExchange.IDJAG.Targets = []authserver.DelegateClientIDJAGTarget{xrtIDJAGTarget(as2.issuer)} + } + }) + return &twoServerIDJAG{as1: as1, as2: as2} +} + +// mintIDJAG mints an ID-JAG for AS-2 from a fresh grant for user-1. +func (h *twoServerIDJAG) mintIDJAG(t *testing.T) string { + t.Helper() + grant := h.as1.idJAGGrant(t, h.as1.broker) + res := h.as1.requestIDJAG(t, h.as1.broker, grant, h.as2.issuer) + require.Equal(t, http.StatusOK, res.status, res.body) + return res.str(t, "access_token") +} + +// TestIDJAGRedemptionAcrossTwoServers proves AS-1 mints an ID-JAG that AS-2 +// redeems for an access token. +func TestIDJAGRedemptionAcrossTwoServers(t *testing.T) { + t.Parallel() + h := startTwoServerIDJAG(t) + + res := h.as2.redeem(t, h.as2.client, h.mintIDJAG(t), xrtIDJAGResource) + require.Equal(t, http.StatusOK, res.status, res.body) + access := accessTokenClaims(t, h.as2.embedded, res.str(t, "access_token")) + assert.Equal(t, h.as1.issuer+"#user-1", access["sub"], "sub is #") + assert.Equal(t, h.as2.issuer, access["iss"]) + assert.Equal(t, []any{xrtIDJAGResource}, access["aud"]) + assert.Equal(t, xrtTargetClientID, access["client_id"]) + assert.NotContains(t, access, "act") +}