From f852ed3f167de768b0923546259f182206a4ecf5 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Sat, 21 Nov 2026 21:51:12 +0100 Subject: [PATCH] Require the issuer as the only client aud A private_key_jwt client assertion could carry the token endpoint URL as aud, or an array holding the issuer plus other values, because fosite only checks that one accepted value is among the aud values. RFC 10070 section 4 requires the issuer identifier as the sole aud value and forbids the token endpoint URL, so a client assertion made for one endpoint could be replayed at another. Accept only an aud that holds the issuer and nothing else, as a string or as a one-element array, which RFC 7519 and RFC 10070 both allow. Refuse everything else with 401 invalid_client, and log the refusal at WARN so operators can see why a client that worked before now fails. The check runs before fosite so it covers both the normal path and the clock skew recovery path, and it refuses an assertion that go-jose v4 cannot read, because fosite's go-jose v3 parser accepts encodings that v4 rejects. There is no setting. Closes #7039 Co-authored-by: Mecatl --- docs/arch/11-auth-server-storage.md | 2 +- docs/arch/17-token-exchange-delegation.md | 34 ++- pkg/authserver/integration_test.go | 14 +- .../server/client_assertion_errors_test.go | 9 +- .../server/client_assertion_store_e2e_test.go | 2 +- pkg/authserver/server/endpoints.go | 5 +- .../server/private_key_jwt_client_auth.go | 132 ++++++++-- .../private_key_jwt_client_auth_test.go | 243 ++++++++++++++++-- pkg/authserver/server/provider.go | 9 +- .../server/provider_spiffe_x509_test.go | 2 +- pkg/authserver/server_test.go | 2 +- .../virtualmcp_private_key_jwt_test.go | 4 +- 12 files changed, 378 insertions(+), 80 deletions(-) diff --git a/docs/arch/11-auth-server-storage.md b/docs/arch/11-auth-server-storage.md index 7aa52ead42..a1015799a2 100644 --- a/docs/arch/11-auth-server-storage.md +++ b/docs/arch/11-auth-server-storage.md @@ -972,7 +972,7 @@ is needed or offered. A client proves possession of its private key by sending a signed `client_assertion` at `/oauth/token`; ToolHive stores only the registered public -JWKS. The assertion's `aud` may be the issuer or the token endpoint URL; see +JWKS. The assertion's `aud` must hold the issuer and nothing else; see [Client-assertion audience](17-token-exchange-delegation.md#client-assertion-audience). The server accepts a clock difference of 60 seconds in the assertion's `exp`, `iat` and `nbf`, so an assertion from a client whose clock runs a little fast or diff --git a/docs/arch/17-token-exchange-delegation.md b/docs/arch/17-token-exchange-delegation.md index 7f441054a7..7c8cf72151 100644 --- a/docs/arch/17-token-exchange-delegation.md +++ b/docs/arch/17-token-exchange-delegation.md @@ -357,7 +357,7 @@ client_assertion= ``` The assertion identifies the registered `client_id` in `iss` and `sub`, targets -the token endpoint in `aud`, and includes a unique `jti` and an `exp`. The +the issuer in `aud`, and includes a unique `jti` and an `exp`. The server verifies it against the stored inline JWKS and rejects replay while the assertion is valid. No `client_secret` is included in registration or token exchange. @@ -438,14 +438,31 @@ public (`none`) client. ### Client-assertion audience -A `private_key_jwt` client assertion is accepted when its `aud` claim is either -of these, as a string or as an array containing either: +A `private_key_jwt` client assertion is accepted only when its `aud` claim holds +the issuer and nothing else. This follows RFC 10070 section 4, which requires +the issuer identifier as the sole value of `aud` and forbids the token endpoint +URL. The issuer may be sent as a JSON string or as a one-element array; RFC 7519 +section 4.1.3 allows both forms. -- the issuer -- the token endpoint URL (`{issuer}/oauth/token`) +The server refuses these with `401 invalid_client` and issues no token: + +- the token endpoint URL (`{issuer}/oauth/token`), as a string or inside an array +- an array with more than one value, even when one of them is the issuer +- a missing `aud`, an empty array, or any other value +- an assertion that go-jose v4 cannot read under strict base64url decoding, such + as one with base64 padding on a segment or a space or tab inside it, which + some JOSE parsers tolerate. The check must see `aud` as sent, so the server + does not leave such an assertion to a more lenient parser. + +The server logs each of these refusals at WARN with the cause and `client_id`, +because a client that worked with an earlier release can start failing here. + +A client that sends the token endpoint URL as `aud` must be updated to send the +issuer instead. The check has no setting; it always applies, including to an +assertion that is accepted only through the 60-second clock skew allowance. Assertions with the `client-authentication+jwt` JOSE `typ` header -(draft-ietf-oauth-rfc7523bis-11 section 4.1) are accepted. +(RFC 10070 section 4) are accepted. Accepting the issuer is safe because the assertion is still bound by `iss == sub == client_id` and a signature from the client's registered keys. @@ -453,11 +470,6 @@ The issuer is this server's unique identifier (RFC 8414 section 2), and `aud` is compared as an exact string. An assertion addressed to this issuer is therefore not accepted by another issuer, even one on the same host. -Two things do not meet draft-11 section 4(b), which requires the issuer as the -sole value of `aud`: accepting the token endpoint URL, and accepting an `aud` -array with more than one value that contains the issuer. Both are deprecated. A -later release will require the issuer as the sole value. - This applies to every `private_key_jwt` client. Inbound `private_key_jwt` clients come from Dynamic Client Registration and from configured delegate clients. The `aud` checks on diff --git a/pkg/authserver/integration_test.go b/pkg/authserver/integration_test.go index 272e6d0bc5..b0cee0a323 100644 --- a/pkg/authserver/integration_test.go +++ b/pkg/authserver/integration_test.go @@ -6824,7 +6824,7 @@ func TestIntegration_PrivateKeyJWTDCRTokenExchange(t *testing.T) { now := time.Now() subjectToken := ts.signSubjectToken("external-subject", now, now.Add(10*time.Minute), "subject-1") - assertion := makeAssertion(registered.ClientID, testIssuer+"/oauth/token", now.Add(2*time.Minute), "client-assertion-1") + assertion := makeAssertion(registered.ClientID, testIssuer, now.Add(2*time.Minute), "client-assertion-1") response, body := request(assertion, subjectToken) t.Cleanup(func() { response.Body.Close() }) require.Equal(t, http.StatusOK, response.StatusCode, body) @@ -6850,8 +6850,8 @@ func TestIntegration_PrivateKeyJWTDCRTokenExchange(t *testing.T) { assertion string }{ {name: "wrong_audience", assertion: makeAssertion(registered.ClientID, "https://wrong.example/token", now.Add(2*time.Minute), "client-assertion-wrong-aud")}, - {name: "wrong_subject", assertion: makeAssertion("different-client", testIssuer+"/oauth/token", now.Add(2*time.Minute), "client-assertion-wrong-sub")}, - {name: "expired", assertion: makeAssertion(registered.ClientID, testIssuer+"/oauth/token", now.Add(-time.Minute), "client-assertion-expired")}, + {name: "wrong_subject", assertion: makeAssertion("different-client", testIssuer, now.Add(2*time.Minute), "client-assertion-wrong-sub")}, + {name: "expired", assertion: makeAssertion(registered.ClientID, testIssuer, now.Add(-2*time.Minute), "client-assertion-expired")}, } { t.Run(negative.name, func(t *testing.T) { response, body := request(negative.assertion, subjectToken) @@ -6866,8 +6866,9 @@ func TestIntegration_PrivateKeyJWTDCRTokenExchange(t *testing.T) { // TestIntegration_PrivateKeyJWTClientAssertionAudience drives a DCR // private_key_jwt client through the token endpoint with different assertion -// audiences and JOSE types. The issuer and the token endpoint URL are accepted; -// any other audience is refused with invalid_client. +// audiences and JOSE types. Only the issuer, and nothing else, is accepted; +// the token endpoint URL, an array with another value and any other audience +// are refused with invalid_client. func TestIntegration_PrivateKeyJWTClientAssertionAudience(t *testing.T) { t.Parallel() @@ -6918,7 +6919,8 @@ func TestIntegration_PrivateKeyJWTClientAssertionAudience(t *testing.T) { wantOK bool }{ {name: "issuer", audience: jwt.Audience{testIssuer}, typ: "JWT", wantOK: true}, - {name: "token URL", audience: jwt.Audience{testIssuer + "/oauth/token"}, typ: "JWT", wantOK: true}, + {name: "token URL", audience: jwt.Audience{testIssuer + "/oauth/token"}, typ: "JWT"}, + {name: "issuer and another value in an array", audience: jwt.Audience{testIssuer, "https://other.example.com"}, typ: "JWT"}, {name: "unrelated audience", audience: jwt.Audience{"https://other.example.com"}, typ: "JWT"}, {name: "rfc7523bis typ header with issuer", audience: jwt.Audience{testIssuer}, typ: "client-authentication+jwt", wantOK: true}, } diff --git a/pkg/authserver/server/client_assertion_errors_test.go b/pkg/authserver/server/client_assertion_errors_test.go index bc268198c3..bc7ceec226 100644 --- a/pkg/authserver/server/client_assertion_errors_test.go +++ b/pkg/authserver/server/client_assertion_errors_test.go @@ -217,14 +217,15 @@ func TestClientAssertionErrorStrategy(t *testing.T) { } cfg := &fosite.Config{AccessTokenIssuer: assertionTestIssuer, TokenURL: assertionTestTokenURL} provider := fosite.NewOAuth2Provider(store, newClientAssertionAudienceConfig(cfg)) - strategy := newClientAssertionErrorStrategy(newClientAssertionClockSkewStrategy( - provider.DefaultClientAuthenticationStrategy, store, clientAssertionAudiences(cfg), - func() time.Time { return now }, true)) + strategy := newClientAssertionErrorStrategy(newClientAssertionAudienceStrategy( + newClientAssertionClockSkewStrategy(provider.DefaultClientAuthenticationStrategy, store, + func() time.Time { return now }, true), + cfg.AccessTokenIssuer)) claims := jwt.Claims{ Issuer: assertionTestClientID, Subject: assertionTestClientID, - Audience: jwt.Audience{assertionTestTokenURL}, + Audience: jwt.Audience{assertionTestIssuer}, ID: "jti-" + tt.name, IssuedAt: jwt.NewNumericDate(now), Expiry: jwt.NewNumericDate(now.Add(time.Minute)), diff --git a/pkg/authserver/server/client_assertion_store_e2e_test.go b/pkg/authserver/server/client_assertion_store_e2e_test.go index c8df18dc5e..4313d57170 100644 --- a/pkg/authserver/server/client_assertion_store_e2e_test.go +++ b/pkg/authserver/server/client_assertion_store_e2e_test.go @@ -89,7 +89,7 @@ func signE2EAssertion(t *testing.T, key *ecdsa.PrivateKey, jti string, exp any) (&josev4.SignerOptions{}).WithType("JWT").WithHeader(josev4.HeaderKey("kid"), e2eKeyID)) require.NoError(t, err) token, err := jwt.Signed(signer).Claims(map[string]any{ - "iss": e2eClientID, "sub": e2eClientID, "aud": e2eTokenURL, "jti": jti, "exp": exp, + "iss": e2eClientID, "sub": e2eClientID, "aud": e2eIssuer, "jti": jti, "exp": exp, }).Serialize() require.NoError(t, err) return token diff --git a/pkg/authserver/server/endpoints.go b/pkg/authserver/server/endpoints.go index 34581f90ab..d1405acc7d 100644 --- a/pkg/authserver/server/endpoints.go +++ b/pkg/authserver/server/endpoints.go @@ -4,6 +4,7 @@ package server // TokenEndpointPath is the path of the token endpoint, relative to the issuer. -// Discovery advertises the issuer joined with it, the router serves it, and -// client assertions may name that URL as their audience. +// Discovery advertises the issuer joined with it and the router serves it. +// Clients send client assertions to this URL but address them to the issuer: +// an assertion with this URL as its audience is refused. const TokenEndpointPath = "/oauth/token" //nolint:gosec // G101: URL path, not a credential diff --git a/pkg/authserver/server/private_key_jwt_client_auth.go b/pkg/authserver/server/private_key_jwt_client_auth.go index 99df3e6b3f..e8dd926c53 100644 --- a/pkg/authserver/server/private_key_jwt_client_auth.go +++ b/pkg/authserver/server/private_key_jwt_client_auth.go @@ -5,12 +5,11 @@ package server import ( "context" + "encoding/json" "errors" "log/slog" "net/http" "net/url" - "slices" - "strings" "time" "github.com/go-jose/go-jose/v4" @@ -43,21 +42,18 @@ func (c clientAssertionAudienceConfig) GetTokenURLs(context.Context) []string { return c.tokenURLs } -// newClientAssertionAudienceConfig wraps config so that client assertions may -// carry either the issuer or the token endpoint URL as audience. +// newClientAssertionAudienceConfig wraps config so that fosite accepts the +// issuer, and nothing else, as the audience of a client assertion. fosite does +// not accept the issuer on its own, so it is handed over as a token URL. RFC +// 10070 section 4 requires the issuer identifier as the sole aud value and +// forbids the token endpoint URL. func newClientAssertionAudienceConfig(config *fosite.Config) clientAssertionAudienceConfig { return clientAssertionAudienceConfig{ Config: config, - tokenURLs: clientAssertionAudiences(config), + tokenURLs: []string{config.AccessTokenIssuer}, } } -// clientAssertionAudiences returns the values accepted as the audience of a -// client assertion: the issuer and the token endpoint URL. -func clientAssertionAudiences(config *fosite.Config) []string { - return []string{config.AccessTokenIssuer, config.TokenURL} -} - // clientAssertionStore is the part of fosite.Storage that the clock skew // fallback uses to finish what fosite's strategy would have done. The store // must be the clientAssertionExpiryStore, so that the marker it records gets the @@ -68,11 +64,51 @@ type clientAssertionStore interface { SetClientAssertionJWT(ctx context.Context, jti string, exp time.Time) error } +// newClientAssertionAudienceStrategy refuses a private_key_jwt client +// assertion whose aud is not issuer and nothing else, before next runs. The +// issuer may be sent as a string or as a one-element array, which RFC 7519 +// section 4.1.3 and RFC 10070 both allow. fosite only checks that aud contains +// an accepted value, so without this an array such as [issuer, "other"] would +// pass. The refusal comes before any client lookup, so such an assertion costs +// no lookup and does not use up its jti. +// +// It applies to every strategy below it, fosite's own or one the caller +// supplied, the same way the JWS guard does. The clock skew recovery does not +// check aud itself and relies on this strategy sitting above it. +// +// An assertion that go-jose v4 cannot read is refused as well, instead of being +// left to next. fosite parses with go-jose v3, which strips spaces and tabs and +// trims base64 padding where v4 does not, so a token v4 rejects can still be +// read and verified by fosite, with an aud array this check never saw. +// Conforming clients send the canonical compact form and are not affected. The +// claims are read without verifying the signature, which is safe because the +// result can only refuse. The JWS guard above this strategy has already +// screened the assertion. +// +// A refusal is logged at WARN on purpose: it is a request shape that older +// releases accepted, and operators need to see why such a client now fails. +func newClientAssertionAudienceStrategy( + next fosite.ClientAuthenticationStrategy, + issuer string, +) fosite.ClientAuthenticationStrategy { + return func(ctx context.Context, r *http.Request, form url.Values) (fosite.Client, error) { + if !isPrivateKeyJWTRequest(form) { + return next(ctx, r, form) + } + if reason, err := checkClientAssertionAudience(form.Get("client_assertion"), issuer); err != nil { + slog.Warn("refused client assertion", "reason", reason, "client_id", form.Get("client_id")) + return nil, err + } + return next(ctx, r, form) + } +} + // newClientAssertionClockSkewStrategy lets a private_key_jwt client assertion // whose exp, iat or nbf is within clientAssertionClockSkew of now authenticate. // fosite offers no leeway setting, and its jwt.TimeFunc is a process-wide // variable, so fosite stays the validator and this wrapper only recovers from -// its time errors. audiences are the values accepted in aud. +// its time errors. It must sit below newClientAssertionAudienceStrategy, which +// checks aud for the recovery. // // recoverTimeErrors turns the recovery on. Only fosite's own strategy may have // it, because the recovery relies on fosite verifying the signature before it @@ -92,7 +128,6 @@ type clientAssertionStore interface { func newClientAssertionClockSkewStrategy( next fosite.ClientAuthenticationStrategy, store clientAssertionStore, - audiences []string, now func() time.Time, recoverTimeErrors bool, ) fosite.ClientAuthenticationStrategy { @@ -116,7 +151,7 @@ func newClientAssertionClockSkewStrategy( // so the claims can be read without verifying them again. Tests pin // this order, because a different order in a later fosite release // would make these claims untrusted. - return recoverSkewedClientAssertion(ctx, store, audiences, form, assertion, now, err) + return recoverSkewedClientAssertion(ctx, store, form, assertion, now, err) } } @@ -126,11 +161,12 @@ func newClientAssertionClockSkewStrategy( // returned unchanged. A GetClient error is refused as invalid_client. A storage // failure while checking the jti is refused as invalid_client here, and becomes // server_error in newClientAssertionErrorStrategy, which reads the failure the -// backend recorded. +// backend recorded. aud is not checked here: newClientAssertionAudienceStrategy, +// which sits above the clock skew strategy, has already required it to be the +// issuer. func recoverSkewedClientAssertion( ctx context.Context, store clientAssertionStore, - audiences []string, form url.Values, assertion string, now func() time.Time, @@ -152,7 +188,7 @@ func recoverSkewedClientAssertion( if reason, refusalErr := checkClientAssertionTimes(claims, now(), fositeErr); reason != "" { return refuse(reason, refusalErr) } - if reason, refusalErr := checkClientAssertionIdentity(claims, clientID, audiences); reason != "" { + if reason, refusalErr := checkClientAssertionIdentity(claims, clientID); reason != "" { return refuse(reason, refusalErr) } @@ -223,10 +259,11 @@ func errClientAssertionUnreadable() error { return fosite.ErrInvalidClient.WithHint("The 'client_assertion' claims could not be read.") } -// checkClientAssertionIdentity checks iss, sub, jti and aud against what fosite -// requires. It returns a refusal reason and error, or an empty reason when the -// claims are fine. -func checkClientAssertionIdentity(claims jwt.Claims, clientID string, audiences []string) (string, error) { +// checkClientAssertionIdentity checks iss, sub and jti against what fosite +// requires. aud is checked before fosite runs, by checkClientAssertionAudience. +// It returns a refusal reason and error, or an empty reason when the claims are +// fine. +func checkClientAssertionIdentity(claims jwt.Claims, clientID string) (string, error) { if clientID == "" || claims.Issuer != clientID { return "iss does not match the client", fosite.ErrInvalidClient.WithHint( "Claim 'iss' from 'client_assertion' must match the 'client_id' of the OAuth 2.0 Client.") @@ -239,19 +276,58 @@ func checkClientAssertionIdentity(claims jwt.Claims, clientID string, audiences return "jti missing", fosite.ErrInvalidClient.WithHint( "Claim 'jti' from 'client_assertion' must be set but is not.") } - if !slices.ContainsFunc(claims.Audience, func(aud string) bool { - return aud != "" && slices.Contains(audiences, aud) - }) { - return "audience not accepted", fosite.ErrInvalidClient.WithHintf( - "Claim 'audience' from 'client_assertion' must match the authorization server's token endpoint '%s'.", - strings.Join(slices.DeleteFunc(slices.Clone(audiences), func(a string) bool { return a == "" }), "' or '")) + return "", nil +} + +// errClientAssertionAudience is the refusal for an aud that is not the issuer +// and nothing else. +func errClientAssertionAudience(issuer string) error { + return fosite.ErrInvalidClient.WithHintf( + "Claim 'audience' from 'client_assertion' must hold only the authorization server's issuer '%s'.", issuer) +} + +// checkClientAssertionAudience refuses an assertion that cannot be read, or +// whose aud is not issuer and nothing else. aud may be the issuer as a string +// or as a one-element array. The raw claim is read, so that a missing, null or +// non-string aud is refused rather than read as empty. It returns a refusal +// reason and error, or an empty reason when the aud is fine. The signature is +// not verified, so the result may only refuse. +func checkClientAssertionAudience(assertion, issuer string) (string, error) { + token, err := jwt.ParseSigned(assertion, clientAssertionSigningAlgorithms) + if err != nil { + return "claims unreadable", errClientAssertionUnreadable() + } + var claims struct { + Audience json.RawMessage `json:"aud"` + } + if token.UnsafeClaimsWithoutVerification(&claims) != nil { + return "claims unreadable", errClientAssertionUnreadable() + } + aud, ok := soleAudience(claims.Audience) + if !ok || aud == "" || aud != issuer { + return "audience is not the issuer alone", errClientAssertionAudience(issuer) } return "", nil } +// soleAudience returns the only value of a raw aud claim, which may be a +// string or an array of strings. ok is false when aud is missing, is not a +// string or an array of strings, or does not hold exactly one value. +func soleAudience(raw json.RawMessage) (aud string, ok bool) { + if json.Unmarshal(raw, &aud) == nil { + return aud, true + } + var auds []string + if json.Unmarshal(raw, &auds) != nil || len(auds) != 1 { + return "", false + } + return auds[0], true +} + // parseVerifiedClientAssertionClaims reads the claims of an assertion without // verifying the signature. Callers only pass assertions that fosite has -// already verified. +// already verified. A check on claims that were not verified, which may only +// refuse, belongs in checkClientAssertionAudience instead. func parseVerifiedClientAssertionClaims(assertion string) (jwt.Claims, bool) { var claims jwt.Claims parsed, err := jwt.ParseSigned(assertion, clientAssertionSigningAlgorithms) diff --git a/pkg/authserver/server/private_key_jwt_client_auth_test.go b/pkg/authserver/server/private_key_jwt_client_auth_test.go index ad667c3ade..0ffb24d2a6 100644 --- a/pkg/authserver/server/private_key_jwt_client_auth_test.go +++ b/pkg/authserver/server/private_key_jwt_client_auth_test.go @@ -9,6 +9,7 @@ import ( "crypto/elliptic" "crypto/rand" "crypto/rsa" + "encoding/base64" "errors" "fmt" "net/http" @@ -19,6 +20,7 @@ import ( "time" josev3 "github.com/go-jose/go-jose/v3" + josev4 "github.com/go-jose/go-jose/v4" "github.com/go-jose/go-jose/v4/jwt" "github.com/ory/fosite" "github.com/stretchr/testify/assert" @@ -74,8 +76,9 @@ func newAssertionHarness(t *testing.T, mutateClient func(*fosite.DefaultOpenIDCo now := func() time.Time { return h.now } wrapped := newClientAssertionExpiryStore(store, now) provider := fosite.NewOAuth2Provider(wrapped, newClientAssertionAudienceConfig(cfg)) - h.strategy = newClientAssertionErrorStrategy(newClientAssertionClockSkewStrategy( - provider.DefaultClientAuthenticationStrategy, wrapped, clientAssertionAudiences(cfg), now, true)) + h.strategy = newClientAssertionErrorStrategy(newClientAssertionAudienceStrategy( + newClientAssertionClockSkewStrategy(provider.DefaultClientAuthenticationStrategy, wrapped, now, true), + cfg.AccessTokenIssuer)) return h } @@ -83,7 +86,7 @@ func (h *assertionHarness) claims(jti string) jwt.Claims { return jwt.Claims{ Issuer: assertionTestClientID, Subject: assertionTestClientID, - Audience: jwt.Audience{assertionTestTokenURL}, + Audience: jwt.Audience{assertionTestIssuer}, ID: jti, IssuedAt: jwt.NewNumericDate(h.now), Expiry: jwt.NewNumericDate(h.now.Add(time.Minute)), @@ -282,22 +285,6 @@ func TestClientAssertionClockSkew(t *testing.T) { }, wantOK: true, }, - { - name: "skewed assertion with the issuer as audience", - mutate: func(h *assertionHarness, c *jwt.Claims) { - h.skewIAT(c) - c.Audience = jwt.Audience{"https://other.example.com", assertionTestIssuer} - }, - wantOK: true, - }, - { - name: "skewed assertion with another audience", - mutate: func(h *assertionHarness, c *jwt.Claims) { - h.skewIAT(c) - c.Audience = jwt.Audience{"https://elsewhere.example.com"} - }, - wantHint: "Claim 'audience'", - }, { name: "skewed assertion with another issuer", mutate: func(h *assertionHarness, c *jwt.Claims) { @@ -360,6 +347,222 @@ func TestClientAssertionClockSkew(t *testing.T) { } } +// signRawAssertion signs a payload built from a map, so that aud can be a +// string, an array or absent, which jwt.Claims cannot express. +func (h *assertionHarness) signRawAssertion(t *testing.T, jti string, skewed bool, aud any, withAud bool) string { + t.Helper() + iat := h.now + if skewed { + iat = h.now.Add(30 * time.Second) + } + payload := map[string]any{ + "iss": assertionTestClientID, "sub": assertionTestClientID, "jti": jti, + "iat": iat.Unix(), "exp": h.now.Add(time.Minute).Unix(), + } + if withAud { + payload["aud"] = aud + } + signer, err := josev4.NewSigner( + josev4.SigningKey{Algorithm: josev4.ES256, Key: h.key}, + (&josev4.SignerOptions{}).WithType("JWT").WithHeader(josev4.HeaderKey("kid"), assertionTestKeyID)) + require.NoError(t, err) + token, err := jwt.Signed(signer).Claims(payload).Serialize() + require.NoError(t, err) + return token +} + +func TestClientAssertionAudience(t *testing.T) { + t.Parallel() + + const audienceHint = "must hold only the authorization server's issuer '" + assertionTestIssuer + "'" + + tests := []struct { + name string + aud any + withAud bool + wantOK bool + }{ + {name: "the issuer as a string", aud: assertionTestIssuer, withAud: true, wantOK: true}, + {name: "the issuer in a one-element array", aud: []string{assertionTestIssuer}, withAud: true, wantOK: true}, + {name: "the token endpoint URL as a string", aud: assertionTestTokenURL, withAud: true}, + {name: "another string", aud: "https://elsewhere.example.com", withAud: true}, + {name: "an empty string", aud: "", withAud: true}, + {name: "a number", aud: 42, withAud: true}, + {name: "an array holding a number", aud: []any{42}, withAud: true}, + {name: "the issuer and another value in an array", aud: []string{assertionTestIssuer, "x"}, withAud: true}, + {name: "the token endpoint URL in an array", aud: []string{assertionTestTokenURL}, withAud: true}, + {name: "the issuer and the token endpoint URL in an array", aud: []string{assertionTestIssuer, assertionTestTokenURL}, withAud: true}, + {name: "an empty array", aud: []string{}, withAud: true}, + {name: "a null aud", aud: nil, withAud: true}, + {name: "a missing aud"}, + } + paths := []struct { + name string + skewed bool + }{ + {name: "on fosite's path"}, + {name: "through the clock skew recovery", skewed: true}, + } + + for _, path := range paths { + for _, tt := range tests { + t.Run(path.name+" "+tt.name, func(t *testing.T) { + t.Parallel() + h := newAssertionHarness(t, nil) + assertion := h.signRawAssertion(t, "jti-aud", path.skewed, tt.aud, tt.withAud) + + client, err := h.authenticateAssertion(t, assertion, nil) + if tt.wantOK { + require.NoError(t, err) + assert.Equal(t, assertionTestClientID, client.GetID()) + return + } + require.Error(t, err) + assert.Nil(t, client) + assert.Contains(t, requireInvalidClient(t, err).HintField, audienceHint) + assert.Zero(t, h.store.validCalls, "a refused assertion must not burn a reservation") + assert.Empty(t, h.store.seen) + }) + } + } + + t.Run("an assertion that cannot be read is refused", func(t *testing.T) { + t.Parallel() + h := newAssertionHarness(t, nil) + + _, err := h.authenticateAssertion(t, "not-a-jwt", nil) + + require.Error(t, err) + assert.Contains(t, requireInvalidClient(t, err).HintField, "could not be read") + }) +} + +// TestClientAssertionAudience_UnreadableEncodings pins that an assertion +// go-jose v4 cannot read is refused, even when fosite's go-jose v3 reads and +// verifies it. v3 strips spaces and tabs and trims base64 padding where v4 does not, +// so deferring such a token to fosite would let an aud array through. +func TestClientAssertionAudience_UnreadableEncodings(t *testing.T) { + t.Parallel() + + withPadding := func(token string) string { + parts := strings.Split(token, ".") + parts[1] += "=" + return strings.Join(parts, ".") + } + withSpace := func(token string) string { + parts := strings.Split(token, ".") + parts[1] = parts[1][:10] + " " + parts[1][10:] + return strings.Join(parts, ".") + } + withTab := func(token string) string { + parts := strings.Split(token, ".") + parts[2] = "\t" + parts[2] + return strings.Join(parts, ".") + } + + tests := []struct { + name string + aud any + rewrite func(string) string + }{ + {name: "array with a padded segment", aud: []string{assertionTestIssuer, "x"}, rewrite: withPadding}, + {name: "array with an embedded space", aud: []string{assertionTestIssuer, "x"}, rewrite: withSpace}, + {name: "one-element array with a padded segment", aud: []string{assertionTestIssuer}, rewrite: withPadding}, + {name: "one-element array with a tab", aud: []string{assertionTestIssuer}, rewrite: withTab}, + {name: "the issuer string with a padded segment", aud: assertionTestIssuer, rewrite: withPadding}, + } + for _, skewed := range []bool{false, true} { + for _, tt := range tests { + t.Run(fmt.Sprintf("skewed=%t %s", skewed, tt.name), func(t *testing.T) { + t.Parallel() + h := newAssertionHarness(t, nil) + assertion := tt.rewrite(h.signRawAssertion(t, "jti-enc", skewed, tt.aud, true)) + + client, err := h.authenticateAssertion(t, assertion, nil) + + require.Error(t, err) + assert.Nil(t, client) + assert.Contains(t, requireInvalidClient(t, err).HintField, "could not be read") + assert.Empty(t, h.store.seen) + }) + } + } +} + +// TestClientAssertionAudienceStrategy pins that the audience strategy refuses +// before any strategy below it runs, including one the caller supplied, and +// that it lets every other kind of request through untouched. The signature is +// never checked here, so the assertions are not signed. +func TestClientAssertionAudienceStrategy(t *testing.T) { + t.Parallel() + + enc := base64.RawURLEncoding + unsigned := func(payload string) string { + return enc.EncodeToString([]byte(`{"alg":"ES256"}`)) + "." + + enc.EncodeToString([]byte(payload)) + "." + enc.EncodeToString([]byte("sig")) + } + assertionForm := func(assertion string) url.Values { + return url.Values{ + "client_id": {assertionTestClientID}, + "client_assertion_type": {privateKeyJWTAssertionType}, + "client_assertion": {assertion}, + } + } + + tests := []struct { + name string + form url.Values + wantNext bool + wantHint string + }{ + { + name: "the issuer as aud reaches the next strategy", + form: assertionForm(unsigned(`{"aud":"` + assertionTestIssuer + `"}`)), + wantNext: true, + }, + { + name: "the token endpoint URL as aud never reaches the next strategy", + form: assertionForm(unsigned(`{"aud":"` + assertionTestTokenURL + `"}`)), + wantHint: "must hold only the authorization server's issuer", + }, + { + name: "a payload that is not a JSON object is refused as unreadable", + form: assertionForm(unsigned(`not json`)), + wantHint: "could not be read", + }, + { + name: "a request without a client assertion passes through", + form: url.Values{"client_id": {assertionTestClientID}, "client_secret": {"s"}}, + wantNext: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + var nextCalls int + want := &fosite.DefaultClient{ID: assertionTestClientID} + strategy := newClientAssertionAudienceStrategy( + func(context.Context, *http.Request, url.Values) (fosite.Client, error) { + nextCalls++ + return want, nil + }, assertionTestIssuer) + + client, err := strategy(context.Background(), httptest.NewRequest(http.MethodPost, "/oauth/token", nil), tt.form) + + if tt.wantNext { + require.NoError(t, err) + assert.Same(t, want, client) + assert.Equal(t, 1, nextCalls) + return + } + require.Error(t, err) + assert.Nil(t, client) + assert.Contains(t, requireInvalidClient(t, err).HintField, tt.wantHint) + assert.Zero(t, nextCalls) + }) + } +} + func TestClientAssertionClockSkew_FallbackRefusals(t *testing.T) { t.Parallel() @@ -489,7 +692,7 @@ func TestRecoverSkewedClientAssertion_UnreadableClaims(t *testing.T) { form := url.Values{"client_id": {assertionTestClientID}} client, err := recoverSkewedClientAssertion( - context.Background(), store, []string{assertionTestTokenURL}, form, "not-a-jwt", time.Now, fositeErr) + context.Background(), store, form, "not-a-jwt", time.Now, fositeErr) require.Error(t, err) assert.Nil(t, client) diff --git a/pkg/authserver/server/provider.go b/pkg/authserver/server/provider.go index 12aae7ff09..b9d44193da 100644 --- a/pkg/authserver/server/provider.go +++ b/pkg/authserver/server/provider.go @@ -750,11 +750,14 @@ func NewAuthorizationServer( recoverTimeErrors = true } // The JWS guard is outermost so it runs before any strategy parses - // a client assertion (see fositejose.IsUnsafeJWS). + // a client assertion (see fositejose.IsUnsafeJWS). The audience strategy + // applies to the caller-supplied strategy too, like the JWS guard, and must + // stay above the clock skew strategy, whose recovery does not check aud. fositeConfig.ClientAuthenticationStrategy = newUnsafeJWSGuardClientAuthenticationStrategy( newSPIFFEClientAuthenticationStrategy( - newClientAssertionErrorStrategy(newClientAssertionClockSkewStrategy( - defaultStrategy, assertionStore, clientAssertionAudiences(&fositeConfig), time.Now, recoverTimeErrors, + newClientAssertionErrorStrategy(newClientAssertionAudienceStrategy( + newClientAssertionClockSkewStrategy(defaultStrategy, assertionStore, time.Now, recoverTimeErrors), + fositeConfig.AccessTokenIssuer, )), config.GetAccessTokenIssuer(), config.SPIFFEJWTBundleSource, config.SPIFFEX509BundleSource, providerConfig.SPIFFEClientResolver, providerConfig.SPIFFEX509ClientMatcher, diff --git a/pkg/authserver/server/provider_spiffe_x509_test.go b/pkg/authserver/server/provider_spiffe_x509_test.go index c5daab5332..0a6919936a 100644 --- a/pkg/authserver/server/provider_spiffe_x509_test.go +++ b/pkg/authserver/server/provider_spiffe_x509_test.go @@ -188,7 +188,7 @@ func TestStaticSPIFFEClientCannotAuthenticateByDefaultStrategy(t *testing.T) { require.NoError(t, err) now := time.Now() assertion, err := jwt.Signed(signer).Claims(jwt.Claims{ - Issuer: "spiffe-client", Subject: "spiffe-client", Audience: jwt.Audience{testIssuer + "/oauth/token"}, + Issuer: "spiffe-client", Subject: "spiffe-client", Audience: jwt.Audience{testIssuer}, ID: "assertion-jti", IssuedAt: jwt.NewNumericDate(now), Expiry: jwt.NewNumericDate(now.Add(time.Minute)), }).Serialize() require.NoError(t, err) diff --git a/pkg/authserver/server_test.go b/pkg/authserver/server_test.go index 35d25ffdca..0af66a6a4d 100644 --- a/pkg/authserver/server_test.go +++ b/pkg/authserver/server_test.go @@ -631,7 +631,7 @@ func TestServer_TokenEndpoint_CIMDFetchesAreRateLimited(t *testing.T) { unsignedAssertion := func(sub string) string { enc := base64.RawURLEncoding header := enc.EncodeToString([]byte(`{"alg":"RS256","typ":"JWT"}`)) - claims, err := json.Marshal(map[string]any{"iss": sub, "sub": sub, "jti": "j", "exp": time.Now().Add(time.Hour).Unix()}) + claims, err := json.Marshal(map[string]any{"iss": sub, "sub": sub, "aud": "https://example.com", "jti": "j", "exp": time.Now().Add(time.Hour).Unix()}) require.NoError(t, err) return header + "." + enc.EncodeToString(claims) + "." + enc.EncodeToString([]byte("sig")) } diff --git a/test/e2e/thv-operator/virtualmcp/virtualmcp_private_key_jwt_test.go b/test/e2e/thv-operator/virtualmcp/virtualmcp_private_key_jwt_test.go index 7fcae53048..d829bc1d95 100644 --- a/test/e2e/thv-operator/virtualmcp/virtualmcp_private_key_jwt_test.go +++ b/test/e2e/thv-operator/virtualmcp/virtualmcp_private_key_jwt_test.go @@ -158,7 +158,7 @@ var _ = ginkgo.Describe("VirtualMCPServer private_key_jwt DCR delegation", ginkg registered := registerPrivateKeyJWTClient(endpoint, clientKey) subjectToken := mintExternalSubjectTokenWithExtraClaim(oidcLocalPort, externalSub, issuer, "azp", "external-agent") - assertion := signPrivateKeyJWTAssertion(clientKey, registered.ClientID, issuer+"/oauth/token", "private-key-jwt-assertion-1") + assertion := signPrivateKeyJWTAssertion(clientKey, registered.ClientID, issuer, "private-key-jwt-assertion-1") status, body := requestPrivateKeyJWTExchange(endpoint, registered.ClientID, assertion, subjectToken, issuer) gomega.Expect(status).To(gomega.Equal(http.StatusOK), string(body)) var token struct { @@ -171,7 +171,7 @@ var _ = ginkgo.Describe("VirtualMCPServer private_key_jwt DCR delegation", ginkg gomega.Expect(ok).To(gomega.BeTrue()) gomega.Expect(act["sub"]).To(gomega.Equal(registered.ClientID)) - wrongKeyAssertion := signPrivateKeyJWTAssertion(serverKey, registered.ClientID, issuer+"/oauth/token", "private-key-jwt-wrong-key") + wrongKeyAssertion := signPrivateKeyJWTAssertion(serverKey, registered.ClientID, issuer, "private-key-jwt-wrong-key") status, body = requestPrivateKeyJWTExchange(endpoint, registered.ClientID, wrongKeyAssertion, subjectToken, issuer) gomega.Expect(status).To(gomega.Equal(http.StatusUnauthorized), string(body))