From 0ca03c23e665fb0fc61257dad16272308c103521 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Tue, 10 Nov 2026 22:10:13 +0100 Subject: [PATCH 1/7] Name RFC 8693 N_A and issued_token_type once The token_type value N_A and the issued_token_type response member were spelled as literals in the auth server handlers, the token exchange client and the vMCP XAA strategy, and the refresh-token handler kept its own private copy of N_A. The ID-JAG protocol code that moves into oauthproto next needs one shared definition of both, so the consumers and the issuer cannot drift apart. Both names move to oauthproto next to the token type URNs. Wire values and error text are unchanged. Refs #6898 Co-authored-by: Mecatl --- pkg/authserver/server/tokenexchange/handler.go | 2 +- .../server/tokenexchange/refresh_token_handler.go | 8 ++------ pkg/oauthproto/constants.go | 10 ++++++++++ pkg/oauthproto/tokenexchange/exchange.go | 2 +- pkg/vmcp/auth/strategies/xaa.go | 4 ++-- 5 files changed, 16 insertions(+), 10 deletions(-) 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/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/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/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..dfd78b9897 100644 --- a/pkg/vmcp/auth/strategies/xaa.go +++ b/pkg/vmcp/auth/strategies/xaa.go @@ -254,7 +254,7 @@ func (*XAAStrategy) performIDPExchange( // 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) + got, _ := token.Extra(oauthproto.ParamIssuedTokenType).(string) if got != oauthproto.TokenTypeIDJAG { return "", fmt.Errorf("IdP exchange: IdP returned issued_token_type=%q, want %q", got, oauthproto.TokenTypeIDJAG) } @@ -262,7 +262,7 @@ func (*XAAStrategy) performIDPExchange( // 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") { + if !strings.EqualFold(token.TokenType, oauthproto.TokenTypeNotApplicable) { return "", fmt.Errorf("IdP exchange: IdP returned token_type=%q, want N_A (draft §5.2)", token.TokenType) } From a59070ee4b9881c96fa840b8e31d5c43cdc72db9 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Tue, 10 Nov 2026 22:32:05 +0100 Subject: [PATCH 2/7] Add oauthproto/idjag for the XAA client side The rules for an ID-JAG were spread through product code: the vMCP XAA client checked the IdP response inline, and two validators each wrote the typ test that keeps an ID-JAG from being used as an access token. Someone who wants to learn how ToolHive does Cross App Access had no single place to start. This adds pkg/oauthproto/idjag. Its doc.go walks through the flow in order: the RFC 8693 exchange at the IdP, then the RFC 7523 redemption. The package has three functions. IsIDJAG is the typ test, and the two validators now share it. FromExchange takes the token that the exchange client returns and checks it against what was requested: the token types, a parsable JWT, a single matching audience and, when one was asked for, a matching resource. ResourceClaim reads the string-or-array resource claim. FromExchange does not import the exchange client, so it adds no import cycle. The XAA client calls it, and the package doc of oauthproto gains a short reading guide. What is accepted and refused does not change. Two diagnostic texts do: the token_type error cited draft section 5.2 and now cites section 4.3.4, which is where the draft says it, and the debug line for a typ header that is not the ID-JAG type has new wording, because it is now logged from the library and not from the XAA client. The tests for the XAA client keep passing, and a new table test pins each rule. Refs #6898 Co-authored-by: Mecatl --- pkg/auth/token.go | 3 +- .../tokenexchange/jwt_bearer_handler.go | 6 +- .../server/tokenexchange/validator.go | 4 +- pkg/oauthproto/doc.go | 10 + pkg/oauthproto/idjag/doc.go | 47 ++++ pkg/oauthproto/idjag/exchange.go | 122 +++++++++ pkg/oauthproto/idjag/exchange_test.go | 241 ++++++++++++++++++ pkg/oauthproto/idjag/typ.go | 16 ++ pkg/oauthproto/idjag/typ_test.go | 34 +++ pkg/vmcp/auth/strategies/xaa.go | 141 +--------- pkg/vmcp/auth/strategies/xaa_test.go | 12 +- 11 files changed, 491 insertions(+), 145 deletions(-) create mode 100644 pkg/oauthproto/idjag/doc.go create mode 100644 pkg/oauthproto/idjag/exchange.go create mode 100644 pkg/oauthproto/idjag/exchange_test.go create mode 100644 pkg/oauthproto/idjag/typ.go create mode 100644 pkg/oauthproto/idjag/typ_test.go 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/jwt_bearer_handler.go b/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go index 003661d7d7..2b1f17587b 100644 --- a/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go +++ b/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go @@ -406,9 +406,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 { 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/doc.go b/pkg/oauthproto/doc.go index b7d7c78ea6..daede1220e 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. +// // 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..9fd4996ef2 --- /dev/null +++ b/pkg/oauthproto/idjag/doc.go @@ -0,0 +1,47 @@ +// 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 two functions today: +// +// - [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. +// +// The resource server's rules arrive in a later change. 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..99c3b1b737 --- /dev/null +++ b/pkg/oauthproto/idjag/exchange.go @@ -0,0 +1,122 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package idjag + +import ( + "errors" + "fmt" + "log/slog" + "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 != "" && !claimContains(claims["resource"], resource) { + return "", newExchangeError(ErrResourceMismatch, + "ID-JAG resource claim %v does not contain requested resource %q", claims["resource"], resource) + } + + return assertion, nil +} + +// claimContains reports whether a string-or-array claim holds want. Array +// elements that are not strings are skipped. +func claimContains(claim any, want string) bool { + switch v := claim.(type) { + case string: + return v == want + case []any: + for _, e := range v { + if s, ok := e.(string); ok && s == want { + return true + } + } + } + return false +} + +// 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/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/vmcp/auth/strategies/xaa.go b/pkg/vmcp/auth/strategies/xaa.go index dfd78b9897..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(oauthproto.ParamIssuedTokenType).(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, oauthproto.TokenTypeNotApplicable) { - 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) { From 9c5eccdb586441ad9e984fa5d532b131b1eeea2d Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Wed, 11 Nov 2026 12:50:55 +0100 Subject: [PATCH 3/7] Split resource choice from JWT-bearer policy validateJWTBearerPolicy checked the assertion's age, chose the resource from the request's single resource parameter, and checked the subject binding, and both the plain RFC 7523 handler and the ID-JAG handler called it. The ID-JAG profile needs to choose its resource differently (the draft's resource claim), and doing that inside the shared function would change plain RFC 7523 assertions too. Split it into checkAssertionMaxAge, requestedResource and checkSubjectBinding. Each handler calls them in the old order, and errors and hints are unchanged. New handler tests pin that the age check still runs before the resource check. Refs #6892 Co-authored-by: Mecatl --- .../server/tokenexchange/id_jag_handler.go | 21 +++++- .../tokenexchange/id_jag_handler_test.go | 15 ++++ .../tokenexchange/jwt_bearer_handler.go | 34 ++++++--- .../tokenexchange/jwt_bearer_handler_test.go | 69 +++++++++++++++++-- 4 files changed, 126 insertions(+), 13 deletions(-) diff --git a/pkg/authserver/server/tokenexchange/id_jag_handler.go b/pkg/authserver/server/tokenexchange/id_jag_handler.go index 0a506fd6dd..6200372bae 100644 --- a/pkg/authserver/server/tokenexchange/id_jag_handler.go +++ b/pkg/authserver/server/tokenexchange/id_jag_handler.go @@ -144,7 +144,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 } @@ -198,6 +198,25 @@ 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 := requestedResource(requester.GetRequestForm()) + if err != nil { + return "", err + } + if err := checkSubjectBinding(claims, policy, resource); err != nil { + return "", err + } + return resource, nil +} + // checkClientGrant refuses an explicit-grant client whose registered grant types // do not include jwt-bearer. func (h *IDJAGHandler) checkClientGrant(requester fosite.AccessRequester) error { diff --git a/pkg/authserver/server/tokenexchange/id_jag_handler_test.go b/pkg/authserver/server/tokenexchange/id_jag_handler_test.go index c34b085b96..832e15babf 100644 --- a/pkg/authserver/server/tokenexchange/id_jag_handler_test.go +++ b/pkg/authserver/server/tokenexchange/id_jag_handler_test.go @@ -425,3 +425,18 @@ 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) +} diff --git a/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go b/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go index 2b1f17587b..f434a741ce 100644 --- a/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go +++ b/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go @@ -180,10 +180,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 +231,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 +250,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.")) } diff --git a/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go b/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go index dcec7f6eca..9d58531fad 100644 --- a/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go +++ b/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go @@ -143,7 +143,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 +160,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 +327,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 +368,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 @@ -806,3 +818,52 @@ func TestJWTBearerHandler_StampsNoUpstreamSessionClaim(t *testing.T) { 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) +} From 1a0f45cedc1e64cfa4ef37399e9b2057cce3a657 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Wed, 11 Nov 2026 13:00:46 +0100 Subject: [PATCH 4/7] Let each handler set the default audience ValidateJWTBearerAssertion took the token endpoint and used it as the only accepted audience when the issuer configures no accepted_audiences. The validator cannot tell a plain RFC 7523 assertion from an ID-JAG, yet the ID-JAG draft (section 4.4.1) wants this server's issuer identifier in aud, so the default has to come from the handler that knows the profile. Take the default audiences from the caller instead. Both handlers pass the token endpoint, so nothing accepted or refused changes. Configured accepted_audiences still take precedence, and an empty default is refused as a programming error. Refs #6892 Co-authored-by: Mecatl --- .../server/tokenexchange/id_jag_handler.go | 2 +- .../tokenexchange/id_jag_handler_test.go | 4 +- .../tokenexchange/jwt_bearer_handler.go | 6 +- .../tokenexchange/jwt_bearer_handler_test.go | 27 ++++---- .../jwt_bearer_validator_test.go | 66 +++++++++++++++++-- .../tokenexchange/multi_issuer_validator.go | 11 ++-- 6 files changed, 91 insertions(+), 25 deletions(-) diff --git a/pkg/authserver/server/tokenexchange/id_jag_handler.go b/pkg/authserver/server/tokenexchange/id_jag_handler.go index 6200372bae..e9da04b376 100644 --- a/pkg/authserver/server/tokenexchange/id_jag_handler.go +++ b/pkg/authserver/server/tokenexchange/id_jag_handler.go @@ -121,7 +121,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, []string{h.core.tokenEndpoint}) if err != nil { return errorsx.WithStack(fosite.ErrInvalidGrant.WithHint("The ID-JAG assertion is invalid or could not be verified.")) } diff --git a/pkg/authserver/server/tokenexchange/id_jag_handler_test.go b/pkg/authserver/server/tokenexchange/id_jag_handler_test.go index 832e15babf..26bee14aba 100644 --- a/pkg/authserver/server/tokenexchange/id_jag_handler_test.go +++ b/pkg/authserver/server/tokenexchange/id_jag_handler_test.go @@ -339,10 +339,12 @@ func TestIDJAGHandler_IssuesBoundSession(t *testing.T) { tj := newTestJWKS(t) claims := validIDJAGClaims() consumer := &recordingAssertionConsumer{} - h := newIDJAGTestHandler(t, &testJWTBearerAssertionValidator{claims: claims}, consumer) + validator := &testJWTBearerAssertionValidator{claims: claims} + h := newIDJAGTestHandler(t, validator, consumer) req := newIDJAGRequest(t, tj, idJAGTestClientID) require.NoError(t, h.HandleTokenEndpointRequest(context.Background(), req)) + assert.Equal(t, []string{testTokenEndpoint}, 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. diff --git a/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go b/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go index f434a741ce..e1c200b65a 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.")) } diff --git a/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go b/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go index 9d58531fad..a8e389edb3 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 } @@ -787,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}, @@ -813,6 +816,8 @@ 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], diff --git a/pkg/authserver/server/tokenexchange/jwt_bearer_validator_test.go b/pkg/authserver/server/tokenexchange/jwt_bearer_validator_test.go index d34cb09b4b..59631e8763 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,59 @@ 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) + validator := newMultiValidator(t, selfJWKS, []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{"https://mcp.example.com"}}, + }, + }, + }}) + + const secondDefault = "https://auth.example.com" + tests := []struct { + name string + defaults []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: "assertion audience must include one of the accepted authorization server identities", + }, + } + + 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 := validator.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..6a1d6faf3b 100644 --- a/pkg/authserver/server/tokenexchange/multi_issuer_validator.go +++ b/pkg/authserver/server/tokenexchange/multi_issuer_validator.go @@ -667,15 +667,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 +700,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 } From 8472049cd9b64ed68600429dbb67254ce3c48a6c Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Wed, 11 Nov 2026 13:12:13 +0100 Subject: [PATCH 5/7] Log ID-JAGs that depart from the draft The ID-JAG handler accepts some assertions that the draft does not allow: an aud with several values, an aud that is not this server's issuer identifier, a malformed resource claim, and a request for a resource that the resource claim does not name. Existing deployments may depend on that, so refusing them now could break customers, and today nobody can tell which deployments would be affected. The handler now works out those departures once a request has passed every check, including replay and the assertion lifetime, and logs each one. A refused request logs nothing, so an "accepted" line is never written for a replay. The first occurrence for an assertion issuer and departure is a warning, and later ones are debug lines. A line carries the issuer, the client ID and the name of the departure, never the subject, the jti or a claim value. The aud line also carries a hint naming jwt_bearer_grant.accepted_audiences, because with no configured list the handler accepts only the token endpoint, so the fix is usually in ToolHive's config rather than at the IdP. idjag.ResourceClaim reads the resource claim and reports whether it is well formed (draft section 3), so the handler can tell a malformed claim from one that names another resource. FromExchange uses it without changing what the client accepts. What the handler accepts and refuses is unchanged. The architecture doc lists the departures, and two more that nothing logs: a public client identified only by client_id, and a cnf claim that no code reads. Refs #6898 Co-authored-by: Mecatl --- docs/arch/17-token-exchange-delegation.md | 46 +++ .../server/tokenexchange/id_jag_handler.go | 99 ++++- .../tokenexchange/id_jag_handler_test.go | 390 ++++++++++++++++++ pkg/oauthproto/doc.go | 2 +- pkg/oauthproto/idjag/doc.go | 9 +- pkg/oauthproto/idjag/exchange.go | 26 +- pkg/oauthproto/idjag/resource.go | 41 ++ pkg/oauthproto/idjag/resource_test.go | 42 ++ 8 files changed, 628 insertions(+), 27 deletions(-) create mode 100644 pkg/oauthproto/idjag/resource.go create mode 100644 pkg/oauthproto/idjag/resource_test.go diff --git a/docs/arch/17-token-exchange-delegation.md b/docs/arch/17-token-exchange-delegation.md index 16e795b01a..ee8db270da 100644 --- a/docs/arch/17-token-exchange-delegation.md +++ b/docs/arch/17-token-exchange-delegation.md @@ -1354,6 +1354,52 @@ Where the two differ is the trust model — the ID-JAG handler is **bound**: exactly-one-`resource` requirement, consume-before-issue, and the issued token's lifetime being capped by the assertion's remaining validity. +**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`, and accepts the token endpoint URL only + when that list is empty. This line also carries a `hint` attribute that says + what to change. If `accepted_audiences` is empty, add both the token + endpoint URL and the issuer identifier to it, because setting the list + removes the token endpoint default, and then have the IdP use the issuer + identifier 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`. +- `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. The handler takes the resource from the + request and does not read the claim. + +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 - **Audience.** The requested audience is bounded by the subject token's own diff --git a/pkg/authserver/server/tokenexchange/id_jag_handler.go b/pkg/authserver/server/tokenexchange/id_jag_handler.go index e9da04b376..d66fb007d0 100644 --- a/pkg/authserver/server/tokenexchange/id_jag_handler.go +++ b/pkg/authserver/server/tokenexchange/id_jag_handler.go @@ -5,7 +5,9 @@ package tokenexchange import ( "context" + "log/slog" "slices" + "sync" "time" "github.com/ory/fosite" @@ -16,6 +18,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 +42,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,8 +72,31 @@ 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 + + // 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. @@ -85,7 +114,7 @@ func newIDJAGIssuanceHandler( for _, id := range explicitGrantClientIDs { explicitGrantClients[id] = struct{}{} } - return &IDJAGHandler{core: core, explicitGrantClients: explicitGrantClients}, nil + return &IDJAGHandler{core: core, explicitGrantClients: explicitGrantClients, issuer: config}, nil } // CanHandleTokenEndpointRequest claims only recognized ID-JAG assertions — @@ -162,6 +191,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 @@ -217,6 +247,65 @@ func checkIDJAGPolicy( return resource, 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) + } + asIssuer := h.issuer.GetAccessTokenIssuer(ctx) + if asIssuer != "" && !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 { + // Setting accepted_audiences removes the token endpoint default, so both must be listed. + case len(policy.AcceptedAudiences) == 0: + return "add both the token endpoint URL and this server's issuer identifier to jwt_bearer_grant.accepted_audiences, " + + "then have the IdP use the issuer identifier 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" + } +} + // checkClientGrant refuses an explicit-grant client whose registered grant types // do not include jwt-bearer. func (h *IDJAGHandler) checkClientGrant(requester fosite.AccessRequester) error { diff --git a/pkg/authserver/server/tokenexchange/id_jag_handler_test.go b/pkg/authserver/server/tokenexchange/id_jag_handler_test.go index 26bee14aba..291bb9b768 100644 --- a/pkg/authserver/server/tokenexchange/id_jag_handler_test.go +++ b/pkg/authserver/server/tokenexchange/id_jag_handler_test.go @@ -6,7 +6,9 @@ package tokenexchange import ( "context" "errors" + "log/slog" "net/url" + "strings" "testing" "time" @@ -442,3 +444,391 @@ func TestIDJAGHandler_MaxAgeIsCheckedBeforeResource(t *testing.T) { assert.ErrorIs(t, err, fosite.ErrInvalidGrant) assert.NotErrorIs(t, err, fosite.ErrInvalidRequest) } + +const ( + idJAGTestASIssuer = "https://as.example.com" + idJAGTestOtherAud = "https://other.example.com" + hintNoAcceptedAud = "add both the token endpoint URL and this server's issuer identifier to jwt_bearer_grant.accepted_audiences, " + + "then have the IdP use the issuer identifier 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, + ) + 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)) +} diff --git a/pkg/oauthproto/doc.go b/pkg/oauthproto/doc.go index daede1220e..7b83fdaada 100644 --- a/pkg/oauthproto/doc.go +++ b/pkg/oauthproto/doc.go @@ -22,7 +22,7 @@ // - 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. +// 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 diff --git a/pkg/oauthproto/idjag/doc.go b/pkg/oauthproto/idjag/doc.go index 9fd4996ef2..e095ee184f 100644 --- a/pkg/oauthproto/idjag/doc.go +++ b/pkg/oauthproto/idjag/doc.go @@ -24,11 +24,12 @@ // 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 two functions today: +// 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 @@ -38,7 +39,11 @@ // issuer identifier, and this check refuses that: ToolHive supports only // issuer-identifier audiences here. // -// The resource server's rules arrive in a later change. Signature checks, +// - [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. // diff --git a/pkg/oauthproto/idjag/exchange.go b/pkg/oauthproto/idjag/exchange.go index 99c3b1b737..50fd3b0a05 100644 --- a/pkg/oauthproto/idjag/exchange.go +++ b/pkg/oauthproto/idjag/exchange.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "log/slog" + "slices" "strings" jwt "github.com/golang-jwt/jwt/v5" @@ -83,30 +84,17 @@ func FromExchange(tok *oauth2.Token, audience, resource string) (string, error) // 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 != "" && !claimContains(claims["resource"], resource) { - return "", newExchangeError(ErrResourceMismatch, - "ID-JAG resource claim %v does not contain requested resource %q", claims["resource"], resource) + 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 } -// claimContains reports whether a string-or-array claim holds want. Array -// elements that are not strings are skipped. -func claimContains(claim any, want string) bool { - switch v := claim.(type) { - case string: - return v == want - case []any: - for _, e := range v { - if s, ok := e.(string); ok && s == want { - return true - } - } - } - return false -} - // exchangeError carries a message and the sentinel it matches. Error returns // the message alone. type exchangeError struct { 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) + }) + } +} From 9bf95cc17f1a2b93842bc673396ade289527355a Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Wed, 11 Nov 2026 13:23:45 +0100 Subject: [PATCH 6/7] Default the ID-JAG resource to its claim An ID-JAG redemption had to carry exactly one resource parameter, but the ID-JAG draft (section 4.4) defines no resource parameter for redemption, so a client that follows the draft and leaves it out got invalid_request even when the ID-JAG itself names a single resource. When the request has no resource parameter at all and the ID-JAG's resource claim is well formed with exactly one value, use that value. It goes through the same URI, subject-binding and client-audience checks as a requested resource. Every other case keeps today's rule and error: no claim, several values, a malformed claim, or an empty or repeated parameter. Only requests that were refused before can now succeed. One refused request changes its error: with no parameter and a single claim value that is not an absolute URI, the answer is now invalid_target ("Resource must be an absolute URI"), the error a requested resource already gets, instead of invalid_request. Plain RFC 7523 assertions are unchanged; a test pins that a resource claim does not become a default there. Refs #6892 Co-authored-by: Mecatl --- docs/arch/17-token-exchange-delegation.md | 20 ++- .../server/tokenexchange/id_jag_handler.go | 29 ++++- .../tokenexchange/id_jag_handler_test.go | 121 ++++++++++++++++++ .../tokenexchange/jwt_bearer_handler_test.go | 54 ++++++++ 4 files changed, 218 insertions(+), 6 deletions(-) diff --git a/docs/arch/17-token-exchange-delegation.md b/docs/arch/17-token-exchange-delegation.md index ee8db270da..77ed3a9c9f 100644 --- a/docs/arch/17-token-exchange-delegation.md +++ b/docs/arch/17-token-exchange-delegation.md @@ -1350,9 +1350,18 @@ 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 @@ -1377,8 +1386,9 @@ subject, `jti` or claim values. The findings are: 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. The handler takes the resource from the - request and does not read the claim. + 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 diff --git a/pkg/authserver/server/tokenexchange/id_jag_handler.go b/pkg/authserver/server/tokenexchange/id_jag_handler.go index d66fb007d0..37134b1d06 100644 --- a/pkg/authserver/server/tokenexchange/id_jag_handler.go +++ b/pkg/authserver/server/tokenexchange/id_jag_handler.go @@ -6,6 +6,7 @@ package tokenexchange import ( "context" "log/slog" + "net/url" "slices" "sync" "time" @@ -237,7 +238,7 @@ func checkIDJAGPolicy( if err := checkAssertionMaxAge(claims, policy); err != nil { return "", err } - resource, err := requestedResource(requester.GetRequestForm()) + resource, err := idJAGResource(requester.GetRequestForm(), claims) if err != nil { return "", err } @@ -247,6 +248,32 @@ func checkIDJAGPolicy( 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 diff --git a/pkg/authserver/server/tokenexchange/id_jag_handler_test.go b/pkg/authserver/server/tokenexchange/id_jag_handler_test.go index 291bb9b768..b31339d8ee 100644 --- a/pkg/authserver/server/tokenexchange/id_jag_handler_test.go +++ b/pkg/authserver/server/tokenexchange/id_jag_handler_test.go @@ -832,3 +832,124 @@ func TestIDJAGHandler_WarnOnceKeyIsIssuerAndFinding(t *testing.T) { 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") + }) + } +} diff --git a/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go b/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go index a8e389edb3..f6bf5c1c6b 100644 --- a/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go +++ b/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go @@ -872,3 +872,57 @@ func TestJWTBearerHandler_MaxAgeIsCheckedBeforeResource(t *testing.T) { 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) +} From d3cc5fa42bcbb728b5e3fbb4853b54f1edf5b10d Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Wed, 11 Nov 2026 13:38:25 +0100 Subject: [PATCH 7/7] Accept the issuer as ID-JAG audience The ID-JAG draft (section 4.4.1) says an ID-JAG's aud is the resource authorization server's issuer identifier. With no accepted_audiences configured, ToolHive accepted only the token endpoint, so an ID-JAG that follows the draft was refused unless the operator listed the issuer by hand. When the assertion issuer configures no accepted_audiences, the ID-JAG handler now accepts this server's issuer identifier as well as the token endpoint. A configured list still replaces both defaults, and plain RFC 7523 assertions still accept only the token endpoint. This is safe because an ID-JAG is already refused as an RFC 8693 subject token and as an access token, and both values name this server. The one exception: when the issuer identifier is also a resource audience (allowed_audiences), the issuer stays out of the defaults, because an access token minted for that resource must never pass as an assertion. The server then logs one warning at startup instead of refusing to start. The audience_not_issuer hint for the empty-list case now says the issuer is accepted and the IdP should use it. When the issuer is a resource audience, audience_not_issuer is not logged at all, because no IdP could fix it. The AcceptedAudiences comments on the RunConfig type and the operator CRD describe the new defaults; swagger, the Go SDK, the CRD manifests and the CRD API docs are regenerated from them. Refs #6892 Co-authored-by: Mecatl --- .../v1beta1/mcpexternalauthconfig_types.go | 6 +- ...e.stacklok.dev_mcpexternalauthconfigs.yaml | 24 ++- ...olhive.stacklok.dev_virtualmcpservers.yaml | 24 ++- ...e.stacklok.dev_mcpexternalauthconfigs.yaml | 24 ++- ...olhive.stacklok.dev_virtualmcpservers.yaml | 24 ++- docs/arch/17-token-exchange-delegation.md | 38 +++-- docs/operator/crd-api.md | 4 +- docs/server/docs.go | 2 +- docs/server/swagger.json | 2 +- docs/server/swagger.yaml | 7 +- .../server/tokenexchange/id_jag_handler.go | 61 +++++-- .../tokenexchange/id_jag_handler_test.go | 151 ++++++++++++++++-- .../tokenexchange/jwt_bearer_handler.go | 7 +- .../jwt_bearer_validator_test.go | 51 ++++-- .../tokenexchange/multi_issuer_validator.go | 7 +- sdk/go/client/oas_schemas_gen.go | 7 +- sdk/go/openapi.json | 2 +- sdk/go/openapi.yaml | 7 +- 18 files changed, 354 insertions(+), 94 deletions(-) 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 77ed3a9c9f..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 @@ -1375,13 +1387,17 @@ 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`, and accepts the token endpoint URL only - when that list is empty. This line also carries a `hint` attribute that says - what to change. If `accepted_audiences` is empty, add both the token - endpoint URL and the issuer identifier to it, because setting the list - removes the token endpoint default, and then have the IdP use the issuer - identifier 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`. + `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. 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/authserver/server/tokenexchange/id_jag_handler.go b/pkg/authserver/server/tokenexchange/id_jag_handler.go index 37134b1d06..20087be15b 100644 --- a/pkg/authserver/server/tokenexchange/id_jag_handler.go +++ b/pkg/authserver/server/tokenexchange/id_jag_handler.go @@ -79,6 +79,15 @@ type IDJAGHandler struct { // 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 @@ -104,7 +113,7 @@ const ( 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) @@ -115,7 +124,21 @@ func newIDJAGIssuanceHandler( for _, id := range explicitGrantClientIDs { explicitGrantClients[id] = struct{}{} } - return &IDJAGHandler{core: core, explicitGrantClients: explicitGrantClients, issuer: config}, 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 — @@ -151,7 +174,7 @@ func (h *IDJAGHandler) HandleTokenEndpointRequest(ctx context.Context, requester if err != nil { return err } - claims, err := h.core.validator.ValidateJWTBearerAssertion(ctx, assertion, []string{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.")) } @@ -286,8 +309,12 @@ func (h *IDJAGHandler) logDraftDepartures( 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 != "" && !slices.Contains(claims.Audience, asIssuer) { + if asIssuer != "" && !h.issuerIsResource && !slices.Contains(claims.Audience, asIssuer) { found = append(found, departureAudienceNotIssuer) } if claim, present := claims.Extra["resource"]; present { @@ -322,10 +349,8 @@ func (h *IDJAGHandler) logDraftDepartures( // audienceHint tells the operator how to stop audience_not_issuer. func audienceHint(policy *JWTBearerGrantPolicy, asIssuer string) string { switch { - // Setting accepted_audiences removes the token endpoint default, so both must be listed. case len(policy.AcceptedAudiences) == 0: - return "add both the token endpoint URL and this server's issuer identifier to jwt_bearer_grant.accepted_audiences, " + - "then have the IdP use the issuer identifier as aud" + 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: @@ -333,6 +358,22 @@ func audienceHint(policy *JWTBearerGrantPolicy, asIssuer string) string { } } +// 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 { @@ -381,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 b31339d8ee..83678bdde2 100644 --- a/pkg/authserver/server/tokenexchange/id_jag_handler_test.go +++ b/pkg/authserver/server/tokenexchange/id_jag_handler_test.go @@ -12,6 +12,8 @@ import ( "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" @@ -81,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 @@ -335,6 +348,17 @@ 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() @@ -342,11 +366,11 @@ func TestIDJAGHandler_IssuesBoundSession(t *testing.T) { claims := validIDJAGClaims() consumer := &recordingAssertionConsumer{} validator := &testJWTBearerAssertionValidator{claims: claims} - h := newIDJAGTestHandler(t, validator, consumer) + h := newIDJAGTestHandlerWithIssuer(t, validator, consumer, idJAGTestASIssuer) req := newIDJAGRequest(t, tj, idJAGTestClientID) require.NoError(t, h.HandleTokenEndpointRequest(context.Background(), req)) - assert.Equal(t, []string{testTokenEndpoint}, validator.gotDefaults) + 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. @@ -446,10 +470,9 @@ func TestIDJAGHandler_MaxAgeIsCheckedBeforeResource(t *testing.T) { } const ( - idJAGTestASIssuer = "https://as.example.com" - idJAGTestOtherAud = "https://other.example.com" - hintNoAcceptedAud = "add both the token endpoint URL and this server's issuer identifier to jwt_bearer_grant.accepted_audiences, " + - "then have the IdP use the issuer identifier as aud" + 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" ) @@ -494,7 +517,7 @@ func newIDJAGDepartureHandler( &mockAccessTokenStrategy{}, &mockAccessTokenStorage{}, resolved, - nil, + nil, nil, nil, ) require.NoError(t, err) var buf strings.Builder @@ -953,3 +976,113 @@ func TestIDJAGHandler_ResourceDefaultsFromClaim(t *testing.T) { }) } } + +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 e1c200b65a..4dedee1e46 100644 --- a/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go +++ b/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go @@ -497,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) @@ -518,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) @@ -575,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_validator_test.go b/pkg/authserver/server/tokenexchange/jwt_bearer_validator_test.go index 59631e8763..b5133a5d78 100644 --- a/pkg/authserver/server/tokenexchange/jwt_bearer_validator_test.go +++ b/pkg/authserver/server/tokenexchange/jwt_bearer_validator_test.go @@ -334,23 +334,31 @@ func TestMultiIssuerTokenValidator_ValidateJWTBearerAssertion_DefaultAudiences(t selfJWKS := newTestJWKS(t) externalJWKS := newTestJWKS(t) jwksServer := startJWKSServer(t, externalJWKS) - validator := newMultiValidator(t, selfJWKS, []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{"https://mcp.example.com"}}, + 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" + 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 }{ @@ -362,7 +370,22 @@ func TestMultiIssuerTokenValidator_ValidateJWTBearerAssertion_DefaultAudiences(t name: "an audience outside the defaults is rejected", defaults: []string{testTokenEndpoint, secondDefault}, aud: jwt.Audience{"https://other.example.com"}, - wantErr: "assertion audience must include one of the accepted authorization server identities", + 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}, }, } @@ -373,7 +396,7 @@ func TestMultiIssuerTokenValidator_ValidateJWTBearerAssertion_DefaultAudiences(t claims.Audience = tt.aud raw := externalJWKS.signToken(t, claims, nil) - validated, err := validator.ValidateJWTBearerAssertion(context.Background(), raw, tt.defaults) + validated, err := newValidator(tt.accepted).ValidateJWTBearerAssertion(context.Background(), raw, tt.defaults) if tt.wantErr != "" { require.ErrorContains(t, err, tt.wantErr) return diff --git a/pkg/authserver/server/tokenexchange/multi_issuer_validator.go b/pkg/authserver/server/tokenexchange/multi_issuer_validator.go index 6a1d6faf3b..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 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