From 0efb519c6ef8e14936bbed1d025db6a59c9fdde7 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 19:17:32 +0800 Subject: [PATCH 1/9] fix(server): refuse embedder claims whose JSON members conflict GrantedAuthorization.IDTokenClaims values are raw JSON, and validateGrantedIDTokenClaims did not look inside them for repeated member names. Since every JWT claims parser here refuses a claims set that repeats a member with differing copies, or as a case variant, at any depth, the server could issue an ID token its own client refuses, and that other readers decode differently (one keeping the first copy, another the last). The nightly fuzz job found it with {"":0,"":1}. Add strictjson.CheckConflictingObject, which applies CheckConflictingMembers to an object given as its members, names the member at fault, and also refuses two names that differ only in case. Use it in: - validateGrantedIDTokenClaims, so CompleteAuthorization and CompleteBackchannelAuthentication refuse such claims with invalid_request; - token.IssueIDToken and IssueAccessToken, so a value only known at the token endpoint (an IdentityClaimsSource's, or one in a grant stored earlier) fails as server_error instead of being signed; - SignUserInfoResponse, which refuses such claims as server_error. A plain "claims" parameter at PAR or the backchannel endpoint that repeats a member with differing copies, or as a case variant, is now invalid_request, as a request object carrying it already was: the values it requests are carried into the access token. The fuzz input is added to the FuzzGrantedIDTokenClaims corpus. Co-Authored-By: Claude Opus 5.5 --- internal/strictjson/members_conflict.go | 35 ++++++++++++++++ .../strictjson/members_conflict_fuzz_test.go | 26 ++++++++++++ internal/strictjson/members_conflict_test.go | 41 +++++++++++++++++++ internal/token/duplicate_claims_test.go | 40 ++++++++++++++++++ internal/token/issue.go | 11 ++++- server/claims_parameter.go | 10 +++++ server/claims_parameter_internal_test.go | 8 ++++ server/claims_parameter_test.go | 4 ++ server/error_description_internal_test.go | 2 + server/granted_id_token_claims.go | 7 ++++ server/granted_id_token_claims_test.go | 32 +++++++++++++++ server/identity_claims.go | 6 +++ server/subject.go | 7 +++- .../FuzzGrantedIDTokenClaims/075b3c05cb8e8e8f | 3 ++ server/token.go | 5 ++- server/userinfo.go | 14 ++++++- server/userinfo_test.go | 34 +++++++++++++++ 17 files changed, 281 insertions(+), 4 deletions(-) create mode 100644 server/testdata/fuzz/FuzzGrantedIDTokenClaims/075b3c05cb8e8e8f diff --git a/internal/strictjson/members_conflict.go b/internal/strictjson/members_conflict.go index f4cffa4d..59f5257c 100644 --- a/internal/strictjson/members_conflict.go +++ b/internal/strictjson/members_conflict.go @@ -6,6 +6,8 @@ import ( "errors" "fmt" "io" + "maps" + "slices" ) // CheckConflictingMembers is CheckDuplicateMembers, except that it @@ -44,6 +46,39 @@ func CheckConflictingMembers(data []byte) error { return walkConflictingMembers(data) } +// CheckConflictingObject is CheckConflictingMembers for the JSON object +// whose members are members, each value already encoded, without +// encoding it: an issuer building a JWT's claims set, or another +// object, from values a caller supplied refuses what a reader running +// CheckConflictingMembers on the result would refuse. It refuses a +// value that isn't valid JSON, or that CheckConflictingMembers refuses +// as a member of the object (one level deeper than on its own), and a +// name FoldKey maps together with another's. It returns the name at +// fault, the first in sorted order, so a caller can say which member it +// refuses. Every member is the object's own (a Go map can't repeat a +// name exactly), so only case variants can repeat a name at the top. +func CheckConflictingObject(members map[string]json.RawMessage) (string, error) { + seen := make(map[string]string, len(members)) // by FoldKey, the name as spelled + for _, name := range slices.Sorted(maps.Keys(members)) { + key := FoldKey(name) + if first, ok := seen[key]; ok { + return name, duplicateMemberError(first, name) + } + seen[key] = name + value := members[name] + if !json.Valid(value) { + return name, fmt.Errorf("strictjson: member %q is not valid JSON", name) + } + // Inside "[...]" the value nests as deeply as inside the object. + nested := make([]byte, 0, len(value)+2) + nested = append(append(append(nested, '['), value...), ']') + if err := CheckConflictingMembers(nested); err != nil { + return name, err + } + } + return "", nil +} + // UnmarshalNoConflicts is Unmarshal, after CheckConflictingMembers: it // refuses a member name repeated in one object with differing copies, // or as a case variant, and accepts one repeated with identical copies, diff --git a/internal/strictjson/members_conflict_fuzz_test.go b/internal/strictjson/members_conflict_fuzz_test.go index df608b8c..42843836 100644 --- a/internal/strictjson/members_conflict_fuzz_test.go +++ b/internal/strictjson/members_conflict_fuzz_test.go @@ -102,3 +102,29 @@ func readFirstWinsObject(dec *json.Decoder) (any, bool) { _, err := dec.Token() return out, err == nil } + +// FuzzCheckConflictingObject: an object whose members +// CheckConflictingObject accepts encodes, with json.Marshal or +// MarshalUnescaped, to one CheckConflictingMembers accepts — what an +// issuer checks with it, a reader accepts. +func FuzzCheckConflictingObject(f *testing.F) { + f.Add("a", []byte(`{"b":1,"b":1}`), "A", []byte(`1`)) + f.Add("0", []byte(`{"":0,"":1}`), "x", []byte(`"<"`)) + f.Add("a\xff", []byte(`1`), "a\xfe", []byte(`2`)) + f.Add("x", []byte(`{"a":"<","a":"<"}`), "y", []byte(`[]`)) + f.Fuzz(func(t *testing.T, name1 string, value1 []byte, name2 string, value2 []byte) { + members := map[string]json.RawMessage{name1: value1, name2: value2} + if _, err := CheckConflictingObject(members); err != nil { + return + } + for _, marshal := range []func(any) ([]byte, error){json.Marshal, MarshalUnescaped} { + encoded, err := marshal(members) + if err != nil { + t.Fatalf("%q: accepted, but doesn't encode: %v", members, err) + } + if err := CheckConflictingMembers(encoded); err != nil { + t.Fatalf("%q: accepted, but its encoding %s is refused: %v", members, encoded, err) + } + } + }) +} diff --git a/internal/strictjson/members_conflict_test.go b/internal/strictjson/members_conflict_test.go index 00c2b21d..09b190d2 100644 --- a/internal/strictjson/members_conflict_test.go +++ b/internal/strictjson/members_conflict_test.go @@ -135,3 +135,44 @@ func TestUnmarshalNoConflicts(t *testing.T) { } } } + +// TestCheckConflictingObject: CheckConflictingObject refuses, naming the +// member at fault, the objects whose encoding CheckConflictingMembers +// refuses — a value repeating a member with differing copies or as a +// case variant, at any depth; two member names that differ only in +// case; a value nesting too deep once inside the object; and a value +// that isn't JSON — and accepts the rest, an identical repeat included. +func TestCheckConflictingObject(t *testing.T) { + deep := strings.Repeat("[", MaxNestingDepth) + strings.Repeat("]", MaxNestingDepth) + if err := CheckConflictingMembers([]byte(deep)); err != nil { + t.Fatalf("CheckConflictingMembers(%d nested arrays) = %v, want nil on its own", MaxNestingDepth, err) + } + for name, tc := range map[string]struct { + members map[string]json.RawMessage + fault string + }{ + "no members": {members: map[string]json.RawMessage{}}, + "plain": {members: map[string]json.RawMessage{"a": json.RawMessage(`1`), "b": json.RawMessage(`{"c":[1,{"d":2}]}`)}}, + "identical repeat": {members: map[string]json.RawMessage{"act": json.RawMessage(`{"sub":"a", "sub" : "a"}`)}}, + "differing repeat": {members: map[string]json.RawMessage{"a": json.RawMessage(`1`), "act": json.RawMessage(`{"sub":"a","sub":"b"}`)}, fault: "act"}, + "empty-name repeat": {members: map[string]json.RawMessage{"0": json.RawMessage(`{"":0,"":1}`)}, fault: "0"}, + "nested repeat": {members: map[string]json.RawMessage{"x": json.RawMessage(`[{"y":{"z":1,"z":2}}]`)}, fault: "x"}, + "case variant": {members: map[string]json.RawMessage{"x": json.RawMessage(`{"kid":"a","KID":"a"}`)}, fault: "x"}, + "top-level case": {members: map[string]json.RawMessage{"roles": json.RawMessage(`1`), "Roles": json.RawMessage(`1`)}, fault: "roles"}, + "too deep inside": {members: map[string]json.RawMessage{"x": json.RawMessage(deep)}, fault: "x"}, + "not JSON": {members: map[string]json.RawMessage{"x": json.RawMessage(`1],[2`)}, fault: "x"}, + } { + t.Run(name, func(t *testing.T) { + fault, err := CheckConflictingObject(tc.members) + if (err != nil) != (tc.fault != "") || fault != tc.fault { + t.Fatalf("CheckConflictingObject = %q, %v; want fault %q", fault, err, tc.fault) + } + if tc.fault == "" { + return + } + if encoded, merr := MarshalUnescaped(tc.members); merr == nil && CheckConflictingMembers(encoded) == nil { + t.Fatalf("CheckConflictingObject refuses %s, which CheckConflictingMembers accepts", encoded) + } + }) + } +} diff --git a/internal/token/duplicate_claims_test.go b/internal/token/duplicate_claims_test.go index 7fa71a53..32720b5a 100644 --- a/internal/token/duplicate_claims_test.go +++ b/internal/token/duplicate_claims_test.go @@ -1,9 +1,11 @@ package token import ( + "encoding/json" "errors" "strings" "testing" + "time" ) // TestParseClaimsRefuseDuplicateMembers: RFC 7519 §4 requires a JWT's @@ -54,3 +56,41 @@ func checkDuplicateRefusal(t *testing.T, err error, wantErr bool) { t.Fatalf("parse = %v, want ErrMalformedClaims for a duplicate member", err) } } + +// TestIssueRefusesParametersItsParsersRefuse: IssueIDToken and +// IssueAccessToken refuse Parameters that ParseIDToken and +// ParseAccessToken would refuse once signed in — a value repeating a +// member with differing copies, or as a case variant, at any depth, and +// two names that differ only in case — rather than sign a token its +// readers take different claims from. An identical repeat is issued. +func TestIssueRefusesParametersItsParsersRefuse(t *testing.T) { + key := generateKey(t) + now := time.Now() + issue := map[string]func(map[string]json.RawMessage) (string, error){ + "ID token": func(params map[string]json.RawMessage) (string, error) { + p := baseIDTokenParams(key, now, time.Minute) + p.Parameters = params + return IssueIDToken(p) + }, + "access token": func(params map[string]json.RawMessage) (string, error) { + p := baseAccessTokenParams(key, now, time.Minute) + p.Parameters = params + tok, _, err := IssueAccessToken(p) + return tok, err + }, + } + for kind, issue := range issue { + if _, err := issue(map[string]json.RawMessage{"act": json.RawMessage(`{"sub":"a","sub":"a"}`)}); err != nil { + t.Errorf("%s with an identical repeat: %v, want issued", kind, err) + } + for name, params := range map[string]map[string]json.RawMessage{ + "differing repeat": {"act": json.RawMessage(`{"sub":"a","sub":"b"}`)}, + "nested variant": {"x": json.RawMessage(`[{"kid":"a","KID":"a"}]`)}, + "case-variant": {"roles": json.RawMessage(`1`), "ROLES": json.RawMessage(`1`)}, + } { + if tok, err := issue(params); err == nil { + t.Errorf("%s, %s: issued %s, want refused", kind, name, tok) + } + } + } +} diff --git a/internal/token/issue.go b/internal/token/issue.go index fe919c26..8c2c8eb6 100644 --- a/internal/token/issue.go +++ b/internal/token/issue.go @@ -167,13 +167,22 @@ func IssueAccessToken(p AccessTokenParams) (token string, jti string, err error) // checkReservedParameters refuses parameters that use a name // claimnames reserves in a JWT of kind against the embedder — the // claims IssueIDToken/IssueAccessToken set themselves, and the ones -// that would change how a recipient processes the token. +// that would change how a recipient processes the token. It refuses, +// too, parameters ParseIDToken and ParseAccessToken would refuse once +// signed into the claims set (strictjson.CheckConflictingObject): a +// value repeating a member with differing copies, or as a case +// variant, at any depth, and two names that differ only in case. +// Readers keeping the first copy and the last would take different +// claims from such a token. func checkReservedParameters(kind claimnames.Kind, parameters map[string]json.RawMessage) error { for name := range parameters { if claimnames.Reserved(kind, claimnames.Embedder, name) { return fmt.Errorf("token: parameters must not set reserved claim %q", name) } } + if name, err := strictjson.CheckConflictingObject(parameters); err != nil { + return fmt.Errorf("token: parameter %q would not parse: %w", name, err) + } return nil } diff --git a/server/claims_parameter.go b/server/claims_parameter.go index 3d008030..cff608bc 100644 --- a/server/claims_parameter.go +++ b/server/claims_parameter.go @@ -55,6 +55,16 @@ func validateClaimsParameter(params map[string]json.RawMessage) error { if !strictjson.DecodesLosslessly(raw) || !strictjson.DecodesLosslessly(object) { return errClaimsNotLossless } + // A request object repeating a member with differing copies, or as + // a case variant, at any depth is refused (requestobject.Parse), and + // so is the same "claims" object sent as a plain parameter: the + // values it requests are carried into the access token + // (RequestedUserinfoClaimValuesKey), which resource servers, this + // module's included, then refuse, or read differently from one + // another. + if err := strictjson.CheckConflictingMembers(object); err != nil { + return errors.New("claims must not repeat a member name with differing values, or in another case") + } // object is already unwrapped: claimsMembers(object) would unwrap a // second string layer, which no reader does. top, ok := objectMembers(object) diff --git a/server/claims_parameter_internal_test.go b/server/claims_parameter_internal_test.go index fbf8c421..4a5eb398 100644 --- a/server/claims_parameter_internal_test.go +++ b/server/claims_parameter_internal_test.go @@ -44,6 +44,14 @@ func TestValidateClaimsParameter(t *testing.T) { "sub value encoded twice": {twice(`{"id_token":{"sub":{"value":"user-1"}}}`), false}, "empty object encoded twice": {twice(`{}`), false}, "encoded three times": {str(string(twice(`{}`))), false}, + // A member repeated with differing copies, or as a case variant, + // at any depth, as a request object carrying it would be; an + // identical repeat is read alike by every reader. + "identical repeat": {json.RawMessage(`{"userinfo":{"email":null,"email":null}}`), true}, + "repeated value": {json.RawMessage(`{"userinfo":{"x":{"value":{"a":1,"a":2}}}}`), false}, + "repeated claim, form string": {str(`{"id_token":{"email":null,"email":{"essential":true}}}`), false}, + "case-variant claim": {json.RawMessage(`{"userinfo":{"email":null,"EMAIL":null}}`), false}, + "repeated top-level, differing": {json.RawMessage(`{"id_token":{},"id_token":{"acr":null}}`), false}, } { t.Run(name, func(t *testing.T) { err := validateClaimsParameter(map[string]json.RawMessage{"claims": tc.raw}) diff --git a/server/claims_parameter_test.go b/server/claims_parameter_test.go index 6f9d1d6b..787ce56f 100644 --- a/server/claims_parameter_test.go +++ b/server/claims_parameter_test.go @@ -18,6 +18,10 @@ func TestMalformedClaimsParameterIsRefused(t *testing.T) { // so it's refused rather than silently honoured or ignored. "ID_TOKEN": `{"ID_TOKEN":{"acr":{"essential":true,"values":["gold"]}}}`, "Essential": `{"id_token":{"acr":{"Essential":true,"values":["gold"]}}}`, + // A member repeated with differing copies, or as a case variant, + // as a request object carrying it would be refused. + "repeated value": `{"userinfo":{"email":{"value":{"a":1,"a":2}}}}`, + "case-variant claim": `{"userinfo":{"email":null,"Email":null}}`, } { t.Run("PAR "+name, func(t *testing.T) { h := newHarness(t, server.ProfileFAPISecurity, true) diff --git a/server/error_description_internal_test.go b/server/error_description_internal_test.go index 7baae0c9..1fb998ab 100644 --- a/server/error_description_internal_test.go +++ b/server/error_description_internal_test.go @@ -58,6 +58,8 @@ var reviewedDescriptions = map[string]bool{ "clientAssertionFailureDescription(err, audiences)": true, // the application's own claim name, a server_error. `fmt.Sprintf("userinfo claims must not set reserved claim %q", name)`: true, + // the application's own claim name, a server_error. + `fmt.Sprintf("userinfo claim %q conflicts with another member of the same name: JSON members may repeat only with identical values, and never in another case", name)`: true, } // TestNewErrorDescriptionsNameNoRequestInput walks every newError call diff --git a/server/granted_id_token_claims.go b/server/granted_id_token_claims.go index 648e6445..5b933e59 100644 --- a/server/granted_id_token_claims.go +++ b/server/granted_id_token_claims.go @@ -55,6 +55,13 @@ func validateGrantedIDTokenClaims(claims map[string]json.RawMessage, maxBytes in return fmt.Errorf("ID token claim %q is not valid UTF-8, or has an unpaired surrogate escape", name) } } + // Relying parties, this module's client included, refuse an ID token + // that repeats a member with differing copies, or as a case variant, + // at any depth: readers keeping the first copy and the last would + // take different claims from it (RFC 7519 §4). + if name, err := strictjson.CheckConflictingObject(claims); err != nil { + return fmt.Errorf("ID token claim %q conflicts with another member of the same name: JSON members may repeat only with identical values, and never in another case", name) + } return nil } diff --git a/server/granted_id_token_claims_test.go b/server/granted_id_token_claims_test.go index acdf2ec7..56fe66ae 100644 --- a/server/granted_id_token_claims_test.go +++ b/server/granted_id_token_claims_test.go @@ -176,6 +176,12 @@ func invalidGrantedIDTokenClaims() map[string]map[string]json.RawMessage { // newHarness sets Limits.MaxIDTokenClaimsBytes to 4096. "over size budget": {"sub_attributes": json.RawMessage(`"` + strings.Repeat("x", 4096) + `"`)}, "invalid JSON": {"sub_type": json.RawMessage(`user`)}, + // Relying parties refuse an ID token repeating a member with + // differing copies, or as a case variant, at any depth. + "repeated member": {"act": json.RawMessage(`{"sub":"delegate-1","sub":"delegate-2"}`)}, + "repeated empty member": {"x": json.RawMessage(`{"":0,"":1}`)}, + "nested case variant": {"sub_attributes": json.RawMessage(`[{"tier":"gold","Tier":"gold"}]`)}, + "case-variant claim name": {"roles": json.RawMessage(`["admin"]`), "Roles": json.RawMessage(`["admin"]`)}, } } @@ -277,3 +283,29 @@ func TestExchangeAuthorizationCodeRejectsIDTokenClaimsOverBudget(t *testing.T) { t.Fatalf("error code = %q, want %q", code, server.ErrorServerError) } } + +// TestExchangeAuthorizationCodeRefusesConflictingIdentityClaims: an +// identity claim is only resolved at the token endpoint, so one whose +// value repeats a member with differing copies, or as a case variant, +// fails there, as server_error, rather than issuing an ID token relying +// parties, this module's client included, refuse. +func TestExchangeAuthorizationCodeRefusesConflictingIdentityClaims(t *testing.T) { + for name, value := range map[string]json.RawMessage{ + "differing repeat": json.RawMessage(`{"country":"A","country":"B"}`), + "case variant": json.RawMessage(`{"country":"A","Country":"A"}`), + } { + t.Run(name, func(t *testing.T) { + identityClaims := fakeIdentityClaims{subject: "user-1", claims: map[string]json.RawMessage{"address": value}} + h := newHarnessWithIdentityClaims(t, identityClaims) + code := completeAuthorizationWithClaims(t, h, `{"id_token":{"address":null}}`) + + result, err := h.server.ExchangeAuthorizationCode(context.Background(), server.AuthorizationCodeExchangeRequest{ + HTTP: server.FormRequest{Parameters: exchangeFormParams(h.clientAssertion(t), code, testRedirectURI, testCodeVerifier)}, + DPoPProofs: []string{createDPoPProof(t, generateKey(t), h.now)}, + }) + if code := serverErrorCode(t, err); code != server.ErrorServerError { + t.Fatalf("error code = %q, want %q (result %+v)", code, server.ErrorServerError, result) + } + }) + } +} diff --git a/server/identity_claims.go b/server/identity_claims.go index cf8150cc..0f22f58e 100644 --- a/server/identity_claims.go +++ b/server/identity_claims.go @@ -43,6 +43,12 @@ type IdentityClaimsSource interface { // server, and serverresource.UserInfoClaims, drop it otherwise, so a // source returns the claim's real value and needn't look at the // request. + // + // A value must not repeat a member name with differing copies, or as + // a case variant, at any depth: relying parties, this module's + // client included, refuse an ID token or UserInfo response carrying + // one, so the token request it would go into fails as server_error, + // and serverresource.UserInfoClaims returns an error. ResolveIdentityClaims(ctx context.Context, subject string, names []string) (map[string]json.RawMessage, error) } diff --git a/server/subject.go b/server/subject.go index f222cfb2..3c51254c 100644 --- a/server/subject.go +++ b/server/subject.go @@ -198,7 +198,12 @@ type GrantedAuthorization struct { // _claim_sources, sub_jwk and events, which change how a relying // party processes the token; and code, state and error, which would // make it look like a JARM response — a name that isn't valid UTF-8, - // a value that isn't valid JSON, and claims whose total size exceeds + // a value that isn't valid JSON, a value that repeats a member name + // with differing copies, or as a case variant, at any depth, two + // names that differ only in case (relying parties, this module's + // client included, refuse an ID token carrying either, which readers + // keeping the first copy and the last would read differently), and + // claims whose total size exceeds // Limits.MaxIDTokenClaimsBytes, a budget identity and extension // claims share at issuance. Authorization attributes (RFC 9068 // roles, groups, entitlements) and delegation claims (RFC 8693 act, diff --git a/server/testdata/fuzz/FuzzGrantedIDTokenClaims/075b3c05cb8e8e8f b/server/testdata/fuzz/FuzzGrantedIDTokenClaims/075b3c05cb8e8e8f new file mode 100644 index 00000000..0fcd61b6 --- /dev/null +++ b/server/testdata/fuzz/FuzzGrantedIDTokenClaims/075b3c05cb8e8e8f @@ -0,0 +1,3 @@ +go test fuzz v1 +string("0") +[]byte("{\"\":0,\"\":1}") diff --git a/server/token.go b/server/token.go index 6c3960a7..aa63ea31 100644 --- a/server/token.go +++ b/server/token.go @@ -1006,7 +1006,10 @@ func withRequestedUserinfoClaims(names []string, values claimvalues.Acceptable, // Limits.MaxIDTokenClaimsBytes; identity claims are only known here, so // this — not CompleteAuthorization — is where the whole budget is // checked, failing as server_error rather than issuing a token a relying -// party would reject. nonce is grant.Nonce for the first ID token issued +// party would reject. So, in token.IssueIDToken, is an identity claim +// whose value repeats a member with differing copies, or as a case +// variant, or whose name differs only in case from another claim's. +// nonce is grant.Nonce for the first ID token issued // from an authorization code, "" otherwise. func (s *Server) issueIDTokenForGrant(ctx context.Context, client storage.RegisteredClient, grant grantRecord, nonce, accessToken string) (string, *Error) { claims, err := s.withIdentityClaims(ctx, grant.Subject, grant.RequestedIDTokenClaims, grant.RequestedIDTokenClaimValues, grant.TokenClaims) diff --git a/server/userinfo.go b/server/userinfo.go index 89e480cf..f4f97e0c 100644 --- a/server/userinfo.go +++ b/server/userinfo.go @@ -11,6 +11,7 @@ import ( "github.com/idfoundry/fapigo/internal/claimnames" "github.com/idfoundry/fapigo/internal/jose" "github.com/idfoundry/fapigo/internal/jwe" + "github.com/idfoundry/fapigo/internal/strictjson" "github.com/idfoundry/fapigo/keys" "github.com/idfoundry/fapigo/pairwise" "github.com/idfoundry/fapigo/storage" @@ -47,7 +48,12 @@ import ( // events, which change how a relying party processes the response; // azp, nonce, at_hash, c_hash and s_hash, which belong to an ID token; // and code, state and error, by whose presence a relying party tells a -// JARM response from another JWT of the same issuer and audience. +// JARM response from another JWT of the same issuer and audience. And +// it fails if a claim's value repeats a member with differing copies, +// or as a case variant, at any depth, or two claim names differ only in +// case: relying parties, this module's client included, refuse such a +// response, and readers keeping the first copy and the last would take +// different claims from it. // // claims must carry "sub", a non-empty string: OIDC Core §5.3.2 says it // "MUST always be returned in the UserInfo Response". For a client that @@ -73,6 +79,12 @@ func (s *Server) SignUserInfoResponse(ctx context.Context, client storage.Regist return "", newError(ErrorServerError, 500, fmt.Sprintf("userinfo claims must not set reserved claim %q", name), nil) } } + // A relying party, this module's client included, refuses a UserInfo + // response repeating a member with differing copies, or as a case + // variant, at any depth. + if name, err := strictjson.CheckConflictingObject(claims); err != nil { + return "", newError(ErrorServerError, 500, fmt.Sprintf("userinfo claim %q conflicts with another member of the same name: JSON members may repeat only with identical values, and never in another case", name), err) + } if subErr := s.checkUserInfoSubject(ctx, client, claims["sub"]); subErr != nil { return "", subErr } diff --git a/server/userinfo_test.go b/server/userinfo_test.go index dd186921..acdf2000 100644 --- a/server/userinfo_test.go +++ b/server/userinfo_test.go @@ -5,6 +5,7 @@ import ( "crypto/rand" "crypto/rsa" "encoding/json" + "maps" "testing" "time" @@ -181,6 +182,39 @@ func TestSignUserInfoResponseRejectsReservedClaims(t *testing.T) { } } +// TestSignUserInfoResponseRefusesConflictingMembers: a relying party, +// this module's client included, refuses a UserInfo response repeating +// a member with differing copies, or as a case variant, at any depth, +// so SignUserInfoResponse refuses claims that would make one — a +// claim's value or two claim names differing only in case — rather +// than sign a response its readers take different claims from. An +// identical repeat is signed. +func TestSignUserInfoResponseRefusesConflictingMembers(t *testing.T) { + h, client := newHarnessWithUserInfo(t, nil, nil, 0, 0, nil) + sign := func(extra map[string]json.RawMessage) *server.Error { + claims := testUserInfoClaims(t) + maps.Copy(claims, extra) + _, srvErr := h.server.SignUserInfoResponse(context.Background(), client, claims) + return srvErr + } + if srvErr := sign(map[string]json.RawMessage{"address": json.RawMessage(`{"country":"A","country":"A"}`)}); srvErr != nil { + t.Fatalf("SignUserInfoResponse with an identical repeat: %v", srvErr) + } + for name, extra := range map[string]map[string]json.RawMessage{ + "differing repeat": {"address": json.RawMessage(`{"country":"A","country":"B"}`)}, + "nested variant": {"groups": json.RawMessage(`[{"id":"a","ID":"a"}]`)}, + "name variant": {"Email": json.RawMessage(`"other@example.com"`)}, + } { + srvErr := sign(extra) + if srvErr == nil { + t.Fatalf("%s: SignUserInfoResponse = nil error, want error", name) + } + if srvErr.Code() != server.ErrorServerError { + t.Fatalf("%s: error code = %q, want %q", name, srvErr.Code(), server.ErrorServerError) + } + } +} + // TestSignUserInfoResponseRequiresSub: OIDC Core §5.3.2, "The sub // (subject) Claim MUST always be returned in the UserInfo Response" — a // public-subject client's response without one, or with one that isn't From 580a2be13b5c175ca56ee06c84a58ddd6384e902 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 19:17:46 +0800 Subject: [PATCH 2/9] fix(serverresource): refuse UserInfo claims whose JSON members conflict UserInfoClaims copied each value its IdentityClaimsSource returned into the UserInfo response unchecked. A value repeating a member with differing copies, or as a case variant, at any depth, or a requested claim named as a case variant of another ("Sub" beside the "sub" it sets), made a response this module's client refuses and other readers decode differently. UserInfoClaims now returns an error for one. Co-Authored-By: Claude Opus 5.5 --- serverresource/userinfo.go | 11 +++++++++++ serverresource/userinfo_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/serverresource/userinfo.go b/serverresource/userinfo.go index 15bf4cd5..d8d41c46 100644 --- a/serverresource/userinfo.go +++ b/serverresource/userinfo.go @@ -12,6 +12,7 @@ import ( "github.com/idfoundry/fapigo/internal/claimnames" "github.com/idfoundry/fapigo/internal/claimvalues" "github.com/idfoundry/fapigo/internal/resourceerr" + "github.com/idfoundry/fapigo/internal/strictjson" "github.com/idfoundry/fapigo/resource" "github.com/idfoundry/fapigo/server" "github.com/idfoundry/fapigo/storage" @@ -45,6 +46,9 @@ import ( // - a client credentials token (resource.SubjectClient) is refused as // a 403 insufficient_scope: it names no end user. // +// A claim whose value repeats a member name with differing copies, or +// as a case variant, at any depth, or whose name differs only in case +// from another's, is an error: relying parties refuse such a response. // A requested-claims entry the token carries malformed is an error, not // an empty request. An error from source is returned wrapped. Sign the // result with SignUserInfoResponse when the client registered for @@ -80,6 +84,13 @@ func UserInfoClaims(ctx context.Context, authz resource.AuthorizationContext, so } // A string always encodes. claims["sub"], _ = json.Marshal(clientSubjectOf(authz)) + // A relying party, this module's client included, refuses a UserInfo + // response repeating a member with differing copies, or as a case + // variant, at any depth, and readers keeping the first copy and the + // last would take different claims from it. + if name, err := strictjson.CheckConflictingObject(claims); err != nil { + return nil, fmt.Errorf("serverresource: UserInfo claim %q from the claims source conflicts with another member of the same name: %w", name, err) + } return claims, nil } diff --git a/serverresource/userinfo_test.go b/serverresource/userinfo_test.go index 4b31b8c7..4d9a28a6 100644 --- a/serverresource/userinfo_test.go +++ b/serverresource/userinfo_test.go @@ -185,3 +185,32 @@ func TestUserInfoClaimsHonoursRequestedValues(t *testing.T) { t.Error("UserInfoClaims(malformed requested claim values) = nil error") } } + +// fixedSource returns claims, whatever it's asked for. +type fixedSource map[string]json.RawMessage + +func (s fixedSource) ResolveIdentityClaims(context.Context, string, []string) (map[string]json.RawMessage, error) { + return s, nil +} + +// TestUserInfoClaimsRefusesConflictingMembers: a relying party, this +// module's client included, refuses a UserInfo response repeating a +// member with differing copies, or as a case variant, at any depth, so +// a claim the source returns that would make one is an error, rather +// than a response its readers take different claims from. An +// identical repeat is returned. +func TestUserInfoClaimsRefusesConflictingMembers(t *testing.T) { + authz := authzFor([]string{"openid"}, `["address","Sub"]`) + if _, err := serverresource.UserInfoClaims(context.Background(), authz, fixedSource{"address": json.RawMessage(`{"country":"A","country":"A"}`)}); err != nil { + t.Fatalf("UserInfoClaims with an identical repeat: %v", err) + } + for name, source := range map[string]fixedSource{ + "differing repeat": {"address": json.RawMessage(`{"country":"A","country":"B"}`)}, + "nested variant": {"address": json.RawMessage(`{"lines":[{"n":1,"N":1}]}`)}, + "variant of sub": {"Sub": json.RawMessage(`"someone-else"`)}, + } { + if claims, err := serverresource.UserInfoClaims(context.Background(), authz, source); err == nil { + t.Errorf("%s: UserInfoClaims = %s, want an error", name, claims) + } + } +} From 6cc90a3e4d14db7fa02f0781b77c49bf4c8dea5d Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 19:17:46 +0800 Subject: [PATCH 3/9] fix(federation): refuse resolved metadata whose JSON members conflict ResolveIssuer.Response signed ResolvedEntity.Metadata as given. A Resolver's own resolution never repeats a member, but a hand-built ResolvedEntity could, and a Resolve Response repeating a member with differing copies, or as a case variant, at any depth is refused by its readers, this module's included, and read differently by others. Response now refuses such metadata, as filtered to the requested Entity Types. Co-Authored-By: Claude Opus 5.5 --- federation/resolve_issue.go | 13 +++++++++++++ federation/resolve_issue_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/federation/resolve_issue.go b/federation/resolve_issue.go index 9b338189..e791ed5b 100644 --- a/federation/resolve_issue.go +++ b/federation/resolve_issue.go @@ -10,6 +10,7 @@ import ( fapi "github.com/idfoundry/fapigo" intfed "github.com/idfoundry/fapigo/internal/federation" + "github.com/idfoundry/fapigo/internal/strictjson" ) // ResolveIssueConfig configures a ResolveIssuer's own Entity Identifier. @@ -130,6 +131,12 @@ type VerifiedTrustMark struct { // leaving that to the caller; Response has no second resolution attempt // to try a different one if it isn't. // +// Response refuses resolved.Metadata (as filtered to entityTypes) that +// repeats a member name with differing copies, or as a case variant, at +// any depth, or holds two Entity Types whose names differ only in case, +// which no Resolver's resolution produces: a reader of the response, +// this module's Resolver included, would refuse it. +// // The response's own "exp" claim is set to the minimum of // resolved.ExpiresAt and every trustMarks entry's own ExpiresAt exactly // (§8.3.2: "MUST be the minimum of the exp value of the Trust Chain @@ -149,6 +156,12 @@ func (i *ResolveIssuer) Response(resolved ResolvedEntity, trustAnchors, entityTy if len(entityTypes) > 0 { metadata = filterResolvedEntityTypes(metadata, entityTypes) } + // A Resolve Response repeating a member with differing copies, or + // as a case variant, at any depth is refused by its readers, this + // module's included: they would take different metadata from it. + if entityType, err := strictjson.CheckConflictingObject(metadata); err != nil { + return "", fmt.Errorf("federation: resolved metadata %q would not parse: %w", entityType, err) + } now := i.deps.Clock.Now() expiresAt := resolved.ExpiresAt diff --git a/federation/resolve_issue_test.go b/federation/resolve_issue_test.go index 5ea30277..198ca9fa 100644 --- a/federation/resolve_issue_test.go +++ b/federation/resolve_issue_test.go @@ -352,3 +352,34 @@ func TestResolveRequestFromHTTPRequiresFields(t *testing.T) { }) } } + +// TestResolveIssuerResponseRefusesConflictingMetadata: a Resolve +// Response repeating a member with differing copies, or as a case +// variant, at any depth is refused by its readers, so Response refuses +// a hand-built ResolvedEntity whose Metadata would make one rather than +// sign it. An identical repeat is signed. +func TestResolveIssuerResponseRefusesConflictingMetadata(t *testing.T) { + issuer, err := federation.NewResolveIssuer(validResolveIssueConfig(), validResolveIssueDependencies(t)) + if err != nil { + t.Fatalf("NewResolveIssuer: %v", err) + } + respond := func(metadata map[string]json.RawMessage) error { + _, err := issuer.Response(federation.ResolvedEntity{ + EntityID: "https://op.example.org", TrustAnchor: "https://ta.example.org", + Metadata: metadata, ExpiresAt: time.Now().Add(time.Hour), Tokens: []string{"placeholder-chain-entry"}, + }, []string{"https://ta.example.org"}, nil, nil) + return err + } + if err := respond(map[string]json.RawMessage{"openid_provider": json.RawMessage(`{"issuer":"https://op.example.org","issuer":"https://op.example.org"}`)}); err != nil { + t.Fatalf("Response with an identical repeat: %v", err) + } + for name, metadata := range map[string]map[string]json.RawMessage{ + "differing repeat": {"openid_provider": json.RawMessage(`{"issuer":"https://op.example.org","issuer":"https://evil.example"}`)}, + "nested variant": {"openid_provider": json.RawMessage(`{"jwks":{"keys":[{"kid":"a","KID":"b"}]}}`)}, + "entity type variant": {"openid_provider": json.RawMessage(`{}`), "OpenID_Provider": json.RawMessage(`{}`)}, + } { + if err := respond(metadata); err == nil { + t.Errorf("%s: Response = nil error, want error", name) + } + } +} From 853c1cbe06eaedc0a70c245218d21464a0156985 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 19:17:46 +0800 Subject: [PATCH 4/9] fix(client): refuse authorization details whose JSON members repeat BeginAuthorization, BeginBackchannelAuthentication and RequestClientCredentialsToken sent the caller's AuthorizationDetails entries as given. An entry repeating a member name, or holding two that differ only in case, is read differently by different authorization servers, and a FAPIgo server refuses any such repeat in authorization_details, identical copies included, as this client does in a token response. Each call now refuses one as invalid_request before anything is sent. requestobject.Create also refuses parameters its own parser would refuse once signed in: a value repeating a member with differing copies, or as a case variant, and a name that differs only in case from another parameter or from a claim Create sets, such as an extension value named "Scope". The request then fails instead of carrying an object the authorization server refuses. Co-Authored-By: Claude Opus 5.5 --- .../authorization_details_unescaped_test.go | 53 +++++++++++ client/backchannel.go | 8 +- client/begin_authorization.go | 27 +++++- client/client_credentials.go | 7 +- internal/requestobject/create.go | 89 +++++++++++++------ internal/requestobject/requestobject_test.go | 36 ++++++++ 6 files changed, 188 insertions(+), 32 deletions(-) diff --git a/client/authorization_details_unescaped_test.go b/client/authorization_details_unescaped_test.go index 18291c49..cfdbfea7 100644 --- a/client/authorization_details_unescaped_test.go +++ b/client/authorization_details_unescaped_test.go @@ -80,3 +80,56 @@ func TestAuthorizationDetailsSentWithoutHTMLEscaping(t *testing.T) { } }) } + +// TestAuthorizationDetailsRefusedWithRepeatedMembers covers every +// request that carries authorization_details: an entry repeating a +// member, or holding two that differ only in case, at any depth, is +// invalid_request before anything is sent — authorization servers would +// read it differently, and a FAPIgo server refuses it, identical copies +// included — while the same detail without the repeat is sent. +func TestAuthorizationDetailsRefusedWithRepeatedMembers(t *testing.T) { + plain := []json.RawMessage{json.RawMessage(`{"type":"payment_initiation","instructedAmount":{"amount":"1"}}`)} + for name, details := range map[string][]json.RawMessage{ + "differing repeat": {json.RawMessage(`{"type":"payment_initiation","instructedAmount":{"amount":"1","amount":"1000"}}`)}, + "identical repeat": {json.RawMessage(`{"type":"payment_initiation","type":"payment_initiation"}`)}, + "case variant": {plain[0], json.RawMessage(`{"type":"a","actions":[{"x":1,"X":1}]}`)}, + } { + for request, send := range authorizationDetailsRequests(t) { + if err := send(plain); err != nil { + t.Fatalf("%s without a repeat: %v", request, err) + } + if code := clientErrorCode(t, send(details)); code != client.ErrorInvalidRequest { + t.Errorf("%s, %s: error code = %q, want %q", request, name, code, client.ErrorInvalidRequest) + } + } + } +} + +// authorizationDetailsRequests sends each request that carries +// authorization_details with the details given. +func authorizationDetailsRequests(t *testing.T) map[string]func([]json.RawMessage) error { + return map[string]func([]json.RawMessage) error{ + "PAR form": func(details []json.RawMessage) error { + c, _, _ := newTestClient(t, false) + _, err := c.BeginAuthorization(context.Background(), client.BeginAuthorizationRequest{Scope: []string{"openid"}, AuthorizationDetails: details}) + return err + }, + "PAR request object": func(details []json.RawMessage) error { + c, _, _ := newTestClient(t, true) + _, err := c.BeginAuthorization(context.Background(), client.BeginAuthorizationRequest{Scope: []string{"openid"}, AuthorizationDetails: details}) + return err + }, + "CIBA request object": func(details []json.RawMessage) error { + c, _, _ := newTestClientWithCIBA(t) + _, err := c.BeginBackchannelAuthentication(context.Background(), client.BeginBackchannelAuthenticationRequest{ + Scope: []string{"openid"}, LoginHint: "user@example.com", AuthorizationDetails: details, + }) + return err + }, + "client_credentials form": func(details []json.RawMessage) error { + c, _ := newTestClientForClientCredentials(t, nil) + _, err := c.RequestClientCredentialsToken(context.Background(), client.ClientCredentialsTokenRequest{Scope: []string{"accounts"}, AuthorizationDetails: details}) + return err + }, + } +} diff --git a/client/backchannel.go b/client/backchannel.go index 72223912..6349ea04 100644 --- a/client/backchannel.go +++ b/client/backchannel.go @@ -84,7 +84,10 @@ type BeginBackchannelAuthenticationRequest struct { // with extension.RARSet, mirroring // BeginAuthorizationRequest.AuthorizationDetails. Unlike PAR, CIBA // always signs a request object, so this is embedded as native JSON - // unconditionally, with no plain-parameter path to consider. + // unconditionally, with no plain-parameter path to consider. An + // entry that repeats a member name, or holds two that differ only in + // case, is refused as invalid_request, as BeginAuthorizationRequest's + // is. AuthorizationDetails []json.RawMessage // Resource, when not empty, names the resource servers the access @@ -304,6 +307,9 @@ func (c *Client) checkBackchannelAuthenticationRequest(req BeginBackchannelAuthe if resourceErr := checkResources(req.Resource); resourceErr != nil { return resourceErr } + if detailsErr := checkAuthorizationDetails(req.AuthorizationDetails); detailsErr != nil { + return detailsErr + } return nil } diff --git a/client/begin_authorization.go b/client/begin_authorization.go index e918d572..4cdf4aa3 100644 --- a/client/begin_authorization.go +++ b/client/begin_authorization.go @@ -116,7 +116,11 @@ type BeginAuthorizationRequest struct { // under every profile (RFC 9396 §2's own form-encoding: a plain // "authorization_details" parameter's value is itself JSON array // text, not a bare string), so it works under the baseline profile - // too, not just ProfileFAPISecurityWithMessageSigning. + // too, not just ProfileFAPISecurityWithMessageSigning. An entry that + // repeats a member name, or holds two that differ only in case, at + // any depth, is refused as invalid_request: authorization servers + // would read it differently from one another, and a FAPIgo server + // refuses it. AuthorizationDetails []json.RawMessage // Claims requests specific identity claims with the OIDC "claims" @@ -787,6 +791,24 @@ func maxAgeSeconds(maxAge time.Duration) (int64, *Error) { return seconds, nil } +// checkAuthorizationDetails refuses an AuthorizationDetails entry that +// repeats a member name, or holds two that differ only in case, at any +// depth (strictjson.CheckDuplicateMembers), as invalid_request. An +// authorization server reading it with encoding/json keeps the last +// copy, another the first, so the two would grant different +// authorizations. A FAPIgo server refuses any such repeat in +// authorization_details, identical copies included, and so does this +// client in the authorization_details of a token response. An entry +// that isn't JSON at all is left to encoding the request to report. +func checkAuthorizationDetails(details []json.RawMessage) *Error { + for i, detail := range details { + if json.Valid(detail) && strictjson.CheckDuplicateMembers(detail) != nil { + return newError(ErrorInvalidRequest, fmt.Sprintf("AuthorizationDetails[%d] repeats a member name, or holds two that differ only in case", i), nil) + } + } + return nil +} + // checkBeginRequest checks what BeginAuthorization can before it does // anything, and returns the redirect URI this authorization goes out // with: Config.RedirectURI, or that with req.RedirectPort. @@ -806,6 +828,9 @@ func (c *Client) checkBeginRequest(req BeginAuthorizationRequest) (string, *Erro if resourceErr := checkResources(req.Resource); resourceErr != nil { return "", resourceErr } + if detailsErr := checkAuthorizationDetails(req.AuthorizationDetails); detailsErr != nil { + return "", detailsErr + } if _, ok := extension.Snapshot(req.Extensions)[resourceParameter]; ok && len(req.Resource) > 0 { return "", newError(ErrorInvalidRequest, `"resource" is set both as Resource and as an Extensions value: set it only as Resource`, nil) } diff --git a/client/client_credentials.go b/client/client_credentials.go index 1cb097b8..887bed5f 100644 --- a/client/client_credentials.go +++ b/client/client_credentials.go @@ -31,7 +31,9 @@ type ClientCredentialsTokenRequest struct { // field of the same name for how to build one. Always sent as native // JSON array text (RFC 9396 §2), the same as a plain-parameter // authorization request: this grant has no signed-request-object - // concept for Config.Profile to matter to. + // concept for Config.Profile to matter to. An entry that repeats a + // member name, or holds two that differ only in case, is refused as + // invalid_request, as BeginAuthorizationRequest's is. AuthorizationDetails []json.RawMessage // Resource, when not empty, names the resource servers the access @@ -188,5 +190,8 @@ func checkClientCredentialsTokenRequest(req ClientCredentialsTokenRequest) *Erro if err := checkScopeTokens(req.Scope); err != nil { return err } + if err := checkAuthorizationDetails(req.AuthorizationDetails); err != nil { + return err + } return checkResources(req.Resource) } diff --git a/internal/requestobject/create.go b/internal/requestobject/create.go index d0fe9048..bf7ec2b0 100644 --- a/internal/requestobject/create.go +++ b/internal/requestobject/create.go @@ -57,50 +57,87 @@ type CreateParams struct { // each already encoded as JSON. Parameters must not use the // JWT-standard claim names iss, aud, exp, nbf, iat or jti, which // Create sets itself, or sub, which Verify refuses in a request - // object. + // object. A value repeating a member with differing copies, or as a + // case variant, and a name that is a case variant of another + // parameter or of one of those claims, are refused, as Verify would + // refuse the object. Parameters map[string]json.RawMessage } // Create builds and signs a request object for p. func Create(p CreateParams) (string, error) { + if err := validateCreateParams(p); err != nil { + return "", err + } + + jti, err := randomJTI(p.Random) + if err != nil { + return "", fmt.Errorf("requestobject: generate jti: %w", err) + } + + claims, err := createClaims(p, jti) + if err != nil { + return "", err + } + + // Without HTML escaping: json.Marshal would escape <, > and & in + // every json.RawMessage parameter too, so authorization_details the + // server keeps byte for byte would arrive as \u003c and so on. + payload, err := strictjson.MarshalUnescaped(claims) + if err != nil { + return "", fmt.Errorf("requestobject: marshal claims: %w", err) + } + + header := jose.Header{Algorithm: p.Algorithm, Type: jwtType, KeyID: p.KeyID} + token, err := jose.Sign(p.Signer, header, payload) + if err != nil { + return "", fmt.Errorf("requestobject: %w", err) + } + return token, nil +} + +// validateCreateParams checks p's required fields and the claims its +// Parameters must not set, split out of Create to keep its cognitive +// complexity manageable. +func validateCreateParams(p CreateParams) error { if p.Signer == nil { - return "", fmt.Errorf("requestobject: signer is nil") + return fmt.Errorf("requestobject: signer is nil") } if !p.Algorithm.IsValid() { - return "", fmt.Errorf("requestobject: invalid algorithm %v", p.Algorithm) + return fmt.Errorf("requestobject: invalid algorithm %v", p.Algorithm) } if p.ClientID == "" { - return "", fmt.Errorf("requestobject: client ID is empty") + return fmt.Errorf("requestobject: client ID is empty") } if p.Audience == "" { - return "", fmt.Errorf("requestobject: audience is empty") + return fmt.Errorf("requestobject: audience is empty") } if p.Now.IsZero() { - return "", fmt.Errorf("requestobject: now is zero") + return fmt.Errorf("requestobject: now is zero") } if p.Lifetime <= 0 { - return "", fmt.Errorf("requestobject: lifetime must be positive") + return fmt.Errorf("requestobject: lifetime must be positive") } // "sub" is refused as Verify refuses it: it's the claim a client // assertion authenticates by (RFC 7523 §3), and a request object // carrying it could be presented as one (see ErrUnexpectedSubject). for _, reserved := range []string{"iss", "aud", "exp", "nbf", "iat", "jti", "sub"} { if _, ok := p.Parameters[reserved]; ok { - return "", fmt.Errorf("requestobject: parameters must not set reserved claim %q", reserved) + return fmt.Errorf("requestobject: parameters must not set reserved claim %q", reserved) } } if clientIDRaw, ok := p.Parameters["client_id"]; ok { var clientID string if err := json.Unmarshal(clientIDRaw, &clientID); err != nil || clientID != p.ClientID { - return "", fmt.Errorf("requestobject: parameters[\"client_id\"] must equal ClientID") + return fmt.Errorf("requestobject: parameters[\"client_id\"] must equal ClientID") } } + return nil +} - jti, err := randomJTI(p.Random) - if err != nil { - return "", fmt.Errorf("requestobject: generate jti: %w", err) - } - +// createClaims is the request object's claims set: p.Parameters and +// the claims Create sets, refused if Verify would refuse it. +func createClaims(p CreateParams, jti string) (map[string]json.RawMessage, error) { claims := make(map[string]json.RawMessage, len(p.Parameters)+6) for k, v := range p.Parameters { claims[k] = v @@ -116,25 +153,19 @@ func Create(p CreateParams) (string, error) { for k, v := range standard { encoded, err := json.Marshal(v) if err != nil { - return "", fmt.Errorf("requestobject: marshal %q: %w", k, err) + return nil, fmt.Errorf("requestobject: marshal %q: %w", k, err) } claims[k] = encoded } - - // Without HTML escaping: json.Marshal would escape <, > and & in - // every json.RawMessage parameter too, so authorization_details the - // server keeps byte for byte would arrive as \u003c and so on. - payload, err := strictjson.MarshalUnescaped(claims) - if err != nil { - return "", fmt.Errorf("requestobject: marshal claims: %w", err) - } - - header := jose.Header{Algorithm: p.Algorithm, Type: jwtType, KeyID: p.KeyID} - token, err := jose.Sign(p.Signer, header, payload) - if err != nil { - return "", fmt.Errorf("requestobject: %w", err) + // Verify refuses a request object repeating a member with differing + // copies, or as a case variant, at any depth: readers keeping the + // first copy and the last would take different requests from it. + // So is a parameter spelled as a case variant of another, or of a + // claim set here ("ISS", say). + if name, err := strictjson.CheckConflictingObject(claims); err != nil { + return nil, fmt.Errorf("requestobject: parameter %q would not parse: %w", name, err) } - return token, nil + return claims, nil } func randomJTI(r io.Reader) (string, error) { diff --git a/internal/requestobject/requestobject_test.go b/internal/requestobject/requestobject_test.go index 680ed82b..b976d5a9 100644 --- a/internal/requestobject/requestobject_test.go +++ b/internal/requestobject/requestobject_test.go @@ -9,6 +9,7 @@ import ( "encoding/base64" "encoding/json" "errors" + "maps" "strings" "testing" "time" @@ -1000,3 +1001,38 @@ func TestParseClaimsRejectsMalformedOptionalClaims(t *testing.T) { t.Fatalf("parseClaims = JTI %q, HasSubject %v, NotBefore %v", c.JTI, c.HasSubject, c.NotBefore) } } + +// TestCreateRefusesParametersParseRefuses: Create refuses Parameters +// that Parse would refuse once signed in — a value repeating a member +// with differing copies, or as a case variant, at any depth, and a name +// that differs only in case from another parameter or from a claim +// Create sets — rather than sign a request object its readers take +// different requests from. An identical repeat is signed, and parses. +func TestCreateRefusesParametersParseRefuses(t *testing.T) { + key := generateKey(t) + create := func(extra map[string]json.RawMessage) (string, error) { + params := testParameters(t) + maps.Copy(params, extra) + return Create(CreateParams{ + Signer: key, Algorithm: fapi.ES256, ClientID: "client-123", + Audience: "https://as.example", Now: time.Now(), Lifetime: time.Minute, Parameters: params, + }) + } + token, err := create(map[string]json.RawMessage{"authorization_details": json.RawMessage(`[{"type":"a","type":"a"}]`)}) + if err != nil { + t.Fatalf("Create with an identical repeat: %v", err) + } + if _, err := Parse(token); err != nil { + t.Fatalf("Parse(Create with an identical repeat): %v", err) + } + for name, extra := range map[string]map[string]json.RawMessage{ + "differing repeat": {"authorization_details": json.RawMessage(`[{"type":"a","type":"b"}]`)}, + "nested variant": {"claims": json.RawMessage(`{"id_token":{"acr":null,"ACR":null}}`)}, + "parameter variant": {"Scope": json.RawMessage(`"admin"`)}, + "set-claim variant": {"ISS": json.RawMessage(`"client-456"`)}, + } { + if token, err := create(extra); err == nil { + t.Errorf("%s: Create = %s, want refused", name, token) + } + } +} From addaa17a95b018f85c1243346effb5a640565be3 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 19:17:47 +0800 Subject: [PATCH 5/9] docs: describe the refusals of JSON with conflicting members Add the v0.88.1 UPGRADING.md section listing each call that now refuses a value repeating a member with differing copies, or as a case variant, and what to change. Co-Authored-By: Claude Opus 5.5 --- UPGRADING.md | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/UPGRADING.md b/UPGRADING.md index 623e069f..b8dc2faa 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -18,6 +18,61 @@ Most production-assurance changes only affect `Config.Assurance = AssuranceProduction`. A development-assurance setup built on `memstore` and `keys/ephemeral` needs only the steps not marked *production only*. +## v0.88.1 + +### JSON you supply may not repeat a member with differing values (server, serverresource, federation, client) + +**Affects:** an application whose own JSON values go into a token, +response or request this module signs or sends, when one of them +repeats a member name with differing copies, or as a case variant +(`{"sub":"a","sub":"b"}`, `{"kid":"a","KID":"a"}`), at any depth, or +when two of its claim names differ only in case (`roles` and `Roles`). +JSON that never repeats a name is unaffected, and so, except in +`authorization_details`, is a repeat whose copies are identical. + +**Why:** since v0.87.0 this module's own readers refuse an ID token, JWT +access token, UserInfo response, request object or Resolve Response +carrying such a repeat, and other readers take different values from it +(one keeps the first copy, another the last, a case-insensitive one +merges the variants). A value carrying one could only ever produce a +token or document this module's own peers refuse and others read +inconsistently, so each is now refused where it is handed over. + +**What fails:** + +- `server.Server.CompleteAuthorization` and + `CompleteBackchannelAuthentication` refuse such a value, or such a pair + of names, in `GrantedAuthorization.IDTokenClaims` with + `invalid_request`, as they refuse invalid JSON there. +- A value an `IdentityClaimsSource` returns for an ID token fails the + token request (authorization code, refresh or CIBA) with + `server_error`, as an identity claim over the ID token claims budget + does. So does a grant stored before this release whose + `IDTokenClaims` carry one, or, with `JWTAccessTokens`, whose + requested UserInfo claim values do. +- `server.Server.SignUserInfoResponse` refuses such a claim with + `server_error`, and `serverresource.UserInfoClaims` returns an error + for one its claims source returns (a claim named `Sub` included, + beside the `sub` it sets). +- A plain (form) `claims` parameter at PAR or the backchannel + authentication endpoint carrying such a repeat is `invalid_request`, + as a request object carrying it already was. +- `federation.ResolveIssuer.Response` refuses `ResolvedEntity.Metadata` + carrying one. A `Resolver`'s own resolution never produces it. +- `client.Client.BeginAuthorization`, `BeginBackchannelAuthentication` + and `RequestClientCredentialsToken` refuse an `AuthorizationDetails` + entry that repeats a member name at all, identical copies included, + with `invalid_request`: a FAPIgo authorization server refuses any + repeat in `authorization_details`, and this client refuses one in a + token response. An `extension.Values` entry that would put such a + repeat in a request object (one named `Scope`, say, beside `scope`) + fails the request as an internal error instead of being signed. + +**What to change:** build these values with `json.Marshal` from Go +values, or `extension.RARSet` for authorization details, which never +repeat a name, rather than by hand, and remove the repeat from any you +store. + ## v0.88.0 ### A DPoP proof is accepted only for the URL that received it (server) From fd5c08136840946bf71c49ff29adb3f9744784d7 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 19:18:23 +0800 Subject: [PATCH 6/9] test: add mutants for the conflicting JSON member refusals Each new refusal of a value repeating a member with differing copies, or as a case variant, gets a mutant disabling it, killed by the test added with it. Co-Authored-By: Claude Opus 5.5 --- .github/mutation/mutants.json | 181 ++++++++++++++++++++++++++++++++++ 1 file changed, 181 insertions(+) diff --git a/.github/mutation/mutants.json b/.github/mutation/mutants.json index 9c5bafac..f327289a 100644 --- a/.github/mutation/mutants.json +++ b/.github/mutation/mutants.json @@ -6391,5 +6391,186 @@ ], "run": "^TestExchangeBackchannelAuthenticationDPoPProofAtMTLSAlias$", "why": "a CIBA token request checks a DPoP proof against the URL its request's route names" + }, + { + "id": "strictjson-conflicting-object-skips-case-variant-names", + "file": "internal/strictjson/members_conflict.go", + "old": "if first, ok := seen[key]; ok {", + "new": "if first, ok := seen[key]; ok && false {", + "module": "root", + "packages": [ + "./internal/strictjson" + ], + "run": "^TestCheckConflictingObject$", + "why": "CheckConflictingObject refuses two member names that differ only in case" + }, + { + "id": "strictjson-conflicting-object-skips-values", + "file": "internal/strictjson/members_conflict.go", + "old": "if err := CheckConflictingMembers(nested); err != nil {", + "new": "if err := CheckConflictingMembers(nested); err != nil && false {", + "module": "root", + "packages": [ + "./internal/strictjson" + ], + "run": "^TestCheckConflictingObject$", + "why": "CheckConflictingObject refuses a member value repeating a member with differing copies" + }, + { + "id": "strictjson-conflicting-object-checks-value-unnested", + "file": "internal/strictjson/members_conflict.go", + "old": "nested = append(append(append(nested, '['), value...), ']')", + "new": "nested = append(nested, value...)", + "module": "root", + "packages": [ + "./internal/strictjson" + ], + "run": "^TestCheckConflictingObject$", + "why": "CheckConflictingObject checks a value's nesting as it is inside the object, one level deeper" + }, + { + "id": "strictjson-conflicting-object-skips-json-validity", + "file": "internal/strictjson/members_conflict.go", + "old": "\t\tif !json.Valid(value) {\n\t\t\treturn name,", + "new": "\t\tif false && !json.Valid(value) {\n\t\t\treturn name,", + "module": "root", + "packages": [ + "./internal/strictjson" + ], + "run": "^TestCheckConflictingObject$", + "why": "CheckConflictingObject refuses a member value that isn't one JSON value" + }, + { + "id": "server-granted-id-token-claims-skip-conflict-check", + "file": "server/granted_id_token_claims.go", + "old": "if name, err := strictjson.CheckConflictingObject(claims); err != nil {", + "new": "if name, err := strictjson.CheckConflictingObject(claims); err != nil && false {", + "module": "root", + "packages": [ + "./server" + ], + "run": "^(TestCompleteAuthorizationRejectsInvalidGrantedIDTokenClaims|TestCompleteBackchannelAuthenticationRejectsInvalidGrantedIDTokenClaims)$", + "why": "CompleteAuthorization/CompleteBackchannelAuthentication refuse IDTokenClaims repeating a member with differing copies or as a case variant" + }, + { + "id": "token-issue-skips-parameter-conflict-check", + "file": "internal/token/issue.go", + "old": "if name, err := strictjson.CheckConflictingObject(parameters); err != nil {", + "new": "if name, err := strictjson.CheckConflictingObject(parameters); err != nil && false {", + "module": "root", + "packages": [ + "./internal/token", + "./server" + ], + "run": "^(TestIssueRefusesParametersItsParsersRefuse|TestExchangeAuthorizationCodeRefusesConflictingIdentityClaims)$", + "why": "ID tokens and JWT access tokens are never signed with parameters their parsers refuse as repeating a member" + }, + { + "id": "requestobject-create-skips-conflict-check", + "file": "internal/requestobject/create.go", + "old": "if name, err := strictjson.CheckConflictingObject(claims); err != nil {", + "new": "if name, err := strictjson.CheckConflictingObject(claims); err != nil && false {", + "module": "root", + "packages": [ + "./internal/requestobject" + ], + "run": "^TestCreateRefusesParametersParseRefuses$", + "why": "a request object is never signed with parameters Parse refuses as repeating a member" + }, + { + "id": "server-sign-userinfo-skips-conflict-check", + "file": "server/userinfo.go", + "old": "if name, err := strictjson.CheckConflictingObject(claims); err != nil {", + "new": "if name, err := strictjson.CheckConflictingObject(claims); err != nil && false {", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestSignUserInfoResponseRefusesConflictingMembers$", + "why": "SignUserInfoResponse refuses claims repeating a member with differing copies or as a case variant" + }, + { + "id": "server-claims-parameter-skips-conflict-check", + "file": "server/claims_parameter.go", + "old": "if err := strictjson.CheckConflictingMembers(object); err != nil {", + "new": "if err := strictjson.CheckConflictingMembers(object); err != nil && false {", + "module": "root", + "packages": [ + "./server" + ], + "run": "^(TestValidateClaimsParameter|TestMalformedClaimsParameterIsRefused)$", + "why": "a plain claims parameter repeating a member with differing copies or as a case variant is invalid_request" + }, + { + "id": "serverresource-userinfo-claims-skip-conflict-check", + "file": "serverresource/userinfo.go", + "old": "if name, err := strictjson.CheckConflictingObject(claims); err != nil {", + "new": "if name, err := strictjson.CheckConflictingObject(claims); err != nil && false {", + "module": "root", + "packages": [ + "./serverresource" + ], + "run": "^TestUserInfoClaimsRefusesConflictingMembers$", + "why": "UserInfoClaims refuses source claims repeating a member with differing copies or as a case variant" + }, + { + "id": "federation-resolve-response-skips-conflict-check", + "file": "federation/resolve_issue.go", + "old": "if entityType, err := strictjson.CheckConflictingObject(metadata); err != nil {", + "new": "if entityType, err := strictjson.CheckConflictingObject(metadata); err != nil && false {", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestResolveIssuerResponseRefusesConflictingMetadata$", + "why": "ResolveIssuer.Response refuses metadata repeating a member with differing copies or as a case variant" + }, + { + "id": "client-authorization-details-skip-repeat-check", + "file": "client/begin_authorization.go", + "old": "if json.Valid(detail) && strictjson.CheckDuplicateMembers(detail) != nil {", + "new": "if json.Valid(detail) && strictjson.CheckDuplicateMembers(detail) != nil && false {", + "module": "root", + "packages": [ + "./client" + ], + "run": "^TestAuthorizationDetailsRefusedWithRepeatedMembers$", + "why": "the client refuses AuthorizationDetails entries repeating a member name" + }, + { + "id": "client-begin-authorization-skips-details-check", + "file": "client/begin_authorization.go", + "old": "if detailsErr := checkAuthorizationDetails(req.AuthorizationDetails); detailsErr != nil {", + "new": "if detailsErr := checkAuthorizationDetails(req.AuthorizationDetails); detailsErr != nil && false {", + "module": "root", + "packages": [ + "./client" + ], + "run": "^TestAuthorizationDetailsRefusedWithRepeatedMembers$", + "why": "BeginAuthorization refuses AuthorizationDetails entries repeating a member name" + }, + { + "id": "client-backchannel-skips-details-check", + "file": "client/backchannel.go", + "old": "if detailsErr := checkAuthorizationDetails(req.AuthorizationDetails); detailsErr != nil {", + "new": "if detailsErr := checkAuthorizationDetails(req.AuthorizationDetails); detailsErr != nil && false {", + "module": "root", + "packages": [ + "./client" + ], + "run": "^TestAuthorizationDetailsRefusedWithRepeatedMembers$", + "why": "BeginBackchannelAuthentication refuses AuthorizationDetails entries repeating a member name" + }, + { + "id": "client-client-credentials-skips-details-check", + "file": "client/client_credentials.go", + "old": "if err := checkAuthorizationDetails(req.AuthorizationDetails); err != nil {", + "new": "if err := checkAuthorizationDetails(req.AuthorizationDetails); err != nil && false {", + "module": "root", + "packages": [ + "./client" + ], + "run": "^TestAuthorizationDetailsRefusedWithRepeatedMembers$", + "why": "RequestClientCredentialsToken refuses AuthorizationDetails entries repeating a member name" } ] From 53ac8287e6326a6392af9ea98126ead5078c132f Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 19:45:15 +0800 Subject: [PATCH 7/9] ci: fuzz FuzzCheckConflictingObject nightly Co-Authored-By: Claude Opus 5.5 --- .github/workflows/fuzz.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 0a2d5586..e644bfa6 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -193,6 +193,8 @@ jobs: name: FuzzScanMembersMatchesWalker - pkg: ./internal/strictjson name: FuzzCheckConflictingMembersOneReading + - pkg: ./internal/strictjson + name: FuzzCheckConflictingObject - pkg: ./extension name: FuzzExtensionValueReadersAgree - pkg: ./internal/sealedcookie From 71026848c7008b90f694d5cab2a235a26a3a0231 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 19:45:15 +0800 Subject: [PATCH 8/9] refactor: build a checked member's nesting without sizing it by hand CheckConflictingObject wraps each value in "[...]" to check it at the readers' depth. It sized that buffer as len(value)+2, an addition CodeQL flags as a possible overflow in an allocation; slices.Concat builds the same bytes. The mutant that drops the wrapping is re-anchored on the new line. Co-Authored-By: Claude Opus 5.5 --- .github/mutation/mutants.json | 4 ++-- internal/strictjson/members_conflict.go | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/mutation/mutants.json b/.github/mutation/mutants.json index f327289a..6bf2c2e1 100644 --- a/.github/mutation/mutants.json +++ b/.github/mutation/mutants.json @@ -6419,8 +6419,8 @@ { "id": "strictjson-conflicting-object-checks-value-unnested", "file": "internal/strictjson/members_conflict.go", - "old": "nested = append(append(append(nested, '['), value...), ']')", - "new": "nested = append(nested, value...)", + "old": "nested := slices.Concat([]byte(\"[\"), value, []byte(\"]\"))", + "new": "nested := slices.Concat(value)", "module": "root", "packages": [ "./internal/strictjson" diff --git a/internal/strictjson/members_conflict.go b/internal/strictjson/members_conflict.go index 59f5257c..c20a12b9 100644 --- a/internal/strictjson/members_conflict.go +++ b/internal/strictjson/members_conflict.go @@ -70,8 +70,7 @@ func CheckConflictingObject(members map[string]json.RawMessage) (string, error) return name, fmt.Errorf("strictjson: member %q is not valid JSON", name) } // Inside "[...]" the value nests as deeply as inside the object. - nested := make([]byte, 0, len(value)+2) - nested = append(append(append(nested, '['), value...), ']') + nested := slices.Concat([]byte("["), value, []byte("]")) if err := CheckConflictingMembers(nested); err != nil { return name, err } From 0f8d9d67cc21e44ba0d35be1861b3ff65dc6b5df Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 19:57:23 +0800 Subject: [PATCH 9/9] test: cover the request object failures Create reports Co-Authored-By: Claude Opus 5.5 --- .../requestobject/create_failures_test.go | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 internal/requestobject/create_failures_test.go diff --git a/internal/requestobject/create_failures_test.go b/internal/requestobject/create_failures_test.go new file mode 100644 index 00000000..c57bf22b --- /dev/null +++ b/internal/requestobject/create_failures_test.go @@ -0,0 +1,55 @@ +package requestobject + +import ( + "crypto" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "errors" + "io" + "testing" + "time" + + fapi "github.com/idfoundry/fapigo" +) + +// failingReader fails every read, as an exhausted randomness source would. +type failingReader struct{} + +func (failingReader) Read([]byte) (int, error) { return 0, errors.New("no randomness") } + +// failingSigner holds a key but fails every signature. +type failingSigner struct{ crypto.Signer } + +func (failingSigner) Sign(io.Reader, []byte, crypto.SignerOpts) ([]byte, error) { + return nil, errors.New("signer unavailable") +} + +// TestCreateReportsWhatStopsIt: Create refuses a nil signer and an +// invalid algorithm, and reports a randomness source and a signer that +// fail, rather than producing an object. +func TestCreateReportsWhatStopsIt(t *testing.T) { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + valid := CreateParams{ + Signer: key, Algorithm: fapi.ES256, ClientID: "client-123", Audience: "https://as.example", + Now: time.Now(), Lifetime: time.Minute, Parameters: testParameters(t), + } + for name, change := range map[string]func(*CreateParams){ + "nil signer": func(p *CreateParams) { p.Signer = nil }, + "invalid algorithm": func(p *CreateParams) { p.Algorithm = 0 }, + "failing randomness": func(p *CreateParams) { p.Random = failingReader{} }, + "failing signer": func(p *CreateParams) { p.Signer = failingSigner{key} }, + } { + p := valid + change(&p) + if token, err := Create(p); err == nil { + t.Errorf("%s: Create = %q, nil error, want an error", name, token) + } + } + if _, err := Create(valid); err != nil { + t.Fatalf("Create with valid parameters: %v", err) + } +}