From 6a89f44f51f64cb1acd8f19c6259972a3d95d419 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Sun, 22 Nov 2026 22:32:23 +0100 Subject: [PATCH 1/2] Share the authorization_details reader The shape check for the authorization_details form parameter is copied by hand in two places, and the hook Subject is built field by field in two places. The two Subject literals have already drifted: the one for token exchange sets External, the one for exchange-grant opening does not. The planned work to narrow a JWT-bearer access token to one MCP call (#7061) needs the same reading and the same Subject in two more places: - ID-JAG redemption will refuse the authorization_details parameter, because the entries come from the assertion's claim instead. It reads the parameter with readDetailsParam, so a repeated parameter, two empty values included, is treated the same as here. - ID-JAG redemption will build the hook Subject for the assertion with detailsSubject, then set External to true and remove the authorization_details key from Claims. detailsSubject returns a value so that the caller can change it. - ID-JAG minting will read the parameter with readDetailsParam and sign the entries into the ID-JAG. That replaces its current rule, under which two empty values count as absent, so all readers then agree on what "repeated" means. Without the helpers each of those adds another copy of the check and of the Subject literal, and the existing copies show that they drift. Add readDetailsParam, which only reports the shape (absent, repeated or one value), and detailsSubject, which returns the hook Subject as a value. Token exchange and exchange-grant opening use them and keep their own policy and wire text. ID-JAG minting keeps its own rule for now. At exchange-grant opening External is now set from the claims. It is always false there, because the login token check refuses external tokens first, and only ToolHive's internal shape hook sees it. No error, description, status or log line changes. Add tests for the two-empty-values shape and for the repeated and malformed WARN fields, which no test asserted before. Co-authored-by: Mecatl --- .../authorization_details_integration_test.go | 1 + .../server/tokenexchange/authdetails.go | 59 +++++++++++++------ .../server/tokenexchange/exchange_grant.go | 13 ++-- .../tokenexchange/exchange_grant_test.go | 14 +++++ .../server/tokenexchange/handler_test.go | 33 +++++++++++ .../tokenexchange/refresh_token_handler.go | 6 +- 6 files changed, 98 insertions(+), 28 deletions(-) diff --git a/pkg/authserver/authorization_details_integration_test.go b/pkg/authserver/authorization_details_integration_test.go index 8f1085de57..9a6e49b7a3 100644 --- a/pkg/authserver/authorization_details_integration_test.go +++ b/pkg/authserver/authorization_details_integration_test.go @@ -152,6 +152,7 @@ func TestIntegration_AuthorizationDetailsOverHTTP(t *testing.T) { {name: "absent parameter is not echoed", wantStatus: http.StatusOK, wantNoEcho: true}, {name: "empty parameter is not echoed", details: []string{""}, wantStatus: http.StatusOK, wantNoEcho: true}, {name: "repeated form values are rejected before the hook", details: []string{`[{"type":"custom"}]`, `[{"type":"custom"}]`}, wantStatus: http.StatusBadRequest, wantError: "invalid_request", wantDescription: "The authorization_details parameter must not be repeated."}, + {name: "two empty form values are rejected as repeated", details: []string{"", ""}, wantStatus: http.StatusBadRequest, wantError: "invalid_request", wantDescription: "The authorization_details parameter must not be repeated."}, {name: "typed hook error keeps its code and reason", details: []string{`[{"type":"custom","reject":true}]`}, wantStatus: http.StatusBadRequest, wantError: "invalid_request", wantDescription: "rejected_by_policy", wantCalls: 1}, {name: "untyped hook error is a server_error without its text", details: []string{`[{"type":"custom","deny":true}]`}, wantStatus: http.StatusInternalServerError, wantError: "server_error", wantDescription: "The authorization_details could not be processed.", wantCalls: 1}, { diff --git a/pkg/authserver/server/tokenexchange/authdetails.go b/pkg/authserver/server/tokenexchange/authdetails.go index bf630771b5..d8218484f2 100644 --- a/pkg/authserver/server/tokenexchange/authdetails.go +++ b/pkg/authserver/server/tokenexchange/authdetails.go @@ -30,6 +30,40 @@ const ( rejectHookFailed = "hook_failed" ) +// errRepeatedDetailsParam reports that the authorization_details parameter was +// sent more than once. Callers map it to their own error and log. +var errRepeatedDetailsParam = errors.New("authorization_details parameter repeated") + +// readDetailsParam reads the shape of the authorization_details form parameter. +// present is false when the parameter is absent or is one empty value. More +// than one value, empty ones included, is errRepeatedDetailsParam. +func readDetailsParam(form url.Values) (raw string, present bool, err error) { + values := form[authorizationDetailsParam] + switch { + case len(values) > 1: + return "", false, errRepeatedDetailsParam + case len(values) == 0, values[0] == "": + return "", false, nil + } + return values[0], true, nil +} + +// detailsSubject builds the hook Subject from validated claims. Audience and +// Claims are copied, so a hook cannot change the validated claims. +func detailsSubject(claims *ValidatedClaims) authorizationdetails.Subject { + return authorizationdetails.Subject{ + Issuer: claims.Issuer, + Subject: claims.Subject, + ClientID: claims.ClientID, + JWTID: claims.JWTID, + Audience: slices.Clone(claims.Audience), + IssuedAt: claims.IssuedAt, + Expiry: claims.Expiry, + External: claims.ExternalIssuer != "", + Claims: deepCopyClaims(claims.Claims), + } +} + // parseAuthorizationDetails runs the early, cheap shape checks. It returns a // nil Pending when the parameter is ignored: no registry is configured, or the // parameter is absent or empty. @@ -37,15 +71,16 @@ func (h *Handler) parseAuthorizationDetails(form url.Values, clientID string) (* if h.authorizationDetailsRegistry == nil { return nil, nil } - values := form[authorizationDetailsParam] - if len(values) == 0 || (len(values) == 1 && values[0] == "") { - return nil, nil - } - if len(values) > 1 { + raw, present, err := readDetailsParam(form) + // readDetailsParam's only error is errRepeatedDetailsParam. + if err != nil { warnAuthorizationDetailsRejected(clientID, rejectRepeated) return nil, repeatedAuthorizationDetailsError() } - pending, err := h.authorizationDetailsRegistry.Parse(values[0], oauthproto.GrantTypeTokenExchange) + if !present { + return nil, nil + } + pending, err := h.authorizationDetailsRegistry.Parse(raw, oauthproto.GrantTypeTokenExchange) if err != nil { warnAuthorizationDetailsRejected(clientID, rejectMalformed) return nil, invalidAuthorizationDetailsError() @@ -73,17 +108,7 @@ func (*Handler) grantAuthorizationDetails( RequestedTokenType: form.Get("requested_token_type"), RequestedScopes: slices.Clone([]string(requester.GetRequestedScopes())), GrantedAudience: slices.Clone([]string(requester.GetGrantedAudience())), - Subject: authorizationdetails.Subject{ - Issuer: claims.Issuer, - Subject: claims.Subject, - ClientID: claims.ClientID, - JWTID: claims.JWTID, - Audience: slices.Clone(claims.Audience), - IssuedAt: claims.IssuedAt, - Expiry: claims.Expiry, - External: claims.ExternalIssuer != "", - Claims: deepCopyClaims(claims.Claims), - }, + Subject: detailsSubject(claims), }) if err != nil { return authorizationDetailsGrantError(clientID, err) diff --git a/pkg/authserver/server/tokenexchange/exchange_grant.go b/pkg/authserver/server/tokenexchange/exchange_grant.go index e8a3529dbb..931825ab5c 100644 --- a/pkg/authserver/server/tokenexchange/exchange_grant.go +++ b/pkg/authserver/server/tokenexchange/exchange_grant.go @@ -97,14 +97,15 @@ func grantExchangeGrantShape(_ context.Context, req authorizationdetails.Request func parseExchangeGrantDetails( registry *authorizationdetails.Registry, form url.Values, ) (*authorizationdetails.Pending, error) { - values := form[authorizationDetailsParam] - if len(values) == 0 || (len(values) == 1 && values[0] == "") { - return nil, missingExchangeGrantDetailsError() - } - if len(values) > 1 { + raw, present, err := readDetailsParam(form) + // readDetailsParam's only error is errRepeatedDetailsParam. + if err != nil { return nil, repeatedAuthorizationDetailsError() } - pending, err := registry.Parse(values[0], oauthproto.GrantTypeTokenExchange) + if !present { + return nil, missingExchangeGrantDetailsError() + } + pending, err := registry.Parse(raw, oauthproto.GrantTypeTokenExchange) if err != nil { return nil, invalidAuthorizationDetailsError() } diff --git a/pkg/authserver/server/tokenexchange/exchange_grant_test.go b/pkg/authserver/server/tokenexchange/exchange_grant_test.go index de9853afe3..5303751d47 100644 --- a/pkg/authserver/server/tokenexchange/exchange_grant_test.go +++ b/pkg/authserver/server/tokenexchange/exchange_grant_test.go @@ -596,6 +596,20 @@ func TestParseExchangeGrantDetails(t *testing.T) { wantCode: "invalid_request", wantDesc: "The authorization_details parameter must not be repeated.", }, + { + name: "two empty values", + form: url.Values{authorizationDetailsParam: {"", ""}}, + wantFosite: true, + wantCode: "invalid_request", + wantDesc: "The authorization_details parameter must not be repeated.", + }, + { + name: "malformed JSON", + form: url.Values{authorizationDetailsParam: {"[{"}}, + wantFosite: true, + wantCode: "invalid_authorization_details", + wantDesc: "The authorization_details parameter is invalid.", + }, { name: "entry with no type", form: url.Values{authorizationDetailsParam: {`[{"issuable_token_types":["x"]}]`}}, diff --git a/pkg/authserver/server/tokenexchange/handler_test.go b/pkg/authserver/server/tokenexchange/handler_test.go index f508c34088..d85a94c1d6 100644 --- a/pkg/authserver/server/tokenexchange/handler_test.go +++ b/pkg/authserver/server/tokenexchange/handler_test.go @@ -3769,3 +3769,36 @@ func TestIssueBoundedAccessTokenBuildsElapsedErrorOnlyWhenElapsed(t *testing.T) }) } } + +// The WARN line for a refused authorization_details shape; a nil registry +// ignores the parameter and logs nothing. +// +//nolint:paralleltest // captures the process-global slog default +func TestTokenExchangeHandler_AuthorizationDetailsShapeLogs(t *testing.T) { + logs := captureLogs(t) + tj := newTestJWKS(t) + run := func(withRegistry bool, details []string) error { + h := newTestHandler(t, tj, 15*time.Minute) + if withRegistry { + h.authorizationDetailsRegistry = newDetailsRegistry(t, func(req authorizationdetails.Request) (authorizationdetails.Result, error) { + return authorizationdetails.Result{Entries: req.Entries}, nil + }) + } + form := defaultFormValues(t, tj) + form["authorization_details"] = details + return h.HandleTokenEndpointRequest(context.Background(), newAccessRequest(t, defaultClient(), form)) + } + + for reason, details := range map[string][]string{"repeated": {"", ""}, "malformed": {"[{"}} { + before := logs.String() + require.Error(t, run(true, details)) + added := strings.TrimPrefix(logs.String(), before) + assert.Contains(t, added, `msg="authorization_details rejected"`) + assert.Contains(t, added, "reason="+reason) + assert.Contains(t, added, "client_id="+testAgentClientID) + } + + before := logs.String() + require.NoError(t, run(false, []string{"[{"})) + assert.NotContains(t, strings.TrimPrefix(logs.String(), before), "authorization_details rejected") +} diff --git a/pkg/authserver/server/tokenexchange/refresh_token_handler.go b/pkg/authserver/server/tokenexchange/refresh_token_handler.go index 30a9c08cdb..11cf6be44a 100644 --- a/pkg/authserver/server/tokenexchange/refresh_token_handler.go +++ b/pkg/authserver/server/tokenexchange/refresh_token_handler.go @@ -681,11 +681,7 @@ func decideEntry( ClientID: clientID, Actor: clientID, RequestedTokenType: oauthproto.TokenTypeRefreshToken, - Subject: authorizationdetails.Subject{ - Issuer: claims.Issuer, Subject: claims.Subject, ClientID: claims.ClientID, JWTID: claims.JWTID, - Audience: slices.Clone(claims.Audience), IssuedAt: claims.IssuedAt, Expiry: claims.Expiry, - Claims: deepCopyClaims(claims.Claims), - }, + Subject: detailsSubject(claims), }) if err != nil { return nil, "", time.Time{}, err From 9110fb1298df1f8cd8012222798169085fbd7124 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Sun, 22 Nov 2026 22:57:17 +0100 Subject: [PATCH 2/2] Pin the authorization_details hook Subject The hook Subject at exchange-grant opening had no test, so a later change to detailsSubject could drop a field or stop copying Claims or Audience without any test failing. The later ID-JAG redemption change builds on detailsSubject, so this is the pin that matters most. Add a test that records the Request the exchange-grant hook gets and checks every Subject field, that External is false, and that Claims and Audience are copies. Add a test for the WARN line when an exchange-grant shape is refused, rows for ["",""] and ["","x"] in the token-exchange and exchange-grant tables, and require the token exchange WARN line to appear exactly once. Co-authored-by: Mecatl --- .../tokenexchange/exchange_grant_test.go | 7 ++ .../server/tokenexchange/handler_test.go | 20 ++++- .../refresh_token_handler_test.go | 83 +++++++++++++++++++ 3 files changed, 109 insertions(+), 1 deletion(-) diff --git a/pkg/authserver/server/tokenexchange/exchange_grant_test.go b/pkg/authserver/server/tokenexchange/exchange_grant_test.go index 5303751d47..59998ec03c 100644 --- a/pkg/authserver/server/tokenexchange/exchange_grant_test.go +++ b/pkg/authserver/server/tokenexchange/exchange_grant_test.go @@ -603,6 +603,13 @@ func TestParseExchangeGrantDetails(t *testing.T) { wantCode: "invalid_request", wantDesc: "The authorization_details parameter must not be repeated.", }, + { + name: "empty value with a second value", + form: url.Values{authorizationDetailsParam: {"", "x"}}, + wantFosite: true, + wantCode: "invalid_request", + wantDesc: "The authorization_details parameter must not be repeated.", + }, { name: "malformed JSON", form: url.Values{authorizationDetailsParam: {"[{"}}, diff --git a/pkg/authserver/server/tokenexchange/handler_test.go b/pkg/authserver/server/tokenexchange/handler_test.go index d85a94c1d6..4bb7056680 100644 --- a/pkg/authserver/server/tokenexchange/handler_test.go +++ b/pkg/authserver/server/tokenexchange/handler_test.go @@ -1297,6 +1297,7 @@ func TestTokenExchangeHandler_AuthorizationDetails(t *testing.T) { hookErr error wantError *fosite.RFC6749Error wantOAuthError string + wantStatus int wantDescription string wantCalls [][]string wantEntries string @@ -1313,6 +1314,20 @@ func TestTokenExchangeHandler_AuthorizationDetails(t *testing.T) { wantOAuthError: "invalid_request", wantDescription: "The authorization_details parameter must not be repeated.", }, + { + name: "two empty values", + details: []string{"", ""}, + wantOAuthError: "invalid_request", + wantStatus: http.StatusBadRequest, + wantDescription: "The authorization_details parameter must not be repeated.", + }, + { + name: "empty value with a second value", + details: []string{"", "x"}, + wantOAuthError: "invalid_request", + wantStatus: http.StatusBadRequest, + wantDescription: "The authorization_details parameter must not be repeated.", + }, { name: "malformed JSON is rejected before the subject token is checked", details: []string{"[{"}, @@ -1476,6 +1491,9 @@ func TestTokenExchangeHandler_AuthorizationDetails(t *testing.T) { require.ErrorAs(t, err, &rfcErr) assert.Equal(t, tt.wantOAuthError, rfcErr.ErrorField) assert.Equal(t, tt.wantDescription, rfcErr.DescriptionField) + if tt.wantStatus != 0 { + assert.Equal(t, tt.wantStatus, rfcErr.CodeField) + } case tt.wantError != nil: require.Error(t, err) assert.ErrorIs(t, err, tt.wantError) @@ -3793,7 +3811,7 @@ func TestTokenExchangeHandler_AuthorizationDetailsShapeLogs(t *testing.T) { before := logs.String() require.Error(t, run(true, details)) added := strings.TrimPrefix(logs.String(), before) - assert.Contains(t, added, `msg="authorization_details rejected"`) + assert.Equal(t, 1, strings.Count(added, `msg="authorization_details rejected"`)) assert.Contains(t, added, "reason="+reason) assert.Contains(t, added, "client_id="+testAgentClientID) } diff --git a/pkg/authserver/server/tokenexchange/refresh_token_handler_test.go b/pkg/authserver/server/tokenexchange/refresh_token_handler_test.go index 01cd4f7457..6d99608093 100644 --- a/pkg/authserver/server/tokenexchange/refresh_token_handler_test.go +++ b/pkg/authserver/server/tokenexchange/refresh_token_handler_test.go @@ -7,7 +7,9 @@ import ( "context" "errors" "log/slog" + "net/http" "net/url" + "slices" "strings" "sync" "testing" @@ -516,6 +518,87 @@ func TestRefreshTokenHandlerInternalFailureIsGeneric(t *testing.T) { } } +// TestRefreshTokenHandlerHookSubject covers the Subject and Request the +// exchange-grant hook receives when a grant is opened. +func TestRefreshTokenHandlerHookSubject(t *testing.T) { + t.Parallel() + + claims := validLoginClaims() + claims.IssuedAt = time.Now().Add(-5 * time.Minute) + claims.Audience = []string{testRefreshAPIAud, "https://other.example.com"} + claims.Claims = map[string]any{ + "nested": map[string]any{"k": "v"}, + "list": []any{"a", "b"}, + } + wantClaims := map[string]any{ + "nested": map[string]any{"k": "v"}, + "list": []any{"a", "b"}, + } + wantAudience := slices.Clone(claims.Audience) + + var recorded []authorizationdetails.Request + registry, err := authorizationdetails.New(map[string]authorizationdetails.Type{ + exchangeGrantType: { + GrantTypes: []string{oauthproto.GrantTypeTokenExchange}, + Grant: func(ctx context.Context, req authorizationdetails.Request) (authorizationdetails.Result, error) { + recorded = append(recorded, req) + return grantExchangeGrantShape(ctx, req) + }, + }, + }) + require.NoError(t, err) + + h := newRefreshHandlerForTest(t, &stubSubjectValidator{claims: claims}, &fakeGrantStore{}) + h.registry = registry + require.NoError(t, h.HandleTokenEndpointRequest(t.Context(), refreshRequestForTest(brokerClientForTest()))) + + require.Len(t, recorded, 1) + got := recorded[0] + assert.Equal(t, testRefreshClient, got.ClientID) + assert.Equal(t, testRefreshClient, got.Actor) + assert.Equal(t, oauthproto.TokenTypeRefreshToken, got.RequestedTokenType) + + subject := got.Subject + assert.Equal(t, claims.Issuer, subject.Issuer) + assert.Equal(t, claims.Subject, subject.Subject) + assert.Equal(t, claims.ClientID, subject.ClientID) + assert.Equal(t, claims.JWTID, subject.JWTID) + assert.Equal(t, wantAudience, subject.Audience) + assert.Equal(t, claims.IssuedAt, subject.IssuedAt) + assert.Equal(t, claims.Expiry, subject.Expiry) + assert.False(t, subject.External) + assert.Equal(t, wantClaims, subject.Claims) + + subject.Claims["nested"].(map[string]any)["k"] = "changed" + subject.Claims["list"].([]any)[0] = "changed" + subject.Claims["added"] = true + subject.Audience[0] = "changed" + assert.Equal(t, wantClaims, claims.Claims, "the hook gets a copy of the claims") + assert.Equal(t, wantAudience, claims.Audience, "the hook gets a copy of the audience") +} + +// A refused exchange-grant shape is logged once at WARN with its reason. +// +//nolint:paralleltest // captures the process-global slog default +func TestRefreshTokenHandlerShapeRefusalLog(t *testing.T) { + logs := captureLogs(t) + h := newRefreshHandlerForTest(t, &stubSubjectValidator{claims: validLoginClaims()}, &fakeGrantStore{}) + req := refreshRequestForTest(brokerClientForTest()) + req.Form["authorization_details"] = []string{"", ""} + + err := h.HandleTokenEndpointRequest(t.Context(), req) + + var oauthErr *fosite.RFC6749Error + require.ErrorAs(t, err, &oauthErr) + assert.Equal(t, http.StatusBadRequest, oauthErr.CodeField) + assert.Equal(t, "invalid_request", oauthErr.ErrorField) + assert.Equal(t, "The authorization_details parameter must not be repeated.", oauthErr.GetDescription()) + out := logs.String() + assert.Equal(t, 1, strings.Count(out, `msg="Exchange grant refused"`)) + assert.Contains(t, out, "level=WARN") + assert.Contains(t, out, "reason="+refuseDetailsInvalid) +} + // TestRefreshTokenHandlerDecidesAgainBeforeIssuing covers a subject token that // stops being acceptable, or is consumed, between handling and the response. func TestRefreshTokenHandlerDecidesAgainBeforeIssuing(t *testing.T) {