From b9873d584bf0e0795569b3a3656874a9e0caa51e Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 09:36:01 +0800 Subject: [PATCH 01/12] docs(resource): say SubjectKind marks only FAPIgo client credentials tokens MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SubjectKind and EndUser tell a client credentials token from an end user's by the "grant_type" claim a FAPIgo authorization server sets on it. A token from any other authorization server carries no such claim: RFC 9068 §2.2 makes a client credentials token's sub the client's own client_id, and §5 leaves keeping client_ids and user identifiers apart to the authorization server. Such a token reads as SubjectEndUser, and EndUser reports its sub, the client_id, as a user, so a client whose client_id equals a user's identifier gets that user's InternalSubject. The same holds for a custom AccessTokenIssuer that drops the claim, or a custom AccessTokenResolver that doesn't return it. Verify doesn't infer the kind from sub equaling client_id: a user's own token can have that too (a user whose identifier is some client's client_id, using that client), and reading it as the client's would refuse that user. The SubjectKind and EndUser docs, GETTING_STARTED and the production checklist now say the distinction holds only for FAPIgo-issued tokens, and what to do behind another authorization server; AccessTokenParams.Claims says an issuer must keep grant_type. A new test pins the behaviour with hand-signed RFC 9068 tokens: a client credentials token (sub == client_id), one whose client_id collides with a user's sub and that user's own token all read as SubjectEndUser with the same InternalSubject, and one carrying grant_type reads as SubjectClient. Co-Authored-By: Claude Opus 5.5 --- GETTING_STARTED.md | 9 +- docs/PRODUCTION_CHECKLIST.md | 6 +- resource/third_party_subject_kind_test.go | 104 ++++++++++++++++++++++ resource/verify.go | 19 ++++ server/accesstoken.go | 8 ++ 5 files changed, 144 insertions(+), 2 deletions(-) create mode 100644 resource/third_party_subject_kind_test.go diff --git a/GETTING_STARTED.md b/GETTING_STARTED.md index 65a03e6a..c7589f17 100644 --- a/GETTING_STARTED.md +++ b/GETTING_STARTED.md @@ -1800,7 +1800,14 @@ Authorize anything that belongs to a user by `EndUser`, never by client's own `client_id` (`SubjectKind` is `SubjectClient`), and a client can be registered with a `client_id` equal to a user's identifier (automatically, through OpenID Federation, for one). `EndUser` reports -`ok` false for it: +`ok` false for it. It can only because FAPIgo's authorization server +marks a client credentials token with a `grant_type` claim: a token from +another authorization server carries no such mark (RFC 9068 makes its +`sub` the `client_id`, and leaves keeping client IDs and user +identifiers apart to the authorization server, §5), so it reads as +`SubjectEndUser`, and `EndUser` reports `ok` true for it. Behind such a +server, refuse a token whose `InternalSubject` equals its `ClientID` +yourself, unless the server guarantees no client ID names a user: ```go user, ok := authCtx.EndUser() diff --git a/docs/PRODUCTION_CHECKLIST.md b/docs/PRODUCTION_CHECKLIST.md index e725ac5c..d37cc8fc 100644 --- a/docs/PRODUCTION_CHECKLIST.md +++ b/docs/PRODUCTION_CHECKLIST.md @@ -161,7 +161,11 @@ are things no constructor can check. - [ ] *(yours)* **Authorize anything a user owns by `AuthorizationContext.EndUser()`**, never by `InternalSubject` alone (a client credentials token's subject is a client), and use - `ClientSubject` for anything returned to a client. [Pairwise subjects at a resource server](../GETTING_STARTED.md#pairwise-subjects-at-a-resource-server) + `ClientSubject` for anything returned to a client. `EndUser` tells a + client's token apart only for FAPIgo's authorization server, which + marks one with `grant_type`; behind another, check that it keeps + client IDs and user identifiers apart (RFC 9068 §5), or refuse a + token whose `InternalSubject` equals its `ClientID`. [Pairwise subjects at a resource server](../GETTING_STARTED.md#pairwise-subjects-at-a-resource-server) - [ ] *(yours)* **`PeerCertificate` behind a proxy:** the same rule as the authorization server's, with `fapihttp.ForwardedClientCertificate`. [Verify a request](../GETTING_STARTED.md#verify-a-request) diff --git a/resource/third_party_subject_kind_test.go b/resource/third_party_subject_kind_test.go new file mode 100644 index 00000000..8d69a4b6 --- /dev/null +++ b/resource/third_party_subject_kind_test.go @@ -0,0 +1,104 @@ +package resource_test + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "fmt" + "net/url" + "testing" + "time" + + fapi "github.com/idfoundry/fapigo" + "github.com/idfoundry/fapigo/internal/jose" + "github.com/idfoundry/fapigo/internal/mtls" + "github.com/idfoundry/fapigo/keys" + "github.com/idfoundry/fapigo/resource" +) + +// TestVerifySubjectKindOfThirdPartyJWTAccessTokens pins what SubjectKind +// and EndUser report for RFC 9068 access tokens from an authorization +// server other than FAPIgo, which sets no "grant_type" claim. RFC 9068 +// §2.2 has a client credentials token's sub be the client's own +// client_id, and its §5 leaves keeping client_ids and user identifiers +// apart to the authorization server; nothing in such a token marks it +// as the client's own. So every token without the claim reads as +// SubjectEndUser, and EndUser reports a client credentials token's sub, +// the client_id, as a user: a client whose client_id equals a user's +// identifier gets an InternalSubject indistinguishable from that user's +// own token's. Verify doesn't guess from sub == client_id, which a +// user's own token can also have (a user whose identifier is a client's +// client_id, or a client acting for a user named like it). A token +// carrying FAPIgo's grant_type claim is still SubjectClient. +func TestVerifySubjectKindOfThirdPartyJWTAccessTokens(t *testing.T) { + for name, tc := range map[string]struct { + sub, clientID, extra string + want resource.SubjectKind + wantEndUser bool + }{ + "client credentials, sub is the client_id": {sub: "client-1", clientID: "client-1", want: resource.SubjectEndUser, wantEndUser: true}, + "client_id colliding with a user's sub": {sub: "alice", clientID: "alice", want: resource.SubjectEndUser, wantEndUser: true}, + "that user's own token": {sub: "alice", clientID: "client-1", want: resource.SubjectEndUser, wantEndUser: true}, + "FAPIgo's grant_type claim": {sub: "client-1", clientID: "client-1", extra: `,"grant_type":"client_credentials"`, want: resource.SubjectClient}, + } { + t.Run(name, func(t *testing.T) { + authz, err := verifyThirdPartyJWT(t, tc.clientID, func(c thirdPartyToken) string { + return thirdPartyClaims(tc.sub, tc.clientID, c) + tc.extra + `}` + }) + if err != nil { + t.Fatalf("Verify: %v", err) + } + assertSubjectKind(t, authz, tc.want, tc.wantEndUser) + if authz.InternalSubject != tc.sub || authz.ClientSubject != tc.sub || authz.ClientID != tc.clientID { + t.Fatalf("InternalSubject, ClientSubject, ClientID = %q, %q, %q; want %q, %q, %q", + authz.InternalSubject, authz.ClientSubject, authz.ClientID, tc.sub, tc.sub, tc.clientID) + } + }) + } +} + +// thirdPartyToken is what a third-party access token's claims set +// depends on: its lifetime, and the thumbprint of the client +// certificate it is bound to. +type thirdPartyToken struct { + exp, iat int64 + thumbprint string +} + +// thirdPartyClaims is an RFC 9068 §2.2 claims set, mTLS-bound as c +// says, without its closing brace. +func thirdPartyClaims(sub, clientID string, c thirdPartyToken) string { + return fmt.Sprintf(`{"iss":%q,"sub":%q,"aud":%q,"client_id":%q,"exp":%d,"iat":%d,"jti":"jti-1","scope":"accounts","cnf":{"x5t#S256":%q}`, + testIssuer, sub, testIssuer, clientID, c.exp, c.iat, c.thumbprint) +} + +// verifyThirdPartyJWT signs the claims set claims returns, as an +// at+jwt, with a key JWTAccessTokens trusts for testIssuer, and +// verifies it, presented over mTLS with a certificate for clientID. +func verifyThirdPartyJWT(t *testing.T, clientID string, claims func(thirdPartyToken) string) (resource.AuthorizationContext, error) { + t.Helper() + issuerKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + cert := selfSignedTestClientCert(t, clientID) + now := time.Now() + payload := claims(thirdPartyToken{exp: now.Add(5 * time.Minute).Unix(), iat: now.Unix(), thumbprint: mtls.Thumbprint(cert)}) + accessToken, err := jose.Sign(issuerKey, jose.Header{Algorithm: fapi.ES256, Type: "at+jwt", KeyID: "third-party-kid"}, []byte(payload)) + if err != nil { + t.Fatalf("sign: %v", err) + } + resolver, err := resource.NewJWTAccessTokens(&fakeIssuerKeySource{set: keys.IssuerKeySet{Keys: []keys.IssuerKey{ + {KeyID: "third-party-kid", Algorithm: fapi.ES256, PublicKey: issuerKey.Public()}, + }}}, testIssuerURL, testIssuer, fapi.ES256, 5*time.Minute, 8) + if err != nil { + t.Fatalf("NewJWTAccessTokens: %v", err) + } + v := pairwiseVerifier(t, resolver, nil, now) + target, err := url.Parse("https://rs.example.com/accounts") + if err != nil { + t.Fatal(err) + } + return v.Verify(context.Background(), resource.VerifyRequest{Method: "GET", URL: target, Authorization: "Bearer " + accessToken, PeerCertificate: cert}) +} diff --git a/resource/verify.go b/resource/verify.go index 6c7727d3..72c92fc0 100644 --- a/resource/verify.go +++ b/resource/verify.go @@ -139,6 +139,19 @@ type AuthorizationContext struct { // credentials grant carries a "grant_type" claim saying so // (SubjectClient); any other is SubjectEndUser. Zero only in an // AuthorizationContext built by hand. + // + // The claim is a FAPIgo authorization server's own (server sets it, + // and an AccessTokenIssuer of its must keep it): a token from any + // other authorization server, or one a custom AccessTokenResolver + // resolves without it, reads as SubjectEndUser even when it came + // from the client credentials grant, whose sub RFC 9068 §2.2 makes + // the client's own client_id. Nothing else in such a token says it + // is the client's own, and Verify doesn't guess from sub equaling + // client_id, which a user's token can also have. With such an + // authorization server, SubjectKind tells a client from a user only + // as far as it keeps client_ids and user identifiers apart (RFC + // 9068 §5); where it doesn't, refuse a token whose InternalSubject + // equals its ClientID yourself, or have it set this claim. SubjectKind SubjectKind // ClientSubject is the sub the client was given for the end user: @@ -234,6 +247,12 @@ func (a AuthorizationContext) CodeGrantID() string { // SubjectKind, and when InternalSubject is "" (a pairwise sub under // PairwiseClientSubjectsOnly, which the verifier doesn't map back; // authorize by ClientSubject with ClientID there). +// +// It tells a client credentials token apart only when the token says +// what it is, as a FAPIgo authorization server's do (see SubjectKind): +// a client credentials token from another authorization server reads +// as an end user's, its sub the client's client_id, so ok is true for +// it. func (a AuthorizationContext) EndUser() (internalSubject string, ok bool) { if a.SubjectKind != SubjectEndUser || a.InternalSubject == "" { return "", false diff --git a/server/accesstoken.go b/server/accesstoken.go index 971f8ff2..0a20b034 100644 --- a/server/accesstoken.go +++ b/server/accesstoken.go @@ -47,6 +47,14 @@ type AccessTokenParams struct { // Always the issuing client's own storage.RegisteredClient.SenderConstrain(). SenderConstrain storage.SenderConstrain + // Claims are the token's other claims, which an issuer must carry + // into the token (JWTAccessTokens signs them in, OpaqueAccessTokens + // keeps them in the token's record). Among them is "grant_type" on + // a client credentials token, which is how + // resource.AuthorizationContext.SubjectKind tells the client's own + // token from an end user's: an issuer dropping it has a resource + // server read a client credentials token, whose subject is the + // client_id, as a user's. Claims map[string]json.RawMessage // Issuer is the token's "iss": JWTAccessTokens signs it into the From 9d0eaf1293e08373e5b9107bd3dc4445bb756fa4 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 09:36:21 +0800 Subject: [PATCH 02/12] fix(resource)!: refuse a JWT access token that repeats a claim MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RFC 7519 §4 requires a JWT's claim names to be unique, and lets a recipient either reject a repeat or keep the lexically last copy. The access token parser kept the last: encoding/json decoded the claims set into a map, so {"sub":"alice",...,"sub":"admin"} verified as admin's token. A gateway or other verifier in front of the resource server that keeps the first copy of a repeated member reads the same signed token as alice's, so the two would authorize different subjects, scopes or bindings from one token. The parser now runs strictjson.CheckDuplicateMembers on the claims set first, as the JOSE header parsers already do, and refuses one that repeats a member name at any depth, or holds two names that differ only in case, with ErrMalformedClaims. Verify answers such a token with invalid_token. A conformant token is unaffected. Tests cover a repeated sub, scope and cnf, and a repeated jkt inside cnf, at the parser, and a hand-signed RFC 9068 token naming its sub twice through Verify. BREAKING CHANGE: a JWT access token whose claims set repeats a member name, or holds two names that differ only in case, is now refused with invalid_token, where its last copy of the claim was used before. Co-Authored-By: Claude Opus 5.5 --- internal/token/accesstoken.go | 9 +++-- internal/token/claims_object.go | 25 ++++++++++++ internal/token/duplicate_claims_test.go | 46 +++++++++++++++++++++++ resource/third_party_subject_kind_test.go | 16 ++++++++ 4 files changed, 93 insertions(+), 3 deletions(-) create mode 100644 internal/token/claims_object.go create mode 100644 internal/token/duplicate_claims_test.go diff --git a/internal/token/accesstoken.go b/internal/token/accesstoken.go index 18389468..0eccaaf3 100644 --- a/internal/token/accesstoken.go +++ b/internal/token/accesstoken.go @@ -53,10 +53,13 @@ type rawConfirmation struct { X5TS256 string `json:"x5t#S256,omitempty"` } +// parseAccessTokenClaims parses a JWT access token's claims set, +// refusing one decodeClaimsObject refuses, such as one that repeats a +// claim. func parseAccessTokenClaims(payload []byte) (AccessTokenClaims, error) { - var raw map[string]json.RawMessage - if err := json.Unmarshal(payload, &raw); err != nil { - return AccessTokenClaims{}, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + raw, err := decodeClaimsObject(payload) + if err != nil { + return AccessTokenClaims{}, err } iss, _, err := popString(raw, "iss", true) diff --git a/internal/token/claims_object.go b/internal/token/claims_object.go new file mode 100644 index 00000000..57670cd4 --- /dev/null +++ b/internal/token/claims_object.go @@ -0,0 +1,25 @@ +package token + +import ( + "encoding/json" + "fmt" + + "github.com/idfoundry/fapigo/internal/strictjson" +) + +// decodeClaimsObject decodes payload, a JWT's claims set, as a JSON +// object, refusing one that repeats a member name at any depth, or holds +// two that differ only in case (strictjson.CheckDuplicateMembers): RFC +// 7519 §4 requires unique claim names, and encoding/json keeps the last +// copy of a repeated one, where another reader of the same JWT may keep +// the first. +func decodeClaimsObject(payload []byte) (map[string]json.RawMessage, error) { + if err := strictjson.CheckDuplicateMembers(payload); err != nil { + return nil, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + } + var raw map[string]json.RawMessage + if err := json.Unmarshal(payload, &raw); err != nil { + return nil, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + } + return raw, nil +} diff --git a/internal/token/duplicate_claims_test.go b/internal/token/duplicate_claims_test.go new file mode 100644 index 00000000..bb6fb762 --- /dev/null +++ b/internal/token/duplicate_claims_test.go @@ -0,0 +1,46 @@ +package token + +import ( + "errors" + "strings" + "testing" +) + +// TestParseClaimsRefuseDuplicateMembers: RFC 7519 §4 requires a JWT's +// claim names to be unique. encoding/json keeps the last copy of a +// repeated one, where a first-wins reader of the same token (a gateway, +// a log processor) keeps the first, so the two would disagree on who +// the token is for. A JWT access token that repeats a member, at any +// depth, is refused. +func TestParseClaimsRefuseDuplicateMembers(t *testing.T) { + const accessToken = `"iss":"https://as.example.com","aud":"https://rs.example.com","exp":2,"iat":1,"jti":"j","client_id":"c"` + for name, tc := range map[string]struct { + parse func([]byte) error + payload string + wantErr bool + }{ + "access token": {parseAT, `{` + accessToken + `,"sub":"alice"}`, false}, + "access token, sub twice": {parseAT, `{"sub":"mallory",` + accessToken + `,"sub":"alice"}`, true}, + "access token, scope twice": {parseAT, `{` + accessToken + `,"sub":"alice","scope":"admin","scope":"read"}`, true}, + "access token, cnf twice": {parseAT, `{` + accessToken + `,"sub":"alice","cnf":{"jkt":"a"},"cnf":{"jkt":"b"}}`, true}, + "access token, jkt twice in cnf": {parseAT, `{` + accessToken + `,"sub":"alice","cnf":{"jkt":"a","jkt":"b"}}`, true}, + } { + t.Run(name, func(t *testing.T) { + checkDuplicateRefusal(t, tc.parse([]byte(tc.payload)), tc.wantErr) + }) + } +} + +func parseAT(p []byte) error { _, err := parseAccessTokenClaims(p); return err } + +// checkDuplicateRefusal checks err is nil, or, when wantErr, that it is +// ErrMalformedClaims naming a duplicate member. +func checkDuplicateRefusal(t *testing.T, err error, wantErr bool) { + t.Helper() + switch { + case !wantErr && err != nil: + t.Fatalf("parse = %v, want nil", err) + case wantErr && (!errors.Is(err, ErrMalformedClaims) || !strings.Contains(err.Error(), "duplicate member name")): + t.Fatalf("parse = %v, want ErrMalformedClaims for a duplicate member", err) + } +} diff --git a/resource/third_party_subject_kind_test.go b/resource/third_party_subject_kind_test.go index 8d69a4b6..86c93203 100644 --- a/resource/third_party_subject_kind_test.go +++ b/resource/third_party_subject_kind_test.go @@ -5,6 +5,7 @@ import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" + "errors" "fmt" "net/url" "testing" @@ -58,6 +59,21 @@ func TestVerifySubjectKindOfThirdPartyJWTAccessTokens(t *testing.T) { } } +// TestVerifyRefusesJWTAccessTokenRepeatingAClaim: RFC 7519 §4 requires +// unique claim names. A token that names its subject twice is refused +// with invalid_token, rather than read as its last sub, which a +// first-wins reader of the same token (a gateway in front of this +// resource server) would read as the first. +func TestVerifyRefusesJWTAccessTokenRepeatingAClaim(t *testing.T) { + _, err := verifyThirdPartyJWT(t, "client-1", func(c thirdPartyToken) string { + return `{"sub":"alice",` + thirdPartyClaims("admin", "client-1", c)[1:] + `}` + }) + var rerr *resource.Error + if !errors.As(err, &rerr) || rerr.Code() != resource.ErrorInvalidToken { + t.Fatalf("Verify = %v, want invalid_token", err) + } +} + // thirdPartyToken is what a third-party access token's claims set // depends on: its lifetime, and the thumbprint of the client // certificate it is bound to. From aa90a333ce3aa7a7f1e147f4d437130aff805dd3 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 09:36:33 +0800 Subject: [PATCH 03/12] fix(client)!: refuse an ID token, JARM or UserInfo response that repeats a claim MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RFC 7519 §4 requires a JWT's claim names to be unique, and lets a recipient either reject a repeat or keep the lexically last copy. The client kept the last: the ID token and JARM parsers, and the UserInfo decoder (for a plain JSON body and a signed response's payload alike), decoded into a map with encoding/json. An ID token or UserInfo response naming sub twice, or a JARM response naming iss or code twice, was read by its last copy, where another reader of the same message that keeps the first copy (a gateway, a log processor, a second verifier) reads the other, so the two would disagree on who signed in or which code to redeem. Each now runs strictjson.CheckDuplicateMembers first, as the JOSE header parsers already do, refusing a claims set or UserInfo body that repeats a member name at any depth, or holds two names that differ only in case. The client answers such a response with invalid_response, as for any malformed one. A conformant response is unaffected. BREAKING CHANGE: an ID token, JARM response or UserInfo response that repeats a member name, or holds two names that differ only in case, is now refused with invalid_response, where its last copy was used before. Co-Authored-By: Claude Opus 5.5 --- client/userinfo.go | 11 +++++++- client/userinfo_duplicate_members_test.go | 31 +++++++++++++++++++++++ internal/jarm/claims.go | 8 +++--- internal/jarm/claims_object.go | 25 ++++++++++++++++++ internal/jarm/duplicate_claims_test.go | 27 ++++++++++++++++++++ internal/token/duplicate_claims_test.go | 10 ++++++-- internal/token/idtoken.go | 8 +++--- 7 files changed, 111 insertions(+), 9 deletions(-) create mode 100644 client/userinfo_duplicate_members_test.go create mode 100644 internal/jarm/claims_object.go create mode 100644 internal/jarm/duplicate_claims_test.go diff --git a/client/userinfo.go b/client/userinfo.go index 8265db6c..6d3c3f64 100644 --- a/client/userinfo.go +++ b/client/userinfo.go @@ -151,11 +151,20 @@ func (c *Client) decodeUserInfoResponse(ctx context.Context, contentType string, // since two different sub values would then compare equal in // checkUserInfoSubject's exact match against the ID token's sub. A // signed response's payload already passed the same check in -// jose.ParseCompact; a plain-JSON one gets it here. +// jose.ParseCompact; a plain-JSON one gets it here. It refuses, too, a +// body, plain JSON or a signed response's payload, that repeats a member +// name at any depth, or holds two that differ only in case +// (strictjson.CheckDuplicateMembers): encoding/json keeps the last copy, +// where another reader of the same response may keep the first, and so +// see a different sub. RFC 7519 §4 requires a JWT's claim names to be +// unique. func decodeUserInfoJSON(body []byte) (map[string]json.RawMessage, *Error) { if !strictjson.DecodesLosslessly(body) { return nil, newError(ErrorInvalidResponse, "malformed UserInfo response: not valid UTF-8, or an unpaired surrogate escape", nil) } + if err := strictjson.CheckDuplicateMembers(body); err != nil { + return nil, newError(ErrorInvalidResponse, "malformed UserInfo response", err) + } var claims map[string]json.RawMessage if err := json.Unmarshal(body, &claims); err != nil { return nil, newError(ErrorInvalidResponse, "malformed UserInfo response", err) diff --git a/client/userinfo_duplicate_members_test.go b/client/userinfo_duplicate_members_test.go new file mode 100644 index 00000000..1b1bfb10 --- /dev/null +++ b/client/userinfo_duplicate_members_test.go @@ -0,0 +1,31 @@ +package client + +import ( + "errors" + "testing" + + "github.com/idfoundry/fapigo/internal/strictjson" +) + +// TestDecodeUserInfoJSONRefusesDuplicateMembers: a UserInfo response, +// plain JSON or a signed JWT's payload, whose sub is compared with the +// ID token's, may not repeat a member: encoding/json keeps the last +// copy, where another reader of the same response (a gateway, a log +// processor) may keep the first, so the two would see different users. +// RFC 7519 §4 requires unique claim names in a JWT, and RFC 8259 §4 has +// a JSON object's names unique. +func TestDecodeUserInfoJSONRefusesDuplicateMembers(t *testing.T) { + if _, err := decodeUserInfoJSON([]byte(`{"sub":"alice","email":"a@example.com"}`)); err != nil { + t.Fatalf("decodeUserInfoJSON(valid) = %v, want nil", err) + } + for _, body := range []string{ + `{"sub":"mallory","sub":"alice"}`, + `{"sub":"alice","address":{"country":"A","country":"B"}}`, + `{"sub":"alice","SUB":"mallory"}`, + } { + _, err := decodeUserInfoJSON([]byte(body)) + if err == nil || err.Code() != ErrorInvalidResponse || !errors.Is(err, strictjson.ErrDuplicateMember) { + t.Errorf("decodeUserInfoJSON(%s) = %v, want invalid_response for a duplicate member", body, err) + } + } +} diff --git a/internal/jarm/claims.go b/internal/jarm/claims.go index 70f4ac2f..07e59723 100644 --- a/internal/jarm/claims.go +++ b/internal/jarm/claims.go @@ -25,10 +25,12 @@ type Claims struct { Parameters map[string]json.RawMessage } +// parseClaims parses a JARM response's claims set, refusing one +// decodeClaimsObject refuses, such as one that repeats a claim. func parseClaims(payload []byte) (Claims, error) { - var raw map[string]json.RawMessage - if err := json.Unmarshal(payload, &raw); err != nil { - return Claims{}, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + raw, err := decodeClaimsObject(payload) + if err != nil { + return Claims{}, err } iss, _, err := popString(raw, "iss", true) diff --git a/internal/jarm/claims_object.go b/internal/jarm/claims_object.go new file mode 100644 index 00000000..a01a52ed --- /dev/null +++ b/internal/jarm/claims_object.go @@ -0,0 +1,25 @@ +package jarm + +import ( + "encoding/json" + "fmt" + + "github.com/idfoundry/fapigo/internal/strictjson" +) + +// decodeClaimsObject decodes payload, a JWT's claims set, as a JSON +// object, refusing one that repeats a member name at any depth, or holds +// two that differ only in case (strictjson.CheckDuplicateMembers): RFC +// 7519 §4 requires unique claim names, and encoding/json keeps the last +// copy of a repeated one, where another reader of the same JWT may keep +// the first. +func decodeClaimsObject(payload []byte) (map[string]json.RawMessage, error) { + if err := strictjson.CheckDuplicateMembers(payload); err != nil { + return nil, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + } + var raw map[string]json.RawMessage + if err := json.Unmarshal(payload, &raw); err != nil { + return nil, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + } + return raw, nil +} diff --git a/internal/jarm/duplicate_claims_test.go b/internal/jarm/duplicate_claims_test.go new file mode 100644 index 00000000..ec169151 --- /dev/null +++ b/internal/jarm/duplicate_claims_test.go @@ -0,0 +1,27 @@ +package jarm + +import ( + "errors" + "strings" + "testing" +) + +// TestParseClaimsRefusesDuplicateMembers: RFC 7519 §4 requires a JWT's +// claim names to be unique. encoding/json keeps the last copy of a +// repeated one, where a first-wins reader of the same JWT keeps the +// first, so the two would act on different claims. A claims set that +// repeats a member, at any depth, is refused. +func TestParseClaimsRefusesDuplicateMembers(t *testing.T) { + if _, err := parseClaims([]byte(`{"iss":"https://as.example","aud":"client-1","exp":9999999999,"code":"c"}`)); err != nil { + t.Fatalf("parseClaims(valid) = %v, want nil", err) + } + for _, payload := range []string{ + `{"iss":"https://evil.example","aud":"client-1","exp":9999999999,"code":"c","iss":"https://as.example"}`, + `{"iss":"https://as.example","aud":"client-1","exp":9999999999,"code":"a","code":"b"}`, + } { + _, err := parseClaims([]byte(payload)) + if !errors.Is(err, ErrMalformedClaims) || !strings.Contains(err.Error(), "duplicate member name") { + t.Errorf("parseClaims(%s) = %v, want ErrMalformedClaims for a duplicate member", payload, err) + } + } +} diff --git a/internal/token/duplicate_claims_test.go b/internal/token/duplicate_claims_test.go index bb6fb762..edee6068 100644 --- a/internal/token/duplicate_claims_test.go +++ b/internal/token/duplicate_claims_test.go @@ -10,15 +10,20 @@ import ( // claim names to be unique. encoding/json keeps the last copy of a // repeated one, where a first-wins reader of the same token (a gateway, // a log processor) keeps the first, so the two would disagree on who -// the token is for. A JWT access token that repeats a member, at any -// depth, is refused. +// the token is for. An ID token or JWT access token that repeats a +// member, at any depth, is refused. func TestParseClaimsRefuseDuplicateMembers(t *testing.T) { + const idToken = `"iss":"https://as.example.com","aud":"client-1","exp":2,"iat":1` const accessToken = `"iss":"https://as.example.com","aud":"https://rs.example.com","exp":2,"iat":1,"jti":"j","client_id":"c"` for name, tc := range map[string]struct { parse func([]byte) error payload string wantErr bool }{ + "ID token": {parseID, `{` + idToken + `,"sub":"alice"}`, false}, + "ID token, sub twice": {parseID, `{"sub":"mallory",` + idToken + `,"sub":"alice"}`, true}, + "ID token, nested repeat": {parseID, `{` + idToken + `,"sub":"alice","address":{"country":"A","country":"B"}}`, true}, + "ID token, case variant": {parseID, `{` + idToken + `,"sub":"alice","SUB":"mallory"}`, true}, "access token": {parseAT, `{` + accessToken + `,"sub":"alice"}`, false}, "access token, sub twice": {parseAT, `{"sub":"mallory",` + accessToken + `,"sub":"alice"}`, true}, "access token, scope twice": {parseAT, `{` + accessToken + `,"sub":"alice","scope":"admin","scope":"read"}`, true}, @@ -31,6 +36,7 @@ func TestParseClaimsRefuseDuplicateMembers(t *testing.T) { } } +func parseID(p []byte) error { _, err := parseIDTokenClaims(p); return err } func parseAT(p []byte) error { _, err := parseAccessTokenClaims(p); return err } // checkDuplicateRefusal checks err is nil, or, when wantErr, that it is diff --git a/internal/token/idtoken.go b/internal/token/idtoken.go index 6edc0e22..8bd29422 100644 --- a/internal/token/idtoken.go +++ b/internal/token/idtoken.go @@ -38,10 +38,12 @@ type IDTokenClaims struct { Parameters map[string]json.RawMessage } +// parseIDTokenClaims parses an ID token's claims set, refusing one +// decodeClaimsObject refuses, such as one that repeats a claim. func parseIDTokenClaims(payload []byte) (IDTokenClaims, error) { - var raw map[string]json.RawMessage - if err := json.Unmarshal(payload, &raw); err != nil { - return IDTokenClaims{}, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + raw, err := decodeClaimsObject(payload) + if err != nil { + return IDTokenClaims{}, err } iss, _, err := popString(raw, "iss", true) From b91e3ce3ae6c863475c3864438d6dfeefb05c98e Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 09:36:43 +0800 Subject: [PATCH 04/12] fix(server)!: refuse a request object, assertion or proof that repeats a claim MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RFC 7519 §4 requires a JWT's claim names to be unique, and lets a recipient either reject a repeat or keep the lexically last copy. The server's parsers for request objects (and signed CIBA requests), client assertions, DPoP proofs and attestation PoPs kept the last copy, which is what encoding/json does. A first-wins reader of the same JWT reads the first, so a request object naming scope twice, an assertion naming aud twice or a proof naming htm or htu twice meant one thing to the server and another to a gateway or audit log in front of it. The DPoP parser is shared with the resource server. Each now refuses a claims set that repeats a member name at any depth, or holds two names that differ only in case (strictjson.CheckDuplicateMembers), as a client attestation's claims and the JOSE headers already were. The PoP parser reuses the attestation's unmarshalUniqueMembers, and the DPoP parser strictjson.UnmarshalNoRepeats. The server answers such a request object with invalid_request_object, a signed CIBA request with invalid_request, a client assertion or attestation PoP with invalid_client, and a DPoP proof with invalid_dpop_proof; a resource server answers the proof with invalid_dpop_proof. A conformant JWT is unaffected. BREAKING CHANGE: a request object, signed CIBA request, client assertion, DPoP proof or attestation PoP that repeats a member name, or holds two names that differ only in case, is now refused, where its last copy was used before. Co-Authored-By: Claude Opus 5.5 --- internal/clientassertion/claims.go | 6 +++++ .../clientassertion/duplicate_claims_test.go | 27 +++++++++++++++++++ internal/clientattestation/claims.go | 10 ++++--- .../pop_duplicate_claims_test.go | 27 +++++++++++++++++++ internal/dpop/duplicate_claims_test.go | 27 +++++++++++++++++++ internal/dpop/proof.go | 5 +++- internal/requestobject/claims.go | 8 +++--- internal/requestobject/claims_object.go | 25 +++++++++++++++++ .../requestobject/duplicate_claims_test.go | 27 +++++++++++++++++++ 9 files changed, 154 insertions(+), 8 deletions(-) create mode 100644 internal/clientassertion/duplicate_claims_test.go create mode 100644 internal/clientattestation/pop_duplicate_claims_test.go create mode 100644 internal/dpop/duplicate_claims_test.go create mode 100644 internal/requestobject/claims_object.go create mode 100644 internal/requestobject/duplicate_claims_test.go diff --git a/internal/clientassertion/claims.go b/internal/clientassertion/claims.go index efaec554..05b9df37 100644 --- a/internal/clientassertion/claims.go +++ b/internal/clientassertion/claims.go @@ -53,6 +53,12 @@ type claims struct { func parseClaims(payload []byte) (claims, error) { dec := json.NewDecoder(bytes.NewReader(payload)) var c claims + // RFC 7519 §4 requires unique claim names: encoding/json keeps the + // last copy of a repeated one, where another reader of the same + // assertion may keep the first. + if err := strictjson.CheckDuplicateMembers(payload); err != nil { + return claims{}, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + } if err := strictjson.CheckFieldCase(payload, &c); err != nil { return claims{}, fmt.Errorf("%w: %v", ErrMalformedClaims, err) } diff --git a/internal/clientassertion/duplicate_claims_test.go b/internal/clientassertion/duplicate_claims_test.go new file mode 100644 index 00000000..915f62d7 --- /dev/null +++ b/internal/clientassertion/duplicate_claims_test.go @@ -0,0 +1,27 @@ +package clientassertion + +import ( + "errors" + "strings" + "testing" +) + +// TestParseClaimsRefusesDuplicateMembers: RFC 7519 §4 requires a JWT's +// claim names to be unique. encoding/json keeps the last copy of a +// repeated one, where a first-wins reader of the same JWT keeps the +// first, so the two would act on different claims. A claims set that +// repeats a member, at any depth, is refused. +func TestParseClaimsRefusesDuplicateMembers(t *testing.T) { + if _, err := parseClaims([]byte(`{"iss":"c","sub":"c","aud":"https://as.example.com","exp":2,"iat":1,"jti":"j"}`)); err != nil { + t.Fatalf("parseClaims(valid) = %v, want nil", err) + } + for _, payload := range []string{ + `{"iss":"c","sub":"c","aud":"https://other.example","exp":2,"iat":1,"jti":"j","aud":"https://as.example.com"}`, + `{"iss":"c","sub":"c","aud":"https://as.example.com","exp":2,"iat":1,"jti":"a","jti":"b"}`, + } { + _, err := parseClaims([]byte(payload)) + if !errors.Is(err, ErrMalformedClaims) || !strings.Contains(err.Error(), "duplicate member name") { + t.Errorf("parseClaims(%s) = %v, want ErrMalformedClaims for a duplicate member", payload, err) + } + } +} diff --git a/internal/clientattestation/claims.go b/internal/clientattestation/claims.go index b7b524da..41c4e01d 100644 --- a/internal/clientattestation/claims.go +++ b/internal/clientattestation/claims.go @@ -52,9 +52,11 @@ func parseAttestationClaims(payload []byte) (attestationClaims, error) { // unmarshalUniqueMembers is strictjson.Unmarshal for a claims set that // repeats no member name at any depth (RFC 7519 §4 requires unique -// claim names): encoding/json would merge two copies of cnf into one, -// and check the case of only the last, where VerifiedAttestation.Claims, -// like another implementation, keeps only the last copy. +// claim names), an attestation's or a PoP's: encoding/json would merge +// two copies of cnf into one, and check the case of only the last, where +// VerifiedAttestation.Claims, like another implementation, keeps only +// the last copy; and it keeps the last copy of a PoP's aud or jti, where +// another reader of the same PoP may keep the first. func unmarshalUniqueMembers(payload []byte, v any) error { if err := strictjson.CheckDuplicateMembers(payload); err != nil { return err @@ -111,7 +113,7 @@ func (a *popAudience) UnmarshalJSON(data []byte) error { func parsePoPClaims(payload []byte) (popClaims, error) { var c popClaims - if err := strictjson.Unmarshal(payload, &c); err != nil { + if err := unmarshalUniqueMembers(payload, &c); err != nil { return popClaims{}, fmt.Errorf("%w: %v", ErrMalformedClaims, err) } if c.Audience == "" || c.JTI == "" || c.IssuedAt == 0 { diff --git a/internal/clientattestation/pop_duplicate_claims_test.go b/internal/clientattestation/pop_duplicate_claims_test.go new file mode 100644 index 00000000..e5ac954a --- /dev/null +++ b/internal/clientattestation/pop_duplicate_claims_test.go @@ -0,0 +1,27 @@ +package clientattestation + +import ( + "errors" + "strings" + "testing" +) + +// TestParsePoPClaimsRefusesDuplicateMembers: an attestation PoP is a +// JWT, whose claim names RFC 7519 §4 requires to be unique, like the +// attestation's own (TestParseAttestationClaimsRefusesDuplicateMembers). +// encoding/json keeps the last copy of a repeated one where another +// reader keeps the first, so a PoP that repeats a member is refused. +func TestParsePoPClaimsRefusesDuplicateMembers(t *testing.T) { + if _, err := parsePoPClaims([]byte(`{"iss":"c","aud":"a","jti":"j","iat":1}`)); err != nil { + t.Fatalf("parsePoPClaims(valid) = %v, want nil", err) + } + for _, payload := range []string{ + `{"iss":"c","aud":"https://other.example","jti":"j","iat":1,"aud":"a"}`, + `{"iss":"c","aud":"a","jti":"j","iat":1,"jti":"k"}`, + } { + _, err := parsePoPClaims([]byte(payload)) + if !errors.Is(err, ErrMalformedClaims) || !strings.Contains(err.Error(), "duplicate member name") { + t.Errorf("parsePoPClaims(%s) = %v, want ErrMalformedClaims for a duplicate member", payload, err) + } + } +} diff --git a/internal/dpop/duplicate_claims_test.go b/internal/dpop/duplicate_claims_test.go new file mode 100644 index 00000000..72ead0d2 --- /dev/null +++ b/internal/dpop/duplicate_claims_test.go @@ -0,0 +1,27 @@ +package dpop + +import ( + "errors" + "strings" + "testing" +) + +// TestParseClaimsRefusesDuplicateMembers: RFC 7519 §4 requires a JWT's +// claim names to be unique. encoding/json keeps the last copy of a +// repeated one, where a first-wins reader of the same JWT keeps the +// first, so the two would act on different claims. A claims set that +// repeats a member, at any depth, is refused. +func TestParseClaimsRefusesDuplicateMembers(t *testing.T) { + if _, err := parseClaims([]byte(`{"jti":"j","htm":"POST","htu":"https://rs.example.com/","iat":1}`)); err != nil { + t.Fatalf("parseClaims(valid) = %v, want nil", err) + } + for _, payload := range []string{ + `{"jti":"j","htm":"GET","htu":"https://rs.example.com/","iat":1,"htm":"POST"}`, + `{"jti":"j","htm":"POST","htu":"https://other.example/","htu":"https://rs.example.com/","iat":1}`, + } { + _, err := parseClaims([]byte(payload)) + if !errors.Is(err, ErrMalformedClaims) || !strings.Contains(err.Error(), "duplicate member name") { + t.Errorf("parseClaims(%s) = %v, want ErrMalformedClaims for a duplicate member", payload, err) + } + } +} diff --git a/internal/dpop/proof.go b/internal/dpop/proof.go index 7c82a100..da4da93d 100644 --- a/internal/dpop/proof.go +++ b/internal/dpop/proof.go @@ -31,7 +31,10 @@ type claims struct { func parseClaims(payload []byte) (claims, error) { var c claims - if err := strictjson.Unmarshal(payload, &c); err != nil { + // UnmarshalNoRepeats: RFC 7519 §4 requires unique claim names, and + // encoding/json keeps the last copy of a repeated one, where another + // reader of the same proof may keep the first. + if err := strictjson.UnmarshalNoRepeats(payload, &c); err != nil { return claims{}, fmt.Errorf("%w: %v", ErrMalformedClaims, err) } if c.JTI == "" || c.HTM == "" || c.HTU == "" { diff --git a/internal/requestobject/claims.go b/internal/requestobject/claims.go index 478f8819..f3e41190 100644 --- a/internal/requestobject/claims.go +++ b/internal/requestobject/claims.go @@ -67,10 +67,12 @@ type Claims struct { Parameters map[string]json.RawMessage } +// parseClaims parses a request object's claims set, refusing one +// decodeClaimsObject refuses, such as one that repeats a claim. func parseClaims(payload []byte) (Claims, error) { - var raw map[string]json.RawMessage - if err := json.Unmarshal(payload, &raw); err != nil { - return Claims{}, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + raw, err := decodeClaimsObject(payload) + if err != nil { + return Claims{}, err } iss, _, err := popString(raw, "iss", true) diff --git a/internal/requestobject/claims_object.go b/internal/requestobject/claims_object.go new file mode 100644 index 00000000..4e10eb0e --- /dev/null +++ b/internal/requestobject/claims_object.go @@ -0,0 +1,25 @@ +package requestobject + +import ( + "encoding/json" + "fmt" + + "github.com/idfoundry/fapigo/internal/strictjson" +) + +// decodeClaimsObject decodes payload, a JWT's claims set, as a JSON +// object, refusing one that repeats a member name at any depth, or holds +// two that differ only in case (strictjson.CheckDuplicateMembers): RFC +// 7519 §4 requires unique claim names, and encoding/json keeps the last +// copy of a repeated one, where another reader of the same JWT may keep +// the first. +func decodeClaimsObject(payload []byte) (map[string]json.RawMessage, error) { + if err := strictjson.CheckDuplicateMembers(payload); err != nil { + return nil, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + } + var raw map[string]json.RawMessage + if err := json.Unmarshal(payload, &raw); err != nil { + return nil, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + } + return raw, nil +} diff --git a/internal/requestobject/duplicate_claims_test.go b/internal/requestobject/duplicate_claims_test.go new file mode 100644 index 00000000..cad95b8a --- /dev/null +++ b/internal/requestobject/duplicate_claims_test.go @@ -0,0 +1,27 @@ +package requestobject + +import ( + "errors" + "strings" + "testing" +) + +// TestParseClaimsRefusesDuplicateMembers: RFC 7519 §4 requires a JWT's +// claim names to be unique. encoding/json keeps the last copy of a +// repeated one, where a first-wins reader of the same JWT keeps the +// first, so the two would act on different claims. A claims set that +// repeats a member, at any depth, is refused. +func TestParseClaimsRefusesDuplicateMembers(t *testing.T) { + if _, err := parseClaims([]byte(`{"iss":"client-123","aud":"https://as.example","exp":4102444800,"scope":"openid"}`)); err != nil { + t.Fatalf("parseClaims(valid) = %v, want nil", err) + } + for _, payload := range []string{ + `{"iss":"client-123","aud":"https://as.example","exp":4102444800,"scope":"openid","scope":"openid payments"}`, + `{"iss":"client-123","aud":"https://as.example","exp":4102444800,"claims":{"id_token":{"acr":{"value":"a"},"acr":{"value":"b"}}}}`, + } { + _, err := parseClaims([]byte(payload)) + if !errors.Is(err, ErrMalformedClaims) || !strings.Contains(err.Error(), "duplicate member name") { + t.Errorf("parseClaims(%s) = %v, want ErrMalformedClaims for a duplicate member", payload, err) + } + } +} From ef44204b225a655e0c2a1cc9bb8f4e4636bb52d8 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 09:37:00 +0800 Subject: [PATCH 05/12] fix(federation)!: refuse a Trust Mark or federation response that repeats a claim MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Entity Statements already refused a repeated member name, but the other federation JWTs did not: Trust Marks, Trust Mark Delegations, Trust Mark Status responses, Resolve responses and Historical Keys responses decoded their claims sets into a map with encoding/json, which keeps the last copy of a repeated member. A Trust Mark Status response naming status twice, or a Resolve response naming sub twice, was read by its last copy, where another resolver reading the same signed response may keep the first. RFC 7519 §4 requires unique claim names. Each parser now decodes its claims set through decodeClaimsObject, which runs refuseDuplicateMembers first, as Entity Statements do, and refuses a repeat at any depth, or two names that differ only in case, with ErrMalformedClaims. A Historical Keys entry's repeated "revoked" is now refused rather than read from its last copy. Resolve response trust_marks parsing moves into its own function, unchanged, to keep the parser's complexity down. A conformant JWT is unaffected. BREAKING CHANGE: a Trust Mark, Trust Mark Delegation or Status response, Resolve response or Historical Keys response that repeats a member name, or holds two names that differ only in case, is now refused, where its last copy was used before. Co-Authored-By: Claude Opus 5.5 --- .../claims_duplicate_members_test.go | 54 +++++++++++++++++++ internal/federation/claims_validation.go | 18 ++++++- internal/federation/historicalkeys.go | 11 ++-- internal/federation/resolveresponse.go | 41 ++++++++------ internal/federation/trustmark.go | 12 ++--- internal/federation/trustmarkstatus.go | 7 ++- 6 files changed, 111 insertions(+), 32 deletions(-) create mode 100644 internal/federation/claims_duplicate_members_test.go diff --git a/internal/federation/claims_duplicate_members_test.go b/internal/federation/claims_duplicate_members_test.go new file mode 100644 index 00000000..fc2a32e4 --- /dev/null +++ b/internal/federation/claims_duplicate_members_test.go @@ -0,0 +1,54 @@ +package federation + +import ( + "errors" + "strings" + "testing" +) + +// TestParseFederationJWTClaimsRefuseDuplicateMembers: an Entity +// Statement already refuses a repeated member (verify.go); the other +// federation JWTs (Trust Marks, Trust Mark Delegations, Trust Mark +// Status, Resolve and Historical Keys responses) do too. RFC 7519 §4 +// requires unique claim names, and encoding/json keeps the last copy of +// a repeated one where another reader of the same JWT may keep the +// first, so the two would see, say, different statuses or subjects. +func TestParseFederationJWTClaimsRefuseDuplicateMembers(t *testing.T) { + const tm = `"iss":"https://ta.example","sub":"https://rp.example","trust_mark_type":"https://ta.example/tm","iat":1` + const status = `"iss":"https://ta.example","trust_mark":"x.y.z","iat":1` + const resolve = `"iss":"https://ta.example","iat":1,"exp":2,"metadata":{"openid_relying_party":{}},"trust_chain":["a.b.c"]` + const historical = `"iss":"https://ta.example","iat":1,"keys":[]` + for name, tc := range map[string]struct { + parse func([]byte) error + payload string + wantErr bool + }{ + "trust mark": {parseTM, `{` + tm + `}`, false}, + "trust mark, sub twice": {parseTM, `{"sub":"https://other.example",` + tm + `}`, true}, + "delegation": {parseTMD, `{` + tm + `}`, false}, + "delegation, sub twice": {parseTMD, `{"sub":"https://other.example",` + tm + `}`, true}, + "status": {parseTMS, `{` + status + `,"status":"active"}`, false}, + "status twice": {parseTMS, `{"status":"revoked",` + status + `,"status":"active"}`, true}, + "resolve": {parseRR, `{"sub":"https://rp.example",` + resolve + `}`, false}, + "resolve, sub twice": {parseRR, `{"sub":"https://other.example",` + resolve + `,"sub":"https://rp.example"}`, true}, + "resolve, nested repeat": {parseRR, `{"sub":"https://rp.example",` + resolve + `,"x":{"a":1,"a":2}}`, true}, + "historical keys": {parseHK, `{` + historical + `}`, false}, + "historical keys twice": {parseHK, `{` + historical + `,"keys":[]}`, true}, + } { + t.Run(name, func(t *testing.T) { + err := tc.parse([]byte(tc.payload)) + switch { + case !tc.wantErr && err != nil: + t.Fatalf("parse = %v, want nil", err) + case tc.wantErr && (!errors.Is(err, ErrMalformedClaims) || !strings.Contains(err.Error(), "duplicate member name")): + t.Fatalf("parse = %v, want ErrMalformedClaims for a duplicate member", err) + } + }) + } +} + +func parseTM(p []byte) error { _, err := parseTrustMarkClaims(p); return err } +func parseTMD(p []byte) error { _, err := parseTrustMarkDelegationClaims(p); return err } +func parseTMS(p []byte) error { _, err := parseTrustMarkStatusResponseClaims(p); return err } +func parseRR(p []byte) error { _, err := parseResolveResponseClaims(p); return err } +func parseHK(p []byte) error { _, err := parseHistoricalKeysClaims(p); return err } diff --git a/internal/federation/claims_validation.go b/internal/federation/claims_validation.go index 3d182a1a..2ccbf0c7 100644 --- a/internal/federation/claims_validation.go +++ b/internal/federation/claims_validation.go @@ -146,7 +146,10 @@ func isHTTPSURL(s string) bool { // silently, and reads names that differ only in case as one, while // another implementation may keep the first, or read two, so two // validators could derive different claims — a different metadata -// policy, say — from one signed statement. §6.1.2 forbids "Duplicate +// policy, say — from one signed statement. Every federation JWT's +// claims parser runs it: Entity Statements', and Trust Marks', Trust +// Mark Delegations', Trust Mark Status, Resolve and Historical Keys +// responses'. §6.1.2 forbids "Duplicate // JSON object member names ... at any of the three levels of the // metadata_policy Claim data structure"; RFC 7519 §4 lets a JWT parser // reject duplicate claim names, which this applies at every level. @@ -156,3 +159,16 @@ func refuseDuplicateMembers(payload []byte) error { } return nil } + +// decodeClaimsObject decodes payload, a federation JWT's claims set, as +// a JSON object, after refuseDuplicateMembers. +func decodeClaimsObject(payload []byte) (map[string]json.RawMessage, error) { + if err := refuseDuplicateMembers(payload); err != nil { + return nil, err + } + var raw map[string]json.RawMessage + if err := json.Unmarshal(payload, &raw); err != nil { + return nil, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + } + return raw, nil +} diff --git a/internal/federation/historicalkeys.go b/internal/federation/historicalkeys.go index dd513cc8..4549cd8a 100644 --- a/internal/federation/historicalkeys.go +++ b/internal/federation/historicalkeys.go @@ -208,8 +208,9 @@ func (r HistoricalKeysResponse) Verify(pub crypto.PublicKey, policy HistoricalKe // detection and shape validation rather than duplicating it. "revoked" // stays raw until decodeKeyRevocation reads it: encoding/json would // merge the copies of a repeated "revoked" into one struct, taking -// revoked_at from one and reason from another, where a json.RawMessage -// keeps the last copy, as it does for every other member here. +// revoked_at from one and reason from another. parseHistoricalKeysClaims +// refuses a repeated member anywhere in the claims set before any of +// them is decoded, so neither a merge nor a last copy is ever read. type rawHistoricalKey struct { IAT *numericdate.Value `json:"iat"` EXP *numericdate.Value `json:"exp"` @@ -238,9 +239,9 @@ func decodeKeyRevocation(raw json.RawMessage) (*rawKeyRevocation, bool) { } func parseHistoricalKeysClaims(payload []byte) (HistoricalKeysClaims, error) { - var raw map[string]json.RawMessage - if err := json.Unmarshal(payload, &raw); err != nil { - return HistoricalKeysClaims{}, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + raw, err := decodeClaimsObject(payload) + if err != nil { + return HistoricalKeysClaims{}, err } iss, err := popRequiredString(raw, "iss") diff --git a/internal/federation/resolveresponse.go b/internal/federation/resolveresponse.go index e837fd2e..ee4ba68f 100644 --- a/internal/federation/resolveresponse.go +++ b/internal/federation/resolveresponse.go @@ -170,9 +170,9 @@ func (r ResolveResponse) Verify(pub crypto.PublicKey, policy ResolveResponseVeri } func parseResolveResponseClaims(payload []byte) (ResolveResponseClaims, error) { - var raw map[string]json.RawMessage - if err := json.Unmarshal(payload, &raw); err != nil { - return ResolveResponseClaims{}, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + raw, err := decodeClaimsObject(payload) + if err != nil { + return ResolveResponseClaims{}, err } iss, err := popRequiredString(raw, "iss") @@ -214,24 +214,33 @@ func parseResolveResponseClaims(payload []byte) (ResolveResponseClaims, error) { Metadata: metadata, TrustChain: trustChain, } if trustMarksRaw, ok := raw["trust_marks"]; ok { - var trustMarks []struct { - TrustMarkType string `json:"trust_mark_type"` - TrustMark string `json:"trust_mark"` - } - if err := json.Unmarshal(trustMarksRaw, &trustMarks); err != nil { - return ResolveResponseClaims{}, fmt.Errorf("%w: trust_marks: %v", ErrMalformedClaims, err) - } - c.TrustMarks = make([]RawTrustMark, len(trustMarks)) - for i, tm := range trustMarks { - if tm.TrustMarkType == "" || tm.TrustMark == "" { - return ResolveResponseClaims{}, fmt.Errorf("%w: trust_marks[%d]: trust_mark_type and trust_mark are both required", ErrMalformedClaims, i) - } - c.TrustMarks[i] = RawTrustMark{TrustMarkType: tm.TrustMarkType, TrustMark: tm.TrustMark} + if c.TrustMarks, err = parseResolveTrustMarks(trustMarksRaw); err != nil { + return ResolveResponseClaims{}, err } } return c, nil } +// parseResolveTrustMarks parses a Resolve Response's "trust_marks": an +// array of objects, each with a trust_mark_type and a trust_mark. +func parseResolveTrustMarks(raw json.RawMessage) ([]RawTrustMark, error) { + var trustMarks []struct { + TrustMarkType string `json:"trust_mark_type"` + TrustMark string `json:"trust_mark"` + } + if err := json.Unmarshal(raw, &trustMarks); err != nil { + return nil, fmt.Errorf("%w: trust_marks: %v", ErrMalformedClaims, err) + } + out := make([]RawTrustMark, len(trustMarks)) + for i, tm := range trustMarks { + if tm.TrustMarkType == "" || tm.TrustMark == "" { + return nil, fmt.Errorf("%w: trust_marks[%d]: trust_mark_type and trust_mark are both required", ErrMalformedClaims, i) + } + out[i] = RawTrustMark{TrustMarkType: tm.TrustMarkType, TrustMark: tm.TrustMark} + } + return out, nil +} + // CreateResolveResponseParams describes one Resolve Response to create // (OpenID Federation 1.0 §8.3.2). This is a low-level signing primitive // only — it does not itself perform a Trust Chain resolution or decide diff --git a/internal/federation/trustmark.go b/internal/federation/trustmark.go index 6a44f395..e4b0b319 100644 --- a/internal/federation/trustmark.go +++ b/internal/federation/trustmark.go @@ -178,9 +178,9 @@ func (tm TrustMark) Verify(pub crypto.PublicKey, policy TrustMarkVerifyPolicy) ( } func parseTrustMarkClaims(payload []byte) (TrustMarkClaims, error) { - var raw map[string]json.RawMessage - if err := json.Unmarshal(payload, &raw); err != nil { - return TrustMarkClaims{}, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + raw, err := decodeClaimsObject(payload) + if err != nil { + return TrustMarkClaims{}, err } iss, err := popRequiredString(raw, "iss") @@ -494,9 +494,9 @@ func (d TrustMarkDelegation) Verify(pub crypto.PublicKey, policy TrustMarkDelega } func parseTrustMarkDelegationClaims(payload []byte) (TrustMarkDelegationClaims, error) { - var raw map[string]json.RawMessage - if err := json.Unmarshal(payload, &raw); err != nil { - return TrustMarkDelegationClaims{}, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + raw, err := decodeClaimsObject(payload) + if err != nil { + return TrustMarkDelegationClaims{}, err } iss, err := popRequiredString(raw, "iss") diff --git a/internal/federation/trustmarkstatus.go b/internal/federation/trustmarkstatus.go index cd321f87..72e5fb34 100644 --- a/internal/federation/trustmarkstatus.go +++ b/internal/federation/trustmarkstatus.go @@ -2,7 +2,6 @@ package federation import ( "crypto" - "encoding/json" "fmt" "time" @@ -176,9 +175,9 @@ func (r TrustMarkStatusResponse) Verify(pub crypto.PublicKey, policy TrustMarkSt } func parseTrustMarkStatusResponseClaims(payload []byte) (TrustMarkStatusResponseClaims, error) { - var raw map[string]json.RawMessage - if err := json.Unmarshal(payload, &raw); err != nil { - return TrustMarkStatusResponseClaims{}, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + raw, err := decodeClaimsObject(payload) + if err != nil { + return TrustMarkStatusResponseClaims{}, err } iss, err := popRequiredString(raw, "iss") From aeedf34c90ebeb669f67f31fd62a9299062e272f Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 09:37:10 +0800 Subject: [PATCH 06/12] test: show a first-wins reader and encoding/json disagree on a repeated claim MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RFC 7515 §10.12 warns that two JSON parsers can take different values from an object that repeats a member. A new strictjson test models a first-wins reader beside encoding/json, which keeps the last copy, on a repeated sub, aud and kid, shows they disagree, and checks that CheckDuplicateMembers refuses each, so no FAPIgo parser that runs it acts on either reading. strictjson's package doc said only the JOSE headers, attestation claims, metadata and Entity Statements ran CheckDuplicateMembers, and that the other claims sets kept encoding/json's last copy. It now lists every JWT claims parser, the UserInfo decoder and the token, PAR and CIBA response decoders, all of which refuse a repeat. Co-Authored-By: Claude Opus 5.5 --- .../first_wins_differential_test.go | 60 +++++++++++++++++++ internal/strictjson/strictjson.go | 20 ++++--- 2 files changed, 72 insertions(+), 8 deletions(-) create mode 100644 internal/strictjson/first_wins_differential_test.go diff --git a/internal/strictjson/first_wins_differential_test.go b/internal/strictjson/first_wins_differential_test.go new file mode 100644 index 00000000..d61b6f18 --- /dev/null +++ b/internal/strictjson/first_wins_differential_test.go @@ -0,0 +1,60 @@ +package strictjson + +import ( + "bytes" + "encoding/json" + "errors" + "testing" +) + +// TestCheckDuplicateMembersClosesFirstWinsDifferential models the +// intermediary RFC 7515 §10.12 warns about: a reader that keeps the +// first copy of a repeated member (as some streaming JSON path readers +// do) and encoding/json, which keeps the last, take different values +// from one claims set. CheckDuplicateMembers, which every JWT claims +// parser runs, refuses the claims set, so neither reading is acted on. +func TestCheckDuplicateMembersClosesFirstWinsDifferential(t *testing.T) { + for _, tc := range []struct{ payload, member, first, last string }{ + {`{"sub":"alice","aud":"rs","sub":"admin"}`, "sub", `"alice"`, `"admin"`}, + {`{"aud":"https://evil.example","iss":"c","aud":"https://as.example"}`, "aud", `"https://evil.example"`, `"https://as.example"`}, + {`{"alg":"ES256","kid":"a","kid":"b"}`, "kid", `"a"`, `"b"`}, + } { + var lastWins map[string]json.RawMessage + if err := json.Unmarshal([]byte(tc.payload), &lastWins); err != nil { + t.Fatal(err) + } + if got := string(lastWins[tc.member]); got != tc.last { + t.Fatalf("encoding/json read %s = %s, want %s", tc.member, got, tc.last) + } + if got := firstWins(t, tc.payload, tc.member); got != tc.first { + t.Fatalf("first-wins reader read %s = %s, want %s", tc.member, got, tc.first) + } + if err := CheckDuplicateMembers([]byte(tc.payload)); !errors.Is(err, ErrDuplicateMember) { + t.Errorf("CheckDuplicateMembers(%s) = %v, want ErrDuplicateMember", tc.payload, err) + } + } +} + +// firstWins returns the first copy of member in payload, a flat JSON +// object of scalar members, as a first-wins reader would. +func firstWins(t *testing.T, payload, member string) string { + t.Helper() + dec := json.NewDecoder(bytes.NewReader([]byte(payload))) + if _, err := dec.Token(); err != nil { // "{" + t.Fatal(err) + } + for dec.More() { + name, err := dec.Token() + if err != nil { + t.Fatal(err) + } + var value json.RawMessage + if err := dec.Decode(&value); err != nil { + t.Fatal(err) + } + if name == member { + return string(value) + } + } + return "" +} diff --git a/internal/strictjson/strictjson.go b/internal/strictjson/strictjson.go index 0578f2b2..b2187511 100644 --- a/internal/strictjson/strictjson.go +++ b/internal/strictjson/strictjson.go @@ -19,14 +19,18 @@ // // A member repeated in one object is the other difference: encoding/json // keeps the last copy, or merges the copies of one that decodes into a -// struct or a map, and the case check sees only the last copy. The JWS -// and JWE header parsers, a client attestation's claims, the metadata -// parser and Entity Statements run CheckDuplicateMembers first, which -// refuses a repeated name, or two names FoldKey maps together, at any -// depth. The other claims sets decoded with this package (DPoP proofs, -// client assertions, attestation PoPs) fill only scalar fields, so they -// keep encoding/json's last copy of a repeated claim, which RFC 7519 §4 -// allows. +// struct or a map, and the case check sees only the last copy, while a +// first-wins reader of the same bytes keeps the first. The JWS and JWE +// header parsers, every JWT claims set's parser (ID tokens, JWT access +// tokens, request objects, JARM responses, client assertions, DPoP +// proofs, client attestations and their PoPs, Entity Statements and the +// other federation JWTs), the UserInfo response decoder, the metadata +// parser and the token, PAR and CIBA response decoders run +// CheckDuplicateMembers first (directly, or through +// UnmarshalNoRepeats), which refuses a repeated name, or two names +// FoldKey maps together, at any depth. RFC 7515 §4 and RFC 7519 §4 let +// a recipient keep the lexically last copy instead; refusing leaves no +// reading for two implementations to disagree on. package strictjson import ( From 29b2fc4a18ea2ca7e8ea1678ef62ef17c0b254a3 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 09:37:31 +0800 Subject: [PATCH 07/12] docs: describe refusing JWTs that repeat a claim in UPGRADING A v0.87.0 section says which peers are affected by the claims parsers now refusing a repeated or case-variant member name, why, the error each path gives, and that a peer must write each claim once. Co-Authored-By: Claude Opus 5.5 --- UPGRADING.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/UPGRADING.md b/UPGRADING.md index 96439747..3fee8df0 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -18,6 +18,41 @@ 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.87.0 + +### A JWT or UserInfo response may not repeat a claim (all packages) + +**Affects:** a deployment whose peer repeats a member name, in any +object at any depth, of a JWT's claims set, or writes two names that +differ only in case there: an authorization server's ID tokens, JARM +responses, UserInfo responses or JWT access tokens; a client's request +objects, signed CIBA requests, client assertions, DPoP proofs or +attestation PoPs; or a federation entity's Trust Marks, Trust Mark +Delegations, Trust Mark Status, Resolve or Historical Keys responses. +v0.81.0 did this for JOSE headers, client attestations, metadata and +Entity Statements; these claims sets kept encoding/json's last copy of +a repeated claim. + +**Why:** RFC 7519 §4 requires a JWT's claim names to be unique, and +lets a recipient reject a repeat or keep the last copy. Keeping the +last copy left a JWT with two readings: another reader of the same +token (a gateway in front of a resource server, a log processor, a +second verifier) that keeps the first copy would see a different +`sub`, `aud` or `scope` than FAPIgo acted on. + +**What fails:** nothing at startup. The server answers such a request +object with `invalid_request_object`, a signed CIBA request with +`invalid_request`, a client assertion or attestation PoP with +`invalid_client`, and a DPoP proof with `invalid_dpop_proof`; a +resource server answers such a JWT access token with `invalid_token`, +and a DPoP proof with `invalid_dpop_proof`. The client refuses such an +ID token, JARM response or UserInfo response, signed, encrypted or +plain JSON, with `invalid_response`. A federation JWT that repeats a +claim fails to parse, with the error its parser gives any malformed one. + +**What to change:** nothing in your code. A peer producing such JWTs +must write each claim once, spelled one way. + ## v0.86.0 ### A Trust Chain that expires while it resolves is refused (federation) From c0b869591efaa2b9d2c0afa3f2c1416abc089ea5 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 09:38:08 +0800 Subject: [PATCH 08/12] test: add mutants for the duplicate-claim checks and SubjectKind One mutant per claims parser that now refuses a repeated member (ID and JWT access tokens, JARM, request objects, client assertions, DPoP proofs, attestation PoPs, federation JWTs and UserInfo responses), each disabling its check, and one making every token read as SubjectEndUser whatever its grant_type claim. Co-Authored-By: Claude Opus 5.5 --- .github/mutation/mutants.json | 109 ++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/.github/mutation/mutants.json b/.github/mutation/mutants.json index 80bbefdb..75a67f06 100644 --- a/.github/mutation/mutants.json +++ b/.github/mutation/mutants.json @@ -5814,5 +5814,114 @@ ], "run": "^TestBackchannelDecisionsAndExpiry$", "why": "sqlstore wraps ErrBackchannelAuthenticationNotFound for an unknown CIBA handle" + }, + { + "id": "token-claims-refuse-duplicate-members", + "file": "internal/token/claims_object.go", + "old": "if err := strictjson.CheckDuplicateMembers(payload); err != nil {", + "new": "if err := strictjson.CheckDuplicateMembers(payload); err != nil && false {", + "module": "root", + "packages": [ + "./internal/token", + "./resource" + ], + "run": "^(TestParseClaimsRefuseDuplicateMembers|TestVerifyRefusesJWTAccessTokenRepeatingAClaim)$", + "why": "ID token and JWT access token claims sets that repeat a member are refused, not read last-wins" + }, + { + "id": "jarm-claims-refuse-duplicate-members", + "file": "internal/jarm/claims_object.go", + "old": "if err := strictjson.CheckDuplicateMembers(payload); err != nil {", + "new": "if err := strictjson.CheckDuplicateMembers(payload); err != nil && false {", + "module": "root", + "packages": [ + "./internal/jarm" + ], + "run": "^TestParseClaimsRefusesDuplicateMembers$", + "why": "a JARM claims set that repeats a member is refused" + }, + { + "id": "requestobject-claims-refuse-duplicate-members", + "file": "internal/requestobject/claims_object.go", + "old": "if err := strictjson.CheckDuplicateMembers(payload); err != nil {", + "new": "if err := strictjson.CheckDuplicateMembers(payload); err != nil && false {", + "module": "root", + "packages": [ + "./internal/requestobject" + ], + "run": "^TestParseClaimsRefusesDuplicateMembers$", + "why": "a request object claims set that repeats a member is refused" + }, + { + "id": "clientassertion-claims-refuse-duplicate-members", + "file": "internal/clientassertion/claims.go", + "old": "if err := strictjson.CheckDuplicateMembers(payload); err != nil {", + "new": "if err := strictjson.CheckDuplicateMembers(payload); err != nil && false {", + "module": "root", + "packages": [ + "./internal/clientassertion" + ], + "run": "^TestParseClaimsRefusesDuplicateMembers$", + "why": "a client assertion claims set that repeats a member is refused" + }, + { + "id": "dpop-claims-refuse-duplicate-members", + "file": "internal/dpop/proof.go", + "old": "strictjson.UnmarshalNoRepeats(payload, &c)", + "new": "strictjson.Unmarshal(payload, &c)", + "module": "root", + "packages": [ + "./internal/dpop" + ], + "run": "^TestParseClaimsRefusesDuplicateMembers$", + "why": "a DPoP proof claims set that repeats a member is refused" + }, + { + "id": "clientattestation-pop-refuse-duplicate-members", + "file": "internal/clientattestation/claims.go", + "old": "var c popClaims\n\tif err := unmarshalUniqueMembers(payload, &c)", + "new": "var c popClaims\n\tif err := strictjson.Unmarshal(payload, &c)", + "module": "root", + "packages": [ + "./internal/clientattestation" + ], + "run": "^TestParsePoPClaimsRefusesDuplicateMembers$", + "why": "an attestation PoP claims set that repeats a member is refused" + }, + { + "id": "federation-jwt-claims-refuse-duplicate-members", + "file": "internal/federation/claims_validation.go", + "old": "\tif err := refuseDuplicateMembers(payload); err != nil {\n\t\treturn nil, err", + "new": "\tif err := refuseDuplicateMembers(payload); err != nil && false {\n\t\treturn nil, err", + "module": "root", + "packages": [ + "./internal/federation" + ], + "run": "^TestParseFederationJWTClaimsRefuseDuplicateMembers$", + "why": "Trust Marks, delegations, status, resolve and historical keys claims sets that repeat a member are refused" + }, + { + "id": "client-userinfo-refuse-duplicate-members", + "file": "client/userinfo.go", + "old": "if err := strictjson.CheckDuplicateMembers(body); err != nil {", + "new": "if err := strictjson.CheckDuplicateMembers(body); err != nil && false {", + "module": "root", + "packages": [ + "./client" + ], + "run": "^TestDecodeUserInfoJSONRefusesDuplicateMembers$", + "why": "a UserInfo response that repeats a member is refused" + }, + { + "id": "resource-subject-kind-grant-type-marks-client", + "file": "resource/verify.go", + "old": "raw, ok := claims[token.GrantTypeClaim]\n\tif !ok {", + "new": "raw, ok := claims[token.GrantTypeClaim]\n\tif !ok || true {", + "module": "root", + "packages": [ + "./resource" + ], + "run": "^(TestVerifySubjectKindOfThirdPartyJWTAccessTokens|TestVerifySubjectKind)$", + "why": "a token carrying grant_type client_credentials reads as SubjectClient" } ] From bfa1d06696f7a3d6978a7a99352b1b086c3ed23b Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 18:54:21 +0800 Subject: [PATCH 09/12] fix: accept a repeated claim whose copies are identical The JWT claims parsers this branch made strict refused any repeated member name. An authorization server that writes iss in a JARM response both as the JWT claim and as the RFC 9207 iss response parameter sends iss twice with one value, and such a response was refused. A repeat whose copies are identical leaves no differential: a reader keeping the first copy and encoding/json, keeping the last, take the same value. strictjson.CheckConflictingMembers (and UnmarshalNoConflicts) is CheckDuplicateMembers, except that an exact repeat whose value is the same JSON text as the first copy's, after json.Compact, is accepted. Copies that differ, including ones spelled differently but equal to some readers ("a" and "a", 1 and 1.0), and two names that differ only in case are still refused, at any depth and within the existing nesting bound; each copy's own members are checked too. A document that repeats nothing still takes the byte scanner's fast path. ID tokens, JWT access tokens, JARM responses, request objects, client assertions, DPoP proofs, attestation PoPs, the federation JWTs other than Entity Statements, and UserInfo responses now use it. The parsers that were strict before (JOSE and JWE headers, client attestations, Entity Statements, metadata, and token, PAR and CIBA responses) still refuse any repeat: clientattestation's shared helper now serves only the attestation, and the federation JWTs no longer go through refuseDuplicateMembers. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/fuzz.yml | 2 + client/userinfo.go | 13 +- client/userinfo_duplicate_members_test.go | 13 +- internal/clientassertion/claims.go | 6 +- .../clientassertion/duplicate_claims_test.go | 13 +- internal/clientattestation/claims.go | 15 +- .../pop_duplicate_claims_test.go | 14 +- internal/dpop/duplicate_claims_test.go | 14 +- internal/dpop/proof.go | 8 +- .../claims_duplicate_members_test.go | 10 +- internal/federation/claims_validation.go | 23 ++- internal/federation/historicalkeys.go | 5 +- internal/jarm/claims.go | 3 +- internal/jarm/claims_object.go | 14 +- internal/jarm/duplicate_claims_test.go | 20 +- internal/requestobject/claims.go | 3 +- internal/requestobject/claims_object.go | 14 +- .../requestobject/duplicate_claims_test.go | 14 +- .../first_wins_differential_test.go | 35 +++- internal/strictjson/members_conflict.go | 173 ++++++++++++++++++ .../strictjson/members_conflict_fuzz_test.go | 104 +++++++++++ internal/strictjson/members_conflict_test.go | 137 ++++++++++++++ internal/strictjson/strictjson.go | 20 +- internal/token/accesstoken.go | 2 +- internal/token/claims_object.go | 14 +- internal/token/duplicate_claims_test.go | 6 +- internal/token/idtoken.go | 3 +- 27 files changed, 619 insertions(+), 79 deletions(-) create mode 100644 internal/strictjson/members_conflict.go create mode 100644 internal/strictjson/members_conflict_fuzz_test.go create mode 100644 internal/strictjson/members_conflict_test.go diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index e2143736..df7cf164 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -191,6 +191,8 @@ jobs: name: FuzzCheckDuplicateMembersThenDecode - pkg: ./internal/strictjson name: FuzzScanMembersMatchesWalker + - pkg: ./internal/strictjson + name: FuzzCheckConflictingMembersOneReading - pkg: ./extension name: FuzzExtensionValueReadersAgree - pkg: ./internal/sealedcookie diff --git a/client/userinfo.go b/client/userinfo.go index 6d3c3f64..daaa73f5 100644 --- a/client/userinfo.go +++ b/client/userinfo.go @@ -153,16 +153,17 @@ func (c *Client) decodeUserInfoResponse(ctx context.Context, contentType string, // signed response's payload already passed the same check in // jose.ParseCompact; a plain-JSON one gets it here. It refuses, too, a // body, plain JSON or a signed response's payload, that repeats a member -// name at any depth, or holds two that differ only in case -// (strictjson.CheckDuplicateMembers): encoding/json keeps the last copy, -// where another reader of the same response may keep the first, and so -// see a different sub. RFC 7519 §4 requires a JWT's claim names to be -// unique. +// name, at any depth, with copies that differ, or holds two names that +// differ only in case (strictjson.CheckConflictingMembers): +// encoding/json keeps the last copy, where another reader of the same +// response may keep the first, and so see a different sub. RFC 7519 §4 +// requires a JWT's claim names to be unique. A repeat whose copies are +// identical is accepted: every reader takes the same value from it. func decodeUserInfoJSON(body []byte) (map[string]json.RawMessage, *Error) { if !strictjson.DecodesLosslessly(body) { return nil, newError(ErrorInvalidResponse, "malformed UserInfo response: not valid UTF-8, or an unpaired surrogate escape", nil) } - if err := strictjson.CheckDuplicateMembers(body); err != nil { + if err := strictjson.CheckConflictingMembers(body); err != nil { return nil, newError(ErrorInvalidResponse, "malformed UserInfo response", err) } var claims map[string]json.RawMessage diff --git a/client/userinfo_duplicate_members_test.go b/client/userinfo_duplicate_members_test.go index 1b1bfb10..aa29c7b4 100644 --- a/client/userinfo_duplicate_members_test.go +++ b/client/userinfo_duplicate_members_test.go @@ -13,10 +13,17 @@ import ( // copy, where another reader of the same response (a gateway, a log // processor) may keep the first, so the two would see different users. // RFC 7519 §4 requires unique claim names in a JWT, and RFC 8259 §4 has -// a JSON object's names unique. +// a JSON object's names unique. A member repeated with identical copies +// reads alike to every reader, so it is accepted. func TestDecodeUserInfoJSONRefusesDuplicateMembers(t *testing.T) { - if _, err := decodeUserInfoJSON([]byte(`{"sub":"alice","email":"a@example.com"}`)); err != nil { - t.Fatalf("decodeUserInfoJSON(valid) = %v, want nil", err) + for _, body := range []string{ + `{"sub":"alice","email":"a@example.com"}`, + `{"sub":"alice","email":"a@example.com","sub":"alice"}`, + `{"sub":"alice","address":{"country":"A","country":"A"}}`, + } { + if _, err := decodeUserInfoJSON([]byte(body)); err != nil { + t.Fatalf("decodeUserInfoJSON(%s) = %v, want nil", body, err) + } } for _, body := range []string{ `{"sub":"mallory","sub":"alice"}`, diff --git a/internal/clientassertion/claims.go b/internal/clientassertion/claims.go index 05b9df37..1c6b08c1 100644 --- a/internal/clientassertion/claims.go +++ b/internal/clientassertion/claims.go @@ -55,8 +55,10 @@ func parseClaims(payload []byte) (claims, error) { var c claims // RFC 7519 §4 requires unique claim names: encoding/json keeps the // last copy of a repeated one, where another reader of the same - // assertion may keep the first. - if err := strictjson.CheckDuplicateMembers(payload); err != nil { + // assertion may keep the first. A repeat with identical copies reads + // the same either way, so only differing copies (and case variants) + // are refused. + if err := strictjson.CheckConflictingMembers(payload); err != nil { return claims{}, fmt.Errorf("%w: %v", ErrMalformedClaims, err) } if err := strictjson.CheckFieldCase(payload, &c); err != nil { diff --git a/internal/clientassertion/duplicate_claims_test.go b/internal/clientassertion/duplicate_claims_test.go index 915f62d7..56b07af9 100644 --- a/internal/clientassertion/duplicate_claims_test.go +++ b/internal/clientassertion/duplicate_claims_test.go @@ -10,10 +10,17 @@ import ( // claim names to be unique. encoding/json keeps the last copy of a // repeated one, where a first-wins reader of the same JWT keeps the // first, so the two would act on different claims. A claims set that -// repeats a member, at any depth, is refused. +// repeats a member with differing copies, at any depth, is refused; one +// whose copies are identical, which every reader reads alike, is +// accepted. func TestParseClaimsRefusesDuplicateMembers(t *testing.T) { - if _, err := parseClaims([]byte(`{"iss":"c","sub":"c","aud":"https://as.example.com","exp":2,"iat":1,"jti":"j"}`)); err != nil { - t.Fatalf("parseClaims(valid) = %v, want nil", err) + for _, payload := range []string{ + `{"iss":"c","sub":"c","aud":"https://as.example.com","exp":2,"iat":1,"jti":"j"}`, + `{"iss":"c","sub":"c","aud":"https://as.example.com","exp":2,"iat":1,"jti":"j","aud":"https://as.example.com"}`, + } { + if _, err := parseClaims([]byte(payload)); err != nil { + t.Fatalf("parseClaims(%s) = %v, want nil", payload, err) + } } for _, payload := range []string{ `{"iss":"c","sub":"c","aud":"https://other.example","exp":2,"iat":1,"jti":"j","aud":"https://as.example.com"}`, diff --git a/internal/clientattestation/claims.go b/internal/clientattestation/claims.go index 41c4e01d..f441531d 100644 --- a/internal/clientattestation/claims.go +++ b/internal/clientattestation/claims.go @@ -52,11 +52,9 @@ func parseAttestationClaims(payload []byte) (attestationClaims, error) { // unmarshalUniqueMembers is strictjson.Unmarshal for a claims set that // repeats no member name at any depth (RFC 7519 §4 requires unique -// claim names), an attestation's or a PoP's: encoding/json would merge -// two copies of cnf into one, and check the case of only the last, where -// VerifiedAttestation.Claims, like another implementation, keeps only -// the last copy; and it keeps the last copy of a PoP's aud or jti, where -// another reader of the same PoP may keep the first. +// claim names): encoding/json would merge two copies of cnf into one, +// and check the case of only the last, where VerifiedAttestation.Claims, +// like another implementation, keeps only the last copy. func unmarshalUniqueMembers(payload []byte, v any) error { if err := strictjson.CheckDuplicateMembers(payload); err != nil { return err @@ -113,7 +111,12 @@ func (a *popAudience) UnmarshalJSON(data []byte) error { func parsePoPClaims(payload []byte) (popClaims, error) { var c popClaims - if err := unmarshalUniqueMembers(payload, &c); err != nil { + // UnmarshalNoConflicts: encoding/json keeps the last copy of a + // repeated aud or jti, where another reader of the same PoP may keep + // the first (RFC 7519 §4 requires unique claim names). A repeat with + // identical copies reads the same either way, so only differing + // copies (and case variants) are refused. + if err := strictjson.UnmarshalNoConflicts(payload, &c); err != nil { return popClaims{}, fmt.Errorf("%w: %v", ErrMalformedClaims, err) } if c.Audience == "" || c.JTI == "" || c.IssuedAt == 0 { diff --git a/internal/clientattestation/pop_duplicate_claims_test.go b/internal/clientattestation/pop_duplicate_claims_test.go index e5ac954a..5a6714f6 100644 --- a/internal/clientattestation/pop_duplicate_claims_test.go +++ b/internal/clientattestation/pop_duplicate_claims_test.go @@ -10,10 +10,18 @@ import ( // JWT, whose claim names RFC 7519 §4 requires to be unique, like the // attestation's own (TestParseAttestationClaimsRefusesDuplicateMembers). // encoding/json keeps the last copy of a repeated one where another -// reader keeps the first, so a PoP that repeats a member is refused. +// reader keeps the first, so a PoP that repeats a member with differing +// copies is refused. One whose copies are identical, which every reader +// reads alike, is accepted (unlike an attestation, whose cnf decodes +// into a struct, and which refuses any repeat). func TestParsePoPClaimsRefusesDuplicateMembers(t *testing.T) { - if _, err := parsePoPClaims([]byte(`{"iss":"c","aud":"a","jti":"j","iat":1}`)); err != nil { - t.Fatalf("parsePoPClaims(valid) = %v, want nil", err) + for _, payload := range []string{ + `{"iss":"c","aud":"a","jti":"j","iat":1}`, + `{"iss":"c","aud":"a","jti":"j","iat":1,"jti":"j"}`, + } { + if _, err := parsePoPClaims([]byte(payload)); err != nil { + t.Fatalf("parsePoPClaims(%s) = %v, want nil", payload, err) + } } for _, payload := range []string{ `{"iss":"c","aud":"https://other.example","jti":"j","iat":1,"aud":"a"}`, diff --git a/internal/dpop/duplicate_claims_test.go b/internal/dpop/duplicate_claims_test.go index 72ead0d2..485892a5 100644 --- a/internal/dpop/duplicate_claims_test.go +++ b/internal/dpop/duplicate_claims_test.go @@ -10,14 +10,22 @@ import ( // claim names to be unique. encoding/json keeps the last copy of a // repeated one, where a first-wins reader of the same JWT keeps the // first, so the two would act on different claims. A claims set that -// repeats a member, at any depth, is refused. +// repeats a member with differing copies, at any depth, is refused; one +// whose copies are identical, which every reader reads alike, is +// accepted. func TestParseClaimsRefusesDuplicateMembers(t *testing.T) { - if _, err := parseClaims([]byte(`{"jti":"j","htm":"POST","htu":"https://rs.example.com/","iat":1}`)); err != nil { - t.Fatalf("parseClaims(valid) = %v, want nil", err) + for _, payload := range []string{ + `{"jti":"j","htm":"POST","htu":"https://rs.example.com/","iat":1}`, + `{"jti":"j","htm":"POST","htu":"https://rs.example.com/","iat":1,"htm":"POST"}`, + } { + if _, err := parseClaims([]byte(payload)); err != nil { + t.Fatalf("parseClaims(%s) = %v, want nil", payload, err) + } } for _, payload := range []string{ `{"jti":"j","htm":"GET","htu":"https://rs.example.com/","iat":1,"htm":"POST"}`, `{"jti":"j","htm":"POST","htu":"https://other.example/","htu":"https://rs.example.com/","iat":1}`, + `{"jti":"j","htm":"POST","htu":"https://rs.example.com/","iat":1,"HTM":"POST"}`, } { _, err := parseClaims([]byte(payload)) if !errors.Is(err, ErrMalformedClaims) || !strings.Contains(err.Error(), "duplicate member name") { diff --git a/internal/dpop/proof.go b/internal/dpop/proof.go index da4da93d..3ec5564a 100644 --- a/internal/dpop/proof.go +++ b/internal/dpop/proof.go @@ -31,10 +31,12 @@ type claims struct { func parseClaims(payload []byte) (claims, error) { var c claims - // UnmarshalNoRepeats: RFC 7519 §4 requires unique claim names, and + // UnmarshalNoConflicts: RFC 7519 §4 requires unique claim names, and // encoding/json keeps the last copy of a repeated one, where another - // reader of the same proof may keep the first. - if err := strictjson.UnmarshalNoRepeats(payload, &c); err != nil { + // reader of the same proof may keep the first. A repeat with + // identical copies reads the same either way, so only differing + // copies (and case variants) are refused. + if err := strictjson.UnmarshalNoConflicts(payload, &c); err != nil { return claims{}, fmt.Errorf("%w: %v", ErrMalformedClaims, err) } if c.JTI == "" || c.HTM == "" || c.HTU == "" { diff --git a/internal/federation/claims_duplicate_members_test.go b/internal/federation/claims_duplicate_members_test.go index fc2a32e4..97ad6b5f 100644 --- a/internal/federation/claims_duplicate_members_test.go +++ b/internal/federation/claims_duplicate_members_test.go @@ -13,6 +13,9 @@ import ( // requires unique claim names, and encoding/json keeps the last copy of // a repeated one where another reader of the same JWT may keep the // first, so the two would see, say, different statuses or subjects. +// These refuse a repeat whose copies differ, and accept one whose copies +// are identical, which every reader reads alike; an Entity Statement +// refuses either. func TestParseFederationJWTClaimsRefuseDuplicateMembers(t *testing.T) { const tm = `"iss":"https://ta.example","sub":"https://rp.example","trust_mark_type":"https://ta.example/tm","iat":1` const status = `"iss":"https://ta.example","trust_mark":"x.y.z","iat":1` @@ -25,15 +28,20 @@ func TestParseFederationJWTClaimsRefuseDuplicateMembers(t *testing.T) { }{ "trust mark": {parseTM, `{` + tm + `}`, false}, "trust mark, sub twice": {parseTM, `{"sub":"https://other.example",` + tm + `}`, true}, + "trust mark, same sub": {parseTM, `{"sub":"https://rp.example",` + tm + `}`, false}, "delegation": {parseTMD, `{` + tm + `}`, false}, "delegation, sub twice": {parseTMD, `{"sub":"https://other.example",` + tm + `}`, true}, "status": {parseTMS, `{` + status + `,"status":"active"}`, false}, "status twice": {parseTMS, `{"status":"revoked",` + status + `,"status":"active"}`, true}, + "status twice, same": {parseTMS, `{"status":"active",` + status + `,"status":"active"}`, false}, "resolve": {parseRR, `{"sub":"https://rp.example",` + resolve + `}`, false}, "resolve, sub twice": {parseRR, `{"sub":"https://other.example",` + resolve + `,"sub":"https://rp.example"}`, true}, "resolve, nested repeat": {parseRR, `{"sub":"https://rp.example",` + resolve + `,"x":{"a":1,"a":2}}`, true}, "historical keys": {parseHK, `{` + historical + `}`, false}, - "historical keys twice": {parseHK, `{` + historical + `,"keys":[]}`, true}, + "historical keys twice": {parseHK, `{` + historical + `,"keys":[{}]}`, true}, + "historical keys, same": {parseHK, `{` + historical + `,"keys":[]}`, false}, + "delegation, same sub": {parseTMD, `{"sub":"https://rp.example",` + tm + `}`, false}, + "resolve, same nested": {parseRR, `{"sub":"https://rp.example",` + resolve + `,"x":{"a":1,"a":1}}`, false}, } { t.Run(name, func(t *testing.T) { err := tc.parse([]byte(tc.payload)) diff --git a/internal/federation/claims_validation.go b/internal/federation/claims_validation.go index 2ccbf0c7..cb43d81b 100644 --- a/internal/federation/claims_validation.go +++ b/internal/federation/claims_validation.go @@ -146,10 +146,7 @@ func isHTTPSURL(s string) bool { // silently, and reads names that differ only in case as one, while // another implementation may keep the first, or read two, so two // validators could derive different claims — a different metadata -// policy, say — from one signed statement. Every federation JWT's -// claims parser runs it: Entity Statements', and Trust Marks', Trust -// Mark Delegations', Trust Mark Status, Resolve and Historical Keys -// responses'. §6.1.2 forbids "Duplicate +// policy, say — from one signed statement. §6.1.2 forbids "Duplicate // JSON object member names ... at any of the three levels of the // metadata_policy Claim data structure"; RFC 7519 §4 lets a JWT parser // reject duplicate claim names, which this applies at every level. @@ -160,11 +157,21 @@ func refuseDuplicateMembers(payload []byte) error { return nil } -// decodeClaimsObject decodes payload, a federation JWT's claims set, as -// a JSON object, after refuseDuplicateMembers. +// decodeClaimsObject decodes payload, the claims set of a federation +// JWT other than an Entity Statement (a Trust Mark, Trust Mark +// Delegation, Trust Mark Status, Resolve or Historical Keys response), +// as a JSON object. It refuses one that repeats a member name, at any +// depth, with copies that differ, or holds two names that differ only +// in case (strictjson.CheckConflictingMembers): RFC 7519 §4 requires +// unique claim names, and encoding/json keeps the last copy of a +// repeated one, where another reader of the same JWT may keep the +// first, and so see a different status or subject. A repeat whose +// copies are identical is accepted: every reader takes the same value +// from it. An Entity Statement's claims go through +// refuseDuplicateMembers instead, which refuses any repeat. func decodeClaimsObject(payload []byte) (map[string]json.RawMessage, error) { - if err := refuseDuplicateMembers(payload); err != nil { - return nil, err + if err := strictjson.CheckConflictingMembers(payload); err != nil { + return nil, fmt.Errorf("%w: %v", ErrMalformedClaims, err) } var raw map[string]json.RawMessage if err := json.Unmarshal(payload, &raw); err != nil { diff --git a/internal/federation/historicalkeys.go b/internal/federation/historicalkeys.go index 4549cd8a..58c7b504 100644 --- a/internal/federation/historicalkeys.go +++ b/internal/federation/historicalkeys.go @@ -209,8 +209,9 @@ func (r HistoricalKeysResponse) Verify(pub crypto.PublicKey, policy HistoricalKe // stays raw until decodeKeyRevocation reads it: encoding/json would // merge the copies of a repeated "revoked" into one struct, taking // revoked_at from one and reason from another. parseHistoricalKeysClaims -// refuses a repeated member anywhere in the claims set before any of -// them is decoded, so neither a merge nor a last copy is ever read. +// refuses a repeated member whose copies differ, anywhere in the claims +// set, before any of them is decoded, so a merge or a last copy is only +// ever of identical copies, and reads as each of them does. type rawHistoricalKey struct { IAT *numericdate.Value `json:"iat"` EXP *numericdate.Value `json:"exp"` diff --git a/internal/jarm/claims.go b/internal/jarm/claims.go index 07e59723..3b874a18 100644 --- a/internal/jarm/claims.go +++ b/internal/jarm/claims.go @@ -26,7 +26,8 @@ type Claims struct { } // parseClaims parses a JARM response's claims set, refusing one -// decodeClaimsObject refuses, such as one that repeats a claim. +// decodeClaimsObject refuses, such as one that repeats a claim with +// differing values. func parseClaims(payload []byte) (Claims, error) { raw, err := decodeClaimsObject(payload) if err != nil { diff --git a/internal/jarm/claims_object.go b/internal/jarm/claims_object.go index a01a52ed..1969d138 100644 --- a/internal/jarm/claims_object.go +++ b/internal/jarm/claims_object.go @@ -8,13 +8,15 @@ import ( ) // decodeClaimsObject decodes payload, a JWT's claims set, as a JSON -// object, refusing one that repeats a member name at any depth, or holds -// two that differ only in case (strictjson.CheckDuplicateMembers): RFC -// 7519 §4 requires unique claim names, and encoding/json keeps the last -// copy of a repeated one, where another reader of the same JWT may keep -// the first. +// object, refusing one that repeats a member name, at any depth, with +// copies that differ, or holds two names that differ only in case +// (strictjson.CheckConflictingMembers): RFC 7519 §4 requires unique +// claim names, and encoding/json keeps the last copy of a repeated one, +// where another reader of the same JWT may keep the first. A repeat +// whose copies are identical is accepted, since every reader takes the +// same value from it. func decodeClaimsObject(payload []byte) (map[string]json.RawMessage, error) { - if err := strictjson.CheckDuplicateMembers(payload); err != nil { + if err := strictjson.CheckConflictingMembers(payload); err != nil { return nil, fmt.Errorf("%w: %v", ErrMalformedClaims, err) } var raw map[string]json.RawMessage diff --git a/internal/jarm/duplicate_claims_test.go b/internal/jarm/duplicate_claims_test.go index ec169151..4b9e286e 100644 --- a/internal/jarm/duplicate_claims_test.go +++ b/internal/jarm/duplicate_claims_test.go @@ -10,14 +10,28 @@ import ( // claim names to be unique. encoding/json keeps the last copy of a // repeated one, where a first-wins reader of the same JWT keeps the // first, so the two would act on different claims. A claims set that -// repeats a member, at any depth, is refused. +// repeats a member with differing copies, at any depth, or as a case +// variant, is refused. One that repeats a member with identical copies +// is accepted: an authorization server writing iss both as the JWT +// claim and as the RFC 9207 iss response parameter sends iss twice, +// with one value, which every reader reads alike. func TestParseClaimsRefusesDuplicateMembers(t *testing.T) { - if _, err := parseClaims([]byte(`{"iss":"https://as.example","aud":"client-1","exp":9999999999,"code":"c"}`)); err != nil { - t.Fatalf("parseClaims(valid) = %v, want nil", err) + for _, payload := range []string{ + `{"iss":"https://as.example","aud":"client-1","exp":9999999999,"code":"c"}`, + `{"exp":9999999999,"aud":"client-1","code":"c","iss":"https://as.example","state":"s","iss":"https://as.example"}`, + } { + c, err := parseClaims([]byte(payload)) + if err != nil { + t.Fatalf("parseClaims(%s) = %v, want nil", payload, err) + } + if c.Issuer != "https://as.example" { + t.Fatalf("parseClaims(%s): Issuer = %q, want https://as.example", payload, c.Issuer) + } } for _, payload := range []string{ `{"iss":"https://evil.example","aud":"client-1","exp":9999999999,"code":"c","iss":"https://as.example"}`, `{"iss":"https://as.example","aud":"client-1","exp":9999999999,"code":"a","code":"b"}`, + `{"iss":"https://as.example","aud":"client-1","exp":9999999999,"code":"c","ISS":"https://as.example"}`, } { _, err := parseClaims([]byte(payload)) if !errors.Is(err, ErrMalformedClaims) || !strings.Contains(err.Error(), "duplicate member name") { diff --git a/internal/requestobject/claims.go b/internal/requestobject/claims.go index f3e41190..07b676c1 100644 --- a/internal/requestobject/claims.go +++ b/internal/requestobject/claims.go @@ -68,7 +68,8 @@ type Claims struct { } // parseClaims parses a request object's claims set, refusing one -// decodeClaimsObject refuses, such as one that repeats a claim. +// decodeClaimsObject refuses, such as one that repeats a claim with +// differing values. func parseClaims(payload []byte) (Claims, error) { raw, err := decodeClaimsObject(payload) if err != nil { diff --git a/internal/requestobject/claims_object.go b/internal/requestobject/claims_object.go index 4e10eb0e..bd866cb2 100644 --- a/internal/requestobject/claims_object.go +++ b/internal/requestobject/claims_object.go @@ -8,13 +8,15 @@ import ( ) // decodeClaimsObject decodes payload, a JWT's claims set, as a JSON -// object, refusing one that repeats a member name at any depth, or holds -// two that differ only in case (strictjson.CheckDuplicateMembers): RFC -// 7519 §4 requires unique claim names, and encoding/json keeps the last -// copy of a repeated one, where another reader of the same JWT may keep -// the first. +// object, refusing one that repeats a member name, at any depth, with +// copies that differ, or holds two names that differ only in case +// (strictjson.CheckConflictingMembers): RFC 7519 §4 requires unique +// claim names, and encoding/json keeps the last copy of a repeated one, +// where another reader of the same JWT may keep the first. A repeat +// whose copies are identical is accepted, since every reader takes the +// same value from it. func decodeClaimsObject(payload []byte) (map[string]json.RawMessage, error) { - if err := strictjson.CheckDuplicateMembers(payload); err != nil { + if err := strictjson.CheckConflictingMembers(payload); err != nil { return nil, fmt.Errorf("%w: %v", ErrMalformedClaims, err) } var raw map[string]json.RawMessage diff --git a/internal/requestobject/duplicate_claims_test.go b/internal/requestobject/duplicate_claims_test.go index cad95b8a..9559c729 100644 --- a/internal/requestobject/duplicate_claims_test.go +++ b/internal/requestobject/duplicate_claims_test.go @@ -10,10 +10,18 @@ import ( // claim names to be unique. encoding/json keeps the last copy of a // repeated one, where a first-wins reader of the same JWT keeps the // first, so the two would act on different claims. A claims set that -// repeats a member, at any depth, is refused. +// repeats a member with differing copies, at any depth, is refused; one +// whose copies are identical, which every reader reads alike, is +// accepted. func TestParseClaimsRefusesDuplicateMembers(t *testing.T) { - if _, err := parseClaims([]byte(`{"iss":"client-123","aud":"https://as.example","exp":4102444800,"scope":"openid"}`)); err != nil { - t.Fatalf("parseClaims(valid) = %v, want nil", err) + for _, payload := range []string{ + `{"iss":"client-123","aud":"https://as.example","exp":4102444800,"scope":"openid"}`, + `{"iss":"client-123","aud":"https://as.example","exp":4102444800,"scope":"openid","scope":"openid"}`, + `{"iss":"client-123","aud":"https://as.example","exp":4102444800,"claims":{"id_token":{"acr":{"value":"a"},"acr":{"value":"a"}}}}`, + } { + if _, err := parseClaims([]byte(payload)); err != nil { + t.Fatalf("parseClaims(%s) = %v, want nil", payload, err) + } } for _, payload := range []string{ `{"iss":"client-123","aud":"https://as.example","exp":4102444800,"scope":"openid","scope":"openid payments"}`, diff --git a/internal/strictjson/first_wins_differential_test.go b/internal/strictjson/first_wins_differential_test.go index d61b6f18..d6caa3d6 100644 --- a/internal/strictjson/first_wins_differential_test.go +++ b/internal/strictjson/first_wins_differential_test.go @@ -11,8 +11,9 @@ import ( // intermediary RFC 7515 §10.12 warns about: a reader that keeps the // first copy of a repeated member (as some streaming JSON path readers // do) and encoding/json, which keeps the last, take different values -// from one claims set. CheckDuplicateMembers, which every JWT claims -// parser runs, refuses the claims set, so neither reading is acted on. +// from one claims set. CheckDuplicateMembers and CheckConflictingMembers, +// one of which every JWT claims parser runs, refuse the claims set, so +// neither reading is acted on. func TestCheckDuplicateMembersClosesFirstWinsDifferential(t *testing.T) { for _, tc := range []struct{ payload, member, first, last string }{ {`{"sub":"alice","aud":"rs","sub":"admin"}`, "sub", `"alice"`, `"admin"`}, @@ -32,6 +33,36 @@ func TestCheckDuplicateMembersClosesFirstWinsDifferential(t *testing.T) { if err := CheckDuplicateMembers([]byte(tc.payload)); !errors.Is(err, ErrDuplicateMember) { t.Errorf("CheckDuplicateMembers(%s) = %v, want ErrDuplicateMember", tc.payload, err) } + if err := CheckConflictingMembers([]byte(tc.payload)); !errors.Is(err, ErrDuplicateMember) { + t.Errorf("CheckConflictingMembers(%s) = %v, want ErrDuplicateMember", tc.payload, err) + } + } +} + +// TestCheckConflictingMembersAcceptsNoDifferential: a claims set that +// repeats a member with identical copies, as an authorization server +// writing iss both as the JWT claim and as the RFC 9207 response +// parameter does, reads the same to a first-wins reader and to +// encoding/json, so CheckConflictingMembers, which the JWT claims +// parsers run, accepts it. +func TestCheckConflictingMembersAcceptsNoDifferential(t *testing.T) { + for _, tc := range []struct{ payload, member, value string }{ + {`{"iss":"https://as.example","code":"c","iss":"https://as.example"}`, "iss", `"https://as.example"`}, + {`{"sub":"alice","aud":"rs","sub":"alice"}`, "sub", `"alice"`}, + } { + var lastWins map[string]json.RawMessage + if err := json.Unmarshal([]byte(tc.payload), &lastWins); err != nil { + t.Fatal(err) + } + if got := string(lastWins[tc.member]); got != tc.value { + t.Fatalf("encoding/json read %s = %s, want %s", tc.member, got, tc.value) + } + if got := firstWins(t, tc.payload, tc.member); got != tc.value { + t.Fatalf("first-wins reader read %s = %s, want %s", tc.member, got, tc.value) + } + if err := CheckConflictingMembers([]byte(tc.payload)); err != nil { + t.Errorf("CheckConflictingMembers(%s) = %v, want nil", tc.payload, err) + } } } diff --git a/internal/strictjson/members_conflict.go b/internal/strictjson/members_conflict.go new file mode 100644 index 00000000..f4cffa4d --- /dev/null +++ b/internal/strictjson/members_conflict.go @@ -0,0 +1,173 @@ +package strictjson + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" +) + +// CheckConflictingMembers is CheckDuplicateMembers, except that it +// accepts an object that repeats a member name exactly (the same once +// unescaped) when every copy's value is the same JSON text as the first +// copy's once json.Compact has removed its insignificant whitespace. A +// reader keeping the first copy and one keeping the last then take the +// same value, so the repeat leaves the document only one reading. It +// still refuses, wrapping ErrDuplicateMember, a repeat whose copies +// differ, and two names that differ only in case (FoldKey maps them +// together), however alike their values: encoding/json reads those as +// one member, where a case-sensitive reader reads two. It checks every +// copy's own value, too, so a repeated member whose copies are the +// same text but each repeat a member of their own with differing +// values is refused. Nesting deeper than MaxNestingDepth and malformed +// JSON are refused as CheckDuplicateMembers refuses them, and anything +// after the first value is likewise left to the caller. +// +// Two copies are compared as text, not as values: "a" and "a", or +// 1 and 1.0, are refused as differing, though some readers would take +// them as equal. Refusing them is conservative; it never accepts copies +// two readers could read differently. +// +// A document that repeats nothing costs what CheckDuplicateMembers +// costs: the same byte scanner (scanMembers) accepts it. Otherwise a +// json.Decoder walks it once, keeping each member's value as a span of +// data, and compacts a value only when a later copy repeats its name: +// the first copy once, each later copy once. A value is compacted once +// for each repeated member it is nested in, so the walk takes time and +// memory at most proportional to len(data) times MaxNestingDepth, and +// linear in len(data) when no repeated member nests in another. +func CheckConflictingMembers(data []byte) error { + if scanMembers(data) { + return nil + } + return walkConflictingMembers(data) +} + +// 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, +// which encoding/json, keeping the last, reads as every other reader +// does. +func UnmarshalNoConflicts(data []byte, v any) error { + if err := CheckConflictingMembers(data); err != nil { + return err + } + return Unmarshal(data, v) +} + +// conflictWalker is CheckConflictingMembers' walk of data by +// json.Decoder tokens. +type conflictWalker struct { + dec *json.Decoder + data []byte +} + +// firstCopy is a member as its object first holds it: its name as +// spelled there, and its value's span in data, compacted once a later +// copy needs comparing with it. +type firstCopy struct { + name string + start, end int + compact []byte +} + +func walkConflictingMembers(data []byte) error { + w := conflictWalker{dec: json.NewDecoder(bytes.NewReader(data)), data: data} + w.dec.UseNumber() // numbers are skipped, never converted, so none overflows + err := w.value(0) + if errors.Is(err, io.EOF) { + return io.ErrUnexpectedEOF // a whole value never ends early + } + return err +} + +// value checks the next value the decoder reads, which depth objects +// and arrays enclose. +func (w *conflictWalker) value(depth int) error { + tok, err := w.dec.Token() + if err != nil { + return err + } + delim, ok := tok.(json.Delim) + if !ok { + return nil + } + if depth >= MaxNestingDepth { + return errNestedTooDeep + } + if delim == '{' { + return w.object(depth) + } + for w.dec.More() { + if err := w.value(depth + 1); err != nil { + return err + } + } + _, err = w.dec.Token() // "]" + return err +} + +// object checks the members of the object whose "{" the decoder has +// just read, and their values, through its "}". +func (w *conflictWalker) object(depth int) error { + seen := make(map[string]*firstCopy) // by FoldKey + for w.dec.More() { + tok, err := w.dec.Token() + if err != nil { + return err + } + name, _ := tok.(string) // a json.Decoder only reads a string here + key := FoldKey(name) + first := seen[key] + if first != nil && first.name != name { + return duplicateMemberError(first.name, name) + } + start := int(w.dec.InputOffset()) // just after the name + if err := w.value(depth + 1); err != nil { + return err + } + end := int(w.dec.InputOffset()) // just after the value + if first == nil { + seen[key] = &firstCopy{name: name, start: start, end: end} + continue + } + if err := w.sameAsFirst(first, start, end); err != nil { + return err + } + } + _, err := w.dec.Token() // "}" + return err +} + +// sameAsFirst reports an error wrapping ErrDuplicateMember unless the +// value spanning data[start:end] is the same text as first's once both +// are compacted. +func (w *conflictWalker) sameAsFirst(first *firstCopy, start, end int) error { + if first.compact == nil { + c, err := compactValue(w.data[first.start:first.end]) + if err != nil { + return err + } + first.compact = c + } + c, err := compactValue(w.data[start:end]) + if err != nil { + return err + } + if !bytes.Equal(first.compact, c) { + return fmt.Errorf("%w %q, whose copies differ", ErrDuplicateMember, first.name) + } + return nil +} + +// compactValue is span, a member's value with the whitespace and colon +// that may precede it, compacted. A value never begins with either, so +// trimming them leaves just the value. +func compactValue(span []byte) ([]byte, error) { + var buf bytes.Buffer + if err := json.Compact(&buf, bytes.TrimLeft(span, " \t\r\n:")); err != nil { + return nil, err + } + return buf.Bytes(), nil +} diff --git a/internal/strictjson/members_conflict_fuzz_test.go b/internal/strictjson/members_conflict_fuzz_test.go new file mode 100644 index 00000000..df608b8c --- /dev/null +++ b/internal/strictjson/members_conflict_fuzz_test.go @@ -0,0 +1,104 @@ +package strictjson + +import ( + "bytes" + "encoding/json" + "errors" + "reflect" + "testing" +) + +// FuzzCheckConflictingMembersOneReading: whatever CheckConflictingMembers +// accepts has one reading. A reader keeping the first copy of each +// repeated member and encoding/json, keeping the last, read its first +// value as the same tree, and no object in it holds two names FoldKey +// maps together. It accepts everything CheckDuplicateMembers accepts, +// and refuses everything CheckDuplicateMembers refuses for a reason +// other than a repeat. +func FuzzCheckConflictingMembersOneReading(f *testing.F) { + for _, s := range []string{ + `{"iss":"a","code":"c","iss":"a"}`, `{"iss":"a","iss":"b"}`, `{"cnf":{"jkt":"a"},"cnf":{"jkt":"a"}}`, + `{"cnf":{"jkt":"a"},"cnf":{}}`, `{"kid":"a","KID":"a"}`, `{"a":1,"a":1.0}`, "{\"a\":\"a\",\"a\":\"\\u0061\"}", + `{"c":{"j":1,"j":2},"c":{"j":1,"j":2}}`, `[{"a":[1],"a":[1]}]`, `{"a":1,"a":1} {}`, + } { + f.Add([]byte(s)) + } + f.Fuzz(func(t *testing.T, data []byte) { + dupErr, conflictErr := CheckDuplicateMembers(data), CheckConflictingMembers(data) + if dupErr == nil && conflictErr != nil { + t.Fatalf("%q: CheckDuplicateMembers accepts, CheckConflictingMembers = %v", data, conflictErr) + } + if dupErr != nil && !errors.Is(dupErr, ErrDuplicateMember) && conflictErr == nil { + t.Fatalf("%q: CheckDuplicateMembers = %v, CheckConflictingMembers accepts", data, dupErr) + } + if conflictErr != nil { + return + } + first, ok := readFirstWins(json.NewDecoder(bytes.NewReader(data))) + if !ok { + t.Fatalf("%q: accepted, but a first-wins reader finds a case variant or can't read it", data) + } + var last any + dec := json.NewDecoder(bytes.NewReader(data)) + dec.UseNumber() + if err := dec.Decode(&last); err != nil { + t.Fatalf("%q: accepted, but encoding/json can't read it: %v", data, err) + } + if !reflect.DeepEqual(first, last) { + t.Fatalf("%q: first-wins reading %#v, encoding/json's %#v", data, first, last) + } + }) +} + +// readFirstWins reads dec's next value as encoding/json would decode it +// into an any, with UseNumber, except that an object keeps the first +// copy of a repeated member. It reports false for an object holding two +// names FoldKey maps together but that differ, or for malformed JSON. +func readFirstWins(dec *json.Decoder) (any, bool) { + dec.UseNumber() + tok, err := dec.Token() + if err != nil { + return nil, false + } + switch tok { + case json.Delim('{'): + return readFirstWinsObject(dec) + case json.Delim('['): + out := []any{} + for dec.More() { + v, ok := readFirstWins(dec) + if !ok { + return nil, false + } + out = append(out, v) + } + _, err := dec.Token() + return out, err == nil + } + return tok, true +} + +func readFirstWinsObject(dec *json.Decoder) (any, bool) { + out := map[string]any{} + spelled := map[string]string{} // by FoldKey + for dec.More() { + tok, err := dec.Token() + if err != nil { + return nil, false + } + name, _ := tok.(string) + if s, ok := spelled[FoldKey(name)]; ok && s != name { + return nil, false + } + spelled[FoldKey(name)] = name + v, ok := readFirstWins(dec) + if !ok { + return nil, false + } + if _, repeated := out[name]; !repeated { + out[name] = v + } + } + _, err := dec.Token() + return out, err == nil +} diff --git a/internal/strictjson/members_conflict_test.go b/internal/strictjson/members_conflict_test.go new file mode 100644 index 00000000..00c2b21d --- /dev/null +++ b/internal/strictjson/members_conflict_test.go @@ -0,0 +1,137 @@ +package strictjson + +import ( + "encoding/json" + "errors" + "io" + "strings" + "testing" +) + +// TestCheckConflictingMembersAcceptsIdenticalRepeats: a member repeated +// with the same value, at the top level or nested, gives every reader +// that value, so it is accepted, as is everything CheckDuplicateMembers +// accepts. Whitespace inside or around a copy's value is not part of it. +func TestCheckConflictingMembersAcceptsIdenticalRepeats(t *testing.T) { + for name, data := range map[string]string{ + "unique names": `{"alg":"ES256","kid":"a"}`, + "top level": `{"iss":"https://as.example","code":"c","iss":"https://as.example"}`, + "three copies": `{"a":1,"a":1,"a":1}`, + "nested": `{"cnf":{"jkt":"a","jkt":"a"}}`, + "object value": `{"cnf":{"jkt":"a","x":[1,2]},"cnf":{"jkt":"a","x":[1,2]}}`, + "in an array": `[{"a":null,"a":null}]`, + "whitespace differs": "{\"cnf\":{\"jkt\":\"a\"},\"cnf\" :\n\t{ \"jkt\" : \"a\" } }", + "escaped name, same": "{\"kid\":\"a\",\"\x5cu006bid\":\"a\"}", + "only the first value": `{"a":1,"a":1} {"a":1,"a":2}`, + "repeat with whitespace": `{"a" : true , "a" : true}`, + } { + if err := CheckConflictingMembers([]byte(data)); err != nil { + t.Errorf("%s: CheckConflictingMembers(%s) = %v, want nil", name, data, err) + } + } +} + +// TestCheckConflictingMembersRefusesConflicts: a repeat whose copies +// differ, at any depth, or whose copies are spelled differently even +// if some reader would take them as equal; two names that differ only +// in case, whatever their values; and a repeat inside each of two +// identical copies, are all refused. +func TestCheckConflictingMembersRefusesConflicts(t *testing.T) { + for name, data := range map[string]string{ + "top level": `{"iss":"https://evil.example","iss":"https://as.example"}`, + "third copy differs": `{"a":1,"a":1,"a":2}`, + "nested": `{"cnf":{"jkt":"a","jkt":"b"}}`, + "object copies differ": `{"cnf":{"jkt":"a"},"cnf":{"jkt":"b"}}`, + "object copies merge": `{"cnf":{"jkt":"a"},"cnf":{}}`, + "in an array": `{"keys":[{"kid":"a"},{"kid":"b","kid":"c"}]}`, + "string spelled differently": "{\"a\":\"a\",\"a\":\"\x5cu0061\"}", + "number spelled differently": `{"a":1,"a":1.0}`, + "member order differs": `{"o":{"x":1,"y":2},"o":{"y":2,"x":1}}`, + "case variant, same value": `{"kid":"a","KID":"a"}`, + "case variant, nested": `{"cnf":{"jkt":"a","Jkt":"a"}}`, + "case variant of a repeat": `{"kid":"a","kid":"a","Kid":"a"}`, + "Kelvin sign, same value": "{\"kid\":\"a\",\"\xe2\x84\xaaid\":\"a\"}", + "repeat inside identical": `{"cnf":{"jkt":"a","jkt":"b"},"cnf":{"jkt":"a","jkt":"b"}}`, + "case variant inside copies": `{"cnf":{"jkt":"a","JKT":"a"},"cnf":{"jkt":"a","JKT":"a"}}`, + } { + if err := CheckConflictingMembers([]byte(data)); !errors.Is(err, ErrDuplicateMember) { + t.Errorf("%s: CheckConflictingMembers(%s) = %v, want ErrDuplicateMember", name, data, err) + } + } +} + +func TestCheckConflictingMembersNamesTheMembers(t *testing.T) { + err := CheckConflictingMembers([]byte(`{"iss":"a","iss":"b"}`)) + if err == nil || err.Error() != `strictjson: duplicate member name "iss", whose copies differ` { + t.Errorf("differing copies: err = %v", err) + } + err = CheckConflictingMembers([]byte(`{"kid":"a","KID":"a"}`)) + if err == nil || !strings.Contains(err.Error(), `"kid" and "KID" differ only in case`) { + t.Errorf("case variant: err = %v", err) + } +} + +// TestCheckConflictingMembersBoundsNesting: the walk that compares +// copies has CheckDuplicateMembers' nesting bound, including inside a +// repeated member. +func TestCheckConflictingMembersBoundsNesting(t *testing.T) { + deep := func(n int) string { return strings.Repeat("[", n) + strings.Repeat("]", n) } + atBound := `{"a":` + deep(MaxNestingDepth-1) + `,"a":` + deep(MaxNestingDepth-1) + `}` + if err := CheckConflictingMembers([]byte(atBound)); err != nil { + t.Errorf("at the bound: CheckConflictingMembers = %v, want nil", err) + } + for name, data := range map[string]string{ + "past the bound": deep(MaxNestingDepth + 1), + "repeated, past the bound": `{"a":` + deep(MaxNestingDepth) + `,"a":` + deep(MaxNestingDepth) + `}`, + "identical repeat past the bound": strings.Repeat("[", MaxNestingDepth) + `{"a":1,"a":1}` + strings.Repeat("]", MaxNestingDepth), + } { + if err := CheckConflictingMembers([]byte(data)); !errors.Is(err, errNestedTooDeep) { + t.Errorf("%s: CheckConflictingMembers = %v, want errNestedTooDeep", name, err) + } + } +} + +func TestCheckConflictingMembersReportsMalformedJSON(t *testing.T) { + for _, data := range []string{``, `{`, `{"a":1,"a":1`, `{"a":1,"a":}`, `{"a":1,"a":1,}`, `{1:2}`, `not json`} { + err := CheckConflictingMembers([]byte(data)) + if err == nil || errors.Is(err, ErrDuplicateMember) { + t.Errorf("CheckConflictingMembers(%q) = %v, want a syntax error", data, err) + } + } + if err := CheckConflictingMembers([]byte(``)); !errors.Is(err, io.ErrUnexpectedEOF) { + t.Errorf("CheckConflictingMembers(``) = %v, want io.ErrUnexpectedEOF", err) + } + err := CheckConflictingMembers([]byte(`{"a":1,"a":1`)) + var syntax *json.SyntaxError + if !errors.Is(err, io.ErrUnexpectedEOF) && !errors.As(err, &syntax) { + t.Errorf("cut off: CheckConflictingMembers = %v, want io.ErrUnexpectedEOF or a *json.SyntaxError", err) + } +} + +// TestUnmarshalNoConflicts: UnmarshalNoConflicts refuses what Unmarshal +// does and a conflicting repeat, and decodes an identical one. +func TestUnmarshalNoConflicts(t *testing.T) { + type target struct { + A string `json:"a"` + M map[string]int `json:"m"` + } + for body, ok := range map[string]bool{ + `{"a":"x"}`: true, + `{"a":"x","a":"x"}`: true, + `{"a":"x","m":{"k":1,"k":1}}`: true, + `{"a":"x","a":"y"}`: false, + `{"a":"x","A":"x"}`: false, + `{"A":"x"}`: false, + `{"a":"x","m":{"k":1,"k":2}}`: false, + `{"a":"x"} {}`: false, + } { + var v target + err := UnmarshalNoConflicts([]byte(body), &v) + if (err == nil) != ok { + t.Errorf("UnmarshalNoConflicts(%s) = %v, want ok %v", body, err, ok) + } + if ok && v.A != "x" { + t.Errorf("UnmarshalNoConflicts(%s): A = %q, want x", body, v.A) + } + } +} diff --git a/internal/strictjson/strictjson.go b/internal/strictjson/strictjson.go index b2187511..6541c720 100644 --- a/internal/strictjson/strictjson.go +++ b/internal/strictjson/strictjson.go @@ -21,16 +21,20 @@ // keeps the last copy, or merges the copies of one that decodes into a // struct or a map, and the case check sees only the last copy, while a // first-wins reader of the same bytes keeps the first. The JWS and JWE -// header parsers, every JWT claims set's parser (ID tokens, JWT access -// tokens, request objects, JARM responses, client assertions, DPoP -// proofs, client attestations and their PoPs, Entity Statements and the -// other federation JWTs), the UserInfo response decoder, the metadata -// parser and the token, PAR and CIBA response decoders run +// header parsers, a client attestation's claims, Entity Statements, the +// metadata parser and the token, PAR and CIBA response decoders run // CheckDuplicateMembers first (directly, or through // UnmarshalNoRepeats), which refuses a repeated name, or two names -// FoldKey maps together, at any depth. RFC 7515 §4 and RFC 7519 §4 let -// a recipient keep the lexically last copy instead; refusing leaves no -// reading for two implementations to disagree on. +// FoldKey maps together, at any depth. The other JWT claims sets' parsers +// (ID tokens, JWT access tokens, request objects, JARM responses, +// client assertions, DPoP proofs, attestation PoPs and the federation +// JWTs other than Entity Statements) and the UserInfo response decoder +// run CheckConflictingMembers (directly, or through +// UnmarshalNoConflicts), which refuses the same, except that it accepts +// a repeated name whose copies are the same JSON text: every reader +// takes that one value. RFC 7515 §4 and RFC 7519 §4 let a recipient keep +// the lexically last copy instead; refusing leaves no reading for two +// implementations to disagree on. package strictjson import ( diff --git a/internal/token/accesstoken.go b/internal/token/accesstoken.go index 0eccaaf3..f28f12de 100644 --- a/internal/token/accesstoken.go +++ b/internal/token/accesstoken.go @@ -55,7 +55,7 @@ type rawConfirmation struct { // parseAccessTokenClaims parses a JWT access token's claims set, // refusing one decodeClaimsObject refuses, such as one that repeats a -// claim. +// claim with differing values. func parseAccessTokenClaims(payload []byte) (AccessTokenClaims, error) { raw, err := decodeClaimsObject(payload) if err != nil { diff --git a/internal/token/claims_object.go b/internal/token/claims_object.go index 57670cd4..d0cd231a 100644 --- a/internal/token/claims_object.go +++ b/internal/token/claims_object.go @@ -8,13 +8,15 @@ import ( ) // decodeClaimsObject decodes payload, a JWT's claims set, as a JSON -// object, refusing one that repeats a member name at any depth, or holds -// two that differ only in case (strictjson.CheckDuplicateMembers): RFC -// 7519 §4 requires unique claim names, and encoding/json keeps the last -// copy of a repeated one, where another reader of the same JWT may keep -// the first. +// object, refusing one that repeats a member name, at any depth, with +// copies that differ, or holds two names that differ only in case +// (strictjson.CheckConflictingMembers): RFC 7519 §4 requires unique +// claim names, and encoding/json keeps the last copy of a repeated one, +// where another reader of the same JWT may keep the first. A repeat +// whose copies are identical is accepted, since every reader takes the +// same value from it. func decodeClaimsObject(payload []byte) (map[string]json.RawMessage, error) { - if err := strictjson.CheckDuplicateMembers(payload); err != nil { + if err := strictjson.CheckConflictingMembers(payload); err != nil { return nil, fmt.Errorf("%w: %v", ErrMalformedClaims, err) } var raw map[string]json.RawMessage diff --git a/internal/token/duplicate_claims_test.go b/internal/token/duplicate_claims_test.go index edee6068..7fa71a53 100644 --- a/internal/token/duplicate_claims_test.go +++ b/internal/token/duplicate_claims_test.go @@ -11,7 +11,9 @@ import ( // repeated one, where a first-wins reader of the same token (a gateway, // a log processor) keeps the first, so the two would disagree on who // the token is for. An ID token or JWT access token that repeats a -// member, at any depth, is refused. +// member with differing copies, at any depth, or as a case variant, is +// refused; one whose copies are identical, which every reader reads +// alike, is accepted. func TestParseClaimsRefuseDuplicateMembers(t *testing.T) { const idToken = `"iss":"https://as.example.com","aud":"client-1","exp":2,"iat":1` const accessToken = `"iss":"https://as.example.com","aud":"https://rs.example.com","exp":2,"iat":1,"jti":"j","client_id":"c"` @@ -21,12 +23,14 @@ func TestParseClaimsRefuseDuplicateMembers(t *testing.T) { wantErr bool }{ "ID token": {parseID, `{` + idToken + `,"sub":"alice"}`, false}, + "ID token, sub twice, same": {parseID, `{"sub":"alice",` + idToken + `,"sub":"alice"}`, false}, "ID token, sub twice": {parseID, `{"sub":"mallory",` + idToken + `,"sub":"alice"}`, true}, "ID token, nested repeat": {parseID, `{` + idToken + `,"sub":"alice","address":{"country":"A","country":"B"}}`, true}, "ID token, case variant": {parseID, `{` + idToken + `,"sub":"alice","SUB":"mallory"}`, true}, "access token": {parseAT, `{` + accessToken + `,"sub":"alice"}`, false}, "access token, sub twice": {parseAT, `{"sub":"mallory",` + accessToken + `,"sub":"alice"}`, true}, "access token, scope twice": {parseAT, `{` + accessToken + `,"sub":"alice","scope":"admin","scope":"read"}`, true}, + "access token, cnf twice, same": {parseAT, `{` + accessToken + `,"sub":"alice","cnf":{"jkt":"a"},"cnf":{ "jkt": "a" }}`, false}, "access token, cnf twice": {parseAT, `{` + accessToken + `,"sub":"alice","cnf":{"jkt":"a"},"cnf":{"jkt":"b"}}`, true}, "access token, jkt twice in cnf": {parseAT, `{` + accessToken + `,"sub":"alice","cnf":{"jkt":"a","jkt":"b"}}`, true}, } { diff --git a/internal/token/idtoken.go b/internal/token/idtoken.go index 8bd29422..7ae567da 100644 --- a/internal/token/idtoken.go +++ b/internal/token/idtoken.go @@ -39,7 +39,8 @@ type IDTokenClaims struct { } // parseIDTokenClaims parses an ID token's claims set, refusing one -// decodeClaimsObject refuses, such as one that repeats a claim. +// decodeClaimsObject refuses, such as one that repeats a claim with +// differing values. func parseIDTokenClaims(payload []byte) (IDTokenClaims, error) { raw, err := decodeClaimsObject(payload) if err != nil { From 9e47e21c301df3eadd4e09b3ca09406cf64321eb Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 18:54:22 +0800 Subject: [PATCH 10/12] docs: say a repeated claim is refused only when its copies differ The UPGRADING section on repeated JWT claims now says a repeat is refused when its copies differ, that identical copies (as in a JARM response carrying iss as both claim and RFC 9207 parameter) are accepted, that case-variant names are always refused, and that copies are compared as text. Co-Authored-By: Claude Opus 5.5 --- UPGRADING.md | 44 ++++++++++++++++++++++++++++---------------- 1 file changed, 28 insertions(+), 16 deletions(-) diff --git a/UPGRADING.md b/UPGRADING.md index 3fee8df0..a4ad6153 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -20,25 +20,35 @@ and `keys/ephemeral` needs only the steps not marked *production only*. ## v0.87.0 -### A JWT or UserInfo response may not repeat a claim (all packages) +### A JWT or UserInfo response may not repeat a claim with differing values (all packages) **Affects:** a deployment whose peer repeats a member name, in any -object at any depth, of a JWT's claims set, or writes two names that -differ only in case there: an authorization server's ID tokens, JARM -responses, UserInfo responses or JWT access tokens; a client's request -objects, signed CIBA requests, client assertions, DPoP proofs or -attestation PoPs; or a federation entity's Trust Marks, Trust Mark -Delegations, Trust Mark Status, Resolve or Historical Keys responses. -v0.81.0 did this for JOSE headers, client attestations, metadata and -Entity Statements; these claims sets kept encoding/json's last copy of -a repeated claim. +object at any depth, of a JWT's claims set, with copies whose values +differ, or writes two names that differ only in case there: an +authorization server's ID tokens, JARM responses, UserInfo responses or +JWT access tokens; a client's request objects, signed CIBA requests, +client assertions, DPoP proofs or attestation PoPs; or a federation +entity's Trust Marks, Trust Mark Delegations, Trust Mark Status, +Resolve or Historical Keys responses. A member repeated with identical +copies (the same JSON text, ignoring whitespace), such as a JARM +response carrying `iss` both as its JWT claim and as the RFC 9207 +response parameter, is still accepted. v0.81.0 refused any repeat in +JOSE headers, client attestations, metadata and Entity Statements, and +still does; these claims sets kept encoding/json's last copy of a +repeated claim. **Why:** RFC 7519 §4 requires a JWT's claim names to be unique, and lets a recipient reject a repeat or keep the last copy. Keeping the -last copy left a JWT with two readings: another reader of the same -token (a gateway in front of a resource server, a log processor, a -second verifier) that keeps the first copy would see a different -`sub`, `aud` or `scope` than FAPIgo acted on. +last copy left a JWT with differing copies two readings: another reader +of the same token (a gateway in front of a resource server, a log +processor, a second verifier) that keeps the first copy would see a +different `sub`, `aud` or `scope` than FAPIgo acted on. Identical +copies read the same to every reader, so they are accepted. Two names +differing only in case are refused whatever their values, since +encoding/json reads them as one member where another reader reads two. +Copies are compared as text: values another reader might take as equal +but written differently (`"a"` and `"\u0061"`, `1` and `1.0`) are +refused. **What fails:** nothing at startup. The server answers such a request object with `invalid_request_object`, a signed CIBA request with @@ -48,10 +58,12 @@ resource server answers such a JWT access token with `invalid_token`, and a DPoP proof with `invalid_dpop_proof`. The client refuses such an ID token, JARM response or UserInfo response, signed, encrypted or plain JSON, with `invalid_response`. A federation JWT that repeats a -claim fails to parse, with the error its parser gives any malformed one. +claim with differing values fails to parse, with the error its parser +gives any malformed one. **What to change:** nothing in your code. A peer producing such JWTs -must write each claim once, spelled one way. +must write each claim once, spelled one way, or repeat it only with an +identical value. ## v0.86.0 From 17394a4f13afa21349c08f54d28dbcc33668484e Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 18:55:24 +0800 Subject: [PATCH 11/12] test: add mutants for accepting identical repeated claims Adds mutants for CheckConflictingMembers' branches (identical copies accepted, differing copies refused, case variants refused, nested objects checked, copies compared after compacting) and for the JARM parser accepting an iss repeated with one value. Re-anchors the duplicate-claim mutants on the call sites' new check. Co-Authored-By: Claude Opus 5.5 --- .github/mutation/mutants.json | 118 +++++++++++++++++++++++++++------- 1 file changed, 95 insertions(+), 23 deletions(-) diff --git a/.github/mutation/mutants.json b/.github/mutation/mutants.json index 75a67f06..ef9c0702 100644 --- a/.github/mutation/mutants.json +++ b/.github/mutation/mutants.json @@ -5818,99 +5818,99 @@ { "id": "token-claims-refuse-duplicate-members", "file": "internal/token/claims_object.go", - "old": "if err := strictjson.CheckDuplicateMembers(payload); err != nil {", - "new": "if err := strictjson.CheckDuplicateMembers(payload); err != nil && false {", + "old": "if err := strictjson.CheckConflictingMembers(payload); err != nil {", + "new": "if err := strictjson.CheckConflictingMembers(payload); err != nil && false {", "module": "root", "packages": [ "./internal/token", "./resource" ], "run": "^(TestParseClaimsRefuseDuplicateMembers|TestVerifyRefusesJWTAccessTokenRepeatingAClaim)$", - "why": "ID token and JWT access token claims sets that repeat a member are refused, not read last-wins" + "why": "ID token and JWT access token claims sets that repeat a member with differing copies are refused, not read last-wins" }, { "id": "jarm-claims-refuse-duplicate-members", "file": "internal/jarm/claims_object.go", - "old": "if err := strictjson.CheckDuplicateMembers(payload); err != nil {", - "new": "if err := strictjson.CheckDuplicateMembers(payload); err != nil && false {", + "old": "if err := strictjson.CheckConflictingMembers(payload); err != nil {", + "new": "if err := strictjson.CheckConflictingMembers(payload); err != nil && false {", "module": "root", "packages": [ "./internal/jarm" ], "run": "^TestParseClaimsRefusesDuplicateMembers$", - "why": "a JARM claims set that repeats a member is refused" + "why": "a JARM claims set that repeats a member with differing copies is refused" }, { "id": "requestobject-claims-refuse-duplicate-members", "file": "internal/requestobject/claims_object.go", - "old": "if err := strictjson.CheckDuplicateMembers(payload); err != nil {", - "new": "if err := strictjson.CheckDuplicateMembers(payload); err != nil && false {", + "old": "if err := strictjson.CheckConflictingMembers(payload); err != nil {", + "new": "if err := strictjson.CheckConflictingMembers(payload); err != nil && false {", "module": "root", "packages": [ "./internal/requestobject" ], "run": "^TestParseClaimsRefusesDuplicateMembers$", - "why": "a request object claims set that repeats a member is refused" + "why": "a request object claims set that repeats a member with differing copies is refused" }, { "id": "clientassertion-claims-refuse-duplicate-members", "file": "internal/clientassertion/claims.go", - "old": "if err := strictjson.CheckDuplicateMembers(payload); err != nil {", - "new": "if err := strictjson.CheckDuplicateMembers(payload); err != nil && false {", + "old": "if err := strictjson.CheckConflictingMembers(payload); err != nil {", + "new": "if err := strictjson.CheckConflictingMembers(payload); err != nil && false {", "module": "root", "packages": [ "./internal/clientassertion" ], "run": "^TestParseClaimsRefusesDuplicateMembers$", - "why": "a client assertion claims set that repeats a member is refused" + "why": "a client assertion claims set that repeats a member with differing copies is refused" }, { "id": "dpop-claims-refuse-duplicate-members", "file": "internal/dpop/proof.go", - "old": "strictjson.UnmarshalNoRepeats(payload, &c)", + "old": "strictjson.UnmarshalNoConflicts(payload, &c)", "new": "strictjson.Unmarshal(payload, &c)", "module": "root", "packages": [ "./internal/dpop" ], "run": "^TestParseClaimsRefusesDuplicateMembers$", - "why": "a DPoP proof claims set that repeats a member is refused" + "why": "a DPoP proof claims set that repeats a member with differing copies is refused" }, { "id": "clientattestation-pop-refuse-duplicate-members", "file": "internal/clientattestation/claims.go", - "old": "var c popClaims\n\tif err := unmarshalUniqueMembers(payload, &c)", - "new": "var c popClaims\n\tif err := strictjson.Unmarshal(payload, &c)", + "old": "if err := strictjson.UnmarshalNoConflicts(payload, &c)", + "new": "if err := strictjson.Unmarshal(payload, &c)", "module": "root", "packages": [ "./internal/clientattestation" ], "run": "^TestParsePoPClaimsRefusesDuplicateMembers$", - "why": "an attestation PoP claims set that repeats a member is refused" + "why": "an attestation PoP claims set that repeats a member with differing copies is refused" }, { "id": "federation-jwt-claims-refuse-duplicate-members", "file": "internal/federation/claims_validation.go", - "old": "\tif err := refuseDuplicateMembers(payload); err != nil {\n\t\treturn nil, err", - "new": "\tif err := refuseDuplicateMembers(payload); err != nil && false {\n\t\treturn nil, err", + "old": "if err := strictjson.CheckConflictingMembers(payload); err != nil {", + "new": "if err := strictjson.CheckConflictingMembers(payload); err != nil && false {", "module": "root", "packages": [ "./internal/federation" ], "run": "^TestParseFederationJWTClaimsRefuseDuplicateMembers$", - "why": "Trust Marks, delegations, status, resolve and historical keys claims sets that repeat a member are refused" + "why": "Trust Marks, delegations, status, resolve and historical keys claims sets that repeat a member with differing copies are refused" }, { "id": "client-userinfo-refuse-duplicate-members", "file": "client/userinfo.go", - "old": "if err := strictjson.CheckDuplicateMembers(body); err != nil {", - "new": "if err := strictjson.CheckDuplicateMembers(body); err != nil && false {", + "old": "if err := strictjson.CheckConflictingMembers(body); err != nil {", + "new": "if err := strictjson.CheckConflictingMembers(body); err != nil && false {", "module": "root", "packages": [ "./client" ], "run": "^TestDecodeUserInfoJSONRefusesDuplicateMembers$", - "why": "a UserInfo response that repeats a member is refused" + "why": "a UserInfo response that repeats a member with differing copies is refused" }, { "id": "resource-subject-kind-grant-type-marks-client", @@ -5923,5 +5923,77 @@ ], "run": "^(TestVerifySubjectKindOfThirdPartyJWTAccessTokens|TestVerifySubjectKind)$", "why": "a token carrying grant_type client_credentials reads as SubjectClient" + }, + { + "id": "strictjson-conflict-identical-copies-accepted", + "file": "internal/strictjson/members_conflict.go", + "old": "if !bytes.Equal(first.compact, c) {", + "new": "if !bytes.Equal(first.compact, c) || true {", + "module": "root", + "packages": [ + "./internal/strictjson" + ], + "run": "^(TestCheckConflictingMembersAcceptsIdenticalRepeats|TestCheckConflictingMembersRefusesConflicts|TestCheckConflictingMembersBoundsNesting|TestCheckConflictingMembersNamesTheMembers|TestUnmarshalNoConflicts|TestCheckConflictingMembersAcceptsNoDifferential|TestCheckDuplicateMembersClosesFirstWinsDifferential)$", + "why": "CheckConflictingMembers accepts a repeated member whose copies are identical" + }, + { + "id": "strictjson-conflict-differing-copies-refused", + "file": "internal/strictjson/members_conflict.go", + "old": "if !bytes.Equal(first.compact, c) {", + "new": "if !bytes.Equal(first.compact, c) && false {", + "module": "root", + "packages": [ + "./internal/strictjson" + ], + "run": "^(TestCheckConflictingMembersAcceptsIdenticalRepeats|TestCheckConflictingMembersRefusesConflicts|TestCheckConflictingMembersBoundsNesting|TestCheckConflictingMembersNamesTheMembers|TestUnmarshalNoConflicts|TestCheckConflictingMembersAcceptsNoDifferential|TestCheckDuplicateMembersClosesFirstWinsDifferential)$", + "why": "CheckConflictingMembers refuses a repeated member whose copies differ" + }, + { + "id": "strictjson-conflict-case-variant-refused", + "file": "internal/strictjson/members_conflict.go", + "old": "if first != nil && first.name != name {", + "new": "if first != nil && first.name != name && false {", + "module": "root", + "packages": [ + "./internal/strictjson" + ], + "run": "^(TestCheckConflictingMembersAcceptsIdenticalRepeats|TestCheckConflictingMembersRefusesConflicts|TestCheckConflictingMembersBoundsNesting|TestCheckConflictingMembersNamesTheMembers|TestUnmarshalNoConflicts|TestCheckConflictingMembersAcceptsNoDifferential|TestCheckDuplicateMembersClosesFirstWinsDifferential)$", + "why": "CheckConflictingMembers refuses two names that differ only in case, even with identical values" + }, + { + "id": "strictjson-conflict-nested-objects-checked", + "file": "internal/strictjson/members_conflict.go", + "old": "\tif delim == '{' {\n\t\treturn w.object(depth)", + "new": "\tif delim == '{' && depth == 0 {\n\t\treturn w.object(depth)", + "module": "root", + "packages": [ + "./internal/strictjson" + ], + "run": "^(TestCheckConflictingMembersAcceptsIdenticalRepeats|TestCheckConflictingMembersRefusesConflicts|TestCheckConflictingMembersBoundsNesting|TestCheckConflictingMembersNamesTheMembers|TestUnmarshalNoConflicts|TestCheckConflictingMembersAcceptsNoDifferential|TestCheckDuplicateMembersClosesFirstWinsDifferential)$", + "why": "CheckConflictingMembers checks the members of nested objects, including inside identical copies" + }, + { + "id": "strictjson-conflict-compares-compacted-copies", + "file": "internal/strictjson/members_conflict.go", + "old": "if err := json.Compact(&buf, bytes.TrimLeft(span, \" \\t\\r\\n:\")); err != nil {", + "new": "if _, err := buf.Write(bytes.TrimLeft(span, \" \\t\\r\\n:\")); err != nil {", + "module": "root", + "packages": [ + "./internal/strictjson" + ], + "run": "^(TestCheckConflictingMembersAcceptsIdenticalRepeats|TestCheckConflictingMembersRefusesConflicts|TestCheckConflictingMembersBoundsNesting|TestCheckConflictingMembersNamesTheMembers|TestUnmarshalNoConflicts|TestCheckConflictingMembersAcceptsNoDifferential|TestCheckDuplicateMembersClosesFirstWinsDifferential)$", + "why": "CheckConflictingMembers compares copies after json.Compact, so whitespace alone is no difference" + }, + { + "id": "jarm-claims-accept-identical-repeat", + "file": "internal/jarm/claims_object.go", + "old": "strictjson.CheckConflictingMembers(payload)", + "new": "strictjson.CheckDuplicateMembers(payload)", + "module": "root", + "packages": [ + "./internal/jarm" + ], + "run": "^TestParseClaimsRefusesDuplicateMembers$", + "why": "a JARM response repeating iss with an identical value (claim and RFC 9207 parameter) is accepted" } ] From 38ec98074e95181d3083c6be7103d17d3c7f1bb1 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 19:07:58 +0800 Subject: [PATCH 12/12] test: cover a claims set that is not an object and an uncompactable copy Co-Authored-By: Claude Opus 5.5 --- .../federation/claims_object_internal_test.go | 16 ++++++++++++++ internal/jarm/claims_object_internal_test.go | 16 ++++++++++++++ .../claims_object_internal_test.go | 16 ++++++++++++++ .../members_conflict_internal_test.go | 21 +++++++++++++++++++ internal/token/claims_object_internal_test.go | 16 ++++++++++++++ 5 files changed, 85 insertions(+) create mode 100644 internal/federation/claims_object_internal_test.go create mode 100644 internal/jarm/claims_object_internal_test.go create mode 100644 internal/requestobject/claims_object_internal_test.go create mode 100644 internal/strictjson/members_conflict_internal_test.go create mode 100644 internal/token/claims_object_internal_test.go diff --git a/internal/federation/claims_object_internal_test.go b/internal/federation/claims_object_internal_test.go new file mode 100644 index 00000000..f6391119 --- /dev/null +++ b/internal/federation/claims_object_internal_test.go @@ -0,0 +1,16 @@ +package federation + +import ( + "errors" + "testing" +) + +// TestDecodeClaimsObjectRefusesANonObject: a claims set that is valid +// JSON with no repeated member, but not a JSON object, is malformed. +func TestDecodeClaimsObjectRefusesANonObject(t *testing.T) { + for _, payload := range []string{`[]`, `"claims"`, `7`} { + if _, err := decodeClaimsObject([]byte(payload)); !errors.Is(err, ErrMalformedClaims) { + t.Errorf("decodeClaimsObject(%s) = %v, want ErrMalformedClaims", payload, err) + } + } +} diff --git a/internal/jarm/claims_object_internal_test.go b/internal/jarm/claims_object_internal_test.go new file mode 100644 index 00000000..d892e430 --- /dev/null +++ b/internal/jarm/claims_object_internal_test.go @@ -0,0 +1,16 @@ +package jarm + +import ( + "errors" + "testing" +) + +// TestDecodeClaimsObjectRefusesANonObject: a claims set that is valid +// JSON with no repeated member, but not a JSON object, is malformed. +func TestDecodeClaimsObjectRefusesANonObject(t *testing.T) { + for _, payload := range []string{`[]`, `"claims"`, `7`} { + if _, err := decodeClaimsObject([]byte(payload)); !errors.Is(err, ErrMalformedClaims) { + t.Errorf("decodeClaimsObject(%s) = %v, want ErrMalformedClaims", payload, err) + } + } +} diff --git a/internal/requestobject/claims_object_internal_test.go b/internal/requestobject/claims_object_internal_test.go new file mode 100644 index 00000000..18e8983e --- /dev/null +++ b/internal/requestobject/claims_object_internal_test.go @@ -0,0 +1,16 @@ +package requestobject + +import ( + "errors" + "testing" +) + +// TestDecodeClaimsObjectRefusesANonObject: a claims set that is valid +// JSON with no repeated member, but not a JSON object, is malformed. +func TestDecodeClaimsObjectRefusesANonObject(t *testing.T) { + for _, payload := range []string{`[]`, `"claims"`, `7`} { + if _, err := decodeClaimsObject([]byte(payload)); !errors.Is(err, ErrMalformedClaims) { + t.Errorf("decodeClaimsObject(%s) = %v, want ErrMalformedClaims", payload, err) + } + } +} diff --git a/internal/strictjson/members_conflict_internal_test.go b/internal/strictjson/members_conflict_internal_test.go new file mode 100644 index 00000000..2c3158f4 --- /dev/null +++ b/internal/strictjson/members_conflict_internal_test.go @@ -0,0 +1,21 @@ +package strictjson + +import "testing" + +// TestCompareCopiesReportsAnUncompactableSpan: sameAsFirst and +// compactValue report a span that isn't a JSON value. The walker only +// hands them spans its decoder has already read as values, so this is +// the defence behind that, exercised directly. +func TestCompareCopiesReportsAnUncompactableSpan(t *testing.T) { + if _, err := compactValue([]byte(`:{"a"`)); err == nil { + t.Error(`compactValue(:{"a") = nil error, want one`) + } + w := &conflictWalker{data: []byte(`{"a" 1}`)} + if err := w.sameAsFirst(&firstCopy{name: "a", start: 0, end: 4}, 5, 6); err == nil { + t.Error("sameAsFirst with an uncompactable first copy = nil error, want one") + } + w = &conflictWalker{data: []byte(`1 {"a"`)} + if err := w.sameAsFirst(&firstCopy{name: "a", start: 0, end: 1}, 2, 6); err == nil { + t.Error("sameAsFirst with an uncompactable second copy = nil error, want one") + } +} diff --git a/internal/token/claims_object_internal_test.go b/internal/token/claims_object_internal_test.go new file mode 100644 index 00000000..e7776b71 --- /dev/null +++ b/internal/token/claims_object_internal_test.go @@ -0,0 +1,16 @@ +package token + +import ( + "errors" + "testing" +) + +// TestDecodeClaimsObjectRefusesANonObject: a claims set that is valid +// JSON with no repeated member, but not a JSON object, is malformed. +func TestDecodeClaimsObjectRefusesANonObject(t *testing.T) { + for _, payload := range []string{`[]`, `"claims"`, `7`} { + if _, err := decodeClaimsObject([]byte(payload)); !errors.Is(err, ErrMalformedClaims) { + t.Errorf("decodeClaimsObject(%s) = %v, want ErrMalformedClaims", payload, err) + } + } +}