diff --git a/.github/mutation/mutants.json b/.github/mutation/mutants.json index 80bbefdb..ef9c0702 100644 --- a/.github/mutation/mutants.json +++ b/.github/mutation/mutants.json @@ -5814,5 +5814,186 @@ ], "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.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 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.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 with differing copies is refused" + }, + { + "id": "requestobject-claims-refuse-duplicate-members", + "file": "internal/requestobject/claims_object.go", + "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 with differing copies is refused" + }, + { + "id": "clientassertion-claims-refuse-duplicate-members", + "file": "internal/clientassertion/claims.go", + "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 with differing copies is refused" + }, + { + "id": "dpop-claims-refuse-duplicate-members", + "file": "internal/dpop/proof.go", + "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 with differing copies is refused" + }, + { + "id": "clientattestation-pop-refuse-duplicate-members", + "file": "internal/clientattestation/claims.go", + "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 with differing copies is refused" + }, + { + "id": "federation-jwt-claims-refuse-duplicate-members", + "file": "internal/federation/claims_validation.go", + "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 with differing copies are refused" + }, + { + "id": "client-userinfo-refuse-duplicate-members", + "file": "client/userinfo.go", + "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 with differing copies 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" + }, + { + "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" } ] 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/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/UPGRADING.md b/UPGRADING.md index 96439747..a4ad6153 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -18,6 +18,53 @@ 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 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, 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 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 +`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 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, or repeat it only with an +identical value. + ## v0.86.0 ### A Trust Chain that expires while it resolves is refused (federation) diff --git a/client/userinfo.go b/client/userinfo.go index 8265db6c..daaa73f5 100644 --- a/client/userinfo.go +++ b/client/userinfo.go @@ -151,11 +151,21 @@ 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, 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.CheckConflictingMembers(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..aa29c7b4 --- /dev/null +++ b/client/userinfo_duplicate_members_test.go @@ -0,0 +1,38 @@ +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. A member repeated with identical copies +// reads alike to every reader, so it is accepted. +func TestDecodeUserInfoJSONRefusesDuplicateMembers(t *testing.T) { + 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"}`, + `{"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/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/internal/clientassertion/claims.go b/internal/clientassertion/claims.go index efaec554..1c6b08c1 100644 --- a/internal/clientassertion/claims.go +++ b/internal/clientassertion/claims.go @@ -53,6 +53,14 @@ 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. 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 { 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..56b07af9 --- /dev/null +++ b/internal/clientassertion/duplicate_claims_test.go @@ -0,0 +1,34 @@ +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 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) { + 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"}`, + `{"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..f441531d 100644 --- a/internal/clientattestation/claims.go +++ b/internal/clientattestation/claims.go @@ -111,7 +111,12 @@ func (a *popAudience) UnmarshalJSON(data []byte) error { func parsePoPClaims(payload []byte) (popClaims, error) { var c popClaims - if err := strictjson.Unmarshal(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 new file mode 100644 index 00000000..5a6714f6 --- /dev/null +++ b/internal/clientattestation/pop_duplicate_claims_test.go @@ -0,0 +1,35 @@ +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 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) { + 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"}`, + `{"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..485892a5 --- /dev/null +++ b/internal/dpop/duplicate_claims_test.go @@ -0,0 +1,35 @@ +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 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) { + 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") { + 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..3ec5564a 100644 --- a/internal/dpop/proof.go +++ b/internal/dpop/proof.go @@ -31,7 +31,12 @@ type claims struct { func parseClaims(payload []byte) (claims, error) { var c claims - if err := strictjson.Unmarshal(payload, &c); err != nil { + // 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. 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 new file mode 100644 index 00000000..97ad6b5f --- /dev/null +++ b/internal/federation/claims_duplicate_members_test.go @@ -0,0 +1,62 @@ +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. +// 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` + 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}, + "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, 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)) + 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_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/federation/claims_validation.go b/internal/federation/claims_validation.go index 3d182a1a..cb43d81b 100644 --- a/internal/federation/claims_validation.go +++ b/internal/federation/claims_validation.go @@ -156,3 +156,26 @@ func refuseDuplicateMembers(payload []byte) error { } return nil } + +// 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 := 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 { + 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..58c7b504 100644 --- a/internal/federation/historicalkeys.go +++ b/internal/federation/historicalkeys.go @@ -208,8 +208,10 @@ 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 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"` @@ -238,9 +240,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") diff --git a/internal/jarm/claims.go b/internal/jarm/claims.go index 70f4ac2f..3b874a18 100644 --- a/internal/jarm/claims.go +++ b/internal/jarm/claims.go @@ -25,10 +25,13 @@ 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 with +// differing values. 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..1969d138 --- /dev/null +++ b/internal/jarm/claims_object.go @@ -0,0 +1,27 @@ +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, 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.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 { + return nil, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + } + return raw, nil +} 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/jarm/duplicate_claims_test.go b/internal/jarm/duplicate_claims_test.go new file mode 100644 index 00000000..4b9e286e --- /dev/null +++ b/internal/jarm/duplicate_claims_test.go @@ -0,0 +1,41 @@ +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 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) { + 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") { + t.Errorf("parseClaims(%s) = %v, want ErrMalformedClaims for a duplicate member", payload, err) + } + } +} diff --git a/internal/requestobject/claims.go b/internal/requestobject/claims.go index 478f8819..07b676c1 100644 --- a/internal/requestobject/claims.go +++ b/internal/requestobject/claims.go @@ -67,10 +67,13 @@ 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 with +// differing values. 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..bd866cb2 --- /dev/null +++ b/internal/requestobject/claims_object.go @@ -0,0 +1,27 @@ +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, 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.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 { + return nil, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + } + return raw, nil +} 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/requestobject/duplicate_claims_test.go b/internal/requestobject/duplicate_claims_test.go new file mode 100644 index 00000000..9559c729 --- /dev/null +++ b/internal/requestobject/duplicate_claims_test.go @@ -0,0 +1,35 @@ +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 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) { + 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"}`, + `{"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) + } + } +} diff --git a/internal/strictjson/first_wins_differential_test.go b/internal/strictjson/first_wins_differential_test.go new file mode 100644 index 00000000..d6caa3d6 --- /dev/null +++ b/internal/strictjson/first_wins_differential_test.go @@ -0,0 +1,91 @@ +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 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"`}, + {`{"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) + } + 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) + } + } +} + +// 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/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_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/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 0578f2b2..6541c720 100644 --- a/internal/strictjson/strictjson.go +++ b/internal/strictjson/strictjson.go @@ -19,14 +19,22 @@ // // 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, 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. 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 18389468..f28f12de 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 with differing values. 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..d0cd231a --- /dev/null +++ b/internal/token/claims_object.go @@ -0,0 +1,27 @@ +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, 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.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 { + return nil, fmt.Errorf("%w: %v", ErrMalformedClaims, err) + } + return raw, nil +} 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) + } + } +} diff --git a/internal/token/duplicate_claims_test.go b/internal/token/duplicate_claims_test.go new file mode 100644 index 00000000..7fa71a53 --- /dev/null +++ b/internal/token/duplicate_claims_test.go @@ -0,0 +1,56 @@ +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. An ID token or JWT access token that repeats a +// 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"` + 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, 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}, + } { + t.Run(name, func(t *testing.T) { + checkDuplicateRefusal(t, tc.parse([]byte(tc.payload)), tc.wantErr) + }) + } +} + +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 +// 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/internal/token/idtoken.go b/internal/token/idtoken.go index 6edc0e22..7ae567da 100644 --- a/internal/token/idtoken.go +++ b/internal/token/idtoken.go @@ -38,10 +38,13 @@ 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 with +// differing values. 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) diff --git a/resource/third_party_subject_kind_test.go b/resource/third_party_subject_kind_test.go new file mode 100644 index 00000000..86c93203 --- /dev/null +++ b/resource/third_party_subject_kind_test.go @@ -0,0 +1,120 @@ +package resource_test + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "errors" + "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) + } + }) + } +} + +// 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. +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