diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go
index 4174c4d4f3..9824512e15 100644
--- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go
+++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go
@@ -553,8 +553,10 @@ type JWTBearerGrantConfig struct {
SubjectBindings []JWTBearerSubjectBinding `json:"subjectBindings"`
// AcceptedAudiences identifies this authorization server's accepted
- // assertion audiences. When omitted, runtime validation defaults to the
- // token endpoint.
+ // assertion audiences. When omitted, plain JWT-bearer assertions must name
+ // the token endpoint, and ID-JAG assertions may name the token endpoint or
+ // this server's issuer identifier, unless the issuer is also an allowed
+ // resource audience. A configured list replaces these defaults.
// +kubebuilder:validation:MaxItems=50
// +kubebuilder:validation:items:MinLength=1
// +kubebuilder:validation:items:MaxLength=2048
diff --git a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml
index 53f1749b82..958bec5085 100644
--- a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml
+++ b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml
@@ -467,8 +467,10 @@ spec:
acceptedAudiences:
description: |-
AcceptedAudiences identifies this authorization server's accepted
- assertion audiences. When omitted, runtime validation defaults to the
- token endpoint.
+ assertion audiences. When omitted, plain JWT-bearer assertions must name
+ the token endpoint, and ID-JAG assertions may name the token endpoint or
+ this server's issuer identifier, unless the issuer is also an allowed
+ resource audience. A configured list replaces these defaults.
items:
maxLength: 2048
minLength: 1
@@ -1540,8 +1542,10 @@ spec:
acceptedAudiences:
description: |-
AcceptedAudiences identifies this authorization server's accepted
- assertion audiences. When omitted, runtime validation defaults to the
- token endpoint.
+ assertion audiences. When omitted, plain JWT-bearer assertions must name
+ the token endpoint, and ID-JAG assertions may name the token endpoint or
+ this server's issuer identifier, unless the issuer is also an allowed
+ resource audience. A configured list replaces these defaults.
items:
maxLength: 2048
minLength: 1
@@ -3604,8 +3608,10 @@ spec:
acceptedAudiences:
description: |-
AcceptedAudiences identifies this authorization server's accepted
- assertion audiences. When omitted, runtime validation defaults to the
- token endpoint.
+ assertion audiences. When omitted, plain JWT-bearer assertions must name
+ the token endpoint, and ID-JAG assertions may name the token endpoint or
+ this server's issuer identifier, unless the issuer is also an allowed
+ resource audience. A configured list replaces these defaults.
items:
maxLength: 2048
minLength: 1
@@ -4677,8 +4683,10 @@ spec:
acceptedAudiences:
description: |-
AcceptedAudiences identifies this authorization server's accepted
- assertion audiences. When omitted, runtime validation defaults to the
- token endpoint.
+ assertion audiences. When omitted, plain JWT-bearer assertions must name
+ the token endpoint, and ID-JAG assertions may name the token endpoint or
+ this server's issuer identifier, unless the issuer is also an allowed
+ resource audience. A configured list replaces these defaults.
items:
maxLength: 2048
minLength: 1
diff --git a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml
index db1701a245..20f557eb37 100644
--- a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml
+++ b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml
@@ -354,8 +354,10 @@ spec:
acceptedAudiences:
description: |-
AcceptedAudiences identifies this authorization server's accepted
- assertion audiences. When omitted, runtime validation defaults to the
- token endpoint.
+ assertion audiences. When omitted, plain JWT-bearer assertions must name
+ the token endpoint, and ID-JAG assertions may name the token endpoint or
+ this server's issuer identifier, unless the issuer is also an allowed
+ resource audience. A configured list replaces these defaults.
items:
maxLength: 2048
minLength: 1
@@ -1427,8 +1429,10 @@ spec:
acceptedAudiences:
description: |-
AcceptedAudiences identifies this authorization server's accepted
- assertion audiences. When omitted, runtime validation defaults to the
- token endpoint.
+ assertion audiences. When omitted, plain JWT-bearer assertions must name
+ the token endpoint, and ID-JAG assertions may name the token endpoint or
+ this server's issuer identifier, unless the issuer is also an allowed
+ resource audience. A configured list replaces these defaults.
items:
maxLength: 2048
minLength: 1
@@ -5883,8 +5887,10 @@ spec:
acceptedAudiences:
description: |-
AcceptedAudiences identifies this authorization server's accepted
- assertion audiences. When omitted, runtime validation defaults to the
- token endpoint.
+ assertion audiences. When omitted, plain JWT-bearer assertions must name
+ the token endpoint, and ID-JAG assertions may name the token endpoint or
+ this server's issuer identifier, unless the issuer is also an allowed
+ resource audience. A configured list replaces these defaults.
items:
maxLength: 2048
minLength: 1
@@ -6956,8 +6962,10 @@ spec:
acceptedAudiences:
description: |-
AcceptedAudiences identifies this authorization server's accepted
- assertion audiences. When omitted, runtime validation defaults to the
- token endpoint.
+ assertion audiences. When omitted, plain JWT-bearer assertions must name
+ the token endpoint, and ID-JAG assertions may name the token endpoint or
+ this server's issuer identifier, unless the issuer is also an allowed
+ resource audience. A configured list replaces these defaults.
items:
maxLength: 2048
minLength: 1
diff --git a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml
index 102a56e524..edd95e98e3 100644
--- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml
+++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml
@@ -470,8 +470,10 @@ spec:
acceptedAudiences:
description: |-
AcceptedAudiences identifies this authorization server's accepted
- assertion audiences. When omitted, runtime validation defaults to the
- token endpoint.
+ assertion audiences. When omitted, plain JWT-bearer assertions must name
+ the token endpoint, and ID-JAG assertions may name the token endpoint or
+ this server's issuer identifier, unless the issuer is also an allowed
+ resource audience. A configured list replaces these defaults.
items:
maxLength: 2048
minLength: 1
@@ -1543,8 +1545,10 @@ spec:
acceptedAudiences:
description: |-
AcceptedAudiences identifies this authorization server's accepted
- assertion audiences. When omitted, runtime validation defaults to the
- token endpoint.
+ assertion audiences. When omitted, plain JWT-bearer assertions must name
+ the token endpoint, and ID-JAG assertions may name the token endpoint or
+ this server's issuer identifier, unless the issuer is also an allowed
+ resource audience. A configured list replaces these defaults.
items:
maxLength: 2048
minLength: 1
@@ -3607,8 +3611,10 @@ spec:
acceptedAudiences:
description: |-
AcceptedAudiences identifies this authorization server's accepted
- assertion audiences. When omitted, runtime validation defaults to the
- token endpoint.
+ assertion audiences. When omitted, plain JWT-bearer assertions must name
+ the token endpoint, and ID-JAG assertions may name the token endpoint or
+ this server's issuer identifier, unless the issuer is also an allowed
+ resource audience. A configured list replaces these defaults.
items:
maxLength: 2048
minLength: 1
@@ -4680,8 +4686,10 @@ spec:
acceptedAudiences:
description: |-
AcceptedAudiences identifies this authorization server's accepted
- assertion audiences. When omitted, runtime validation defaults to the
- token endpoint.
+ assertion audiences. When omitted, plain JWT-bearer assertions must name
+ the token endpoint, and ID-JAG assertions may name the token endpoint or
+ this server's issuer identifier, unless the issuer is also an allowed
+ resource audience. A configured list replaces these defaults.
items:
maxLength: 2048
minLength: 1
diff --git a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml
index b05887e1ae..5a97fb5f56 100644
--- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml
+++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml
@@ -357,8 +357,10 @@ spec:
acceptedAudiences:
description: |-
AcceptedAudiences identifies this authorization server's accepted
- assertion audiences. When omitted, runtime validation defaults to the
- token endpoint.
+ assertion audiences. When omitted, plain JWT-bearer assertions must name
+ the token endpoint, and ID-JAG assertions may name the token endpoint or
+ this server's issuer identifier, unless the issuer is also an allowed
+ resource audience. A configured list replaces these defaults.
items:
maxLength: 2048
minLength: 1
@@ -1430,8 +1432,10 @@ spec:
acceptedAudiences:
description: |-
AcceptedAudiences identifies this authorization server's accepted
- assertion audiences. When omitted, runtime validation defaults to the
- token endpoint.
+ assertion audiences. When omitted, plain JWT-bearer assertions must name
+ the token endpoint, and ID-JAG assertions may name the token endpoint or
+ this server's issuer identifier, unless the issuer is also an allowed
+ resource audience. A configured list replaces these defaults.
items:
maxLength: 2048
minLength: 1
@@ -5886,8 +5890,10 @@ spec:
acceptedAudiences:
description: |-
AcceptedAudiences identifies this authorization server's accepted
- assertion audiences. When omitted, runtime validation defaults to the
- token endpoint.
+ assertion audiences. When omitted, plain JWT-bearer assertions must name
+ the token endpoint, and ID-JAG assertions may name the token endpoint or
+ this server's issuer identifier, unless the issuer is also an allowed
+ resource audience. A configured list replaces these defaults.
items:
maxLength: 2048
minLength: 1
@@ -6959,8 +6965,10 @@ spec:
acceptedAudiences:
description: |-
AcceptedAudiences identifies this authorization server's accepted
- assertion audiences. When omitted, runtime validation defaults to the
- token endpoint.
+ assertion audiences. When omitted, plain JWT-bearer assertions must name
+ the token endpoint, and ID-JAG assertions may name the token endpoint or
+ this server's issuer identifier, unless the issuer is also an allowed
+ resource audience. A configured list replaces these defaults.
items:
maxLength: 2048
minLength: 1
diff --git a/docs/arch/17-token-exchange-delegation.md b/docs/arch/17-token-exchange-delegation.md
index 16e795b01a..c6b1dad130 100644
--- a/docs/arch/17-token-exchange-delegation.md
+++ b/docs/arch/17-token-exchange-delegation.md
@@ -1166,8 +1166,18 @@ rejected, regardless of which issuer each one refers to.
`allowed_audiences` identifies resources that issued access tokens may target.
They must be disjoint: configuring the same value in both is rejected, because
a resource audience must not also make an assertion acceptable to the token
-endpoint. When `accepted_audiences` is omitted, the token endpoint URL is the
-only accepted assertion audience.
+endpoint. When `accepted_audiences` is omitted, a plain JWT-bearer assertion
+must name the token endpoint URL. An ID-JAG may name the token endpoint URL or
+this server's issuer identifier, which is the `aud` the draft requires. A
+configured list replaces both defaults.
+
+The one exception to the issuer default: when this server's issuer identifier
+is also listed in `allowed_audiences`, the ID-JAG handler does not accept it by
+default, for the same reason as the rule above. ID-JAGs then must name the
+token endpoint URL, as before. The server starts normally and logs one warning
+at startup, naming the issuer, if any trusted issuer enables the grant without
+`accepted_audiences`. To accept the issuer in that case, a deployment must
+stop using it as a resource audience.
A `RunConfig` enables the grant per trusted issuer. This example accepts
assertions for the authorization-server URL and permits the exact assertion
@@ -1224,8 +1234,10 @@ spec:
strings the assertion's `aud` must intersect (`audienceIntersects`),
checked by exact-match membership rather than equality — RFC 7523 §3
permits a multi-valued `aud`, so an assertion may additionally name other
- audiences without losing its match. Defaults to `[tokenEndpoint]` when
- unset, preserving the original exact-endpoint-match behavior. This exists
+ audiences without losing its match. When unset, the plain JWT-bearer
+ grant defaults to `[tokenEndpoint]`, preserving the original
+ exact-endpoint-match behavior, and the ID-JAG grant defaults to
+ `[tokenEndpoint, issuer]`, so the issuer identifier is accepted. This exists
to let an issuer's assertions target this AS by more than one valid name
(e.g. across an issuer/token-endpoint URL migration) — it is deliberately
NOT the same relaxation as accepting an arbitrary RFC 8707 resource
@@ -1350,9 +1362,69 @@ Where the two differ is the trust model — the ID-JAG handler is **bound**:
`sub_profile`) are validated as opaque extras and not propagated.
- Everything else is shared with the plain handler: JWKS verification through
the shared `MultiIssuerTokenValidator`, `NoUpstreamSessionClaimKey` stamping
- (an ID-JAG conveys no upstream vendor session at this server), the
- exactly-one-`resource` requirement, consume-before-issue, and the issued
- token's lifetime being capped by the assertion's remaining validity.
+ (an ID-JAG conveys no upstream vendor session at this server),
+ consume-before-issue, and the issued token's lifetime being capped by the
+ assertion's remaining validity.
+- **One exception to the shared `resource` rule.** The plain handler needs
+ exactly one `resource` parameter. The ID-JAG handler needs the same, except
+ when the request has no `resource` parameter at all and the ID-JAG's
+ `resource` claim holds a single valid value: draft §4.4 defines no `resource`
+ parameter for redemption, so that value is used. Every other case, including
+ an empty or repeated parameter, still needs exactly one parameter. A single
+ claim value that is not an absolute URI is refused with `invalid_target`, the
+ same error a requested resource gets for that. The chosen
+ resource goes through the same subject-binding and client-audience checks.
+
+**Departures from the draft are logged, not refused.** The handler accepts some
+ID-JAGs that draft §4.4.1 does not allow. It logs these only for a request that
+passes validation: after the replay check and the lifetime check have both
+succeeded. Issuance can still fail later. A refused request, such as a replay,
+logs nothing. The handler logs each finding once per assertion issuer and
+finding at WARN, and later ones at DEBUG. The line carries only `issuer`,
+`client_id`, `finding` and, for one finding, `hint`. It never carries the
+subject, `jti` or claim values. The findings are:
+
+- `multiple_audiences`: `aud` has more than one value.
+- `audience_not_issuer`: `aud` does not contain this server's issuer
+ identifier. The handler accepts any value in the assertion issuer's
+ `jwt_bearer_grant.accepted_audiences`. When that list is empty, it accepts
+ both the token endpoint URL and the issuer identifier, so this finding means
+ the IdP still uses the token endpoint (or another configured value) as `aud`.
+ This line also carries a `hint` attribute that says what to change. If
+ `accepted_audiences` is empty, the issuer identifier is already accepted, so
+ have the IdP use it as `aud`. If the list does not hold the issuer
+ identifier, add it. If the list already holds it, have the IdP use it as
+ `aud`. This finding is not logged when the issuer identifier is also in
+ `allowed_audiences`, because then no `aud` can name it (see
+ [JWT-bearer configuration](#jwt-bearer-configuration)); the startup warning
+ reports that case instead.
+- `resource_malformed`: the ID-JAG has a `resource` claim (a JSON `null` counts)
+ that is not a non-empty string or a non-empty array of distinct non-empty
+ strings.
+- `resource_not_covered`: the `resource` claim is well formed, and the `resource`
+ the client requested is not in it. When the request has a `resource`
+ parameter, the handler takes the resource from it, so the claim can disagree.
+ A resource defaulted from the claim is always covered.
+
+A malformed claim is never also reported as not covered. An ID-JAG with no
+`resource` claim has no resource finding. The two audience findings can appear
+together.
+
+This is logging only. It changes nothing about what is accepted.
+
+The handler also accepts two things the draft does not allow, and nothing logs
+them:
+
+- Draft §4.4 says the server MUST reject a request that has neither client
+ authentication nor a sender-constrained ID-JAG (§9.11) with `invalid_client`.
+ The handler accepts a public client that is identified only by `client_id`.
+- Draft §9.11 says an ID-JAG with a `cnf` claim needs proof of possession, and
+ a server that cannot check it MUST refuse the ID-JAG with `invalid_grant`.
+ No code at this server reads `cnf`, so such an ID-JAG is accepted without
+ proof of possession.
+
+A strict mode would have to refuse these two as well as the four logged
+findings.
## Operational notes
diff --git a/docs/operator/crd-api.md b/docs/operator/crd-api.md
index 38e13b2d76..7b2b42cb59 100644
--- a/docs/operator/crd-api.md
+++ b/docs/operator/crd-api.md
@@ -2494,7 +2494,7 @@ _Appears in:_
| --- | --- | --- | --- |
| `maxAssertionAge` _[Duration](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#duration-v1-meta)_ | MaxAssertionAge caps the exp-iat interval independently of exp. | | Required: \{\}
|
| `subjectBindings` _[api.v1beta1.JWTBearerSubjectBinding](#apiv1beta1jwtbearersubjectbinding) array_ | SubjectBindings maps an exact external subject to allowed RFC 8707
resources. | | MaxItems: 50
MinItems: 1
Required: \{\}
|
-| `acceptedAudiences` _string array_ | AcceptedAudiences identifies this authorization server's accepted
assertion audiences. When omitted, runtime validation defaults to the
token endpoint. | | MaxItems: 50
items:MaxLength: 2048
items:MinLength: 1
items:Pattern: `^https?://[^[:space:]]+$`
Optional: \{\}
|
+| `acceptedAudiences` _string array_ | AcceptedAudiences identifies this authorization server's accepted
assertion audiences. When omitted, plain JWT-bearer assertions must name
the token endpoint, and ID-JAG assertions may name the token endpoint or
this server's issuer identifier, unless the issuer is also an allowed
resource audience. A configured list replaces these defaults. | | MaxItems: 50
items:MaxLength: 2048
items:MinLength: 1
items:Pattern: `^https?://[^[:space:]]+$`
Optional: \{\}
|
#### api.v1beta1.JWTBearerInboundGrantConfig
@@ -2529,7 +2529,7 @@ _Appears in:_
| `issuerRef` _string_ | IssuerRef references trustedIssuers[].name. | | MaxLength: 253
MinLength: 1
|
| `maxAssertionAge` _[Duration](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#duration-v1-meta)_ | MaxAssertionAge caps the exp-iat interval independently of exp. | | Required: \{\}
|
| `subjectBindings` _[api.v1beta1.JWTBearerSubjectBinding](#apiv1beta1jwtbearersubjectbinding) array_ | SubjectBindings maps an exact external subject to allowed RFC 8707
resources. | | MaxItems: 50
MinItems: 1
Required: \{\}
|
-| `acceptedAudiences` _string array_ | AcceptedAudiences identifies this authorization server's accepted
assertion audiences. When omitted, runtime validation defaults to the
token endpoint. | | MaxItems: 50
items:MaxLength: 2048
items:MinLength: 1
items:Pattern: `^https?://[^[:space:]]+$`
Optional: \{\}
|
+| `acceptedAudiences` _string array_ | AcceptedAudiences identifies this authorization server's accepted
assertion audiences. When omitted, plain JWT-bearer assertions must name
the token endpoint, and ID-JAG assertions may name the token endpoint or
this server's issuer identifier, unless the issuer is also an allowed
resource audience. A configured list replaces these defaults. | | MaxItems: 50
items:MaxLength: 2048
items:MinLength: 1
items:Pattern: `^https?://[^[:space:]]+$`
Optional: \{\}
|
diff --git a/docs/server/docs.go b/docs/server/docs.go
index 82a17c2662..10f941b7ea 100644
--- a/docs/server/docs.go
+++ b/docs/server/docs.go
@@ -5787,7 +5787,7 @@ const docTemplate = `{
"description": "JWTBearerGrant optionally enables the plain RFC 7523 JWT-bearer grant.\nIt accepts assertions from this issuer without client authentication and\nlimits their maximum age, subjects, and RFC 8707 resources. It is\nindependent from RFC 8693 delegation policy.\n\nThis legacy field is deprecated; configure RFC 7523 policy under\ninbound_grants.jwt_bearer.issuer_policies.",
"properties": {
"accepted_audiences": {
- "description": "AcceptedAudiences is the set of \"this AS\" identity strings an\nassertion's \"aud\" claim must intersect — e.g. to support migrating\nthis server's issuer/token-endpoint URL, or exposing it under more\nthan one valid name. Each value uniquely identifies this\nauthorization server for this grant; it is NOT a resource/API\nidentifier — a bare resource audience is deliberately not accepted\nhere, that would let any RFC 8707 resource-scoped token satisfy the\ngrant instead of only tokens minted for this AS. Defaults to\n[tokenEndpoint] when empty, preserving prior exact-match behavior.",
+ "description": "AcceptedAudiences is the set of \"this AS\" identity strings an\nassertion's \"aud\" claim must intersect — e.g. to support migrating\nthis server's issuer/token-endpoint URL, or exposing it under more\nthan one valid name. Each value uniquely identifies this\nauthorization server for this grant; it is NOT a resource/API\nidentifier — a bare resource audience is deliberately not accepted\nhere, that would let any RFC 8707 resource-scoped token satisfy the\ngrant instead of only tokens minted for this AS. When empty, the plain\nJWT-bearer grant accepts the token endpoint, and the ID-JAG grant accepts\nthe token endpoint and this server's issuer identifier, unless the issuer\nis also an allowed resource audience. A configured list replaces both\ndefaults.",
"items": {
"type": "string"
},
diff --git a/docs/server/swagger.json b/docs/server/swagger.json
index 6474cfa7ff..c992b69158 100644
--- a/docs/server/swagger.json
+++ b/docs/server/swagger.json
@@ -5780,7 +5780,7 @@
"description": "JWTBearerGrant optionally enables the plain RFC 7523 JWT-bearer grant.\nIt accepts assertions from this issuer without client authentication and\nlimits their maximum age, subjects, and RFC 8707 resources. It is\nindependent from RFC 8693 delegation policy.\n\nThis legacy field is deprecated; configure RFC 7523 policy under\ninbound_grants.jwt_bearer.issuer_policies.",
"properties": {
"accepted_audiences": {
- "description": "AcceptedAudiences is the set of \"this AS\" identity strings an\nassertion's \"aud\" claim must intersect — e.g. to support migrating\nthis server's issuer/token-endpoint URL, or exposing it under more\nthan one valid name. Each value uniquely identifies this\nauthorization server for this grant; it is NOT a resource/API\nidentifier — a bare resource audience is deliberately not accepted\nhere, that would let any RFC 8707 resource-scoped token satisfy the\ngrant instead of only tokens minted for this AS. Defaults to\n[tokenEndpoint] when empty, preserving prior exact-match behavior.",
+ "description": "AcceptedAudiences is the set of \"this AS\" identity strings an\nassertion's \"aud\" claim must intersect — e.g. to support migrating\nthis server's issuer/token-endpoint URL, or exposing it under more\nthan one valid name. Each value uniquely identifies this\nauthorization server for this grant; it is NOT a resource/API\nidentifier — a bare resource audience is deliberately not accepted\nhere, that would let any RFC 8707 resource-scoped token satisfy the\ngrant instead of only tokens minted for this AS. When empty, the plain\nJWT-bearer grant accepts the token endpoint, and the ID-JAG grant accepts\nthe token endpoint and this server's issuer identifier, unless the issuer\nis also an allowed resource audience. A configured list replaces both\ndefaults.",
"items": {
"type": "string"
},
diff --git a/docs/server/swagger.yaml b/docs/server/swagger.yaml
index 7d16c424f2..03308f8537 100644
--- a/docs/server/swagger.yaml
+++ b/docs/server/swagger.yaml
@@ -5586,8 +5586,11 @@ components:
authorization server for this grant; it is NOT a resource/API
identifier — a bare resource audience is deliberately not accepted
here, that would let any RFC 8707 resource-scoped token satisfy the
- grant instead of only tokens minted for this AS. Defaults to
- [tokenEndpoint] when empty, preserving prior exact-match behavior.
+ grant instead of only tokens minted for this AS. When empty, the plain
+ JWT-bearer grant accepts the token endpoint, and the ID-JAG grant accepts
+ the token endpoint and this server's issuer identifier, unless the issuer
+ is also an allowed resource audience. A configured list replaces both
+ defaults.
items:
type: string
type: array
diff --git a/pkg/auth/token.go b/pkg/auth/token.go
index 9ef9c07a30..21b0a49e27 100644
--- a/pkg/auth/token.go
+++ b/pkg/auth/token.go
@@ -31,6 +31,7 @@ import (
"github.com/stacklok/toolhive/pkg/authserver/server/keys"
"github.com/stacklok/toolhive/pkg/networking"
"github.com/stacklok/toolhive/pkg/oauthproto"
+ "github.com/stacklok/toolhive/pkg/oauthproto/idjag"
)
// TokenIntrospector defines the interface for token introspection providers
@@ -908,7 +909,7 @@ func validateTokenHeader(token *jwt.Token) (string, error) {
// get one accepted here when no audience is configured. This runs in the
// key function, before the signature is verified; that is safe because the
// check can only refuse a token.
- if typ, _ := token.Header["typ"].(string); oauthproto.IsJOSEType(typ, oauthproto.JWTTypeIDJAG) {
+ if typ, _ := token.Header["typ"].(string); idjag.IsIDJAG(typ) {
return "", errors.New("an ID-JAG is not accepted as an access token")
}
diff --git a/pkg/authserver/server/tokenexchange/handler.go b/pkg/authserver/server/tokenexchange/handler.go
index 91ba3d32e7..4999a7b40f 100644
--- a/pkg/authserver/server/tokenexchange/handler.go
+++ b/pkg/authserver/server/tokenexchange/handler.go
@@ -326,7 +326,7 @@ func (h *Handler) PopulateTokenEndpointResponse(
}
// Per RFC 8693 Section 2.2.1, the response MUST include issued_token_type.
- responder.SetExtra("issued_token_type", oauthproto.TokenTypeAccessToken)
+ responder.SetExtra(oauthproto.ParamIssuedTokenType, oauthproto.TokenTypeAccessToken)
h.echoAuthorizationDetails(requester, responder)
diff --git a/pkg/authserver/server/tokenexchange/id_jag_handler.go b/pkg/authserver/server/tokenexchange/id_jag_handler.go
index 0a506fd6dd..20087be15b 100644
--- a/pkg/authserver/server/tokenexchange/id_jag_handler.go
+++ b/pkg/authserver/server/tokenexchange/id_jag_handler.go
@@ -5,7 +5,10 @@ package tokenexchange
import (
"context"
+ "log/slog"
+ "net/url"
"slices"
+ "sync"
"time"
"github.com/ory/fosite"
@@ -16,6 +19,7 @@ import (
"github.com/stacklok/toolhive/pkg/authserver/server/session"
"github.com/stacklok/toolhive/pkg/authserver/storage"
"github.com/stacklok/toolhive/pkg/oauthproto"
+ "github.com/stacklok/toolhive/pkg/oauthproto/idjag"
)
// idJAGReplayPurpose namespaces ID-JAG replay keys apart from plain
@@ -39,10 +43,13 @@ const idJAGReplayPurpose = "id-jag"
// connection — so this handler never skips client authentication
// (CanSkipClientAuth) and requires the authenticated client to be that
// client. Confidential clients authenticate fully; a public client is
-// identified by client_id, which is sufficient binding here because the
-// assertion itself is the primary credential: single-use (required jti),
-// short-lived (maxAssertionAge), and audience-pinned to this server
-// (acceptedAudiences). The plain handler's synthetic client is not needed —
+// identified by client_id, which is accepted here because the assertion
+// itself is the primary credential: single-use (required jti), short-lived
+// (maxAssertionAge), and audience-pinned to this server (acceptedAudiences).
+// Draft §4.4 does not allow this: it requires client authentication or a
+// sender-constrained ID-JAG. This is a known departure that is not logged;
+// see the departures paragraph in docs/arch/17-token-exchange-delegation.md.
+// The plain handler's synthetic client is not needed —
// the redeeming client is a real registered one.
//
// The redeeming client's registered grant_types metadata is deliberately not
@@ -66,15 +73,47 @@ type IDJAGHandler struct {
// explicitGrantClients holds the IDs of clients that must list the
// jwt-bearer grant in their registered grant types.
explicitGrantClients map[string]struct{}
+
+ // issuer supplies this authorization server's issuer identifier, the same
+ // value the server's own token validator uses (fosite.Config
+ // AccessTokenIssuer).
+ issuer fosite.AccessTokenIssuerProvider
+
+ // issuerIsResource is set once at construction when the issuer identifier
+ // is also one of the server's resource audiences (allowed_audiences). The
+ // issuer then stays out of the default accepted audiences, because an
+ // access token minted for that resource would otherwise be redeemable as
+ // an assertion, and audience_not_issuer is not logged, because no IdP
+ // could fix it. It is a bool, not a copy of the issuer, so the issuer
+ // provider above remains the only source of the issuer value.
+ issuerIsResource bool
+
+ // logger receives the draft-departure lines; nil means slog.Default().
+ logger *slog.Logger
+
+ // warned records the (assertion issuer, finding) pairs already logged at
+ // Warn. Its size is bounded by the trusted issuers times the findings.
+ warned sync.Map
}
+// draftDeparture names a way an accepted ID-JAG departs from draft-ietf-oauth-
+// identity-assertion-authz-grant-06 Section 4.4.1.
+type draftDeparture string
+
+const (
+ departureMultipleAudiences draftDeparture = "multiple_audiences"
+ departureAudienceNotIssuer draftDeparture = "audience_not_issuer"
+ departureResourceMalformed draftDeparture = "resource_malformed"
+ departureResourceNotCovered draftDeparture = "resource_not_covered"
+)
+
// newIDJAGIssuanceHandler constructs the production bound handler over the
// same issuance core as newJWTBearerIssuanceHandler; see that constructor
// for the dependency requirements.
func newIDJAGIssuanceHandler(
validator JWTBearerAssertionValidator, tokenEndpoint string, consumer storage.AssertionJWTConsumer,
config *fosite.Config, strategy oauth2.AccessTokenStrategy, tokenStorage oauth2.AccessTokenStorage,
- trustedIssuers []TrustedIssuer, explicitGrantClientIDs []string,
+ trustedIssuers []TrustedIssuer, explicitGrantClientIDs, allowedAudiences []string, logger *slog.Logger,
) (*IDJAGHandler, error) {
core, err := newJWTBearerIssuanceHandler(
validator, tokenEndpoint, consumer, config, strategy, tokenStorage, trustedIssuers)
@@ -85,7 +124,21 @@ func newIDJAGIssuanceHandler(
for _, id := range explicitGrantClientIDs {
explicitGrantClients[id] = struct{}{}
}
- return &IDJAGHandler{core: core, explicitGrantClients: explicitGrantClients}, nil
+ h := &IDJAGHandler{core: core, explicitGrantClients: explicitGrantClients, issuer: config, logger: logger}
+ asIssuer := config.GetAccessTokenIssuer(context.Background())
+ h.issuerIsResource = asIssuer != "" && slices.Contains(allowedAudiences, asIssuer)
+ if h.issuerIsResource && slices.ContainsFunc(trustedIssuers, func(ti TrustedIssuer) bool {
+ return ti.JWTBearerGrant != nil && len(ti.JWTBearerGrant.AcceptedAudiences) == 0
+ }) {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ logger.Warn("The issuer identifier is also a resource audience (allowed_audiences), "+
+ "so ID-JAGs with aud set to the issuer are not accepted by default; "+
+ "have the IdP use the token endpoint as aud, or stop listing the issuer in allowed_audiences",
+ "issuer", asIssuer)
+ }
+ return h, nil
}
// CanHandleTokenEndpointRequest claims only recognized ID-JAG assertions —
@@ -121,7 +174,7 @@ func (h *IDJAGHandler) HandleTokenEndpointRequest(ctx context.Context, requester
if err != nil {
return err
}
- claims, err := h.core.validator.ValidateJWTBearerAssertion(ctx, assertion, h.core.tokenEndpoint)
+ claims, err := h.core.validator.ValidateJWTBearerAssertion(ctx, assertion, h.defaultAudiences(ctx))
if err != nil {
return errorsx.WithStack(fosite.ErrInvalidGrant.WithHint("The ID-JAG assertion is invalid or could not be verified."))
}
@@ -144,7 +197,7 @@ func (h *IDJAGHandler) HandleTokenEndpointRequest(ctx context.Context, requester
if err := h.checkClientBinding(requester, claims); err != nil {
return err
}
- resource, err := validateJWTBearerPolicy(requester.GetRequestForm(), claims, policy)
+ resource, err := checkIDJAGPolicy(requester, claims, policy)
if err != nil {
return err
}
@@ -162,6 +215,7 @@ func (h *IDJAGHandler) HandleTokenEndpointRequest(ctx context.Context, requester
if err != nil {
return err
}
+ h.logDraftDepartures(ctx, claims, policy, requester.GetClient().GetID(), resource)
// Subject is namespaced by issuer exactly like the plain handler's, so a
// resource server sees one consistent subject form for every
// assertion-derived token regardless of which handler minted it. The
@@ -198,6 +252,128 @@ func (h *IDJAGHandler) PopulateTokenEndpointResponse(
return h.core.populateAccessTokenResponse(ctx, requester, responder)
}
+// checkIDJAGPolicy runs the per-issuer policy checks in the same order as
+// the plain handler (assertion age, then resource, then subject binding) and
+// returns the resource the token is for.
+func checkIDJAGPolicy(
+ requester fosite.AccessRequester, claims *ValidatedClaims, policy *JWTBearerGrantPolicy,
+) (string, error) {
+ if err := checkAssertionMaxAge(claims, policy); err != nil {
+ return "", err
+ }
+ resource, err := idJAGResource(requester.GetRequestForm(), claims)
+ if err != nil {
+ return "", err
+ }
+ if err := checkSubjectBinding(claims, policy, resource); err != nil {
+ return "", err
+ }
+ return resource, nil
+}
+
+// idJAGResource picks the resource an ID-JAG redemption is for. Draft section
+// 4.4 defines no resource parameter for redemption, so a client may leave it
+// out. A resource claim with a single value names the target without
+// ambiguity, so it is used as the default when the request has no resource
+// parameter. Every other case keeps the rule of requestedResource: if the
+// parameter is present in any form (empty or repeated too) it decides, and
+// without a usable single-value claim the request is refused exactly as
+// before. A defaulted value gets the same URI check as a requested one.
+func idJAGResource(form url.Values, claims *ValidatedClaims) (string, error) {
+ if _, present := form["resource"]; present {
+ return requestedResource(form)
+ }
+ claim, present := claims.Extra["resource"]
+ if !present {
+ return requestedResource(form)
+ }
+ values, wellFormed := idjag.ResourceClaim(claim)
+ if !wellFormed || len(values) != 1 {
+ return requestedResource(form)
+ }
+ if err := server.ValidateAudienceURI(values[0]); err != nil {
+ return "", errorsx.WithStack(err)
+ }
+ return values[0], nil
+}
+
+// logDraftDepartures reports an ID-JAG that departs from the draft. It runs
+// once the request has passed validation (issuance can still fail later in
+// Populate) and changes nothing about what is accepted. The first occurrence
+// of each (assertion issuer, finding) pair is logged at Warn and later ones
+// at Debug. The lines carry no subject, jti or claim values.
+func (h *IDJAGHandler) logDraftDepartures(
+ ctx context.Context, claims *ValidatedClaims, policy *JWTBearerGrantPolicy, clientID, resource string,
+) {
+ var found []draftDeparture
+ if len(claims.Audience) > 1 {
+ found = append(found, departureMultipleAudiences)
+ }
+ // An issuer that is also a resource audience can never be an accepted aud:
+ // it is left out of the defaults, and accepted_audiences must not overlap
+ // allowed_audiences. No IdP could fix the finding, and the startup warning
+ // in newIDJAGIssuanceHandler already reports the configuration.
+ asIssuer := h.issuer.GetAccessTokenIssuer(ctx)
+ if asIssuer != "" && !h.issuerIsResource && !slices.Contains(claims.Audience, asIssuer) {
+ found = append(found, departureAudienceNotIssuer)
+ }
+ if claim, present := claims.Extra["resource"]; present {
+ values, wellFormed := idjag.ResourceClaim(claim)
+ switch {
+ case !wellFormed:
+ found = append(found, departureResourceMalformed)
+ case !slices.Contains(values, resource):
+ found = append(found, departureResourceNotCovered)
+ }
+ }
+ if len(found) == 0 {
+ return
+ }
+ logger := h.logger
+ if logger == nil {
+ logger = slog.Default()
+ }
+ for _, finding := range found {
+ level := slog.LevelDebug
+ if _, seen := h.warned.LoadOrStore([2]string{claims.Issuer, string(finding)}, struct{}{}); !seen {
+ level = slog.LevelWarn
+ }
+ attrs := []any{"issuer", claims.Issuer, "client_id", clientID, "finding", string(finding)}
+ if finding == departureAudienceNotIssuer {
+ attrs = append(attrs, "hint", audienceHint(policy, asIssuer))
+ }
+ logger.Log(ctx, level, "ID-JAG departs from the draft; accepted for compatibility", attrs...)
+ }
+}
+
+// audienceHint tells the operator how to stop audience_not_issuer.
+func audienceHint(policy *JWTBearerGrantPolicy, asIssuer string) string {
+ switch {
+ case len(policy.AcceptedAudiences) == 0:
+ return "this server's issuer identifier is accepted by default; have the IdP use it as aud"
+ case !slices.Contains(policy.AcceptedAudiences, asIssuer):
+ return "add this server's issuer identifier to jwt_bearer_grant.accepted_audiences"
+ default:
+ return "have the IdP use this server's issuer identifier as aud"
+ }
+}
+
+// defaultAudiences is what an ID-JAG's aud may name when the issuer's policy
+// configures no accepted_audiences. Draft section 4.4.1 makes the resource
+// AS's issuer identifier the aud, so it is accepted along with the token
+// endpoint. This is safe because an ID-JAG is already refused as an RFC 8693
+// subject token and as an access token (typ checks), a plain JWT with aud =
+// issuer goes to the plain handler, which still accepts only the token
+// endpoint, and the issuer and token endpoint both name this server. The
+// issuer is left out when it is also a resource audience (issuerIsResource).
+func (h *IDJAGHandler) defaultAudiences(ctx context.Context) []string {
+ audiences := []string{h.core.tokenEndpoint}
+ if issuer := h.issuer.GetAccessTokenIssuer(ctx); issuer != "" && !h.issuerIsResource {
+ audiences = append(audiences, issuer)
+ }
+ return audiences
+}
+
// checkClientGrant refuses an explicit-grant client whose registered grant types
// do not include jwt-bearer.
func (h *IDJAGHandler) checkClientGrant(requester fosite.AccessRequester) error {
@@ -246,10 +422,10 @@ func IDJAGIssuanceFactory(
func(
validator JWTBearerAssertionValidator, tokenEndpoint string, consumer storage.AssertionJWTConsumer,
config *fosite.Config, strategy oauth2.AccessTokenStrategy, tokenStorage oauth2.AccessTokenStorage,
- resolvedIssuers []TrustedIssuer,
+ resolvedIssuers []TrustedIssuer, allowedAudiences []string,
) (any, error) {
- return newIDJAGIssuanceHandler(
- validator, tokenEndpoint, consumer, config, strategy, tokenStorage, resolvedIssuers, explicitGrantClientIDs)
+ return newIDJAGIssuanceHandler(validator, tokenEndpoint, consumer, config, strategy, tokenStorage,
+ resolvedIssuers, explicitGrantClientIDs, allowedAudiences, nil)
})
}
diff --git a/pkg/authserver/server/tokenexchange/id_jag_handler_test.go b/pkg/authserver/server/tokenexchange/id_jag_handler_test.go
index c34b085b96..83678bdde2 100644
--- a/pkg/authserver/server/tokenexchange/id_jag_handler_test.go
+++ b/pkg/authserver/server/tokenexchange/id_jag_handler_test.go
@@ -6,10 +6,14 @@ package tokenexchange
import (
"context"
"errors"
+ "log/slog"
"net/url"
+ "strings"
"testing"
"time"
+ "github.com/go-jose/go-jose/v4"
+ "github.com/go-jose/go-jose/v4/jwt"
"github.com/ory/fosite"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -79,17 +83,28 @@ func validIDJAGClaims() *ValidatedClaims {
func newIDJAGTestHandler(
t *testing.T, validator *testJWTBearerAssertionValidator, consumer *recordingAssertionConsumer,
+) *IDJAGHandler {
+ t.Helper()
+ return newIDJAGTestHandlerWithIssuer(t, validator, consumer, "")
+}
+
+func newIDJAGTestHandlerWithIssuer(
+ t *testing.T, validator *testJWTBearerAssertionValidator, consumer *recordingAssertionConsumer, asIssuer string,
) *IDJAGHandler {
t.Helper()
handler, err := newIDJAGIssuanceHandler(
validator,
testTokenEndpoint,
consumer,
- &fosite.Config{AccessTokenLifespan: time.Hour, AudienceMatchingStrategy: fosite.DefaultAudienceMatchingStrategy},
+ &fosite.Config{
+ AccessTokenLifespan: time.Hour,
+ AudienceMatchingStrategy: fosite.DefaultAudienceMatchingStrategy,
+ AccessTokenIssuer: asIssuer,
+ },
&mockAccessTokenStrategy{},
&mockAccessTokenStorage{},
idJAGResolvedIssuers(t),
- nil,
+ nil, nil, nil,
)
require.NoError(t, err)
return handler
@@ -333,16 +348,29 @@ func TestIDJAGHandler_ClientGrantAndAudience(t *testing.T) {
}
}
+func TestIDJAGHandler_DefaultAudiencesWithoutIssuer(t *testing.T) {
+ t.Parallel()
+
+ tj := newTestJWKS(t)
+ validator := &testJWTBearerAssertionValidator{claims: validIDJAGClaims()}
+ h := newIDJAGTestHandler(t, validator, &recordingAssertionConsumer{})
+
+ require.NoError(t, h.HandleTokenEndpointRequest(context.Background(), newIDJAGRequest(t, tj, idJAGTestClientID)))
+ assert.Equal(t, []string{testTokenEndpoint}, validator.gotDefaults)
+}
+
func TestIDJAGHandler_IssuesBoundSession(t *testing.T) {
t.Parallel()
tj := newTestJWKS(t)
claims := validIDJAGClaims()
consumer := &recordingAssertionConsumer{}
- h := newIDJAGTestHandler(t, &testJWTBearerAssertionValidator{claims: claims}, consumer)
+ validator := &testJWTBearerAssertionValidator{claims: claims}
+ h := newIDJAGTestHandlerWithIssuer(t, validator, consumer, idJAGTestASIssuer)
req := newIDJAGRequest(t, tj, idJAGTestClientID)
require.NoError(t, h.HandleTokenEndpointRequest(context.Background(), req))
+ assert.Equal(t, []string{testTokenEndpoint, idJAGTestASIssuer}, validator.gotDefaults)
// Replay consumption happened under the ID-JAG purpose with the JAG's jti —
// never the plain handler's purpose or an assertion-hash fallback.
@@ -425,3 +453,636 @@ func TestIDJAGIssuanceFactory_RequiresSharedValidator(t *testing.T) {
require.Error(t, err)
assert.Contains(t, err.Error(), "shared validator")
}
+
+func TestIDJAGHandler_MaxAgeIsCheckedBeforeResource(t *testing.T) {
+ t.Parallel()
+
+ claims := validIDJAGClaims()
+ claims.IssuedAt = time.Now().Add(-2 * time.Hour)
+ h := newIDJAGTestHandler(t, &testJWTBearerAssertionValidator{claims: claims}, &recordingAssertionConsumer{})
+ req := newIDJAGRequest(t, newTestJWKS(t), idJAGTestClientID)
+ delete(req.Form, "resource")
+
+ err := h.HandleTokenEndpointRequest(context.Background(), req)
+ require.Error(t, err)
+ assert.ErrorIs(t, err, fosite.ErrInvalidGrant)
+ assert.NotErrorIs(t, err, fosite.ErrInvalidRequest)
+}
+
+const (
+ idJAGTestASIssuer = "https://as.example.com"
+ idJAGTestOtherAud = "https://other.example.com"
+ hintNoAcceptedAud = "this server's issuer identifier is accepted by default; have the IdP use it as aud"
+ hintAcceptedAudMissed = "add this server's issuer identifier to jwt_bearer_grant.accepted_audiences"
+ hintIdPUsesWrongAud = "have the IdP use this server's issuer identifier as aud"
+)
+
+// newIDJAGDepartureHandler builds a handler whose AS issuer identifier is
+// asIssuer, whose trusted issuers all carry acceptedAudiences, and whose
+// departure lines go to the returned buffer. The logger is handler-local, so
+// the process-wide default logger is untouched and tests stay parallel.
+func newIDJAGDepartureHandler(
+ t *testing.T, claims *ValidatedClaims, asIssuer string, acceptedAudiences []string, trustedIssuerURLs ...string,
+) (*IDJAGHandler, *recordingAssertionConsumer, *strings.Builder) {
+ t.Helper()
+ if len(trustedIssuerURLs) == 0 {
+ trustedIssuerURLs = []string{idJAGTestIssuer}
+ }
+ trusted := make([]TrustedIssuer, 0, len(trustedIssuerURLs))
+ for _, issuerURL := range trustedIssuerURLs {
+ trusted = append(trusted, TrustedIssuer{
+ IssuerURL: issuerURL,
+ AllowedDelegateClients: []string{anyDelegateClient},
+ JWTBearerGrant: &JWTBearerGrantPolicy{
+ MaxAssertionAge: time.Hour.String(),
+ AcceptedAudiences: acceptedAudiences,
+ SubjectBindings: []JWTBearerSubjectBinding{
+ {Subject: idJAGTestSubject, AllowedResources: []string{idJAGTestResource}},
+ },
+ },
+ })
+ }
+ resolved, err := ResolveJWTBearerGrantPolicies(trusted)
+ require.NoError(t, err)
+ consumer := &recordingAssertionConsumer{}
+ handler, err := newIDJAGIssuanceHandler(
+ &testJWTBearerAssertionValidator{claims: claims},
+ testTokenEndpoint,
+ consumer,
+ &fosite.Config{
+ AccessTokenIssuer: asIssuer,
+ AccessTokenLifespan: time.Hour,
+ AudienceMatchingStrategy: fosite.DefaultAudienceMatchingStrategy,
+ },
+ &mockAccessTokenStrategy{},
+ &mockAccessTokenStorage{},
+ resolved,
+ nil, nil, nil,
+ )
+ require.NoError(t, err)
+ var buf strings.Builder
+ handler.logger = slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
+ return handler, consumer, &buf
+}
+
+func logLinesAt(out *strings.Builder, level string) []string {
+ var lines []string
+ for _, line := range strings.Split(out.String(), "\n") {
+ if strings.Contains(line, "level="+level+" ") {
+ lines = append(lines, line)
+ }
+ }
+ return lines
+}
+
+func nonEmptyLines(out *strings.Builder) []string {
+ var lines []string
+ for _, line := range strings.Split(out.String(), "\n") {
+ if line != "" {
+ lines = append(lines, line)
+ }
+ }
+ return lines
+}
+
+func TestIDJAGHandler_LogsDraftDepartures(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ asIssuer string
+ accepted []string
+ audience []string
+ resource any // the resource claim; nil leaves it out
+ want []draftDeparture
+ wantHint string // expected hint on the audience_not_issuer line; empty means no hint attr
+ }{
+ {
+ name: "conforming ID-JAG logs nothing",
+ asIssuer: idJAGTestASIssuer,
+ audience: []string{idJAGTestASIssuer},
+ resource: idJAGTestResource,
+ },
+ {
+ name: "absent resource claim is not a departure",
+ asIssuer: idJAGTestASIssuer,
+ audience: []string{idJAGTestASIssuer},
+ },
+ {
+ name: "two audiences",
+ asIssuer: idJAGTestASIssuer,
+ audience: []string{idJAGTestASIssuer, testTokenEndpoint},
+ want: []draftDeparture{departureMultipleAudiences},
+ },
+ {
+ name: "audience is the token endpoint only, accepted_audiences empty",
+ asIssuer: idJAGTestASIssuer,
+ audience: []string{testTokenEndpoint},
+ want: []draftDeparture{departureAudienceNotIssuer},
+ wantHint: hintNoAcceptedAud,
+ },
+ {
+ name: "accepted_audiences lacks the issuer",
+ asIssuer: idJAGTestASIssuer,
+ accepted: []string{idJAGTestOtherAud},
+ audience: []string{idJAGTestOtherAud},
+ want: []draftDeparture{departureAudienceNotIssuer},
+ wantHint: hintAcceptedAudMissed,
+ },
+ {
+ name: "accepted_audiences has the issuer but the IdP does not use it",
+ asIssuer: idJAGTestASIssuer,
+ accepted: []string{idJAGTestASIssuer, idJAGTestOtherAud},
+ audience: []string{idJAGTestOtherAud},
+ want: []draftDeparture{departureAudienceNotIssuer},
+ wantHint: hintIdPUsesWrongAud,
+ },
+ {
+ name: "unknown AS issuer skips the audience check",
+ audience: []string{testTokenEndpoint},
+ },
+ {
+ name: "resource claim does not contain the requested resource",
+ asIssuer: idJAGTestASIssuer,
+ audience: []string{idJAGTestASIssuer},
+ resource: []any{idJAGTestOtherAud},
+ want: []draftDeparture{departureResourceNotCovered},
+ },
+ {
+ name: "string resource claim names another resource",
+ asIssuer: idJAGTestASIssuer,
+ audience: []string{idJAGTestASIssuer},
+ resource: idJAGTestOtherAud,
+ want: []draftDeparture{departureResourceNotCovered},
+ },
+ {
+ name: "resource claim array covers the requested resource",
+ asIssuer: idJAGTestASIssuer,
+ audience: []string{idJAGTestASIssuer},
+ resource: []any{idJAGTestResource, idJAGTestOtherAud},
+ },
+ {
+ name: "empty resource array is malformed",
+ asIssuer: idJAGTestASIssuer,
+ audience: []string{idJAGTestASIssuer},
+ resource: []any{},
+ want: []draftDeparture{departureResourceMalformed},
+ },
+ {
+ name: "non-string resource element is malformed",
+ asIssuer: idJAGTestASIssuer,
+ audience: []string{idJAGTestASIssuer},
+ resource: []any{42.0},
+ want: []draftDeparture{departureResourceMalformed},
+ },
+ {
+ name: "duplicate resource elements are malformed even when they cover the request",
+ asIssuer: idJAGTestASIssuer,
+ audience: []string{idJAGTestASIssuer},
+ resource: []any{idJAGTestResource, idJAGTestResource},
+ want: []draftDeparture{departureResourceMalformed},
+ },
+ {
+ name: "empty string resource is malformed",
+ asIssuer: idJAGTestASIssuer,
+ audience: []string{idJAGTestASIssuer},
+ resource: "",
+ want: []draftDeparture{departureResourceMalformed},
+ },
+ {
+ name: "null resource is malformed",
+ asIssuer: idJAGTestASIssuer,
+ audience: []string{idJAGTestASIssuer},
+ resource: jsonNull{},
+ want: []draftDeparture{departureResourceMalformed},
+ },
+ {
+ name: "every audience and resource finding at once",
+ asIssuer: idJAGTestASIssuer,
+ audience: []string{testTokenEndpoint, idJAGTestOtherAud},
+ resource: idJAGTestOtherAud,
+ want: []draftDeparture{
+ departureMultipleAudiences, departureAudienceNotIssuer, departureResourceNotCovered,
+ },
+ wantHint: hintNoAcceptedAud,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ tj := newTestJWKS(t)
+ claims := validIDJAGClaims()
+ claims.Audience = tt.audience
+ switch tt.resource.(type) {
+ case nil:
+ case jsonNull:
+ claims.Extra["resource"] = nil
+ default:
+ claims.Extra["resource"] = tt.resource
+ }
+ h, consumer, out := newIDJAGDepartureHandler(t, claims, tt.asIssuer, tt.accepted)
+
+ redeem := func() {
+ req := newIDJAGRequest(t, tj, idJAGTestClientID)
+ require.NoError(t, h.HandleTokenEndpointRequest(t.Context(), req))
+ // The outcome is the one an unlogged redemption produces.
+ assert.Equal(t, fosite.Arguments{idJAGTestResource}, req.GetGrantedAudience())
+ issued, ok := req.GetSession().(*session.Session)
+ require.True(t, ok)
+ assert.Equal(t, idJAGTestIssuer+"#"+idJAGTestSubject, issued.GetSubject())
+ assert.Equal(t, claims.JWTID, consumer.key)
+ }
+
+ redeem()
+ warns := logLinesAt(out, "WARN")
+ require.Len(t, warns, len(tt.want))
+ for i, finding := range tt.want {
+ assert.Contains(t, warns[i], "finding="+string(finding))
+ assert.Contains(t, warns[i], "issuer="+idJAGTestIssuer)
+ assert.Contains(t, warns[i], "client_id="+idJAGTestClientID)
+ if finding == departureAudienceNotIssuer {
+ assert.Contains(t, warns[i], `hint="`+tt.wantHint+`"`)
+ } else {
+ assert.NotContains(t, warns[i], "hint=")
+ }
+ }
+ assert.Empty(t, logLinesAt(out, "DEBUG"))
+
+ // The same issuer and finding again is only a Debug line.
+ redeem()
+ assert.Len(t, logLinesAt(out, "WARN"), len(tt.want))
+ assert.Len(t, logLinesAt(out, "DEBUG"), len(tt.want))
+
+ for _, secret := range []string{
+ idJAGTestSubject, claims.JWTID, testTokenEndpoint, idJAGTestASIssuer, idJAGTestResource, idJAGTestOtherAud,
+ } {
+ // Hints name the config keys, never values; the AS issuer value is
+ // absent from every line.
+ assert.NotContains(t, out.String(), secret)
+ }
+ })
+ }
+}
+
+// jsonNull marks a resource claim that is present with a JSON null value.
+type jsonNull struct{}
+
+func TestIDJAGHandler_ResourceMalformedExcludesNotCovered(t *testing.T) {
+ t.Parallel()
+
+ claims := validIDJAGClaims()
+ claims.Audience = []string{idJAGTestASIssuer}
+ claims.Extra["resource"] = []any{idJAGTestOtherAud, idJAGTestOtherAud}
+ h, _, out := newIDJAGDepartureHandler(t, claims, idJAGTestASIssuer, nil)
+
+ require.NoError(t, h.HandleTokenEndpointRequest(t.Context(), newIDJAGRequest(t, newTestJWKS(t), idJAGTestClientID)))
+
+ lines := nonEmptyLines(out)
+ require.Len(t, lines, 1)
+ assert.Contains(t, lines[0], "finding=resource_malformed")
+ assert.NotContains(t, out.String(), "resource_not_covered")
+}
+
+func TestIDJAGHandler_RefusedRedemptionLogsNoDeparture(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ prepare func(claims *ValidatedClaims, consumer *recordingAssertionConsumer, req *fosite.AccessRequest)
+ wantErr error
+ wantConsumed bool
+ }{
+ {
+ name: "resource the client may not target",
+ prepare: func(_ *ValidatedClaims, _ *recordingAssertionConsumer, req *fosite.AccessRequest) {
+ req.Client = &fosite.DefaultClient{ID: idJAGTestClientID, Audience: []string{idJAGTestOtherAud}}
+ },
+ wantErr: server.ErrInvalidTarget,
+ },
+ {
+ name: "replayed assertion",
+ prepare: func(_ *ValidatedClaims, consumer *recordingAssertionConsumer, _ *fosite.AccessRequest) {
+ consumer.err = fosite.ErrJTIKnown
+ },
+ wantErr: fosite.ErrInvalidGrant,
+ },
+ {
+ name: "assertion expired by the lifetime check",
+ prepare: func(claims *ValidatedClaims, _ *recordingAssertionConsumer, _ *fosite.AccessRequest) {
+ claims.Expiry = time.Now().Add(-time.Minute)
+ },
+ wantErr: fosite.ErrInvalidGrant,
+ wantConsumed: true,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ // Each ID-JAG would depart from the draft in every audience and resource way.
+ claims := validIDJAGClaims()
+ claims.Audience = []string{testTokenEndpoint, idJAGTestOtherAud}
+ claims.Extra["resource"] = []any{}
+ h, consumer, out := newIDJAGDepartureHandler(t, claims, idJAGTestASIssuer, nil)
+ req := newIDJAGRequest(t, newTestJWKS(t), idJAGTestClientID)
+ tt.prepare(claims, consumer, req)
+
+ err := h.HandleTokenEndpointRequest(t.Context(), req)
+
+ require.ErrorIs(t, err, tt.wantErr)
+ assert.Empty(t, out.String())
+ if tt.wantConsumed {
+ assert.Equal(t, claims.JWTID, consumer.key, "the lifetime check must run after the assertion is consumed")
+ }
+ })
+ }
+}
+
+func TestIDJAGHandler_ReplayAfterAcceptanceLogsNothingNew(t *testing.T) {
+ t.Parallel()
+
+ claims := validIDJAGClaims()
+ claims.Audience = []string{testTokenEndpoint}
+ h, consumer, out := newIDJAGDepartureHandler(t, claims, idJAGTestASIssuer, nil)
+ tj := newTestJWKS(t)
+
+ require.NoError(t, h.HandleTokenEndpointRequest(t.Context(), newIDJAGRequest(t, tj, idJAGTestClientID)))
+ before := len(nonEmptyLines(out))
+ require.Equal(t, 1, before)
+
+ consumer.err = fosite.ErrJTIKnown
+ err := h.HandleTokenEndpointRequest(t.Context(), newIDJAGRequest(t, tj, idJAGTestClientID))
+
+ require.ErrorIs(t, err, fosite.ErrInvalidGrant)
+ assert.Len(t, nonEmptyLines(out), before)
+}
+
+func TestIDJAGHandler_WarnOnceKeyIsIssuerAndFinding(t *testing.T) {
+ t.Parallel()
+
+ const (
+ issuerA = idJAGTestIssuer
+ issuerB = "https://idp-b.example.com"
+ )
+ // The same validator claims are changed between redemptions.
+ claims := validIDJAGClaims()
+ h, _, out := newIDJAGDepartureHandler(t, claims, idJAGTestASIssuer, nil, issuerA, issuerB)
+ tj := newTestJWKS(t)
+
+ redeem := func(issuer, jti string, audience []string) {
+ claims.Issuer = issuer
+ claims.JWTID = jti
+ claims.Audience = audience
+ require.NoError(t, h.HandleTokenEndpointRequest(t.Context(), newIDJAGRequest(t, tj, idJAGTestClientID)))
+ }
+ notIssuer := []string{testTokenEndpoint} // finding X: audience_not_issuer
+ twoAudiences := []string{idJAGTestASIssuer, testTokenEndpoint} // finding Y: multiple_audiences
+
+ redeem(issuerA, "jti-1", notIssuer)
+ require.Len(t, logLinesAt(out, "WARN"), 1)
+ assert.Contains(t, logLinesAt(out, "WARN")[0], "issuer="+issuerA)
+
+ redeem(issuerB, "jti-2", notIssuer)
+ require.Len(t, logLinesAt(out, "WARN"), 2)
+ assert.Contains(t, logLinesAt(out, "WARN")[1], "issuer="+issuerB)
+
+ redeem(issuerA, "jti-3", twoAudiences)
+ require.Len(t, logLinesAt(out, "WARN"), 3)
+ assert.Contains(t, logLinesAt(out, "WARN")[2], "finding="+string(departureMultipleAudiences))
+ assert.Empty(t, logLinesAt(out, "DEBUG"))
+
+ redeem(issuerA, "jti-4", notIssuer)
+ assert.Len(t, logLinesAt(out, "WARN"), 3)
+ require.Len(t, logLinesAt(out, "DEBUG"), 1)
+ assert.Contains(t, logLinesAt(out, "DEBUG")[0], "finding="+string(departureAudienceNotIssuer))
+}
+
+const requestedResourceHint = "Exactly one resource parameter is required for the JWT-bearer grant."
+
+func TestIDJAGHandler_ResourceDefaultsFromClaim(t *testing.T) {
+ t.Parallel()
+
+ const unboundResource = "https://unbound.example.com"
+ tests := []struct {
+ name string
+ form func(url.Values)
+ claim any // nil leaves the claim absent; jsonNull{} sets it to JSON null
+ clientAud []string
+ wantErrIs error
+ wantCode string // OAuth error code, for errors that are not sentinel values
+ wantInvalid string // input whose ValidateAudienceURI error is expected
+ wantAudience string
+ }{
+ {
+ name: "absent param and string claim is accepted",
+ claim: idJAGTestResource,
+ wantAudience: idJAGTestResource,
+ },
+ {
+ name: "absent param and one-element array claim is accepted",
+ claim: []any{idJAGTestResource},
+ wantAudience: idJAGTestResource,
+ },
+ {name: "absent param and two-value claim is refused", claim: []any{idJAGTestResource, unboundResource}, wantErrIs: fosite.ErrInvalidRequest},
+ {name: "absent param and no claim is refused", wantErrIs: fosite.ErrInvalidRequest},
+ {name: "absent param and empty array claim is refused", claim: []any{}, wantErrIs: fosite.ErrInvalidRequest},
+ {name: "absent param and non-string element claim is refused", claim: []any{42}, wantErrIs: fosite.ErrInvalidRequest},
+ {name: "absent param and empty string claim is refused", claim: "", wantErrIs: fosite.ErrInvalidRequest},
+ {name: "absent param and null claim is refused", claim: jsonNull{}, wantErrIs: fosite.ErrInvalidRequest},
+ {name: "absent param and array of an empty string is refused", claim: []any{""}, wantErrIs: fosite.ErrInvalidRequest},
+ {
+ name: "absent param and duplicate-value array claim is refused",
+ claim: []any{idJAGTestResource, idJAGTestResource},
+ wantErrIs: fosite.ErrInvalidRequest,
+ },
+ {
+ name: "empty param wins over the claim",
+ form: func(f url.Values) { f.Set("resource", "") },
+ claim: idJAGTestResource,
+ wantErrIs: fosite.ErrInvalidRequest,
+ },
+ {
+ name: "repeated params win over the claim",
+ form: func(f url.Values) { f["resource"] = []string{idJAGTestResource, idJAGTestResource} },
+ claim: idJAGTestResource,
+ wantErrIs: fosite.ErrInvalidRequest,
+ },
+ {
+ name: "claim outside the subject binding is refused as a requested one is",
+ claim: unboundResource,
+ clientAud: []string{unboundResource},
+ wantCode: "invalid_target",
+ },
+ {
+ name: "claim outside the client audiences is refused",
+ claim: idJAGTestResource,
+ clientAud: []string{idJAGTestOtherAud},
+ wantErrIs: server.ErrInvalidTarget,
+ },
+ {
+ name: "claim that is not a valid URI is refused as a requested one is",
+ claim: "not-a-uri",
+ wantInvalid: "not-a-uri",
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ claims := validIDJAGClaims()
+ switch tt.claim.(type) {
+ case nil:
+ case jsonNull:
+ claims.Extra["resource"] = nil
+ default:
+ claims.Extra["resource"] = tt.claim
+ }
+ h, consumer, out := newIDJAGDepartureHandler(t, claims, idJAGTestASIssuer, nil)
+ req := newIDJAGRequest(t, newTestJWKS(t), idJAGTestClientID)
+ delete(req.Form, "resource")
+ if tt.form != nil {
+ tt.form(req.Form)
+ }
+ if tt.clientAud != nil {
+ req.Client = &fosite.DefaultClient{ID: idJAGTestClientID, Audience: tt.clientAud}
+ }
+
+ err := h.HandleTokenEndpointRequest(t.Context(), req)
+ if tt.wantErrIs == nil && tt.wantCode == "" && tt.wantInvalid == "" {
+ require.NoError(t, err)
+ assert.Equal(t, fosite.Arguments{tt.wantAudience}, req.GetGrantedAudience())
+ assert.NotEmpty(t, consumer.key, "an accepted redemption consumes the assertion")
+ assert.NotContains(t, out.String(), "resource_not_covered")
+ return
+ }
+ require.Error(t, err)
+ switch {
+ case tt.wantInvalid != "":
+ assert.EqualError(t, err, server.ValidateAudienceURI(tt.wantInvalid).Error())
+ var oauthErr *fosite.RFC6749Error
+ require.True(t, errors.As(err, &oauthErr))
+ assert.Equal(t, "invalid_target", oauthErr.ErrorField)
+ case tt.wantCode != "":
+ var oauthErr *fosite.RFC6749Error
+ require.True(t, errors.As(err, &oauthErr))
+ assert.Equal(t, tt.wantCode, oauthErr.ErrorField)
+ default:
+ assert.ErrorIs(t, err, tt.wantErrIs)
+ if errors.Is(tt.wantErrIs, fosite.ErrInvalidRequest) {
+ var oauthErr *fosite.RFC6749Error
+ require.True(t, errors.As(err, &oauthErr))
+ assert.Equal(t, requestedResourceHint, oauthErr.HintField)
+ }
+ }
+ assert.Empty(t, consumer.key, "a refused redemption must not consume the assertion")
+ })
+ }
+}
+
+func TestIDJAGHandler_IssuerAudienceSkippedWhenIssuerIsResource(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ allowed []string
+ wantDefaults []string
+ wantWarnIssuer bool
+ acceptedFromIdP []string
+ // wantNotIssuer is whether the redemption, whose aud does not name the
+ // issuer, logs audience_not_issuer. It is never logged when the issuer
+ // is a resource audience, because no aud could name it.
+ wantNotIssuer bool
+ }{
+ {name: "issuer is a resource audience", allowed: []string{idJAGTestASIssuer, idJAGTestResource},
+ wantDefaults: []string{testTokenEndpoint}, wantWarnIssuer: true},
+ {name: "issuer is not a resource audience", allowed: []string{idJAGTestResource},
+ wantDefaults: []string{testTokenEndpoint, idJAGTestASIssuer}, wantNotIssuer: true},
+ {name: "configured accepted_audiences need no warning", allowed: []string{idJAGTestASIssuer},
+ wantDefaults: []string{testTokenEndpoint}, acceptedFromIdP: []string{idJAGTestOtherAud}},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ resolved, err := ResolveJWTBearerGrantPolicies([]TrustedIssuer{{
+ IssuerURL: idJAGTestIssuer,
+ AllowedDelegateClients: []string{anyDelegateClient},
+ JWTBearerGrant: &JWTBearerGrantPolicy{
+ MaxAssertionAge: time.Hour.String(),
+ AcceptedAudiences: tt.acceptedFromIdP,
+ SubjectBindings: []JWTBearerSubjectBinding{
+ {Subject: idJAGTestSubject, AllowedResources: []string{idJAGTestResource}},
+ },
+ },
+ }})
+ require.NoError(t, err)
+ var buf strings.Builder
+ validator := &testJWTBearerAssertionValidator{claims: validIDJAGClaims()}
+ h, err := newIDJAGIssuanceHandler(validator, testTokenEndpoint, &recordingAssertionConsumer{},
+ &fosite.Config{
+ AccessTokenIssuer: idJAGTestASIssuer,
+ AccessTokenLifespan: time.Hour,
+ AudienceMatchingStrategy: fosite.DefaultAudienceMatchingStrategy,
+ },
+ &mockAccessTokenStrategy{}, &mockAccessTokenStorage{}, resolved, nil, tt.allowed,
+ slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug})))
+ require.NoError(t, err)
+
+ warns := logLinesAt(&buf, "WARN")
+ if tt.wantWarnIssuer {
+ require.Len(t, warns, 1)
+ assert.Contains(t, warns[0], idJAGTestASIssuer)
+ } else {
+ assert.Empty(t, warns)
+ }
+ buf.Reset()
+
+ req := newIDJAGRequest(t, newTestJWKS(t), idJAGTestClientID)
+ require.NoError(t, h.HandleTokenEndpointRequest(context.Background(), req))
+ assert.Equal(t, tt.wantDefaults, validator.gotDefaults)
+ assert.Equal(t, tt.wantNotIssuer,
+ strings.Contains(buf.String(), "finding="+string(departureAudienceNotIssuer)))
+ })
+ }
+}
+
+func TestIDJAGHandler_RealValidatorRedeemsIssuerAudience(t *testing.T) {
+ t.Parallel()
+
+ externalJWKS := newTestJWKS(t)
+ jwksServer := startJWKSServer(t, externalJWKS)
+ trusted := []TrustedIssuer{{
+ IssuerURL: testExternalIssuer,
+ ExpectedAudience: testExternalAudience,
+ JWKSURL: jwksServer.URL + "/jwks",
+ AllowedDelegateClients: []string{anyDelegateClient},
+ JWTBearerGrant: &JWTBearerGrantPolicy{
+ MaxAssertionAge: time.Hour.String(),
+ SubjectBindings: []JWTBearerSubjectBinding{
+ {Subject: "ext-user-456", AllowedResources: []string{idJAGTestResource}},
+ },
+ },
+ }}
+ validator := newMultiValidator(t, newTestJWKS(t), trusted)
+ resolved, err := ResolveJWTBearerGrantPolicies(trusted)
+ require.NoError(t, err)
+ consumer := &recordingAssertionConsumer{}
+ h, err := newIDJAGIssuanceHandler(validator, testTokenEndpoint, consumer,
+ &fosite.Config{
+ AccessTokenIssuer: idJAGTestASIssuer,
+ AccessTokenLifespan: time.Hour,
+ AudienceMatchingStrategy: fosite.DefaultAudienceMatchingStrategy,
+ },
+ &mockAccessTokenStrategy{}, &mockAccessTokenStorage{}, resolved, nil, []string{idJAGTestResource}, nil)
+ require.NoError(t, err)
+
+ signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.ES256, Key: externalJWKS.jwk},
+ (&jose.SignerOptions{}).WithHeader(jose.HeaderType, oauthproto.JWTTypeIDJAG))
+ require.NoError(t, err)
+ claims := jwtBearerExternalClaims()
+ claims.Audience = jwt.Audience{idJAGTestASIssuer}
+ raw, err := jwt.Signed(signer).Claims(claims).Claims(map[string]any{"client_id": idJAGTestClientID}).Serialize()
+ require.NoError(t, err)
+
+ req := newIDJAGRequest(t, externalJWKS, idJAGTestClientID)
+ req.Form.Set("assertion", raw)
+ require.NoError(t, h.HandleTokenEndpointRequest(context.Background(), req))
+ assert.Equal(t, "jwt-bearer-jti", consumer.key)
+}
diff --git a/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go b/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go
index 003661d7d7..4dedee1e46 100644
--- a/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go
+++ b/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go
@@ -36,7 +36,9 @@ const (
// JWTBearerAssertionValidator verifies cryptographic and registered claims of a
// plain RFC 7523 JWT-bearer assertion.
type JWTBearerAssertionValidator interface {
- ValidateJWTBearerAssertion(ctx context.Context, rawToken, tokenEndpoint string) (*ValidatedClaims, error)
+ ValidateJWTBearerAssertion(
+ ctx context.Context, rawToken string, defaultAudiences []string,
+ ) (*ValidatedClaims, error)
}
// JWTBearerHandler implements the unbound RFC 7523 JWT-bearer grant.
@@ -164,7 +166,7 @@ func (h *JWTBearerHandler) HandleTokenEndpointRequest(ctx context.Context, reque
if err := validateAssertionType(assertion); err != nil {
return err
}
- claims, err := h.validator.ValidateJWTBearerAssertion(ctx, assertion, h.tokenEndpoint)
+ claims, err := h.validator.ValidateJWTBearerAssertion(ctx, assertion, []string{h.tokenEndpoint})
if err != nil {
return errorsx.WithStack(fosite.ErrInvalidGrant.WithHint("The JWT bearer assertion is invalid or could not be verified."))
}
@@ -180,10 +182,16 @@ func (h *JWTBearerHandler) HandleTokenEndpointRequest(ctx context.Context, reque
if h.consumer == nil {
return errorsx.WithStack(fosite.ErrServerError.WithHint("The JWT-bearer grant is not fully configured."))
}
- resource, err := validateJWTBearerPolicy(requester.GetRequestForm(), claims, policy)
+ if err := checkAssertionMaxAge(claims, policy); err != nil {
+ return err
+ }
+ resource, err := requestedResource(requester.GetRequestForm())
if err != nil {
return err
}
+ if err := checkSubjectBinding(claims, policy, resource); err != nil {
+ return err
+ }
// Consume before issuing. This intentionally fails closed: if issuance fails
// after this point, the assertion remains consumed rather than becoming
// replayable.
@@ -225,10 +233,17 @@ func (h *JWTBearerHandler) HandleTokenEndpointRequest(ctx context.Context, reque
return nil
}
-func validateJWTBearerPolicy(form url.Values, claims *ValidatedClaims, policy *JWTBearerGrantPolicy) (string, error) {
+// checkAssertionMaxAge rejects assertions whose lifetime exceeds the policy maximum.
+func checkAssertionMaxAge(claims *ValidatedClaims, policy *JWTBearerGrantPolicy) error {
if claims.IssuedAt.IsZero() || claims.Expiry.IsZero() || claims.Expiry.Sub(claims.IssuedAt) > policy.maxAssertionAge {
- return "", errorsx.WithStack(fosite.ErrInvalidGrant.WithHint("The JWT bearer assertion exceeds the configured maximum age."))
+ return errorsx.WithStack(fosite.ErrInvalidGrant.WithHint("The JWT bearer assertion exceeds the configured maximum age."))
}
+ return nil
+}
+
+// requestedResource returns the single resource parameter of the request. Each assertion profile
+// chooses its resource, so this is the choice for plain RFC 7523 and other profiles may differ.
+func requestedResource(form url.Values) (string, error) {
resources, present := form["resource"]
if !present || len(resources) != 1 || resources[0] == "" {
return "", errorsx.WithStack(fosite.ErrInvalidRequest.WithHint(
@@ -237,20 +252,25 @@ func validateJWTBearerPolicy(form url.Values, claims *ValidatedClaims, policy *J
if err := server.ValidateAudienceURI(resources[0]); err != nil {
return "", errorsx.WithStack(err)
}
+ return resources[0], nil
+}
+
+// checkSubjectBinding requires the assertion subject to be bound to the given resource.
+func checkSubjectBinding(claims *ValidatedClaims, policy *JWTBearerGrantPolicy, resource string) error {
for _, binding := range policy.SubjectBindings {
if binding.Subject == claims.Subject {
- for _, resource := range binding.AllowedResources {
- if resource == resources[0] {
- return resource, nil
+ for _, allowed := range binding.AllowedResources {
+ if allowed == resource {
+ return nil
}
}
- return "", errorsx.WithStack(&fosite.RFC6749Error{
+ return errorsx.WithStack(&fosite.RFC6749Error{
ErrorField: "invalid_target",
CodeField: http.StatusBadRequest,
})
}
}
- return "", errorsx.WithStack(fosite.ErrInvalidGrant.WithHint(
+ return errorsx.WithStack(fosite.ErrInvalidGrant.WithHint(
"The JWT bearer assertion subject is not configured for this grant."))
}
@@ -406,9 +426,9 @@ func validateAssertionType(assertion string) error {
// "application/" prefix, as the same type, but redemption does not: such an
// assertion is not routed to IDJAGHandler, and validateAssertionType refuses it
// with invalid_grant. That narrowness is intended and fails closed. The deny
-// side is the opposite: rejectIDJAGType and pkg/auth compare with
-// oauthproto.IsJOSEType, so no spelling of the ID-JAG type passes as an access
-// token. Revisit this if an issuer is found to emit a variant spelling.
+// side is the opposite: rejectIDJAGType and pkg/auth call idjag.IsIDJAG, which
+// compares with oauthproto.IsJOSEType, so no spelling of the ID-JAG type passes
+// as an access token. Revisit this if an issuer is found to emit a variant spelling.
func assertionType(assertion string) string {
parsed, err := jwt.ParseSigned(assertion, allowedSignatureAlgorithms)
if err != nil || len(parsed.Headers) != 1 {
@@ -477,7 +497,7 @@ func JWTBearerIssuanceFactory(trustedIssuers []TrustedIssuer, shared *MultiIssue
func(
validator JWTBearerAssertionValidator, tokenEndpoint string, consumer storage.AssertionJWTConsumer,
config *fosite.Config, strategy oauth2.AccessTokenStrategy, tokenStorage oauth2.AccessTokenStorage,
- resolvedIssuers []TrustedIssuer,
+ resolvedIssuers []TrustedIssuer, _ []string,
) (any, error) {
return newJWTBearerIssuanceHandler(
validator, tokenEndpoint, consumer, config, strategy, tokenStorage, resolvedIssuers)
@@ -498,7 +518,7 @@ func jwtBearerGrantFactory(
build func(
validator JWTBearerAssertionValidator, tokenEndpoint string, consumer storage.AssertionJWTConsumer,
config *fosite.Config, strategy oauth2.AccessTokenStrategy, tokenStorage oauth2.AccessTokenStorage,
- resolvedIssuers []TrustedIssuer,
+ resolvedIssuers []TrustedIssuer, allowedAudiences []string,
) (any, error),
) (server.Factory, error) {
resolvedIssuers, err := ResolveJWTBearerGrantPolicies(trustedIssuers)
@@ -555,7 +575,8 @@ func jwtBearerGrantFactory(
// the validator is always the caller-owned, closeable one — this closure
// never builds a MultiIssuerTokenValidator whose JWKS workers leak.
var validator JWTBearerAssertionValidator = shared
- return build(validator, config.TokenURL, consumer, config.Config, atStrategy, atStorage, resolvedIssuers)
+ return build(validator, config.TokenURL, consumer, config.Config, atStrategy, atStorage, resolvedIssuers,
+ config.AllowedAudiences)
}, nil
}
diff --git a/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go b/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go
index dcec7f6eca..f6bf5c1c6b 100644
--- a/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go
+++ b/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go
@@ -30,15 +30,17 @@ import (
const testTokenEndpoint = "https://auth.example.com/oauth/token"
type testJWTBearerAssertionValidator struct {
- calls int
- err error
- claims *ValidatedClaims
+ calls int
+ err error
+ claims *ValidatedClaims
+ gotDefaults []string
}
func (v *testJWTBearerAssertionValidator) ValidateJWTBearerAssertion(
- context.Context, string, string,
+ _ context.Context, _ string, defaultAudiences []string,
) (*ValidatedClaims, error) {
v.calls++
+ v.gotDefaults = defaultAudiences
if v.err != nil {
return nil, v.err
}
@@ -143,7 +145,7 @@ func TestJWTBearerHandler_MatchingAndClientAuth(t *testing.T) {
}
}
-func TestValidateJWTBearerPolicy_RejectsMalformedResourceURI(t *testing.T) {
+func TestJWTBearerPolicyChecks_RejectsMalformedResourceURI(t *testing.T) {
t.Parallel()
now := time.Now()
@@ -160,7 +162,7 @@ func TestValidateJWTBearerPolicy_RejectsMalformedResourceURI(t *testing.T) {
Expiry: now.Add(time.Minute),
}
- _, err := validateJWTBearerPolicy(url.Values{"resource": {"not-a-uri"}}, claims, policy)
+ err := runJWTBearerPolicy(url.Values{"resource": {"not-a-uri"}}, claims, policy)
require.Error(t, err)
assert.ErrorIs(t, err, server.ErrInvalidTarget)
}
@@ -327,7 +329,19 @@ func TestJWTBearerHandler_CanSkipClientAuthRejectsFormCredentials(t *testing.T)
}
}
-func TestValidateJWTBearerPolicy_ResourceAndPolicyErrors(t *testing.T) {
+// runJWTBearerPolicy runs the three policy checks in sequence for table tests.
+func runJWTBearerPolicy(form url.Values, claims *ValidatedClaims, policy *JWTBearerGrantPolicy) error {
+ if err := checkAssertionMaxAge(claims, policy); err != nil {
+ return err
+ }
+ resource, err := requestedResource(form)
+ if err != nil {
+ return err
+ }
+ return checkSubjectBinding(claims, policy, resource)
+}
+
+func TestJWTBearerPolicyChecks_ResourceAndPolicyErrors(t *testing.T) {
t.Parallel()
now := time.Now()
@@ -356,7 +370,7 @@ func TestValidateJWTBearerPolicy_ResourceAndPolicyErrors(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
- _, err := validateJWTBearerPolicy(tt.form, tt.claims, policy)
+ err := runJWTBearerPolicy(tt.form, tt.claims, policy)
require.Error(t, err)
if tt.wantCode != "" {
var oauthErr *fosite.RFC6749Error
@@ -775,14 +789,15 @@ func TestJWTBearerHandler_StampsNoUpstreamSessionClaim(t *testing.T) {
tj := newTestJWKS(t)
now := time.Now()
+ validator := &testJWTBearerAssertionValidator{claims: &ValidatedClaims{
+ Issuer: issuer,
+ Subject: subject,
+ JWTID: "jti-no-upstream-session",
+ IssuedAt: now,
+ Expiry: now.Add(30 * time.Minute),
+ }}
handler, err := newJWTBearerIssuanceHandler(
- &testJWTBearerAssertionValidator{claims: &ValidatedClaims{
- Issuer: issuer,
- Subject: subject,
- JWTID: "jti-no-upstream-session",
- IssuedAt: now,
- Expiry: now.Add(30 * time.Minute),
- }},
+ validator,
testTokenEndpoint,
testAssertionJWTConsumer{},
&fosite.Config{AccessTokenLifespan: time.Hour},
@@ -801,8 +816,113 @@ func TestJWTBearerHandler_StampsNoUpstreamSessionClaim(t *testing.T) {
require.NoError(t, handler.HandleTokenEndpointRequest(context.Background(), req))
+ assert.Equal(t, []string{testTokenEndpoint}, validator.gotDefaults)
+
issued, ok := req.GetSession().(*session.Session)
require.True(t, ok, "expected the handler to install a *session.Session")
assert.Equal(t, true, issued.JWTClaims.Extra[session.NoUpstreamSessionClaimKey],
"JWT-bearer tokens must declare that they have no upstream session")
}
+
+func TestJWTBearerHandler_MaxAgeIsCheckedBeforeResource(t *testing.T) {
+ t.Parallel()
+
+ const (
+ issuer = "https://idp.example.com"
+ subject = "ext-user"
+ resource = "https://mcp.example.com"
+ )
+ resolvedIssuers, err := ResolveJWTBearerGrantPolicies([]TrustedIssuer{{
+ IssuerURL: issuer,
+ AllowedDelegateClients: []string{anyDelegateClient},
+ JWTBearerGrant: &JWTBearerGrantPolicy{
+ MaxAssertionAge: time.Hour.String(),
+ SubjectBindings: []JWTBearerSubjectBinding{
+ {Subject: subject, AllowedResources: []string{resource}},
+ },
+ },
+ }})
+ require.NoError(t, err)
+
+ now := time.Now()
+ validator := &testJWTBearerAssertionValidator{claims: &ValidatedClaims{
+ Issuer: issuer,
+ Subject: subject,
+ JWTID: "jti-order-test",
+ IssuedAt: now.Add(-2 * time.Hour),
+ Expiry: now.Add(time.Minute),
+ }}
+ handler, err := newJWTBearerIssuanceHandler(
+ validator,
+ testTokenEndpoint,
+ testAssertionJWTConsumer{},
+ &fosite.Config{AccessTokenLifespan: time.Hour},
+ &mockAccessTokenStrategy{},
+ &mockAccessTokenStorage{},
+ resolvedIssuers,
+ )
+ require.NoError(t, err)
+
+ req := fosite.NewAccessRequest(&session.Session{})
+ req.GrantTypes = fosite.Arguments{oauthproto.GrantTypeJWTBearer}
+ req.Form = map[string][]string{"assertion": {signAssertionWithType(t, newTestJWKS(t), nil)}}
+
+ err = handler.HandleTokenEndpointRequest(context.Background(), req)
+ require.Error(t, err)
+ assert.ErrorIs(t, err, fosite.ErrInvalidGrant)
+ assert.NotErrorIs(t, err, fosite.ErrInvalidRequest)
+}
+
+// TestJWTBearerHandler_ResourceClaimIsNotADefault pins plain RFC 7523: only the
+// ID-JAG handler falls back to a resource claim.
+func TestJWTBearerHandler_ResourceClaimIsNotADefault(t *testing.T) {
+ t.Parallel()
+
+ const (
+ issuer = "https://idp.example.com"
+ subject = "ext-user"
+ resource = "https://mcp.example.com"
+ )
+ resolvedIssuers, err := ResolveJWTBearerGrantPolicies([]TrustedIssuer{{
+ IssuerURL: issuer,
+ AllowedDelegateClients: []string{anyDelegateClient},
+ JWTBearerGrant: &JWTBearerGrantPolicy{
+ MaxAssertionAge: time.Hour.String(),
+ SubjectBindings: []JWTBearerSubjectBinding{
+ {Subject: subject, AllowedResources: []string{resource}},
+ },
+ },
+ }})
+ require.NoError(t, err)
+
+ now := time.Now()
+ validator := &testJWTBearerAssertionValidator{claims: &ValidatedClaims{
+ Issuer: issuer,
+ Subject: subject,
+ JWTID: "jti-claim-default",
+ IssuedAt: now,
+ Expiry: now.Add(time.Minute),
+ Extra: map[string]any{"resource": resource},
+ }}
+ handler, err := newJWTBearerIssuanceHandler(
+ validator,
+ testTokenEndpoint,
+ testAssertionJWTConsumer{},
+ &fosite.Config{AccessTokenLifespan: time.Hour},
+ &mockAccessTokenStrategy{},
+ &mockAccessTokenStorage{},
+ resolvedIssuers,
+ )
+ require.NoError(t, err)
+
+ req := fosite.NewAccessRequest(&session.Session{})
+ req.GrantTypes = fosite.Arguments{oauthproto.GrantTypeJWTBearer}
+ req.Form = map[string][]string{"assertion": {signAssertionWithType(t, newTestJWKS(t), nil)}}
+
+ err = handler.HandleTokenEndpointRequest(context.Background(), req)
+ require.Error(t, err)
+ assert.ErrorIs(t, err, fosite.ErrInvalidRequest)
+ var oauthErr *fosite.RFC6749Error
+ require.True(t, errors.As(err, &oauthErr))
+ assert.Equal(t, requestedResourceHint, oauthErr.HintField)
+}
diff --git a/pkg/authserver/server/tokenexchange/jwt_bearer_validator_test.go b/pkg/authserver/server/tokenexchange/jwt_bearer_validator_test.go
index d34cb09b4b..b5133a5d78 100644
--- a/pkg/authserver/server/tokenexchange/jwt_bearer_validator_test.go
+++ b/pkg/authserver/server/tokenexchange/jwt_bearer_validator_test.go
@@ -136,7 +136,7 @@ func TestMultiIssuerTokenValidator_ValidateJWTBearerAssertion(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
raw := tt.signer.signToken(t, tt.claims(), nil)
- claims, err := validator.ValidateJWTBearerAssertion(context.Background(), raw, testTokenEndpoint)
+ claims, err := validator.ValidateJWTBearerAssertion(context.Background(), raw, []string{testTokenEndpoint})
if tt.wantErr != "" {
require.Error(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
@@ -174,7 +174,7 @@ func TestMultiIssuerTokenValidator_ValidateJWTBearerAssertionAcceptsIDJAGType(t
}})
raw := externalJWKS.signTokenWithType(t, oauthproto.JWTTypeIDJAG, jwtBearerExternalClaims(), nil)
- claims, err := validator.ValidateJWTBearerAssertion(context.Background(), raw, testTokenEndpoint)
+ claims, err := validator.ValidateJWTBearerAssertion(context.Background(), raw, []string{testTokenEndpoint})
require.NoError(t, err)
assert.Equal(t, "ext-user-456", claims.Subject)
}
@@ -193,7 +193,7 @@ func TestMultiIssuerTokenValidator_ValidateJWTBearerAssertionRejectsIssuerWithou
}})
raw := externalJWKS.signToken(t, externalClaims(), nil)
- claims, err := validator.ValidateJWTBearerAssertion(context.Background(), raw, testTokenEndpoint)
+ claims, err := validator.ValidateJWTBearerAssertion(context.Background(), raw, []string{testTokenEndpoint})
require.Error(t, err)
assert.Contains(t, err.Error(), "not enabled for the JWT-bearer grant")
@@ -251,7 +251,7 @@ func TestMultiIssuerTokenValidator_ValidateJWTBearerAssertion_AcceptedAudiences(
claims.Audience = tt.aud
raw := externalJWKS.signToken(t, claims, nil)
- validated, err := validator.ValidateJWTBearerAssertion(context.Background(), raw, testTokenEndpoint)
+ validated, err := validator.ValidateJWTBearerAssertion(context.Background(), raw, []string{testTokenEndpoint})
if tt.wantErr != "" {
require.Error(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
@@ -294,7 +294,7 @@ func TestMultiIssuerTokenValidator_ValidateJWTBearerAssertionRejectsIDTokenClaim
}})
raw := externalJWKS.signToken(t, jwtBearerExternalClaims(), map[string]any{"at_hash": "id-token-marker"})
- _, err := validator.ValidateJWTBearerAssertion(context.Background(), raw, testTokenEndpoint)
+ _, err := validator.ValidateJWTBearerAssertion(context.Background(), raw, []string{testTokenEndpoint})
require.Error(t, err)
assert.Contains(t, err.Error(), "at_hash")
}
@@ -327,3 +327,82 @@ func TestValidateJWTBearerAssertionClaims_ClockSkewAndExpiry(t *testing.T) {
})
}
}
+
+func TestMultiIssuerTokenValidator_ValidateJWTBearerAssertion_DefaultAudiences(t *testing.T) {
+ t.Parallel()
+
+ selfJWKS := newTestJWKS(t)
+ externalJWKS := newTestJWKS(t)
+ jwksServer := startJWKSServer(t, externalJWKS)
+ newValidator := func(accepted []string) *MultiIssuerTokenValidator {
+ return newMultiValidator(t, selfJWKS, []TrustedIssuer{{
+ IssuerURL: testExternalIssuer,
+ ExpectedAudience: testExternalAudience,
+ JWKSURL: jwksServer.URL + "/jwks",
+ AllowedDelegateClients: []string{anyDelegateClient},
+ JWTBearerGrant: &JWTBearerGrantPolicy{
+ MaxAssertionAge: time.Hour.String(),
+ AcceptedAudiences: accepted,
+ SubjectBindings: []JWTBearerSubjectBinding{
+ {Subject: "ext-user-456", AllowedResources: []string{"https://mcp.example.com"}},
+ },
+ },
+ }})
+ }
+
+ const (
+ secondDefault = "https://auth.example.com"
+ configured = "https://configured.example.com"
+ )
+ const wantAudErr = "assertion audience must include one of the accepted authorization server identities"
+ tests := []struct {
+ name string
+ defaults []string
+ accepted []string
+ aud jwt.Audience
+ wantErr string
+ }{
+ {name: "nil defaults are refused", defaults: nil, aud: jwt.Audience{testTokenEndpoint}, wantErr: "default audiences must not be empty"},
+ {name: "empty defaults are refused", defaults: []string{}, aud: jwt.Audience{testTokenEndpoint}, wantErr: "default audiences must not be empty"},
+ {name: "an empty element is refused", defaults: []string{testTokenEndpoint, ""}, aud: jwt.Audience{testTokenEndpoint}, wantErr: "default audiences must not be empty"},
+ {name: "the second default is accepted", defaults: []string{testTokenEndpoint, secondDefault}, aud: jwt.Audience{secondDefault}},
+ {
+ name: "an audience outside the defaults is rejected",
+ defaults: []string{testTokenEndpoint, secondDefault},
+ aud: jwt.Audience{"https://other.example.com"},
+ wantErr: wantAudErr,
+ },
+ {
+ name: "a configured list replaces the second default",
+ defaults: []string{testTokenEndpoint, secondDefault}, accepted: []string{configured},
+ aud: jwt.Audience{secondDefault}, wantErr: wantAudErr,
+ },
+ {
+ name: "a configured list replaces the token endpoint default",
+ defaults: []string{testTokenEndpoint, secondDefault}, accepted: []string{configured},
+ aud: jwt.Audience{testTokenEndpoint}, wantErr: wantAudErr,
+ },
+ {
+ name: "a configured list accepts its own entry",
+ defaults: []string{testTokenEndpoint, secondDefault}, accepted: []string{configured},
+ aud: jwt.Audience{configured},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ claims := jwtBearerExternalClaims()
+ claims.Audience = tt.aud
+ raw := externalJWKS.signToken(t, claims, nil)
+
+ validated, err := newValidator(tt.accepted).ValidateJWTBearerAssertion(context.Background(), raw, tt.defaults)
+ if tt.wantErr != "" {
+ require.ErrorContains(t, err, tt.wantErr)
+ return
+ }
+ require.NoError(t, err)
+ assert.Equal(t, "ext-user-456", validated.Subject)
+ })
+ }
+}
diff --git a/pkg/authserver/server/tokenexchange/multi_issuer_validator.go b/pkg/authserver/server/tokenexchange/multi_issuer_validator.go
index d5368bb530..3a4920c97c 100644
--- a/pkg/authserver/server/tokenexchange/multi_issuer_validator.go
+++ b/pkg/authserver/server/tokenexchange/multi_issuer_validator.go
@@ -129,8 +129,11 @@ type JWTBearerGrantPolicy struct {
// authorization server for this grant; it is NOT a resource/API
// identifier — a bare resource audience is deliberately not accepted
// here, that would let any RFC 8707 resource-scoped token satisfy the
- // grant instead of only tokens minted for this AS. Defaults to
- // [tokenEndpoint] when empty, preserving prior exact-match behavior.
+ // grant instead of only tokens minted for this AS. When empty, the plain
+ // JWT-bearer grant accepts the token endpoint, and the ID-JAG grant accepts
+ // the token endpoint and this server's issuer identifier, unless the issuer
+ // is also an allowed resource audience. A configured list replaces both
+ // defaults.
AcceptedAudiences []string `json:"accepted_audiences,omitempty" yaml:"accepted_audiences,omitempty"`
maxAssertionAge time.Duration
@@ -667,15 +670,16 @@ func (v *MultiIssuerTokenValidator) Validate(ctx context.Context, rawToken strin
// assertion's authorization policy is separate from delegation policy.
//
// The assertion audience must intersect the issuer's configured
-// JWTBearerGrant.AcceptedAudiences, or just tokenEndpoint when that is unset.
+// JWTBearerGrant.AcceptedAudiences, or the caller's defaultAudiences when that
+// is unset.
// The caller is responsible for the phase-specific subject binding, maximum
// age, replay, and issuance policy after this cryptographic verification
// succeeds.
func (v *MultiIssuerTokenValidator) ValidateJWTBearerAssertion(
- ctx context.Context, rawToken, tokenEndpoint string,
+ ctx context.Context, rawToken string, defaultAudiences []string,
) (*ValidatedClaims, error) {
- if tokenEndpoint == "" {
- return nil, errors.New("token endpoint must not be empty")
+ if len(defaultAudiences) == 0 || slices.Contains(defaultAudiences, "") {
+ return nil, errors.New("default audiences must not be empty")
}
issuer, err := peekIssuer(rawToken)
@@ -699,7 +703,7 @@ func (v *MultiIssuerTokenValidator) ValidateJWTBearerAssertion(
return nil, err
}
- acceptedAudiences := []string{tokenEndpoint}
+ acceptedAudiences := defaultAudiences
if issuerConfig.JWTBearerGrant != nil && len(issuerConfig.JWTBearerGrant.AcceptedAudiences) > 0 {
acceptedAudiences = issuerConfig.JWTBearerGrant.AcceptedAudiences
}
diff --git a/pkg/authserver/server/tokenexchange/refresh_token_handler.go b/pkg/authserver/server/tokenexchange/refresh_token_handler.go
index 74dfe1ffed..a44324eb9b 100644
--- a/pkg/authserver/server/tokenexchange/refresh_token_handler.go
+++ b/pkg/authserver/server/tokenexchange/refresh_token_handler.go
@@ -29,10 +29,6 @@ import (
// Compile-time check that RefreshTokenHandler implements fosite.TokenEndpointHandler.
var _ fosite.TokenEndpointHandler = (*RefreshTokenHandler)(nil)
-// tokenTypeNotApplicable is the RFC 6749 token_type for a response whose
-// access_token member is not an access token (RFC 8693 section 2.2.1).
-const tokenTypeNotApplicable = "N_A"
-
// Reasons logged with a refusal. They are fixed strings; the
// authorization_details reasons are the ones returned to the client.
const (
@@ -600,9 +596,9 @@ func (h *RefreshTokenHandler) issue(
}
responder.SetAccessToken(token)
- responder.SetTokenType(tokenTypeNotApplicable)
+ responder.SetTokenType(oauthproto.TokenTypeNotApplicable)
responder.SetExpiresIn(exchangeGrantExpiresIn(grant.ExpiresAt, d.now))
- responder.SetExtra("issued_token_type", oauthproto.TokenTypeRefreshToken)
+ responder.SetExtra(oauthproto.ParamIssuedTokenType, oauthproto.TokenTypeRefreshToken)
// RFC 9396 section 7.1: the response member is an array of the granted entries.
responder.SetExtra(authorizationDetailsParam, []json.RawMessage{d.echo})
if grant.ParentSignature != "" {
diff --git a/pkg/authserver/server/tokenexchange/validator.go b/pkg/authserver/server/tokenexchange/validator.go
index d114a1f59a..3a4290da0e 100644
--- a/pkg/authserver/server/tokenexchange/validator.go
+++ b/pkg/authserver/server/tokenexchange/validator.go
@@ -14,7 +14,7 @@ import (
"github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
- "github.com/stacklok/toolhive/pkg/oauthproto"
+ "github.com/stacklok/toolhive/pkg/oauthproto/idjag"
)
// allowedSignatureAlgorithms lists the signing algorithms accepted during JWT verification.
@@ -266,7 +266,7 @@ func rejectIDJAGType(token *jwt.JSONWebToken) error {
return errors.New("token must contain exactly one JOSE signature")
}
typ, _ := token.Headers[0].ExtraHeaders[jose.HeaderType].(string)
- if oauthproto.IsJOSEType(typ, oauthproto.JWTTypeIDJAG) {
+ if idjag.IsIDJAG(typ) {
return errors.New("token is an ID-JAG, which is not accepted in place of an access token")
}
return nil
diff --git a/pkg/oauthproto/constants.go b/pkg/oauthproto/constants.go
index e3f3f8a321..61553af324 100644
--- a/pkg/oauthproto/constants.go
+++ b/pkg/oauthproto/constants.go
@@ -101,6 +101,16 @@ const (
TokenTypeRefreshToken = "urn:ietf:params:oauth:token-type:refresh_token"
)
+// TokenTypeNotApplicable is the RFC 6749 token_type for a response whose
+// access_token member is not an access token (RFC 8693 Section 2.2.1), that is,
+// a token that cannot be used as a bearer access token. The ID-JAG draft
+// requires it on the response that carries an ID-JAG (Section 4.3.4).
+const TokenTypeNotApplicable = "N_A"
+
+// ParamIssuedTokenType is the name of the token exchange response parameter that
+// carries the type of the issued token (RFC 8693 Section 2.2.1).
+const ParamIssuedTokenType = "issued_token_type" //nolint:gosec // G101: RFC 8693 response parameter name, not a credential
+
// Grant type URNs for token exchange protocols.
//
//nolint:gosec // G101: this is an RFC 8693 grant-type URN identifier, not a credential
diff --git a/pkg/oauthproto/doc.go b/pkg/oauthproto/doc.go
index b7d7c78ea6..7b83fdaada 100644
--- a/pkg/oauthproto/doc.go
+++ b/pkg/oauthproto/doc.go
@@ -14,6 +14,16 @@
// pkg/authserver/server/registration.
// - Shared constants: UserAgent, well-known paths, grant types, PKCE methods
//
+// Reading guide:
+// - oauthproto: constants for grant types, token types and JWT typ values, and
+// shared helpers.
+// - oauthproto/tokenexchange: the RFC 8693 client. It does not depend on the
+// token types it exchanges.
+// - oauthproto/jwtbearer: the RFC 7523 JWT-bearer client.
+// - oauthproto/idjag: Cross App Access (ID-JAG). Start at its doc.go.
+// FromExchange is the client's check of an IdP response. IsIDJAG is the
+// deny-side typ test. ResourceClaim reads the resource claim.
+//
// Leaf-package invariant: this package has no dependency on
// github.com/stacklok/toolhive/pkg/networking. All callers that need both
// networking helpers and oauthproto types must import both packages independently.
diff --git a/pkg/oauthproto/idjag/doc.go b/pkg/oauthproto/idjag/doc.go
new file mode 100644
index 0000000000..e095ee184f
--- /dev/null
+++ b/pkg/oauthproto/idjag/doc.go
@@ -0,0 +1,52 @@
+// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc.
+// SPDX-License-Identifier: Apache-2.0
+
+// Package idjag holds the ToolHive rules for ID-JAG, the assertion used by
+// Cross App Access (XAA). It follows
+// draft-ietf-oauth-identity-assertion-authz-grant-06.
+//
+// An ID-JAG is a short-lived signed JWT whose "typ" header is
+// oauth-id-jag+jwt (draft 3.1, 4.4.1; RFC 8725 Section 3.11). Three roles
+// take part. The IdP authorization server issues it. The client obtains it and
+// presents it. The resource authorization server redeems it.
+//
+// Step 1, the exchange. The client sends an RFC 8693 token exchange to the IdP
+// with requested_token_type set to the ID-JAG token type, exactly one
+// "audience" (draft 4.3, 4.3.3) and a "resource" (draft 4.3), which is
+// RECOMMENDED and must be included when the client found the resource through
+// RFC 9728 metadata. The response carries issued_token_type set to the ID-JAG
+// token type, token_type N_A, and the ID-JAG in the access_token member (draft
+// 4.3.4).
+//
+// Step 2, the redemption. The client sends the ID-JAG to the resource
+// authorization server as an RFC 7523 JWT-bearer grant (draft 4.4). The server
+// validates it as draft 4.4.1 describes: all of RFC 7521 Section 5.2 plus the
+// ID-JAG rules. An ID-JAG is a JWT-bearer assertion profile that is obtained
+// through a token exchange. The redemption is not itself a token exchange.
+//
+// This package holds three functions:
+//
+// - [IsIDJAG] is the typ test. Every access-token validator that shares a
+// signing key with an ID-JAG issuer must call it, so an ID-JAG is never
+// accepted as an access token.
+//
+// - [FromExchange] is the client's sanity check on the IdP response from
+// step 1. It checks that the IdP honoured the request: token types, a
+// parsable JWT, the requested audience and the requested resource. The
+// rule that aud is a single issuer identifier belongs to the resource
+// server (draft 4.4.1). The check here requires aud to be exactly the
+// requested value. Draft 4.3 lets an IdP resolve a URN audience to the
+// issuer identifier, and this check refuses that: ToolHive supports only
+// issuer-identifier audiences here.
+//
+// - [ResourceClaim] reads the resource claim as a list of strings and reports
+// whether the claim is well formed under draft 3.
+//
+// The server-side jti and client_id binding checks live inline in
+// pkg/authserver/server/tokenexchange/id_jag_handler.go. Signature checks,
+// issuer trust, replay protection and client authentication are product
+// concerns. This package never does them.
+//
+// The wiring lives in pkg/vmcp/auth/strategies/xaa.go (the client) and in
+// pkg/authserver/server/tokenexchange (the authorization server).
+package idjag
diff --git a/pkg/oauthproto/idjag/exchange.go b/pkg/oauthproto/idjag/exchange.go
new file mode 100644
index 0000000000..50fd3b0a05
--- /dev/null
+++ b/pkg/oauthproto/idjag/exchange.go
@@ -0,0 +1,110 @@
+// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc.
+// SPDX-License-Identifier: Apache-2.0
+
+package idjag
+
+import (
+ "errors"
+ "fmt"
+ "log/slog"
+ "slices"
+ "strings"
+
+ jwt "github.com/golang-jwt/jwt/v5"
+ "golang.org/x/oauth2"
+
+ "github.com/stacklok/toolhive/pkg/oauthproto"
+)
+
+// Sentinel errors returned by [FromExchange]. Use errors.Is to tell them apart.
+var (
+ ErrNoToken = errors.New("no token")
+ ErrIssuedTokenType = errors.New("issued_token_type is not the ID-JAG type")
+ ErrTokenType = errors.New("token_type is not N_A")
+ ErrEmptyAssertion = errors.New("empty ID-JAG assertion")
+ ErrNotJWT = errors.New("ID-JAG assertion is not a valid JWT")
+ ErrAudienceMismatch = errors.New("ID-JAG aud does not match the requested audience")
+ ErrResourceMismatch = errors.New("ID-JAG resource does not contain the requested resource")
+)
+
+// FromExchange checks the token an RFC 8693 token exchange at the IdP returned
+// for an ID-JAG request (draft 4.3.4) and returns the ID-JAG assertion. The
+// token is the one a pkg/oauthproto/tokenexchange token source returns.
+//
+// The checks run in this order: issued_token_type is the ID-JAG type, token_type
+// is N_A, the assertion is not empty, the assertion parses as a JWT, aud is
+// exactly the requested audience, and, when resource is not empty, the resource
+// claim contains it. A typ header that is not the ID-JAG type is logged and
+// accepted. The JWT is parsed without verifying its signature: this is a check
+// that the IdP honoured the request, not a trust decision.
+//
+// Error messages hold only the checked value and the wanted value, never the
+// assertion.
+func FromExchange(tok *oauth2.Token, audience, resource string) (string, error) {
+ if tok == nil {
+ return "", ErrNoToken
+ }
+
+ got, _ := tok.Extra(oauthproto.ParamIssuedTokenType).(string)
+ if got != oauthproto.TokenTypeIDJAG {
+ return "", newExchangeError(ErrIssuedTokenType,
+ "IdP returned issued_token_type=%q, want %q", got, oauthproto.TokenTypeIDJAG)
+ }
+
+ if !strings.EqualFold(tok.TokenType, oauthproto.TokenTypeNotApplicable) {
+ return "", newExchangeError(ErrTokenType,
+ "IdP returned token_type=%q, want N_A (draft §4.3.4)", tok.TokenType)
+ }
+
+ assertion := tok.AccessToken
+ if assertion == "" {
+ return "", newExchangeError(ErrEmptyAssertion, "IdP returned an empty ID-JAG assertion")
+ }
+
+ parsed, _, err := jwt.NewParser().ParseUnverified(assertion, jwt.MapClaims{})
+ if err != nil {
+ return "", fmt.Errorf("%w: %w", ErrNotJWT, err)
+ }
+ if typ, _ := parsed.Header["typ"].(string); !IsIDJAG(typ) {
+ slog.Debug("ID-JAG typ header is not oauth-id-jag+jwt",
+ "got", typ, "want", oauthproto.JWTTypeIDJAG,
+ )
+ }
+
+ claims, ok := parsed.Claims.(jwt.MapClaims)
+ if !ok {
+ return "", fmt.Errorf("%w: claims are not a JSON object", ErrNotJWT)
+ }
+
+ if aud, err := claims.GetAudience(); err != nil || len(aud) != 1 || aud[0] != audience {
+ return "", newExchangeError(ErrAudienceMismatch,
+ "ID-JAG aud claim %v does not match requested audience %q", claims["aud"], audience)
+ }
+
+ // Draft 4.3.3: each granted requested resource MUST appear in the resource
+ // claim exactly as sent, and the IdP MUST answer invalid_target if it
+ // grants none. With one requested resource, this is that rule.
+ if resource != "" {
+ // A malformed claim is not refused on its own; only the requested value matters.
+ if values, _ := ResourceClaim(claims["resource"]); !slices.Contains(values, resource) {
+ return "", newExchangeError(ErrResourceMismatch,
+ "ID-JAG resource claim %v does not contain requested resource %q", claims["resource"], resource)
+ }
+ }
+
+ return assertion, nil
+}
+
+// exchangeError carries a message and the sentinel it matches. Error returns
+// the message alone.
+type exchangeError struct {
+ msg string
+ sentinel error
+}
+
+func (e *exchangeError) Error() string { return e.msg }
+func (e *exchangeError) Unwrap() error { return e.sentinel }
+
+func newExchangeError(sentinel error, format string, args ...any) error {
+ return &exchangeError{msg: fmt.Sprintf(format, args...), sentinel: sentinel}
+}
diff --git a/pkg/oauthproto/idjag/exchange_test.go b/pkg/oauthproto/idjag/exchange_test.go
new file mode 100644
index 0000000000..e939a4cbe9
--- /dev/null
+++ b/pkg/oauthproto/idjag/exchange_test.go
@@ -0,0 +1,241 @@
+// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc.
+// SPDX-License-Identifier: Apache-2.0
+
+package idjag
+
+import (
+ "testing"
+
+ jwt "github.com/golang-jwt/jwt/v5"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "golang.org/x/oauth2"
+
+ "github.com/stacklok/toolhive/pkg/oauthproto"
+)
+
+const (
+ testAudience = "https://as.example.com"
+ testResource = "https://api.example.com/mcp"
+)
+
+// buildJWT returns a signed token that is only ever parsed unverified. A nil
+// aud or resource value omits the claim.
+func buildJWT(t *testing.T, typ string, aud, resource any) string {
+ t.Helper()
+
+ claims := jwt.MapClaims{"sub": "test"}
+ if aud != nil {
+ claims["aud"] = aud
+ }
+ if resource != nil {
+ claims["resource"] = resource
+ }
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+ token.Header["typ"] = typ
+ signed, err := token.SignedString([]byte("test-key-not-verified"))
+ require.NoError(t, err)
+ return signed
+}
+
+func exchangeToken(accessToken, tokenType, issuedType string) *oauth2.Token {
+ tok := &oauth2.Token{AccessToken: accessToken, TokenType: tokenType}
+ return tok.WithExtra(map[string]any{oauthproto.ParamIssuedTokenType: issuedType})
+}
+
+func TestFromExchange(t *testing.T) {
+ t.Parallel()
+
+ good := buildJWT(t, oauthproto.JWTTypeIDJAG, testAudience, testResource)
+
+ tests := []struct {
+ name string
+ tok *oauth2.Token
+ resource string
+ wantErr string
+ wantIs error
+ wantValue string
+ }{
+ {
+ name: "success",
+ tok: exchangeToken(good, "N_A", oauthproto.TokenTypeIDJAG),
+ resource: testResource,
+ wantValue: good,
+ },
+ {
+ name: "token_type N_A matches case-insensitively",
+ tok: exchangeToken(good, "n_a", oauthproto.TokenTypeIDJAG),
+ resource: testResource,
+ wantValue: good,
+ },
+ {
+ name: "nil token",
+ tok: nil,
+ wantErr: "no token",
+ wantIs: ErrNoToken,
+ },
+ {
+ name: "wrong issued_token_type",
+ tok: exchangeToken(good, "N_A", oauthproto.TokenTypeAccessToken),
+ wantErr: `IdP returned issued_token_type="urn:ietf:params:oauth:token-type:access_token", want ` +
+ `"urn:ietf:params:oauth:token-type:id-jag"`,
+ wantIs: ErrIssuedTokenType,
+ },
+ {
+ name: "missing issued_token_type",
+ tok: &oauth2.Token{AccessToken: good, TokenType: "N_A"},
+ wantErr: `IdP returned issued_token_type="", want "urn:ietf:params:oauth:token-type:id-jag"`,
+ wantIs: ErrIssuedTokenType,
+ },
+ {
+ name: "wrong token_type",
+ tok: exchangeToken(good, "Bearer", oauthproto.TokenTypeIDJAG),
+ wantErr: `IdP returned token_type="Bearer", want N_A (draft §4.3.4)`,
+ wantIs: ErrTokenType,
+ },
+ {
+ name: "both wrong reports issued_token_type first",
+ tok: exchangeToken(good, "Bearer", oauthproto.TokenTypeAccessToken),
+ wantErr: `IdP returned issued_token_type="urn:ietf:params:oauth:token-type:access_token", want ` +
+ `"urn:ietf:params:oauth:token-type:id-jag"`,
+ wantIs: ErrIssuedTokenType,
+ },
+ {
+ name: "empty assertion",
+ tok: exchangeToken("", "N_A", oauthproto.TokenTypeIDJAG),
+ wantErr: "IdP returned an empty ID-JAG assertion",
+ wantIs: ErrEmptyAssertion,
+ },
+ {
+ name: "assertion is not a JWT",
+ tok: exchangeToken("not-a-jwt", "N_A", oauthproto.TokenTypeIDJAG),
+ wantErr: "ID-JAG assertion is not a valid JWT: token is malformed: token contains an invalid number of segments",
+ wantIs: ErrNotJWT,
+ },
+ {
+ name: "typ mismatch is accepted",
+ tok: exchangeToken(buildJWT(t, "JWT", testAudience, nil), "N_A", oauthproto.TokenTypeIDJAG),
+ wantValue: buildJWT(t, "JWT", testAudience, nil),
+ },
+ {
+ name: "aud string equal",
+ tok: exchangeToken(buildJWT(t, "JWT", testAudience, nil), "N_A", oauthproto.TokenTypeIDJAG),
+ wantValue: buildJWT(t, "JWT", testAudience, nil),
+ },
+ {
+ name: "aud string different",
+ tok: exchangeToken(buildJWT(t, "JWT", "https://other.example.com", nil), "N_A", oauthproto.TokenTypeIDJAG),
+ wantErr: `ID-JAG aud claim https://other.example.com does not match requested audience "https://as.example.com"`,
+ wantIs: ErrAudienceMismatch,
+ },
+ {
+ name: "aud one-element array equal",
+ tok: exchangeToken(buildJWT(t, "JWT", []any{testAudience}, nil), "N_A", oauthproto.TokenTypeIDJAG),
+ wantValue: buildJWT(t, "JWT", []any{testAudience}, nil),
+ },
+ {
+ name: "aud two-element array",
+ tok: exchangeToken(buildJWT(t, "JWT", []any{testAudience, "https://other.example.com"}, nil), "N_A", oauthproto.TokenTypeIDJAG),
+ wantErr: `ID-JAG aud claim [https://as.example.com https://other.example.com] does not match requested audience "https://as.example.com"`,
+ wantIs: ErrAudienceMismatch,
+ },
+ {
+ name: "aud empty array",
+ tok: exchangeToken(buildJWT(t, "JWT", []any{}, nil), "N_A", oauthproto.TokenTypeIDJAG),
+ wantErr: `ID-JAG aud claim [] does not match requested audience "https://as.example.com"`,
+ wantIs: ErrAudienceMismatch,
+ },
+ {
+ name: "aud array with a non-string element",
+ tok: exchangeToken(buildJWT(t, "JWT", []any{42}, nil), "N_A", oauthproto.TokenTypeIDJAG),
+ wantErr: `ID-JAG aud claim [42] does not match requested audience "https://as.example.com"`,
+ wantIs: ErrAudienceMismatch,
+ },
+ {
+ name: "aud number",
+ tok: exchangeToken(buildJWT(t, "JWT", 42, nil), "N_A", oauthproto.TokenTypeIDJAG),
+ wantErr: `ID-JAG aud claim 42 does not match requested audience "https://as.example.com"`,
+ wantIs: ErrAudienceMismatch,
+ },
+ {
+ name: "aud missing",
+ tok: exchangeToken(buildJWT(t, "JWT", nil, nil), "N_A", oauthproto.TokenTypeIDJAG),
+ wantErr: `ID-JAG aud claim does not match requested audience "https://as.example.com"`,
+ wantIs: ErrAudienceMismatch,
+ },
+ {
+ name: "resource string equal",
+ tok: exchangeToken(good, "N_A", oauthproto.TokenTypeIDJAG),
+ resource: testResource,
+ wantValue: good,
+ },
+ {
+ name: "resource array containing the value",
+ tok: exchangeToken(buildJWT(t, "JWT", testAudience, []any{"https://x.example.com", testResource}),
+ "N_A", oauthproto.TokenTypeIDJAG),
+ resource: testResource,
+ wantValue: buildJWT(t, "JWT", testAudience, []any{"https://x.example.com", testResource}),
+ },
+ {
+ name: "resource array skips non-string elements",
+ tok: exchangeToken(buildJWT(t, "JWT", testAudience, []any{42, nil, testResource}),
+ "N_A", oauthproto.TokenTypeIDJAG),
+ resource: testResource,
+ wantValue: buildJWT(t, "JWT", testAudience, []any{42, nil, testResource}),
+ },
+ {
+ name: "resource string different",
+ tok: exchangeToken(buildJWT(t, "JWT", testAudience, "https://x.example.com"),
+ "N_A", oauthproto.TokenTypeIDJAG),
+ resource: testResource,
+ wantErr: `ID-JAG resource claim https://x.example.com does not contain requested resource ` +
+ `"https://api.example.com/mcp"`,
+ wantIs: ErrResourceMismatch,
+ },
+ {
+ name: "resource array without the value",
+ tok: exchangeToken(buildJWT(t, "JWT", testAudience, []any{42}), "N_A", oauthproto.TokenTypeIDJAG),
+ resource: testResource,
+ wantErr: `ID-JAG resource claim [42] does not contain requested resource "https://api.example.com/mcp"`,
+ wantIs: ErrResourceMismatch,
+ },
+ {
+ name: "resource number",
+ tok: exchangeToken(buildJWT(t, "JWT", testAudience, 7), "N_A", oauthproto.TokenTypeIDJAG),
+ resource: testResource,
+ wantErr: `ID-JAG resource claim 7 does not contain requested resource "https://api.example.com/mcp"`,
+ wantIs: ErrResourceMismatch,
+ },
+ {
+ name: "resource missing",
+ tok: exchangeToken(buildJWT(t, "JWT", testAudience, nil), "N_A", oauthproto.TokenTypeIDJAG),
+ resource: testResource,
+ wantErr: `ID-JAG resource claim does not contain requested resource "https://api.example.com/mcp"`,
+ wantIs: ErrResourceMismatch,
+ },
+ {
+ name: "resource not checked when none requested",
+ tok: exchangeToken(buildJWT(t, "JWT", testAudience, "https://x.example.com"),
+ "N_A", oauthproto.TokenTypeIDJAG),
+ wantValue: buildJWT(t, "JWT", testAudience, "https://x.example.com"),
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ got, err := FromExchange(tt.tok, testAudience, tt.resource)
+ if tt.wantErr == "" {
+ require.NoError(t, err)
+ assert.Equal(t, tt.wantValue, got)
+ return
+ }
+ require.Error(t, err)
+ assert.Equal(t, tt.wantErr, err.Error())
+ assert.Empty(t, got)
+ if tt.wantIs != nil {
+ assert.ErrorIs(t, err, tt.wantIs)
+ }
+ })
+ }
+}
diff --git a/pkg/oauthproto/idjag/resource.go b/pkg/oauthproto/idjag/resource.go
new file mode 100644
index 0000000000..46ab4182c1
--- /dev/null
+++ b/pkg/oauthproto/idjag/resource.go
@@ -0,0 +1,41 @@
+// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc.
+// SPDX-License-Identifier: Apache-2.0
+
+package idjag
+
+// ResourceClaim reads the "resource" claim of an ID-JAG.
+//
+// values holds the claim's strings: a string gives a one-element slice, an
+// array gives its string elements (other elements are skipped), and any other
+// value gives nil.
+//
+// ok is true only when the claim is well formed under draft-ietf-oauth-
+// identity-assertion-authz-grant-06 section 3: a non-empty string, or a
+// non-empty array whose elements are all non-empty strings with no duplicates.
+//
+// ResourceClaim cannot tell an absent claim from a malformed one. A caller
+// that needs that distinction checks the claims map for the key itself (the
+// comma-ok form). A JSON null counts as present but malformed.
+func ResourceClaim(claim any) (values []string, ok bool) {
+ switch v := claim.(type) {
+ case string:
+ return []string{v}, v != ""
+ case []any:
+ ok = len(v) > 0
+ seen := make(map[string]struct{}, len(v))
+ for _, e := range v {
+ s, isString := e.(string)
+ if !isString {
+ ok = false
+ continue
+ }
+ values = append(values, s)
+ if _, dup := seen[s]; dup || s == "" {
+ ok = false
+ }
+ seen[s] = struct{}{}
+ }
+ return values, ok
+ }
+ return nil, false
+}
diff --git a/pkg/oauthproto/idjag/resource_test.go b/pkg/oauthproto/idjag/resource_test.go
new file mode 100644
index 0000000000..da5971d7d0
--- /dev/null
+++ b/pkg/oauthproto/idjag/resource_test.go
@@ -0,0 +1,42 @@
+// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc.
+// SPDX-License-Identifier: Apache-2.0
+
+package idjag
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestResourceClaim(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ claim any
+ wantValues []string
+ wantOK bool
+ }{
+ {name: "nil", claim: nil, wantValues: nil, wantOK: false},
+ {name: "empty string", claim: "", wantValues: []string{""}, wantOK: false},
+ {name: "string", claim: "a", wantValues: []string{"a"}, wantOK: true},
+ {name: "empty array", claim: []any{}, wantValues: nil, wantOK: false},
+ {name: "one element", claim: []any{"a"}, wantValues: []string{"a"}, wantOK: true},
+ {name: "two elements", claim: []any{"a", "b"}, wantValues: []string{"a", "b"}, wantOK: true},
+ {name: "number element", claim: []any{42.0}, wantValues: nil, wantOK: false},
+ {name: "string and number", claim: []any{"a", 42.0}, wantValues: []string{"a"}, wantOK: false},
+ {name: "duplicates", claim: []any{"a", "a"}, wantValues: []string{"a", "a"}, wantOK: false},
+ {name: "empty element", claim: []any{""}, wantValues: []string{""}, wantOK: false},
+ {name: "number", claim: 42.0, wantValues: nil, wantOK: false},
+ {name: "object", claim: map[string]any{"x": 1}, wantValues: nil, wantOK: false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ values, ok := ResourceClaim(tt.claim)
+ assert.Equal(t, tt.wantValues, values)
+ assert.Equal(t, tt.wantOK, ok)
+ })
+ }
+}
diff --git a/pkg/oauthproto/idjag/typ.go b/pkg/oauthproto/idjag/typ.go
new file mode 100644
index 0000000000..b760a1b9c5
--- /dev/null
+++ b/pkg/oauthproto/idjag/typ.go
@@ -0,0 +1,16 @@
+// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc.
+// SPDX-License-Identifier: Apache-2.0
+
+package idjag
+
+import "github.com/stacklok/toolhive/pkg/oauthproto"
+
+// IsIDJAG reports whether a JOSE "typ" header value names the ID-JAG type. It
+// is true for every RFC 7515 Section 4.1.9 spelling: the comparison ignores
+// case and the "application/" prefix is optional.
+//
+// This is the deny-side predicate. Every access-token validator that shares a
+// signing key with an ID-JAG issuer must refuse a token for which it is true.
+func IsIDJAG(typ string) bool {
+ return oauthproto.IsJOSEType(typ, oauthproto.JWTTypeIDJAG)
+}
diff --git a/pkg/oauthproto/idjag/typ_test.go b/pkg/oauthproto/idjag/typ_test.go
new file mode 100644
index 0000000000..170358f65d
--- /dev/null
+++ b/pkg/oauthproto/idjag/typ_test.go
@@ -0,0 +1,34 @@
+// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc.
+// SPDX-License-Identifier: Apache-2.0
+
+package idjag
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestIsIDJAG(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ typ string
+ want bool
+ }{
+ {name: "exact", typ: "oauth-id-jag+jwt", want: true},
+ {name: "upper case", typ: "OAUTH-ID-JAG+JWT", want: true},
+ {name: "application prefix", typ: "application/oauth-id-jag+jwt", want: true},
+ {name: "mixed case with prefix", typ: "Application/OAuth-ID-JAG+JWT", want: true},
+ {name: "JWT", typ: "JWT", want: false},
+ {name: "at+jwt", typ: "at+jwt", want: false},
+ {name: "empty", typ: "", want: false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ assert.Equal(t, tt.want, IsIDJAG(tt.typ))
+ })
+ }
+}
diff --git a/pkg/oauthproto/tokenexchange/exchange.go b/pkg/oauthproto/tokenexchange/exchange.go
index 55d90f6a81..ea3809520d 100644
--- a/pkg/oauthproto/tokenexchange/exchange.go
+++ b/pkg/oauthproto/tokenexchange/exchange.go
@@ -243,7 +243,7 @@ func (ts *tokenSource) Token() (*oauth2.Token, error) {
// Surface the RFC 8693 issued_token_type so callers can verify the server
// returned the type they asked for (e.g., XAA's IdP exchange requires an ID-JAG).
token := resp.Token.WithExtra(map[string]any{
- "issued_token_type": resp.IssuedTokenType,
+ oauthproto.ParamIssuedTokenType: resp.IssuedTokenType,
})
return token, nil
diff --git a/pkg/vmcp/auth/strategies/xaa.go b/pkg/vmcp/auth/strategies/xaa.go
index 5b31ea3694..6f6878f480 100644
--- a/pkg/vmcp/auth/strategies/xaa.go
+++ b/pkg/vmcp/auth/strategies/xaa.go
@@ -10,15 +10,14 @@ import (
"log/slog"
"net/http"
"net/url"
- "strings"
- jwt "github.com/golang-jwt/jwt/v5"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
"github.com/stacklok/toolhive-core/env"
"github.com/stacklok/toolhive/pkg/auth"
"github.com/stacklok/toolhive/pkg/oauthproto"
+ "github.com/stacklok/toolhive/pkg/oauthproto/idjag"
"github.com/stacklok/toolhive/pkg/oauthproto/jwtbearer"
"github.com/stacklok/toolhive/pkg/oauthproto/tokenexchange"
authtypes "github.com/stacklok/toolhive/pkg/vmcp/auth/types"
@@ -223,11 +222,10 @@ func (*XAAStrategy) authenticateWithClientCredentials(
}
// performIDPExchange runs the RFC 8693 token exchange at the IdP to obtain an
-// ID-JAG. It verifies the response's issued_token_type matches the ID-JAG URN
-// (draft §4.3.3) and that token_type is N_A (draft §5.2), logs a mismatch on
-// the JWT typ header, rejects an empty or unparsable assertion, and validates
-// the aud/resource binding claims against what was requested (confused-deputy
-// defence; see validateIDJAGClaims).
+// ID-JAG, then hands the response to idjag.FromExchange, which checks it
+// against what was requested (draft §4.3.4): issued_token_type, token_type,
+// a parsable JWT, and the aud and resource binding claims (confused-deputy
+// defence).
func (*XAAStrategy) performIDPExchange(
ctx context.Context, idToken string, config *xaaParsedConfig,
) (string, error) {
@@ -250,136 +248,13 @@ func (*XAAStrategy) performIDPExchange(
return "", fmt.Errorf("IdP exchange: %w", err)
}
- // Per draft-ietf-oauth-identity-assertion-authz-grant §4.3.3, the IdP MUST
- // return issued_token_type = urn:ietf:params:oauth:token-type:id-jag. Fail
- // loudly if it returned anything else so target grant cannot accidentally
- // be fed a non-assertion token.
- got, _ := token.Extra("issued_token_type").(string)
- if got != oauthproto.TokenTypeIDJAG {
- return "", fmt.Errorf("IdP exchange: IdP returned issued_token_type=%q, want %q", got, oauthproto.TokenTypeIDJAG)
- }
-
- // Per draft-ietf-oauth-identity-assertion-authz-grant §5.2, the RFC 8693
- // response MUST carry token_type=N_A for an assertion that is not usable
- // as a bearer token at the IdP.
- if !strings.EqualFold(token.TokenType, "N_A") {
- return "", fmt.Errorf("IdP exchange: IdP returned token_type=%q, want N_A (draft §5.2)", token.TokenType)
- }
-
- // The AccessToken field holds the ID-JAG per RFC 8693 response format.
- assertion := token.AccessToken
- if assertion == "" {
- return "", fmt.Errorf("IdP exchange: IdP returned an empty ID-JAG assertion")
- }
-
- // Defence-in-depth: inspect the JWT typ header. The draft §3.1 MUST for
- // typ: oauth-id-jag+jwt is on the issuer (IdP); ToolHive is the
- // holder/presenter — the target AS validates the ID-JAG in target grant. A
- // mismatch is deliberately logged rather than fatal; the fatal contract
- // enforced here is issued_token_type (RFC 8693 §2.2.1, checked above).
- parser := jwt.NewParser()
- parsed, _, parseErr := parser.ParseUnverified(assertion, jwt.MapClaims{})
- if parseErr != nil {
- // A non-parseable assertion cannot carry valid aud/resource claims and
- // therefore cannot be a valid ID-JAG. Fail fast rather than forwarding
- // an unvalidated assertion to the target AS.
- return "", fmt.Errorf("IdP exchange: ID-JAG assertion is not a valid JWT: %w", parseErr)
- }
- if typ, _ := parsed.Header["typ"].(string); !oauthproto.IsJOSEType(typ, oauthproto.JWTTypeIDJAG) {
- slog.Debug("xaa: ID-JAG JWT typ header mismatch",
- "got", typ, "want", oauthproto.JWTTypeIDJAG,
- )
- }
- // The assertion cannot fail: ParseUnverified was called with a literal
- // jwt.MapClaims{}, which it decodes into in place. The !ok branch is
- // defensive.
- claims, ok := parsed.Claims.(jwt.MapClaims)
- if !ok {
- return "", fmt.Errorf("IdP exchange: ID-JAG claims are not MapClaims")
- }
- if err := validateIDJAGClaims(claims, config.targetAudience, config.targetResource); err != nil {
- return "", err
+ assertion, err := idjag.FromExchange(token, config.targetAudience, config.targetResource)
+ if err != nil {
+ return "", fmt.Errorf("IdP exchange: %w", err)
}
-
return assertion, nil
}
-// validateIDJAGClaims checks the aud and resource claims of the returned ID-JAG
-// JWT against the values requested in the IdP exchange (draft §3.1, §5).
-//
-// Per draft §4.4.1, aud MUST be a single-value issuer identifier: either a JSON
-// string, or a JSON array containing exactly one element. A multi-element aud
-// array is malformed and is rejected (see audMatches). resource is checked
-// only when one was requested (the resource parameter is OPTIONAL per draft
-// §4.3); when one was requested, ToolHive requires the returned ID-JAG to echo
-// it — a deliberate strict-binding policy, stricter than the draft, which
-// leaves resource OPTIONAL in the response even when requested.
-//
-// This is defence-in-depth against token misbinding: if the IdP mints an ID-JAG
-// for a different audience/resource, the target AS should reject it — but
-// ToolHive fails fast rather than forwarding a mismatched assertion.
-//
-// Per RFC 7519 §4.1.3, the aud claim may be a string or an array of strings;
-// golang-jwt/v5 decodes a JSON array as []interface{} whose elements are
-// strings. resource legitimately allows an array of URIs per draft §3.1, so a
-// membership check (claimContainsString) is used there; aud does not permit
-// multiple values, so a dedicated single-value check (audMatches) is used
-// instead.
-func validateIDJAGClaims(claims jwt.MapClaims, wantAudience, wantResource string) error {
- // aud is REQUIRED and single-valued per draft §4.4.1.
- if !audMatches(claims, wantAudience) {
- return fmt.Errorf("IdP exchange: ID-JAG aud claim %v does not match requested audience %q", claims["aud"], wantAudience)
- }
-
- // Deliberately stricter than the draft: resource is OPTIONAL in the ID-JAG
- // even when requested, but ToolHive rejects an ID-JAG that omits it once
- // the operator has configured a resource to bind to.
- if wantResource != "" && !claimContainsString(claims, "resource", wantResource) {
- return fmt.Errorf(
- "IdP exchange: ID-JAG resource claim %v does not contain requested resource %q",
- claims["resource"], wantResource,
- )
- }
-
- return nil
-}
-
-// audMatches reports whether the aud claim is a single-value issuer identifier
-// equal to want, per draft §4.4.1: either a JSON string, or a JSON array
-// containing exactly one element. Any other shape — missing, multi-element
-// array, empty array, wrong type, or a non-string element — is rejected.
-func audMatches(claims jwt.MapClaims, want string) bool {
- switch v := claims["aud"].(type) {
- case string:
- return v == want
- case []interface{}:
- if len(v) != 1 {
- return false
- }
- s, ok := v[0].(string)
- return ok && s == want
- default:
- return false
- }
-}
-
-// claimContainsString reports whether the named claim contains want. Per RFC
-// 7519 the claim may be a single string or an array; golang-jwt/v5 decodes JSON
-// arrays as []interface{} whose elements are strings.
-func claimContainsString(claims jwt.MapClaims, key, want string) bool {
- switch v := claims[key].(type) {
- case string:
- return v == want
- case []interface{}:
- for _, e := range v {
- if s, ok := e.(string); ok && s == want {
- return true
- }
- }
- }
- return false
-}
-
// performTargetGrant runs the RFC 7523 JWT Bearer grant at the target AS using
// the ID-JAG assertion returned by IdP exchange.
func (*XAAStrategy) performTargetGrant(
diff --git a/pkg/vmcp/auth/strategies/xaa_test.go b/pkg/vmcp/auth/strategies/xaa_test.go
index 9b7e1747aa..0fa5d5d7c3 100644
--- a/pkg/vmcp/auth/strategies/xaa_test.go
+++ b/pkg/vmcp/auth/strategies/xaa_test.go
@@ -757,7 +757,7 @@ func TestXAAStrategy_Authenticate(t *testing.T) {
})
},
expectError: true,
- errorContains: []string{"N_A"},
+ errorContains: []string{"want N_A (draft §4.3.4)"},
},
{
name: "IdP exchange rejects empty access_token",
@@ -1058,7 +1058,7 @@ func TestXAAStrategy_Authenticate(t *testing.T) {
errorContains: []string{"IdP exchange", "resource"},
},
// resource check skipped when TargetResource is not configured
- // (wantResource == "" early-return branch in validateIDJAGClaims).
+ // (the empty-resource case in idjag.FromExchange).
{
name: "IdP exchange accepts ID-JAG when TargetResource is not configured",
setupCtx: func() context.Context {
@@ -1200,10 +1200,10 @@ func buildIDJAGJWT(t *testing.T, typ string, aud, resource any) string {
// setClaim sets a string-or-array claim on a MapClaims, omitting it when v is
// nil or an empty string. []string is marshalled as a JSON array (decoded back
-// by golang-jwt as []interface{}, exercising the array branch of
-// claimContainsString). []interface{} is set directly, allowing heterogeneous
-// arrays (e.g. mixing strings with non-string elements) to exercise the
-// type-guard in claimContainsString's array branch.
+// by golang-jwt as []interface{}, exercising the array branch of the resource
+// check in idjag.FromExchange). []interface{} is set directly, allowing
+// heterogeneous arrays (e.g. mixing strings with non-string elements) to
+// exercise the skipping of non-string elements in that same check.
func setClaim(t *testing.T, claims jwt.MapClaims, key string, v any) {
t.Helper()
switch c := v.(type) {
diff --git a/sdk/go/client/oas_schemas_gen.go b/sdk/go/client/oas_schemas_gen.go
index 1d35fc9b2e..9db0a0e926 100644
--- a/sdk/go/client/oas_schemas_gen.go
+++ b/sdk/go/client/oas_schemas_gen.go
@@ -21465,8 +21465,11 @@ type TokenExchangeJWTBearerGrantPolicy struct {
// authorization server for this grant; it is NOT a resource/API
// identifier — a bare resource audience is deliberately not accepted
// here, that would let any RFC 8707 resource-scoped token satisfy the
- // grant instead of only tokens minted for this AS. Defaults to
- // [tokenEndpoint] when empty, preserving prior exact-match behavior.
+ // grant instead of only tokens minted for this AS. When empty, the plain
+ // JWT-bearer grant accepts the token endpoint, and the ID-JAG grant accepts
+ // the token endpoint and this server's issuer identifier, unless the issuer
+ // is also an allowed resource audience. A configured list replaces both
+ // defaults.
AcceptedAudiences []string `json:"accepted_audiences"`
MaxAssertionAge OptString `json:"max_assertion_age"`
SubjectBindings []TokenExchangeJWTBearerSubjectBinding `json:"subject_bindings"`
diff --git a/sdk/go/openapi.json b/sdk/go/openapi.json
index 3333464665..b9e7f869f4 100644
--- a/sdk/go/openapi.json
+++ b/sdk/go/openapi.json
@@ -5221,7 +5221,7 @@
"description": "JWTBearerGrant optionally enables the plain RFC 7523 JWT-bearer grant.\nIt accepts assertions from this issuer without client authentication and\nlimits their maximum age, subjects, and RFC 8707 resources. It is\nindependent from RFC 8693 delegation policy.\n\nThis legacy field is deprecated; configure RFC 7523 policy under\ninbound_grants.jwt_bearer.issuer_policies.",
"properties": {
"accepted_audiences": {
- "description": "AcceptedAudiences is the set of \"this AS\" identity strings an\nassertion's \"aud\" claim must intersect — e.g. to support migrating\nthis server's issuer/token-endpoint URL, or exposing it under more\nthan one valid name. Each value uniquely identifies this\nauthorization server for this grant; it is NOT a resource/API\nidentifier — a bare resource audience is deliberately not accepted\nhere, that would let any RFC 8707 resource-scoped token satisfy the\ngrant instead of only tokens minted for this AS. Defaults to\n[tokenEndpoint] when empty, preserving prior exact-match behavior.",
+ "description": "AcceptedAudiences is the set of \"this AS\" identity strings an\nassertion's \"aud\" claim must intersect — e.g. to support migrating\nthis server's issuer/token-endpoint URL, or exposing it under more\nthan one valid name. Each value uniquely identifies this\nauthorization server for this grant; it is NOT a resource/API\nidentifier — a bare resource audience is deliberately not accepted\nhere, that would let any RFC 8707 resource-scoped token satisfy the\ngrant instead of only tokens minted for this AS. When empty, the plain\nJWT-bearer grant accepts the token endpoint, and the ID-JAG grant accepts\nthe token endpoint and this server's issuer identifier, unless the issuer\nis also an allowed resource audience. A configured list replaces both\ndefaults.",
"items": {
"type": "string"
},
diff --git a/sdk/go/openapi.yaml b/sdk/go/openapi.yaml
index b4c0613f7e..1508e6da18 100644
--- a/sdk/go/openapi.yaml
+++ b/sdk/go/openapi.yaml
@@ -4989,8 +4989,11 @@ components:
authorization server for this grant; it is NOT a resource/API
identifier — a bare resource audience is deliberately not accepted
here, that would let any RFC 8707 resource-scoped token satisfy the
- grant instead of only tokens minted for this AS. Defaults to
- [tokenEndpoint] when empty, preserving prior exact-match behavior.
+ grant instead of only tokens minted for this AS. When empty, the plain
+ JWT-bearer grant accepts the token endpoint, and the ID-JAG grant accepts
+ the token endpoint and this server's issuer identifier, unless the issuer
+ is also an allowed resource audience. A configured list replaces both
+ defaults.
items:
type: string
type: array