diff --git a/docs/arch/17-token-exchange-delegation.md b/docs/arch/17-token-exchange-delegation.md index 7f441054a7..00beb81b92 100644 --- a/docs/arch/17-token-exchange-delegation.md +++ b/docs/arch/17-token-exchange-delegation.md @@ -774,8 +774,13 @@ in addition to other grants can log users in. operator adds an audience, an existing DCR client that asks for it gets `invalid_target` at `/authorize`, before the upstream login. The client has to register again to use the new audience. -- **ID-JAG redemption.** The `resource` of an ID-JAG gets the same client - check, except for DCR and CIMD clients, which are not narrowed. They hold a +- **ID-JAG redemption.** Only a client that authenticates gets this far: a + public client, which includes every CIMD client and a DCR client registered + with `token_endpoint_auth_method: none`, is refused with `invalid_client` + before the audience check (see + [Bound ID-JAG assertions](#bound-id-jag-assertions)). The `resource` of an ID-JAG + gets the same client check, except for DCR clients, which are not narrowed. + They hold a copy of the server's allowed audiences taken at registration, not a per-client policy, so checking them adds nothing while the copy is current and would wrongly refuse an audience added since. The resource must still be @@ -900,7 +905,9 @@ the client type: [SPIFFE Association Declarations](18-spiffe-association-declarations.md) for the full rule). - **DCR and CIMD clients.** A copy of the server's list taken at registration. - ID-JAG redemption does not narrow them, so only the server list applies. + ID-JAG redemption does not narrow a confidential DCR client, so only the + server list applies. Public clients, including every CIMD client, cannot + redeem an ID-JAG at all. - **Device flow.** The client receives all of its `audiences`. On token exchange, every audience the client receives must also appear, exactly, @@ -1327,8 +1334,8 @@ spec: ``` - **Clientless.** `JWTBearerHandler.CanSkipClientAuth` permits a - credential-free plain assertion. Form-supplied client credentials prevent - this clientless path. Every storage backend's request-marshaling path still + credential-free plain assertion. Client credentials in the form or in HTTP + Basic prevent this clientless path. Every storage backend's request-marshaling path still needs a non-nil `fosite.Client`, so the handler attaches a synthetic one — see "Synthetic subject and client identity" below. - **Assertion bounds.** Beyond the standard RFC 7523 §3 claims (`iss`, `sub`, @@ -1359,6 +1366,13 @@ spec: must be one of that binding's `allowed_resources`. There is no wildcard subject or resource — every accepted assertion subject and resource pair is named explicitly. +- **No `cnf`.** An assertion that carries a `cnf` claim (RFC 7800) is refused + with `invalid_grant`, whatever the value: the claim means the issuer expects + proof of possession of a key, and redeeming the assertion as a bearer token + would silently drop that. Only the presence of the claim counts, so + `"cnf": null` and `"cnf": {}` are refused too. The check runs before the + assertion is consumed. It stays until proof of possession (DPoP or mTLS) is + verified. The grant still does not require client authentication. - **Synthetic subject and client identity.** The issued token's `sub` is `#` (`session.New`'s first argument, matching the delegated-token subject qualification pattern in [Accepted @@ -1428,7 +1442,8 @@ spec: Both assertion forms refuse with an `error_description` that starts with a reason code, so a client can act on the refusal without parsing prose. This holds for every refusal that carries a reason; the plain grant's two -`subject_bindings` refusals do not (see the table). The description matches +`subject_bindings` refusals and fosite's own client-authentication errors do +not (see the table). The description matches `^[a-z_]+(: .*)?$`: the reason, optionally followed by `: ` and a fixed hint. The hint is printable ASCII without `"` or `\` and never contains a claim value (`sub`, `jti`, `client_id`, issuer). The handlers build the error as a literal (`redemptionRefusal`) because fosite's `WithHint` puts @@ -1438,8 +1453,11 @@ its own default text before the reason. | --- | --- | --- | | Not a compact signed JWT, bad `typ` or algorithm (an assertion with such a `typ` is routed to the plain handler, never the ID-JAG one) | 400 `invalid_grant`, `invalid_assertion: ` | n/a | | Signature or claim validation fails, issuer not enabled, assertion whose issued lifetime (`exp` − `iat`) exceeds `max_assertion_age`, replayed or expired | 400 `invalid_grant`, `invalid_assertion: ` | same code and reason; the hint names an ID-JAG for the first two | +| Redeeming client is public, or the request names no client at all (no `client_id`, `client_secret`, `client_assertion` or `client_assertion_type` form field, and no HTTP Basic credentials) | n/a (the plain grant does not require client authentication) | 401 `invalid_client`, `client_authentication_required: The ID-JAG grant requires client authentication.` The status is 401 whatever the request sent, the same as fosite's own `invalid_client`. The check runs before the assertion is validated or consumed (only its unverified `typ` header is read, to route the request), so the response says nothing about the assertion and the ID-JAG is not consumed | +| Client credentials sent, but fosite cannot authenticate them (wrong secret, unknown client, a confidential client that sends only `client_id`, or a `client_secret` without a `client_id`) | fosite's error, before the handler runs: usually 401 `invalid_client`, or 400 `invalid_request` for missing or malformed credentials; fosite's text, no reason | same | | ID-JAG without a `jti` or `client_id`, or issued to another client | n/a | 400 `invalid_grant`, `invalid_assertion: ` | | ID-JAG whose `aud` is an array with more than one value, for any issuer | n/a | 400 `invalid_grant`, `invalid_assertion: ` | +| Assertion that carries a `cnf` claim, with any value including `null`, for any issuer | 400 `invalid_grant`, `invalid_assertion: The JWT bearer assertion must not carry a 'cnf' claim.` | 400 `invalid_grant`, `invalid_assertion: The ID-JAG assertion must not carry a 'cnf' claim.` Both checks run before the assertion is consumed | | Subject not listed in `subject_bindings` | 400 `invalid_grant`, fosite text, no reason | 400 `access_denied`, `subject_unknown` | | Subject listed, resource not in its `allowed_resources` | 400 `invalid_target`, no description | 400 `access_denied`, `resource_denied` | | A malformed `resource` claim | n/a | 400 `invalid_grant`, `invalid_assertion: The ID-JAG assertion resource claim is malformed.` | @@ -1505,15 +1523,24 @@ configuration surface). Where the two differ is the trust model — the ID-JAG handler is **bound**: -- **Client authentication is never skipped.** An ID-JAG carries a `client_id` +- **The client must authenticate.** An ID-JAG carries a `client_id` claim naming the OAuth client that may redeem it (draft §4.4.1; the IdP - mints it from its administrator-configured resource connection). The - handler's `CanSkipClientAuth` is unconditionally false, so fosite resolves - the caller before the handler runs — full authentication for a confidential - client, `client_id` identification for a public one — and the handler - rejects the grant unless the resolved client is the one the assertion names. - A public client suffices here because the assertion itself is the primary - credential: single-use, short-lived, and audience-pinned to this AS. The + mints it from its administrator-configured resource connection). fosite + authenticates a confidential client before the handler runs. A public client + it only identifies by `client_id`, and a request with no credentials gets a + placeholder client with an empty ID. Before it validates the assertion, the + handler refuses both with `invalid_client`, because draft §4.4 requires + client authentication or a sender-constrained ID-JAG, and this server + cannot yet verify a sender-constrained one (proof of possession, DPoP or + mTLS). A `client_id` is not a credential, and an assertion that is + single-use, short-lived and audience-pinned to this AS only decides who + redeems a leaked copy first. For a request with no client credentials at + all, `CanSkipClientAuth` returns true so that the handler returns this + refusal instead of fosite's `invalid_request`. A request with any + credentials is authenticated by fosite first, and a failure is fosite's own + error with no reason code (see the table). After the check, the handler + rejects the grant unless the authenticated client is the one the assertion + names. A CIMD or public DCR client therefore cannot redeem an ID-JAG. The client's registered `grant_types` metadata is deliberately not consulted — with open DCR, self-asserted metadata authorizes nothing. The exception is an operator-configured client that sets `grant_types` explicitly: those grants @@ -1585,18 +1612,13 @@ subject, `jti` or claim values. The findings are: 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 logged finding. +**ID-JAGs that carry `cnf` are refused.** 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`. This server cannot check it yet, so the +handler refuses every ID-JAG that has a `cnf` claim, for every issuer. Only the +presence of the claim counts: `"cnf": null` and `"cnf": {}` are refused too, and +the value is never read. The refusal stays until proof of possession (DPoP or +mTLS) is verified. **Keeping AS-2 ID-JAG-only.** Trusting AS-1 as a JWT-bearer issuer at AS-2 also lets AS-2's plain handler (`typ` `JWT`, empty or absent) accept AS-1's @@ -2287,7 +2309,7 @@ inbound_grants: id_jag: targets: - issuer: https://as2.example.com # AS-2: the request's `audience`, the ID-JAG's `aud` - client_id: broker-at-as2 # the broker's client_id registered at AS-2 + client_id: broker-at-as2 # the broker's confidential client at AS-2; its credentials are set where the broker redeems, not here resources: [https://gw.example.com/mcp] # behind AS-2: the request's `resource` lifetime: 60s # how long each ID-JAG lives ``` diff --git a/pkg/authserver/authorization_details_integration_test.go b/pkg/authserver/authorization_details_integration_test.go index 68a435f10b..8f1085de57 100644 --- a/pkg/authserver/authorization_details_integration_test.go +++ b/pkg/authserver/authorization_details_integration_test.go @@ -258,10 +258,11 @@ func TestIntegration_AuthorizationDetailsIgnoredOnOtherGrants(t *testing.T) { form: func(ts *testServerWithUpstream, _ func(string, time.Time, time.Time, string) string) url.Values { now := time.Now() return url.Values{ - "grant_type": {oauthproto.GrantTypeJWTBearer}, - "assertion": {ts.signIDJAGAssertion("external-subject", now, now.Add(2*time.Minute), "authorization-details-id-jag")}, - "client_id": {testClientID}, - "resource": {testAudience}, + "grant_type": {oauthproto.GrantTypeJWTBearer}, + "assertion": {ts.signIDJAGAssertion("external-subject", now, now.Add(2*time.Minute), "authorization-details-id-jag")}, + "client_id": {idJAGClientID}, + "client_secret": {idJAGClientSecret}, + "resource": {testAudience}, } }, }, diff --git a/pkg/authserver/id_jag_client_auth_integration_test.go b/pkg/authserver/id_jag_client_auth_integration_test.go new file mode 100644 index 0000000000..f4cdd05697 --- /dev/null +++ b/pkg/authserver/id_jag_client_auth_integration_test.go @@ -0,0 +1,131 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package authserver + +import ( + "net/http" + "net/url" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/oauthproto" +) + +func idJAGRedemptionForm(assertion string, clientCreds url.Values) url.Values { + form := url.Values{ + "grant_type": {oauthproto.GrantTypeJWTBearer}, + "assertion": {assertion}, + "resource": {testAudience}, + } + for k, v := range clientCreds { + form[k] = v + } + return form +} + +func redeemIDJAG(t *testing.T, serverURL string, form url.Values) (int, map[string]any) { + t.Helper() + response := makeTokenRequest(t, serverURL, form) + t.Cleanup(func() { _ = response.Body.Close() }) + return response.StatusCode, parseTokenResponse(t, response) +} + +func TestIntegration_IDJAGRedemptionRequiresClientAuthentication(t *testing.T) { + t.Parallel() + + ts, _ := setupJWTBearerGrantTestServer(t, withoutUpstreams()) + now := time.Now() + confidential := url.Values{"client_id": {idJAGClientID}, "client_secret": {idJAGClientSecret}} + + t.Run("a public client is refused", func(t *testing.T) { + t.Parallel() + // The ID-JAG names the public client, so only its public status refuses it. + assertion := ts.signIDJAGAssertionWith(testClientID, nil, "external-subject", now, now.Add(2*time.Minute), "public-client") + + status, body := redeemIDJAG(t, ts.Server.URL, + idJAGRedemptionForm(assertion, url.Values{"client_id": {testClientID}})) + + assert.Equal(t, http.StatusUnauthorized, status, body) + assert.Equal(t, "invalid_client", body["error"]) + assert.True(t, strings.HasPrefix(body["error_description"].(string), "client_authentication_required"), body) + }) + + t.Run("a request with no client credentials is refused", func(t *testing.T) { + t.Parallel() + assertion := ts.signIDJAGAssertion("external-subject", now, now.Add(2*time.Minute), "no-credentials") + + status, body := redeemIDJAG(t, ts.Server.URL, idJAGRedemptionForm(assertion, nil)) + + assert.Equal(t, http.StatusUnauthorized, status, body) + assert.Equal(t, "invalid_client", body["error"]) + assert.True(t, strings.HasPrefix(body["error_description"].(string), "client_authentication_required"), body) + }) + + t.Run("a public client is refused before the assertion is validated", func(t *testing.T) { + t.Parallel() + // An ID-JAG-typed assertion with a broken signature: validating it would + // give invalid_grant, so invalid_client shows the assertion was not judged. + assertion := ts.signIDJAGAssertionWith(testClientID, nil, "external-subject", now, now.Add(2*time.Minute), "bad-signature") + "x" + + status, body := redeemIDJAG(t, ts.Server.URL, + idJAGRedemptionForm(assertion, url.Values{"client_id": {testClientID}})) + + assert.Equal(t, http.StatusUnauthorized, status, body) + assert.Equal(t, "invalid_client", body["error"]) + assert.True(t, strings.HasPrefix(body["error_description"].(string), "client_authentication_required"), body) + }) + + t.Run("a refused public client does not consume the ID-JAG", func(t *testing.T) { + t.Parallel() + assertion := ts.signIDJAGAssertion("external-subject", now, now.Add(2*time.Minute), "not-consumed") + + status, body := redeemIDJAG(t, ts.Server.URL, + idJAGRedemptionForm(assertion, url.Values{"client_id": {testClientID}})) + require.Equal(t, http.StatusUnauthorized, status, body) + require.Equal(t, "invalid_client", body["error"]) + + status, body = redeemIDJAG(t, ts.Server.URL, idJAGRedemptionForm(assertion, confidential)) + assert.Equal(t, http.StatusOK, status, body) + assert.NotEmpty(t, body["access_token"]) + }) + + t.Run("a confidential client redeems", func(t *testing.T) { + t.Parallel() + assertion := ts.signIDJAGAssertion("external-subject", now, now.Add(2*time.Minute), "confidential-client") + + status, body := redeemIDJAG(t, ts.Server.URL, idJAGRedemptionForm(assertion, confidential)) + + assert.Equal(t, http.StatusOK, status, body) + assert.NotEmpty(t, body["access_token"]) + }) +} + +func TestIntegration_IDJAGRedemptionRefusesConfirmationClaim(t *testing.T) { + t.Parallel() + + ts, _ := setupJWTBearerGrantTestServer(t, withoutUpstreams()) + now := time.Now() + confidential := url.Values{"client_id": {idJAGClientID}, "client_secret": {idJAGClientSecret}} + + for name, cnf := range map[string]any{ + "cnf null": nil, + "cnf object": map[string]any{"jkt": "0ZcOCORZNYy-DWpqq30jZyJGHTN0d2HglBV3uiguA4I"}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + assertion := ts.signIDJAGAssertionWith(idJAGClientID, map[string]any{"cnf": cnf}, + "external-subject", now, now.Add(2*time.Minute), "cnf-"+strings.ReplaceAll(name, " ", "-")) + + status, body := redeemIDJAG(t, ts.Server.URL, idJAGRedemptionForm(assertion, confidential)) + + assert.Equal(t, http.StatusBadRequest, status, body) + assert.Equal(t, "invalid_grant", body["error"]) + assert.Equal(t, "invalid_assertion: The ID-JAG assertion must not carry a 'cnf' claim.", body["error_description"]) + }) + } +} diff --git a/pkg/authserver/integration_test.go b/pkg/authserver/integration_test.go index 272e6d0bc5..daf9ccc66c 100644 --- a/pkg/authserver/integration_test.go +++ b/pkg/authserver/integration_test.go @@ -17,6 +17,7 @@ import ( "fmt" "io" "log/slog" + "maps" "net" "net/http" "net/http/httptest" @@ -50,6 +51,13 @@ import ( "github.com/stacklok/toolhive/pkg/oauthproto" ) +// idJAGClientID is the confidential client that redeems ID-JAGs signed by +// setupJWTBearerGrantTestServer. +const ( + idJAGClientID = "id-jag-client" + idJAGClientSecret = "id-jag-client-secret" +) + const ( testClientID = "test-client" testRedirectURI = "http://localhost:8080/callback" @@ -567,7 +575,17 @@ func setupJWTBearerGrantTestServer(t *testing.T, opts ...testServerOption) (*tes })) t.Cleanup(jwksServer.Close) - serverOpts := append([]testServerOption{}, opts...) + // ID-JAGs are redeemed by a confidential client: AS-2 refuses public ones. + idJAGClient, err := registration.New(registration.Config{ + ID: idJAGClientID, Secret: idJAGClientSecret, + TokenEndpointAuthMethod: oauthproto.TokenEndpointAuthMethodClientSecretPost, + GrantTypes: []string{oauthproto.GrantTypeJWTBearer}, + Scopes: registration.DefaultScopes, + Audience: []string{testAudience}, + }) + require.NoError(t, err) + + serverOpts := append([]testServerOption{withExtraClient(idJAGClient)}, opts...) serverOpts = append(serverOpts, withTrustedIssuers([]tokenexchange.TrustedIssuer{{ IssuerURL: externalIssuer, ExpectedAudience: testAudience, @@ -594,8 +612,10 @@ func setupJWTBearerGrantTestServer(t *testing.T, opts ...testServerOption) (*tes ) require.NoError(t, err) - sign := func(subject, audience string, issuedAt, expiry time.Time, id string) string { + signWith := func(extra map[string]any, subject, audience string, issuedAt, expiry time.Time, id string) string { t.Helper() + claims := map[string]any{"azp": subject} + maps.Copy(claims, extra) builder := jwt.Signed(signer).Claims(jwt.Claims{ Issuer: externalIssuer, Subject: subject, @@ -603,26 +623,40 @@ func setupJWTBearerGrantTestServer(t *testing.T, opts ...testServerOption) (*tes IssuedAt: jwt.NewNumericDate(issuedAt), Expiry: jwt.NewNumericDate(expiry), ID: id, - }).Claims(map[string]any{"azp": subject}) + }).Claims(claims) assertion, err := builder.Serialize() require.NoError(t, err) return assertion } + sign := func(subject, audience string, issuedAt, expiry time.Time, id string) string { + t.Helper() + return signWith(nil, subject, audience, issuedAt, expiry, id) + } + ts.signAssertionWith = func(extra map[string]any, subject string, issuedAt, expiry time.Time, id string) string { + t.Helper() + return signWith(extra, subject, testIssuer+"/oauth/token", issuedAt, expiry, id) + } signAssertion := func(subject string, issuedAt, expiry time.Time, id string) string { return sign(subject, testIssuer+"/oauth/token", issuedAt, expiry, id) } ts.signSubjectToken = func(subject string, issuedAt, expiry time.Time, id string) string { return sign(subject, testAudience, issuedAt, expiry, id) } - ts.signIDJAGAssertion = func(subject string, issuedAt, expiry time.Time, id string) string { + ts.signIDJAGAssertionWith = func(clientID string, extra map[string]any, subject string, issuedAt, expiry time.Time, id string) string { t.Helper() + claims := map[string]any{"client_id": clientID} + maps.Copy(claims, extra) assertion, err := jwt.Signed(idjagSigner).Claims(jwt.Claims{ Issuer: externalIssuer, Subject: subject, Audience: jwt.Audience{testIssuer + "/oauth/token"}, IssuedAt: jwt.NewNumericDate(issuedAt), Expiry: jwt.NewNumericDate(expiry), ID: id, - }).Claims(map[string]any{"client_id": testClientID}).Serialize() + }).Claims(claims).Serialize() require.NoError(t, err) return assertion } + ts.signIDJAGAssertion = func(subject string, issuedAt, expiry time.Time, id string) string { + t.Helper() + return ts.signIDJAGAssertionWith(idJAGClientID, nil, subject, issuedAt, expiry, id) + } return ts, signAssertion } @@ -2486,6 +2520,12 @@ type testServerWithUpstream struct { upstreamProvider upstream.OAuth2Provider signSubjectToken func(string, time.Time, time.Time, string) string signIDJAGAssertion func(string, time.Time, time.Time, string) string + // signAssertionWith signs a plain RFC 7523 assertion with extra claims + // merged over the defaults. + signAssertionWith func(extra map[string]any, subject string, issuedAt, expiry time.Time, id string) string + // signIDJAGAssertionWith signs an ID-JAG naming clientID, with extra claims + // merged over the defaults. + signIDJAGAssertionWith func(clientID string, extra map[string]any, subject string, issuedAt, expiry time.Time, id string) string } // startMockOIDC starts a mockoidc server with default test user. @@ -7356,10 +7396,11 @@ func TestIntegration_AccessTokenType(t *testing.T) { t.Helper() token := jwtBearerAccessToken(t, opts, func(ts *testServerWithUpstream, _ func(string, time.Time, time.Time, string) string, now time.Time) url.Values { return url.Values{ - "grant_type": {oauthproto.GrantTypeJWTBearer}, - "assertion": {ts.signIDJAGAssertion("external-subject", now, now.Add(2*time.Minute), "typ-id-jag")}, - "client_id": {testClientID}, - "resource": {testAudience}, + "grant_type": {oauthproto.GrantTypeJWTBearer}, + "assertion": {ts.signIDJAGAssertion("external-subject", now, now.Add(2*time.Minute), "typ-id-jag")}, + "client_id": {idJAGClientID}, + "client_secret": {idJAGClientSecret}, + "resource": {testAudience}, } }) // The plain JWT-bearer handler would mint a synthetic client_id, so @@ -7368,7 +7409,7 @@ func TestIntegration_AccessTokenType(t *testing.T) { require.NoError(t, err) var claims map[string]any require.NoError(t, parsed.UnsafeClaimsWithoutVerification(&claims)) - require.Equal(t, testClientID, claims["client_id"]) + require.Equal(t, idJAGClientID, claims["client_id"]) return token }}, } diff --git a/pkg/authserver/jwt_bearer_cnf_integration_test.go b/pkg/authserver/jwt_bearer_cnf_integration_test.go new file mode 100644 index 0000000000..517dcd057b --- /dev/null +++ b/pkg/authserver/jwt_bearer_cnf_integration_test.go @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package authserver + +import ( + "net/http" + "net/url" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + + "github.com/stacklok/toolhive/pkg/oauthproto" +) + +func TestIntegration_JWTBearerRedemptionRefusesConfirmationClaim(t *testing.T) { + t.Parallel() + + ts, signAssertion := setupJWTBearerGrantTestServer(t, withoutUpstreams()) + now := time.Now() + redeem := func(t *testing.T, assertion string) (int, map[string]any) { + t.Helper() + return redeemIDJAG(t, ts.Server.URL, url.Values{ + "grant_type": {oauthproto.GrantTypeJWTBearer}, + "assertion": {assertion}, + "resource": {testAudience}, + }) + } + + for name, cnf := range map[string]any{ + "cnf null": nil, + "cnf object": map[string]any{"jkt": "0ZcOCORZNYy-DWpqq30jZyJGHTN0d2HglBV3uiguA4I"}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + assertion := ts.signAssertionWith(map[string]any{"cnf": cnf}, + "external-subject", now, now.Add(2*time.Minute), "plain-"+strings.ReplaceAll(name, " ", "-")) + + status, body := redeem(t, assertion) + + assert.Equal(t, http.StatusBadRequest, status, body) + assert.Equal(t, "invalid_grant", body["error"]) + assert.Equal(t, "invalid_assertion: The JWT bearer assertion must not carry a 'cnf' claim.", body["error_description"]) + }) + } + + t.Run("an assertion without cnf still redeems", func(t *testing.T) { + t.Parallel() + status, body := redeem(t, signAssertion("external-subject", now, now.Add(2*time.Minute), "plain-no-cnf")) + + assert.Equal(t, http.StatusOK, status, body) + }) +} diff --git a/pkg/authserver/removed_client_admission_integration_test.go b/pkg/authserver/removed_client_admission_integration_test.go index 94a1344b6d..5f0b18d39e 100644 --- a/pkg/authserver/removed_client_admission_integration_test.go +++ b/pkg/authserver/removed_client_admission_integration_test.go @@ -383,8 +383,8 @@ func TestRemovedClientProbeCoverage(t *testing.T) { // TestRemovedClientHandlerTypes is what lets a single token-endpoint probe stand // for every grant. Fosite drops the client authentication error only when a // handler that handles the request returns true from CanSkipClientAuth, so two -// properties are pinned: without credentials only the plain JWT-bearer handler -// may skip, and with credentials no handler may skip. It also pins the set of +// properties are pinned: without credentials only the two JWT-bearer handlers +// (plain and ID-JAG) may skip, and with credentials no handler may skip. It also pins the set of // authorize and token handler types so a new grant has to be considered here. // The provider comes from the same parameter construction newServer uses. func TestRemovedClientHandlerTypes(t *testing.T) { @@ -398,6 +398,7 @@ func TestRemovedClientHandlerTypes(t *testing.T) { require.True(t, ok) const jwtBearerHandler = "*tokenexchange.JWTBearerHandler" + const idJAGHandler = "*tokenexchange.IDJAGHandler" grants := []string{ "authorization_code", "refresh_token", oauthproto.GrantTypeTokenExchange, oauthproto.GrantTypeJWTBearer, "urn:ietf:params:oauth:grant-type:device_code", "client_credentials", "password", @@ -420,7 +421,8 @@ func TestRemovedClientHandlerTypes(t *testing.T) { return h.CanSkipClientAuth(context.WithValue(ctx, fosite.RequestContextKey, httpReq), req) }) } - assert.Equalf(t, name == jwtBearerHandler, skips(false), "%s: only the JWT-bearer handler may skip client authentication", name) + assert.Equalf(t, name == jwtBearerHandler || name == idJAGHandler, skips(false), + "%s: only the JWT-bearer handlers may skip client authentication", name) assert.Falsef(t, skips(true), "%s: no handler may skip client authentication when credentials are present", name) } for _, h := range provider.Config.GetAuthorizeEndpointHandlers(ctx) { @@ -428,7 +430,7 @@ func TestRemovedClientHandlerTypes(t *testing.T) { } assert.ElementsMatch(t, []string{ "*oauth2.AuthorizeExplicitGrantHandler", "*oauth2.RefreshTokenGrantHandler", "*pkce.Handler", "*tokenexchange.Handler", - "*tokenexchange.RefreshTokenHandler", jwtBearerHandler, "*tokenexchange.IDJAGHandler", "*deviceflow.Handler", + "*tokenexchange.RefreshTokenHandler", jwtBearerHandler, idJAGHandler, "*deviceflow.Handler", "*authserver.refreshGrantValidators", }, gotToken, "token endpoint handlers changed: decide whether the new one authenticates the client") assert.ElementsMatch(t, []string{"*oauth2.AuthorizeExplicitGrantHandler", "*pkce.Handler"}, gotAuthorize, diff --git a/pkg/authserver/server/tokenexchange/id_jag_client_auth_test.go b/pkg/authserver/server/tokenexchange/id_jag_client_auth_test.go new file mode 100644 index 0000000000..3ece1ae24e --- /dev/null +++ b/pkg/authserver/server/tokenexchange/id_jag_client_auth_test.go @@ -0,0 +1,150 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package tokenexchange + +import ( + "context" + "net/http" + "net/url" + "testing" + + "github.com/ory/fosite" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/oauthproto" +) + +const clientAuthRequiredDescription = "client_authentication_required: The ID-JAG grant requires client authentication." + +func TestIDJAGHandler_RefusesUnauthenticatedClient(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + client fosite.Client + }{ + {name: "public client", client: &fosite.DefaultClient{ID: idJAGTestClientID, Public: true}}, + {name: "nil client"}, + {name: "placeholder client with an empty ID", client: &fosite.DefaultClient{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + validator := &testJWTBearerAssertionValidator{claims: validIDJAGClaims()} + consumer := &recordingAssertionConsumer{} + h := newIDJAGTestHandler(t, validator, consumer) + req := newIDJAGRequest(t, newTestJWKS(t), "") + req.Client = tt.client + + err := h.HandleTokenEndpointRequest(context.Background(), req) + + requireRefusalStatus(t, err, http.StatusUnauthorized, "invalid_client", clientAuthRequiredDescription) + assert.Zero(t, validator.calls, "the assertion must not be validated") + assert.Empty(t, consumer.key, "the assertion must not be consumed") + }) + } +} + +func TestIDJAGHandler_checkClientBinding(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + client fosite.Client + wantErr string + }{ + {name: "nil client fails closed", wantErr: "invalid_client"}, + {name: "placeholder client with an empty ID fails closed", client: &fosite.DefaultClient{}, wantErr: "invalid_client"}, + {name: "public client fails closed", client: &fosite.DefaultClient{ID: idJAGTestClientID, Public: true}, wantErr: "invalid_client"}, + { + name: "client other than the assertion's", + client: &fosite.DefaultClient{ID: "some-other-client"}, + wantErr: "invalid_grant", + }, + {name: "matching client", client: &fosite.DefaultClient{ID: idJAGTestClientID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + h := newIDJAGTestHandler(t, &testJWTBearerAssertionValidator{}, &recordingAssertionConsumer{}) + req := newIDJAGRequest(t, newTestJWKS(t), "") + req.Client = tt.client + + err := h.checkClientBinding(req, validIDJAGClaims()) + + if tt.wantErr == "" { + require.NoError(t, err) + return + } + var rfcErr *fosite.RFC6749Error + require.ErrorAs(t, err, &rfcErr) + assert.Equal(t, tt.wantErr, rfcErr.ErrorField) + if tt.wantErr == "invalid_client" { + assert.Equal(t, "client_authentication_required: The ID-JAG grant requires client authentication.", + rfcErr.GetDescription()) + } + }) + } +} + +func TestIDJAGHandler_CanSkipClientAuth(t *testing.T) { + t.Parallel() + + tj := newTestJWKS(t) + idJAG := signAssertionWithType(t, tj, oauthproto.JWTTypeIDJAG) + plain := signAssertionWithType(t, tj, nil) + idJAGHandler := newIDJAGTestHandler(t, &testJWTBearerAssertionValidator{}, &recordingAssertionConsumer{}) + plainHandler, err := newJWTBearerHandler(&testJWTBearerAssertionValidator{}, testTokenEndpoint) + require.NoError(t, err) + + const assertionType = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" + tests := []struct { + name string + extra url.Values + basicUser string + basicPass string + noReqCtx bool + wantIDJAG bool + wantPlain bool + }{ + {name: "no credentials", wantIDJAG: true, wantPlain: true}, + {name: "client_assertion_type with a blank first value", extra: url.Values{ + "client_assertion_type": {"", assertionType}, + }}, + {name: "client_id with a blank first value", extra: url.Values{"client_id": {"", "c"}}}, + {name: "blank form credential values", extra: url.Values{ + "client_id": {""}, "client_secret": {""}, "client_assertion": {""}, "client_assertion_type": {""}, + }, wantIDJAG: true, wantPlain: true}, + {name: "client_id", extra: url.Values{"client_id": {"c"}}}, + {name: "client_secret", extra: url.Values{"client_secret": {"s"}}}, + {name: "client_assertion", extra: url.Values{"client_assertion": {"a"}}}, + {name: "client_assertion_type", extra: url.Values{"client_assertion_type": {assertionType}}}, + {name: "HTTP Basic", basicUser: "c", basicPass: "s"}, + {name: "HTTP Basic with empty username", basicPass: "s"}, + {name: "no HTTP request in context", noReqCtx: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + ctx := context.Background() + if !tt.noReqCtx { + ctx = contextWithHTTPRequest(t, tt.basicUser, tt.basicPass) + } + form := func(assertion string) url.Values { + f := url.Values{"assertion": {assertion}} + for k, v := range tt.extra { + f[k] = v + } + return f + } + + assert.Equal(t, tt.wantIDJAG, idJAGHandler.CanSkipClientAuth(ctx, newJWTBearerRequest(form(idJAG)))) + assert.Equal(t, tt.wantPlain, plainHandler.CanSkipClientAuth(ctx, newJWTBearerRequest(form(plain)))) + // The plain handler never skips for an ID-JAG, whatever else the + // request carries. + assert.False(t, plainHandler.CanSkipClientAuth(ctx, newJWTBearerRequest(form(idJAG)))) + }) + } +} diff --git a/pkg/authserver/server/tokenexchange/id_jag_cnf_test.go b/pkg/authserver/server/tokenexchange/id_jag_cnf_test.go new file mode 100644 index 0000000000..fa94029378 --- /dev/null +++ b/pkg/authserver/server/tokenexchange/id_jag_cnf_test.go @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package tokenexchange + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestIDJAGHandler_RefusesConfirmationClaim(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + mutate func(*ValidatedClaims) + }{ + { + name: "cnf object in the full claim set and Extra", + mutate: func(c *ValidatedClaims) { + cnf := map[string]any{"jkt": "thumbprint"} + c.Claims = map[string]any{"cnf": cnf} + c.Extra["cnf"] = cnf + }, + }, + {name: "cnf object in Extra only", mutate: func(c *ValidatedClaims) { c.Extra["cnf"] = map[string]any{"jkt": "thumbprint"} }}, + {name: "cnf object in the full claim set only", mutate: func(c *ValidatedClaims) { + c.Claims = map[string]any{"cnf": map[string]any{"jkt": "thumbprint"}} + }}, + {name: "cnf null", mutate: func(c *ValidatedClaims) { c.Extra["cnf"] = nil }}, + {name: "cnf null in the full claim set only", mutate: func(c *ValidatedClaims) { c.Claims = map[string]any{"cnf": nil} }}, + {name: "cnf empty object", mutate: func(c *ValidatedClaims) { c.Extra["cnf"] = map[string]any{} }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + claims := validIDJAGClaims() + tt.mutate(claims) + consumer := &recordingAssertionConsumer{} + h := newIDJAGTestHandler(t, &testJWTBearerAssertionValidator{claims: claims}, consumer) + req := newIDJAGRequest(t, newTestJWKS(t), idJAGTestClientID) + + err := h.HandleTokenEndpointRequest(context.Background(), req) + + requireRefusal(t, err, "invalid_grant", "invalid_assertion: The ID-JAG assertion must not carry a 'cnf' claim.") + assert.Empty(t, consumer.key, "a refused assertion must not be consumed") + }) + } +} diff --git a/pkg/authserver/server/tokenexchange/id_jag_handler.go b/pkg/authserver/server/tokenexchange/id_jag_handler.go index c8cf5dc75f..13d7cb91dc 100644 --- a/pkg/authserver/server/tokenexchange/id_jag_handler.go +++ b/pkg/authserver/server/tokenexchange/id_jag_handler.go @@ -42,17 +42,16 @@ const idJAGReplayPurpose = "id-jag" // "Bound" is the trust-model difference from the plain handler. An ID-JAG // names the OAuth client that may redeem it — the IdP mints the draft // §4.4.1 client_id claim from its administrator-configured resource -// 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 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. +// connection — so this handler requires the authenticated client to be that +// client. Only a confidential client that authenticated can redeem. Public +// clients, and requests with no client credentials, are refused with +// invalid_client before the assertion is validated: draft §4.4 requires client +// authentication or a sender-constrained ID-JAG, and this server cannot yet +// verify a sender-constrained one (proof of possession, DPoP or mTLS). A +// client_id alone is not authentication, and the assertion's single-use, +// short-lived, audience-pinned form only decides who redeems a leaked copy +// first. 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 // consulted, except for the operator-configured clients that set grant_types: @@ -159,15 +158,16 @@ func (*IDJAGHandler) CanHandleTokenEndpointRequest(_ context.Context, requester assertionType(requester.GetRequestForm().Get("assertion")) == oauthproto.JWTTypeIDJAG } -// CanSkipClientAuth never permits skipping client authentication: an ID-JAG -// is issued TO a specific client (its client_id claim), so fosite must have -// authenticated — or, for a public client, at least identified via client_id -// — the caller before HandleTokenEndpointRequest can check the binding. -// fosite.NewAccessRequest returns the client-authentication error whenever -// this is false and authentication failed, so the handler below only ever -// runs with a resolved client. -func (*IDJAGHandler) CanSkipClientAuth(context.Context, fosite.AccessRequester) bool { - return false +// CanSkipClientAuth permits skipping client authentication only for a request +// that carries no client credentials at all. fosite then gives the handler its +// placeholder client with an empty ID, and HandleTokenEndpointRequest refuses +// it with invalid_client, instead of fosite's invalid_request. A request that +// carries any credentials, or a client_id alone, is authenticated or +// identified by fosite first, and a failure is returned to the client. Public +// clients are refused by HandleTokenEndpointRequest (draft §4.4), so a +// client_id alone never redeems an ID-JAG. +func (*IDJAGHandler) CanSkipClientAuth(ctx context.Context, requester fosite.AccessRequester) bool { + return !mayCarryClientCredentials(ctx, requester.GetRequestForm()) } // HandleTokenEndpointRequest validates the ID-JAG assertion, its client @@ -177,6 +177,12 @@ func (h *IDJAGHandler) HandleTokenEndpointRequest(ctx context.Context, requester if !h.CanHandleTokenEndpointRequest(ctx, requester) { return errorsx.WithStack(fosite.ErrUnknownRequest) } + // First, so a caller that did not authenticate learns nothing about the + // assertion: no validation and no consumption. Only the unverified JOSE + // typ header was read, for routing. + if err := checkClientAuthenticated(requester.GetClient()); err != nil { + return err + } if err := h.checkClientGrant(requester); err != nil { return err } @@ -233,14 +239,21 @@ func (h *IDJAGHandler) HandleTokenEndpointRequest(ctx context.Context, requester return err } h.logDraftDepartures(ctx, claims, policy, requester.GetClient().GetID()) + requester.GrantAudience(resource) + requester.SetSession(newIDJAGSession(claims, requester.GetClient().GetID(), lifetime)) + return nil +} + +// newIDJAGSession builds the bounded access-token session for a redeemed +// ID-JAG. +func newIDJAGSession(claims *ValidatedClaims, clientID string, lifetime time.Duration) *session.Session { // 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 - // client, unlike there, is the real authenticated one — fosite resolved - // it (CanSkipClientAuth is always false), so requester already carries - // it and no synthetic replacement happens. + // client, unlike there, is the real authenticated one, so no synthetic + // replacement happens. issuedSession := session.New(claimnames.QualifySubject(claims.Issuer, claims.Subject), "", - requester.GetClient().GetID(), session.UserClaims{}) + clientID, session.UserClaims{}) // An ID-JAG links to no upstream IdP login at THIS server, same as a // plain assertion; see claimnames.NoUpstreamSessionKey. issuedSession.JWTClaims.Extra[claimnames.NoUpstreamSessionKey] = true @@ -254,9 +267,7 @@ func (h *IDJAGHandler) HandleTokenEndpointRequest(ctx context.Context, requester issuedSession.JWTClaims.Extra["act"] = act } issuedSession.SetExpiresAt(fosite.AccessToken, time.Now().UTC().Add(lifetime)) - requester.GrantAudience(resource) - requester.SetSession(issuedSession) - return nil + return issuedSession } // PopulateTokenEndpointResponse issues only an access token, sharing the @@ -405,7 +416,8 @@ func (h *IDJAGHandler) defaultAudiences(ctx context.Context) []string { } // validateAssertion verifies the assertion and refuses an aud array with more -// than one element, for every issuer. It runs before the assertion is consumed. +// than one element and a cnf claim, for every issuer. It runs before the +// assertion is consumed. func (h *IDJAGHandler) validateAssertion(ctx context.Context, assertion string) (*ValidatedClaims, error) { claims, err := h.core.validator.ValidateJWTBearerAssertion(ctx, assertion, h.defaultAudiences(ctx)) if err != nil { @@ -414,6 +426,14 @@ func (h *IDJAGHandler) validateAssertion(ctx context.Context, assertion string) if len(claims.Audience) > 1 { return nil, invalidAssertion("The ID-JAG assertion aud must name exactly one audience.") } + // Draft section 9.11 says a server that cannot verify the confirmation + // method of an ID-JAG with a cnf claim MUST refuse it. This server cannot + // verify proof of possession yet, so accepting the ID-JAG would silently + // drop the key binding the IdP asked for. The refusal stays until proof of + // possession (DPoP or mTLS) is verified. + if hasConfirmationClaim(claims) { + return nil, invalidAssertion("The ID-JAG assertion must not carry a 'cnf' claim.") + } return claims, nil } @@ -430,20 +450,32 @@ func (h *IDJAGHandler) checkClientGrant(requester fosite.AccessRequester) error return nil } +// checkClientAuthenticated refuses a nil client, the ID-less placeholder fosite +// uses when a request carried no credentials, and a public client, which fosite +// only identifies by client_id. Draft §4.4 requires client authentication or a +// sender-constrained ID-JAG, and sender-constrained ID-JAGs are refused until +// proof of possession (DPoP or mTLS) can be verified. +func checkClientAuthenticated(client fosite.Client) error { + if client == nil || client.GetID() == "" || client.IsPublic() { + return clientAuthRequired() + } + return nil +} + // checkClientBinding enforces the draft's §4.4.1 client_id continuity: the // assertion's client_id claim (minted by the IdP from its resource // connection) must name the client fosite resolved for this request. Both // sides are required to be non-empty first so the check can never -// degenerate into an empty-equals-empty pass — fosite initializes an -// unauthenticated request's client to an ID-less placeholder, and this -// handler must not depend on that staying unreachable. +// degenerate into an empty-equals-empty pass. HandleTokenEndpointRequest +// already refuses an unauthenticated client; repeating checkClientAuthenticated +// here keeps the binding safe on its own and returns the same refusal. func (*IDJAGHandler) checkClientBinding(requester fosite.AccessRequester, claims *ValidatedClaims) error { if claims.ClientID == "" { return invalidAssertion("The ID-JAG assertion must carry a 'client_id' claim.") } client := requester.GetClient() - if client == nil || client.GetID() == "" { - return errorsx.WithStack(fosite.ErrInvalidClient.WithHint("The ID-JAG grant requires an authenticated or identified client.")) + if err := checkClientAuthenticated(client); err != nil { + return err } if claims.ClientID != client.GetID() { return invalidAssertion("The ID-JAG assertion was not issued to the requesting client.") diff --git a/pkg/authserver/server/tokenexchange/id_jag_handler_test.go b/pkg/authserver/server/tokenexchange/id_jag_handler_test.go index 3e4eb04c4b..ac03f73fbb 100644 --- a/pkg/authserver/server/tokenexchange/id_jag_handler_test.go +++ b/pkg/authserver/server/tokenexchange/id_jag_handler_test.go @@ -172,10 +172,11 @@ func TestIDJAGHandler_MatchingAndClientAuth(t *testing.T) { req.GrantTypes = tt.grantTypes ctx := contextWithHTTPRequest(t, "", "") assert.Equal(t, tt.wantHandles, h.CanHandleTokenEndpointRequest(ctx, req)) - // Bound means bound: client authentication is never skippable, with or - // without credentials in the request, whether or not this handler even - // claims the request. - assert.False(t, h.CanSkipClientAuth(ctx, req)) + // A request with no client credentials may skip fosite's client + // authentication whether or not this handler claims it: the handler + // then refuses the placeholder client. Requests that carry + // credentials are covered by TestIDJAGHandler_CanSkipClientAuth. + assert.True(t, h.CanSkipClientAuth(ctx, req)) }) } } @@ -184,12 +185,10 @@ func TestIDJAGHandler_ClientBindingAndJTI(t *testing.T) { t.Parallel() tests := []struct { - name string - mutateClaims func(*ValidatedClaims) - requestClient string - wantErrIs error // checked alongside wantErrContain - wantErrContain string // substring of the reason, for refusals without a reason code - wantDesc string // exact error_description of an invalid_grant refusal + name string + mutateClaims func(*ValidatedClaims) + requestClient string + wantDesc string // exact error_description of an invalid_grant refusal }{ { name: "missing jti is rejected", @@ -203,15 +202,6 @@ func TestIDJAGHandler_ClientBindingAndJTI(t *testing.T) { requestClient: idJAGTestClientID, wantDesc: "invalid_assertion: The ID-JAG assertion must carry a 'client_id' claim.", }, - { - // fosite initializes an unauthenticated request's client to an - // ID-less placeholder; the binding check must fail closed on it - // rather than compare against the empty ID. - name: "unresolved client fails closed", - mutateClaims: func(*ValidatedClaims) {}, - wantErrIs: fosite.ErrInvalidClient, - wantErrContain: "authenticated or identified client", - }, { name: "client mismatch is rejected", mutateClaims: func(*ValidatedClaims) {}, @@ -224,7 +214,6 @@ func TestIDJAGHandler_ClientBindingAndJTI(t *testing.T) { c.Audience = []string{idJAGTestASIssuer, testTokenEndpoint} }, requestClient: idJAGTestClientID, - wantErrIs: fosite.ErrInvalidGrant, wantDesc: "invalid_assertion: The ID-JAG assertion aud must name exactly one audience.", }, } @@ -239,15 +228,7 @@ func TestIDJAGHandler_ClientBindingAndJTI(t *testing.T) { req := newIDJAGRequest(t, tj, tt.requestClient) err := h.HandleTokenEndpointRequest(context.Background(), req) - if tt.wantDesc != "" { - requireRefusal(t, err, "invalid_grant", tt.wantDesc) - } - if tt.wantErrContain != "" { - assert.ErrorIs(t, err, tt.wantErrIs) - var rfcErr *fosite.RFC6749Error - require.True(t, errors.As(err, &rfcErr)) - assert.Contains(t, rfcErr.Reason(), tt.wantErrContain) - } + requireRefusal(t, err, "invalid_grant", tt.wantDesc) // None of these rejections may consume the assertion: they are all // caller-fixable, and a consumed jti would turn a retry with the // right client into a replay rejection. diff --git a/pkg/authserver/server/tokenexchange/jwt_bearer_cnf_test.go b/pkg/authserver/server/tokenexchange/jwt_bearer_cnf_test.go new file mode 100644 index 0000000000..b6b4af931d --- /dev/null +++ b/pkg/authserver/server/tokenexchange/jwt_bearer_cnf_test.go @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package tokenexchange + +import ( + "context" + "testing" + "time" + + "github.com/ory/fosite" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestHasConfirmationClaim(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + claims *ValidatedClaims + want bool + }{ + {name: "nil claims"}, + {name: "no claims", claims: &ValidatedClaims{}}, + {name: "unrelated claims", claims: &ValidatedClaims{ + Claims: map[string]any{"azp": "x"}, Extra: map[string]any{"azp": "x"}, + }}, + {name: "in Extra", claims: &ValidatedClaims{Extra: map[string]any{"cnf": map[string]any{"jkt": "t"}}}, want: true}, + {name: "in the full claim set", claims: &ValidatedClaims{Claims: map[string]any{"cnf": map[string]any{}}}, want: true}, + {name: "null", claims: &ValidatedClaims{Claims: map[string]any{"cnf": nil}}, want: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.want, hasConfirmationClaim(tt.claims)) + }) + } +} + +func TestJWTBearerHandler_RefusesConfirmationClaim(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + mutate func(*ValidatedClaims) + }{ + {name: "cnf object", mutate: func(c *ValidatedClaims) { + c.Claims = map[string]any{"cnf": map[string]any{"jkt": "thumbprint"}} + c.Extra = map[string]any{"cnf": map[string]any{"jkt": "thumbprint"}} + }}, + {name: "cnf null", mutate: func(c *ValidatedClaims) { c.Extra = map[string]any{"cnf": nil} }}, + {name: "cnf empty object", mutate: func(c *ValidatedClaims) { c.Claims = map[string]any{"cnf": map[string]any{}} }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + claims := refusalClaims() + tt.mutate(claims) + consumer := &recordingAssertionConsumer{} + handler, err := newJWTBearerIssuanceHandler(&testJWTBearerAssertionValidator{claims: claims}, testTokenEndpoint, + consumer, &fosite.Config{AccessTokenLifespan: time.Hour}, + &mockAccessTokenStrategy{}, &mockAccessTokenStorage{}, refusalPolicies(t)) + require.NoError(t, err) + req := newJWTBearerRequest(map[string][]string{ + "assertion": {signAssertionWithType(t, newTestJWKS(t), nil)}, + "resource": {refusalResource}, + }) + + err = handler.HandleTokenEndpointRequest(context.Background(), req) + + requireRefusal(t, err, "invalid_grant", "invalid_assertion: The JWT bearer assertion must not carry a 'cnf' claim.") + assert.Empty(t, consumer.key, "a refused assertion must not be consumed") + }) + } +} diff --git a/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go b/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go index fa6fd80f64..59f3e94881 100644 --- a/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go +++ b/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go @@ -134,21 +134,44 @@ func (*JWTBearerHandler) CanHandleTokenEndpointRequest(_ context.Context, reques // closed rather than open. func (*JWTBearerHandler) CanSkipClientAuth(ctx context.Context, requester fosite.AccessRequester) bool { form := requester.GetRequestForm() - if assertionType(form.Get("assertion")) == oauthproto.JWTTypeIDJAG || - form.Get("client_id") != "" || - form.Get("client_secret") != "" || - form.Get("client_assertion") != "" || - form.Get("client_assertion_type") != "" { - return false + return assertionType(form.Get("assertion")) != oauthproto.JWTTypeIDJAG && !mayCarryClientCredentials(ctx, form) +} + +// mayCarryClientCredentials reports whether a token request might carry client +// credentials: a client_id, client_secret, client_assertion or +// client_assertion_type form field, or HTTP Basic credentials. A missing or +// malformed raw request counts as "might carry", so callers fail closed. +func mayCarryClientCredentials(ctx context.Context, form url.Values) bool { + // Every value of a field is checked, not just the first, so the decision + // matches what a client-authentication strategy that reads any value accepts. + for _, field := range []string{"client_id", "client_secret", "client_assertion", "client_assertion_type"} { + if slices.ContainsFunc(form[field], func(v string) bool { return v != "" }) { + return true + } } req, ok := ctx.Value(fosite.RequestContextKey).(*http.Request) if !ok || req == nil { - return false + return true } - if _, _, ok := req.BasicAuth(); ok { + _, _, basic := req.BasicAuth() + return basic +} + +// claimConfirmation is the RFC 7800 confirmation claim. +const claimConfirmation = "cnf" + +// hasConfirmationClaim reports whether a validated assertion carries a cnf +// claim. Only presence counts, so "cnf": null and "cnf": {} are both found; the +// value is never read. +func hasConfirmationClaim(claims *ValidatedClaims) bool { + if claims == nil { return false } - return true + // Claims is the full decoded set and Extra a subset of it. Both are checked + // so hand-built ValidatedClaims and a later change to assignClaim stay safe. + _, inClaims := claims.Claims[claimConfirmation] + _, inExtra := claims.Extra[claimConfirmation] + return inClaims || inExtra } // HandleTokenEndpointRequest validates policy and prepares a bounded access-token session. @@ -167,9 +190,9 @@ func (h *JWTBearerHandler) HandleTokenEndpointRequest(ctx context.Context, reque if err := validateAssertionType(assertion); err != nil { return err } - claims, err := h.validator.ValidateJWTBearerAssertion(ctx, assertion, []string{h.tokenEndpoint}) + claims, err := h.validateAssertion(ctx, assertion) if err != nil { - return assertionValidationRefusal(err, "The JWT bearer assertion is invalid or could not be verified.") + return err } // h.policies is nil when this handler was built by newJWTBearerHandler // directly rather than newJWTBearerIssuanceHandler (the seam tests use it @@ -234,6 +257,23 @@ func (h *JWTBearerHandler) HandleTokenEndpointRequest(ctx context.Context, reque return nil } +// validateAssertion verifies the assertion and refuses a cnf claim. It runs +// before the assertion is consumed. +func (h *JWTBearerHandler) validateAssertion(ctx context.Context, assertion string) (*ValidatedClaims, error) { + claims, err := h.validator.ValidateJWTBearerAssertion(ctx, assertion, []string{h.tokenEndpoint}) + if err != nil { + return nil, assertionValidationRefusal(err, "The JWT bearer assertion is invalid or could not be verified.") + } + // RFC 7800 cnf means the issuer expects proof of possession of a key. + // Redeeming the assertion as a bearer token would silently drop that + // binding, so refuse it until proof of possession (DPoP or mTLS) is + // verified. + if hasConfirmationClaim(claims) { + return nil, invalidAssertion("The JWT bearer assertion must not carry a 'cnf' claim.") + } + return claims, nil +} + // 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 { diff --git a/pkg/authserver/server/tokenexchange/redemption_refusal.go b/pkg/authserver/server/tokenexchange/redemption_refusal.go index 994b458d1f..4b3efcee6c 100644 --- a/pkg/authserver/server/tokenexchange/redemption_refusal.go +++ b/pkg/authserver/server/tokenexchange/redemption_refusal.go @@ -6,6 +6,7 @@ package tokenexchange import ( "context" "errors" + "net/http" "github.com/ory/fosite" "github.com/ory/x/errorsx" @@ -27,6 +28,10 @@ const ( // could not be obtained. The refusal is temporarily_unavailable (HTTP 503) // and the same request may succeed once the issuer is reachable. reasonIssuerUnavailable = "issuer_unavailable" + // reasonClientAuthRequired marks an ID-JAG redemption by a client that is + // public or sent no client credentials. It is only ever used with + // invalid_client and says nothing about the assertion, which was not validated or consumed. + reasonClientAuthRequired = "client_authentication_required" ) const hintAssertionValidationFailed = "The assertion could not be validated." @@ -52,6 +57,19 @@ func invalidAssertion(hint string) error { return errorsx.WithStack(redemptionRefusal(fosite.ErrInvalidGrant.ErrorField, reasonInvalidAssertion, hint)) } +// clientAuthRequired is the refusal for an ID-JAG redemption by a client that +// did not authenticate: invalid_client with the client_authentication_required +// reason and HTTP 401, the status fosite uses for its own invalid_client. RFC +// 6749 section 5.2 allows 401 for invalid_client in every case and requires it +// when the client used the Authorization header, so one status fits all. The +// hint says nothing about the assertion. +func clientAuthRequired() error { + refusal := redemptionRefusal(fosite.ErrInvalidClient.ErrorField, reasonClientAuthRequired, + "The ID-JAG grant requires client authentication.") + refusal.CodeField = http.StatusUnauthorized + return errorsx.WithStack(refusal) +} + // issuerUnavailable is the refusal for an assertion whose issuer's signing // keys could not be obtained: temporarily_unavailable with HTTP 503 and the // bare issuer_unavailable description, which never names the issuer. The cause diff --git a/pkg/authserver/server/tokenexchange/redemption_refusal_test.go b/pkg/authserver/server/tokenexchange/redemption_refusal_test.go index 8b4e184ac5..a3d5c569ad 100644 --- a/pkg/authserver/server/tokenexchange/redemption_refusal_test.go +++ b/pkg/authserver/server/tokenexchange/redemption_refusal_test.go @@ -185,7 +185,7 @@ func TestJWTBearerRedemptionRefusals(t *testing.T) { func TestRedemptionRefusal_Grammar(t *testing.T) { t.Parallel() - for _, reason := range []string{reasonInvalidAssertion, reasonSubjectUnknown, reasonResourceDenied, reasonIssuerUnavailable} { + for _, reason := range []string{reasonInvalidAssertion, reasonSubjectUnknown, reasonResourceDenied, reasonIssuerUnavailable, reasonClientAuthRequired} { for _, hint := range []string{"", "A hint."} { description := redemptionRefusal("access_denied", reason, hint).GetDescription() assert.Regexp(t, `^[a-z_]+(: .*)?$`, description)