diff --git a/.github/mutation/mutants.json b/.github/mutation/mutants.json index d2c32f0d..c970bba1 100644 --- a/.github/mutation/mutants.json +++ b/.github/mutation/mutants.json @@ -1215,8 +1215,8 @@ { "id": "srv-code-reuse-audit-access-token-failure", "file": "server/token.go", - "old": "failures = append(failures, s.deps.Revocation.Revoke(ctx, reused.IssuedAccessTokenKey, s.deps.Clock.Now().Add(timeutil.SaturatingAdd(s.cfg.Limits.AccessTokenLifetime, s.cfg.Limits.MaxClockSkew, s.cfg.Limits.MaxClockSkew))))", - "new": "_ = s.deps.Revocation.Revoke(ctx, reused.IssuedAccessTokenKey, s.deps.Clock.Now().Add(timeutil.SaturatingAdd(s.cfg.Limits.AccessTokenLifetime, s.cfg.Limits.MaxClockSkew, s.cfg.Limits.MaxClockSkew)))", + "old": "failures = append(failures, s.deps.Revocation.Revoke(ctx, key, until))", + "new": "_ = s.deps.Revocation.Revoke(ctx, key, until)", "module": "root", "packages": [ "./server" @@ -4910,5 +4910,113 @@ ], "run": "^TestBackchannelDecisionsAndExpiry$", "why": "sqlstore wraps ErrBackchannelAuthenticationAlreadyDecided for a second decision" + }, + { + "id": "server-code-digest-covers-issuer", + "file": "server/token.go", + "old": "codeHashPrefix + lengthPrefixed(issuer) +", + "new": "codeHashPrefix + lengthPrefixed(\"\") +", + "module": "root", + "packages": [ + "./server" + ], + "run": "^(TestAnotherIssuersCodeIsLeftUnspent|TestAuthorizationCodeHash)$", + "why": "an authorization code's digest covers the issuer, so another issuer's server sharing the store neither finds nor spends it" + }, + { + "id": "server-refresh-digest-covers-issuer", + "file": "server/token.go", + "old": "refreshHashPrefix + lengthPrefixed(issuer) + token", + "new": "refreshHashPrefix + lengthPrefixed(\"\") + token", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestAnotherIssuersRefreshTokenIsNotFound$", + "why": "a refresh token's digest covers the issuer, so another issuer's server sharing the store doesn't find it" + }, + { + "id": "server-auth-req-id-digest-covers-issuer", + "file": "server/backchannel_token.go", + "old": "backchannelAuthReqIDHashPrefix + lengthPrefixed(issuer) +", + "new": "backchannelAuthReqIDHashPrefix + lengthPrefixed(\"\") +", + "module": "root", + "packages": [ + "./server" + ], + "run": "^(TestAnotherIssuersAuthReqIDIsLeftUnspent|TestBackchannelAuthReqIDHash)$", + "why": "an auth_req_id's digest covers the issuer, so another issuer's server sharing the store neither polls nor spends it" + }, + { + "id": "server-reuse-revokes-namespaced-access-token-key", + "file": "server/token.go", + "old": "range grantrevocation.AccessTokenKeys(s.cfg.Issuer.String(), reused.IssuedAccessTokenKey)", + "new": "range []string{reused.IssuedAccessTokenKey}", + "module": "root", + "packages": [ + "./server" + ], + "run": "^(TestExchangeAuthorizationCodeReuseRevokesAccessToken|TestExchangeAuthorizationCodeReuseRevokesOpaqueAccessToken)$", + "why": "a reused code's access token is revoked under its issuer-namespaced key" + }, + { + "id": "server-reuse-still-revokes-raw-access-token-key", + "file": "server/token.go", + "old": "range grantrevocation.AccessTokenKeys(s.cfg.Issuer.String(), reused.IssuedAccessTokenKey)", + "new": "range grantrevocation.AccessTokenKeys(s.cfg.Issuer.String(), reused.IssuedAccessTokenKey)[:1]", + "module": "root", + "packages": [ + "./server" + ], + "run": "^(TestExchangeAuthorizationCodeReuseRevokesAccessToken|TestExchangeAuthorizationCodeReuseRevokesOpaqueAccessToken)$", + "why": "during the transition a reused code's access token is still revoked under its raw key, for resource servers not yet upgraded" + }, + { + "id": "resource-checks-namespaced-token-key", + "file": "resource/verify.go", + "old": "\treturn grantrevocation.AccessTokenKeys(resolved.Issuer, resolved.Key)\n", + "new": "\treturn []string{resolved.Key}\n", + "module": "root", + "packages": [ + "./resource" + ], + "run": "^TestVerifyChecksTheTokenRevocationKeys$", + "why": "Verify refuses a token revoked under its issuer-namespaced key" + }, + { + "id": "resource-still-checks-raw-token-key", + "file": "resource/verify.go", + "old": "\treturn grantrevocation.AccessTokenKeys(resolved.Issuer, resolved.Key)\n", + "new": "\treturn grantrevocation.AccessTokenKeys(resolved.Issuer, resolved.Key)[:1]\n", + "module": "root", + "packages": [ + "./resource" + ], + "run": "^TestVerifyChecksTheTokenRevocationKeys$", + "why": "Verify still refuses a token an older server revoked under its raw key" + }, + { + "id": "resource-batch-checks-namespaced-token-key", + "file": "resource/verify.go", + "old": "batch.IsAnyRevoked(ctx, append(tokenRevocationKeys(resolved), keys...))", + "new": "batch.IsAnyRevoked(ctx, append([]string{resolved.Key}, keys...))", + "module": "root", + "packages": [ + "./resource" + ], + "run": "^(TestVerifyChecksTheTokenRevocationKeys|TestVerifyChecksRevocationInOneBatch)$", + "why": "a batch revocation check covers the token's issuer-namespaced key, so its 'none revoked' answer can't pass a revoked token" + }, + { + "id": "grantrevocation-access-token-key-length-prefix", + "file": "internal/grantrevocation/grantrevocation.go", + "old": "\"access-token:\" + strconv.Itoa(len(issuer)) + \":\" + issuer + key", + "new": "\"access-token:\" + strconv.Itoa(0*len(issuer)) + \":\" + issuer + key", + "module": "root", + "packages": [ + "./internal/grantrevocation" + ], + "run": "^TestAccessTokenKeysAreNamespacedByIssuer$", + "why": "the issuer's length prefix splits an access token revocation key into issuer and token key one way only" } ] diff --git a/UPGRADING.md b/UPGRADING.md index 027a668c..89e54478 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -18,6 +18,91 @@ 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.85.0 + +### Codes, refresh tokens and `auth_req_id`s are stored under digests covering the issuer (server, storage) + +**Affects:** every server, once, at deploy. Most visibly a server +issuing refresh tokens (`offline_access`). No code changes. + +**Why:** the digest an authorization code, a refresh token or a CIBA +`auth_req_id` is stored under (`NewAuthorizationCode.CodeHash`, +`NewRefreshToken.TokenHash`, `NewBackchannelAuthentication.AuthReqIDHash`) +didn't include the server's issuer. Two servers of different issuers +sharing one store found each other's records: the store spent the code +or the CIBA approval (or reported a code reused, revoking what it had +issued) before the server could refuse the record as another issuer's. +So one issuer's client could burn a code or `auth_req_id` the other +issued. Each digest is now taken over the issuer as well, behind a new +domain-separation prefix: a code, refresh token or `auth_req_id` +presented to a server of another issuer is unknown to the store, and +neither found nor consumed. + +**What fails:** every value stored before the upgrade is under the old +digest, which the upgraded server no longer computes, so: + +- **Every refresh token issued before the upgrade stops working.** + `RefreshAccessToken` answers `invalid_grant` ("refresh_token is + invalid, expired, or already used"), as for a token that never + existed, and `RevokeToken` treats it as unknown too. Clients must get a new one through a new + authorization: the end user signs in (and consents) again. Access + tokens already issued are unaffected and run out their lifetime. +- Authorization codes in flight at deploy (issued, not yet redeemed) + fail once: the exchange answers `invalid_grant` and the client starts + the authorization again. Codes live `Limits.AuthorizationCodeLifetime` + (a minute at most). A pre-upgrade code presented again after the + upgrade is unknown rather than reused, so it no longer revokes the + tokens issued from it; those tokens were issued at most a code + lifetime before the upgrade, and expire as usual. +- CIBA requests in flight at deploy fail once: a poll answers + `invalid_grant` and the client starts a new request. +- Rows a `GrantStore`, `BackchannelAuthenticationStore` or + `GrantRegistry` holds for the old digests are no longer reachable + through the server and expire as usual. `ListGrants` may still list + a pre-upgrade grant until its entry expires, and `RevokeListedGrant` + still revokes it. + +**What to change:** nothing in code, and no store migration: `memstore`, +`sqlstore` and any custom store key records by whatever digest the +server hands them. Plan the deploy: expect every refresh-token holder +to re-authorize, and tell client operators (or their users) that a +one-time sign-in is coming. A store shared by servers of different +issuers needs nothing more; each server now sees only its own records. + +### A reused code's access token is revoked under an issuer-namespaced key too (server, resource) + +**Affects:** a deployment with its own `server.RevocationSink` or +`resource.RevocationChecker` that does more than store and compare keys +exactly, such as one that only accepts keys shaped like a jti or an +opaque token's hex hash, or limits a key's length. + +**Why:** the server revoked a reused code's access token under the +token's own key alone (a JWT's `jti`, an opaque token's hex SHA-256). +With servers of different issuers sharing one revocation store, one +issuer's revoked `jti` would refuse another issuer's token with the same +`jti`. The server now also revokes it under that key namespaced by its +issuer: `access-token:`, the issuer's length in bytes, `:`, the issuer, +then the token's key. It still writes the raw key as well, so a resource +server that hasn't been upgraded, or a checker that knows only the raw +form, keeps refusing the token. `resource.Verifier` asks about the +namespaced key (when the resolver reports the token's issuer) and then +the raw one, so a record an older server wrote still refuses the token. +A later release will stop writing and checking the raw key. + +**What fails:** nothing for `memstore`, `sqlstore` or any store that +keeps keys as given and compares them exactly; such a store holds one +more record per reused code. A sink that refuses the new key makes a +code reuse's revocation report a failure +(`AuditEventRevokeReusedAuthorizationCode` with +`AuditOutcomeFailure`), though the raw key is still written. + +**What to change:** make a custom sink accept any key (an opaque +token's namespaced key runs about 30 bytes longer than the +`code-grant:` keys it already stores for the same issuer), and a custom +checker answer the namespaced key from what the sink stored, as it +answers every other key. Don't rely on the raw key alone: it will be +dropped. + ## v0.84.0 ### A JWT access token's `client_sub` claim no longer sets `ClientSubject` (resource) diff --git a/internal/grantrevocation/grantrevocation.go b/internal/grantrevocation/grantrevocation.go index ebfd25ba..5a212c09 100644 --- a/internal/grantrevocation/grantrevocation.go +++ b/internal/grantrevocation/grantrevocation.go @@ -1,13 +1,41 @@ -// Package grantrevocation is how a revoked grant is recorded and found: -// shared by server, which revokes grants and refuses their codes and -// refresh tokens, and resource, which refuses their access tokens. +// Package grantrevocation is how a revoked grant, or a revoked access +// token, is recorded and found: shared by server, which revokes grants +// and access tokens and refuses the grants' codes and refresh tokens, +// and resource, which refuses their access tokens. package grantrevocation import ( "crypto/sha256" "encoding/base64" + "strconv" ) +// AccessTokenKey is the revocation-store key recording one access token +// issuer issued, whose own revocation key (a JWT's jti, an opaque +// token's hex SHA-256: resource.ResolvedAccessToken.Key) is key, as +// revoked: "access-token:", the issuer's length in bytes, ":", the +// issuer, then key. The prefix keeps it apart from Key's and CodeKey's, +// and the issuer keeps one issuer's tokens apart from another's when +// servers with different issuers share the store: one issuer's revoked +// jti no longer refuses another issuer's token with the same jti. The +// length prefix splits the key into issuer and token key one way only, +// whatever either holds. +func AccessTokenKey(issuer, key string) string { + return "access-token:" + strconv.Itoa(len(issuer)) + ":" + issuer + key +} + +// AccessTokenKeys are the keys a server writes, and IsRevoked checks, +// for the access token whose own revocation key is key: AccessTokenKey, +// then key itself, the only form servers before v0.84.0 wrote and that +// a custom RevocationChecker may still look for. Both are written so a +// resource server not yet upgraded, or a checker that only knows the +// raw form, still refuses a token a new server revoked; both are checked +// so a record an older server wrote still refuses the token. The raw +// form will be dropped in a later release. +func AccessTokenKeys(issuer, key string) []string { + return []string{AccessTokenKey(issuer, key), key} +} + // Claim is the access token claim carrying the grant ID — the name the // OAuth Grant Management draft (FAPI working group) uses for the same // concept. diff --git a/internal/grantrevocation/grantrevocation_test.go b/internal/grantrevocation/grantrevocation_test.go index 34462496..e5cd35b7 100644 --- a/internal/grantrevocation/grantrevocation_test.go +++ b/internal/grantrevocation/grantrevocation_test.go @@ -51,3 +51,26 @@ func TestKeysAreNamespacedByIssuer(t *testing.T) { }) } } + +func TestAccessTokenKeysAreNamespacedByIssuer(t *testing.T) { + const a, b = "https://a.example.com", "https://b.example.com" + if got, want := AccessTokenKey(a, "jti-1"), "access-token:21:"+a+"jti-1"; got != want { + t.Errorf("AccessTokenKey = %q, want %q", got, want) + } + if AccessTokenKey(a, "jti-1") == AccessTokenKey(b, "jti-1") { + t.Error("two issuers' tokens of one key share a revocation key") + } + // The length prefix splits issuer and key one way only, whatever + // either holds. + if AccessTokenKey("https://a.example.com/x", "y") == AccessTokenKey("https://a.example.com/", "xy") { + t.Error("two splits of the same text between issuer and key share a revocation key") + } + for _, other := range []string{Key(a, "jti-1"), CodeKey(a, "jti-1"), "jti-1"} { + if AccessTokenKey(a, "jti-1") == other { + t.Errorf("AccessTokenKey equals %q", other) + } + } + if got := AccessTokenKeys(a, "jti-1"); len(got) != 2 || got[0] != AccessTokenKey(a, "jti-1") || got[1] != "jti-1" { + t.Errorf("AccessTokenKeys = %q, want [the namespaced key, the raw key]", got) + } +} diff --git a/resource/accesstoken.go b/resource/accesstoken.go index 62dda598..f9499fd9 100644 --- a/resource/accesstoken.go +++ b/resource/accesstoken.go @@ -73,7 +73,8 @@ type ResolvedAccessToken struct { // Key is this token's revocation-lookup identifier — a JWT's jti // claim for JWTAccessTokens, an opaque token's own hash for // OpaqueAccessTokens — passed to Dependencies.Revocation.IsRevoked - // exactly as returned; its shape is an implementation detail + // exactly as returned, and also namespaced by Issuer when Issuer is + // set (see RevocationChecker); its shape is an implementation detail // specific to each AccessTokenResolver. Required: Verify answers a // resolved token with no Key as 500 server_error, since revocation // couldn't apply to it. diff --git a/resource/revocation.go b/resource/revocation.go index cb22726d..5518a067 100644 --- a/resource/revocation.go +++ b/resource/revocation.go @@ -19,14 +19,28 @@ import ( type RevocationChecker interface { // IsRevoked reports whether key has been revoked. Verify asks about // two kinds of key, which must both be answered from what the - // server recorded: the token's own key (ResolvedAccessToken.Key — - // a JWT's jti claim for JWTAccessTokens, an opaque token's own hash - // for OpaqueAccessTokens), and, for a token carrying a grant_id + // server recorded: the token's own key, and, for a token carrying a grant_id // claim, the key server.Server.RevokeGrant records that grant under, // and for one carrying a code_grant_id claim, the key the server // records when the authorization code the token's grant came from // is reused. Run storage.TestRevocationStoreContract against an - // implementation. An implementation that is also a + // implementation. + // + // The token's own key comes in two forms, and Verify asks about + // both. ResolvedAccessToken.Key is the raw form: a JWT's jti claim + // for JWTAccessTokens, an opaque token's own hash (hex SHA-256) for + // OpaqueAccessTokens. A server since v0.84.0 also records it + // namespaced by its issuer, as "access-token:", the length of the + // issuer in bytes, ":", the issuer, then the raw key (for issuer + // "https://as.example" and jti "j1", + // "access-token:18:https://as.example" followed by "j1"), so a jti + // one issuer revoked doesn't refuse another issuer's token sharing + // the store. Verify asks about the namespaced form first, when the + // resolver reports the token's Issuer, then the raw one. The server + // writes both for now, so a checker that only knows the raw form + // keeps working; the raw form will be dropped in a later release, + // so a checker that derives or filters keys itself should accept + // the namespaced one too. An implementation that is also a // storage.RevocationBatchChecker is asked about all of a token's // keys in one IsAnyRevoked call instead. IsRevoked(ctx context.Context, key string) (bool, error) diff --git a/resource/revocation_batch_test.go b/resource/revocation_batch_test.go index a226938b..5902e445 100644 --- a/resource/revocation_batch_test.go +++ b/resource/revocation_batch_test.go @@ -75,13 +75,14 @@ type batchRevocationCase struct { // batchRevocationClaims names, in the order Verify asks about them. var ( batchRevocationClaims = map[string]json.RawMessage{"grant_id": json.RawMessage(`"g-1"`), "code_grant_id": json.RawMessage(`"cg-1"`)} - batchRevocationKeys = []string{"token-1", "grant:g-1@" + testIssuer, "grant:g-1", "code-grant:cg-1@" + testIssuer, "code-grant:cg-1"} + batchRevocationKeys = []string{"access-token:22:" + testIssuer + "token-1", "token-1", "grant:g-1@" + testIssuer, "grant:g-1", "code-grant:cg-1@" + testIssuer, "code-grant:cg-1"} ) // TestVerifyChecksRevocationInOneBatch: with a // storage.RevocationBatchChecker, a token carrying grant_id and -// code_grant_id is checked in one IsAnyRevoked call covering its own key -// and every grant key, current and pre-v0.61.0; anything but "none +// code_grant_id is checked in one IsAnyRevoked call covering its own +// keys, namespaced by issuer and raw, and every grant key, current and +// pre-v0.61.0; anything but "none // revoked" falls back to the IsRevoked calls, so each outcome keeps the // response it has without a batch checker, and a batch answer of // revoked is never overturned. diff --git a/resource/token_revocation_keys_test.go b/resource/token_revocation_keys_test.go new file mode 100644 index 00000000..87c3ffd6 --- /dev/null +++ b/resource/token_revocation_keys_test.go @@ -0,0 +1,86 @@ +package resource_test + +import ( + "context" + "net/url" + "strconv" + "testing" + "time" + + "github.com/idfoundry/fapigo/internal/mtls" + "github.com/idfoundry/fapigo/resource" +) + +// singleRevocationChecker is a RevocationChecker without IsAnyRevoked, +// as a custom checker may be. +type singleRevocationChecker struct{ revoked map[string]bool } + +func (c singleRevocationChecker) IsRevoked(_ context.Context, key string) (bool, error) { + return c.revoked[key], nil +} + +// namespacedTokenKey is the key a server of issuer revokes the access +// token whose own key is key under, besides key itself. +func namespacedTokenKey(issuer, key string) string { + return "access-token:" + strconv.Itoa(len(issuer)) + ":" + issuer + key +} + +// TestVerifyChecksTheTokenRevocationKeys covers a token's own +// revocation keys: one its issuer revoked under the namespaced key, as +// a server since v0.84.0 writes it, or under the raw key alone, as an +// older server wrote it, refuses the token; another issuer's +// namespaced revocation of the same key doesn't. A resolver reporting +// no issuer is checked under the raw key alone. Each holds for a +// checker with and without IsAnyRevoked. +func TestVerifyChecksTheTokenRevocationKeys(t *testing.T) { + for name, tc := range map[string]struct { + revoked string + noIssuer bool + refused bool + }{ + "namespaced": {revoked: namespacedTokenKey(testIssuer, "token-1"), refused: true}, + "raw, from an older server": {revoked: "token-1", refused: true}, + "another issuer's namespaced": {revoked: namespacedTokenKey("https://other.example.com", "token-1")}, + "another token's namespaced": {revoked: namespacedTokenKey(testIssuer, "token-2")}, + "no issuer, raw": {revoked: "token-1", noIssuer: true, refused: true}, + "no issuer, the issuer-namespaced": {revoked: namespacedTokenKey(testIssuer, "token-1"), noIssuer: true}, + } { + revoked := map[string]bool{tc.revoked: true} + for kind, checker := range map[string]resource.RevocationChecker{ + "single": singleRevocationChecker{revoked: revoked}, + "batch": &batchRevocationChecker{revoked: revoked}, + } { + t.Run(name+"/"+kind, func(t *testing.T) { + err := verifyWithRevocation(t, checker, tc.noIssuer) + if !tc.refused { + requireVerifyOutcome(t, err, "", "") + return + } + requireVerifyOutcome(t, err, resource.ErrorInvalidToken, "access token has been revoked") + }) + } + } +} + +// verifyWithRevocation verifies an mTLS-bound token with key "token-1" +// and no grant claims against checker. +func verifyWithRevocation(t *testing.T, checker resource.RevocationChecker, noIssuer bool) error { + t.Helper() + now := time.Now() + cert := selfSignedTestClientCert(t, "client-1") + target, err := url.Parse("https://rs.example.com/accounts") + if err != nil { + t.Fatal(err) + } + v, err := resource.NewVerifier(validConfig(t), resource.Dependencies{ + AccessTokens: grantClaimResolver{thumbprint: mtls.Thumbprint(cert), now: now, noIssuer: noIssuer}, + Replay: &fakeReplayStore{}, + Revocation: checker, + Clock: fixedClock{now: now}, + }) + if err != nil { + t.Fatalf("NewVerifier: %v", err) + } + _, err = v.Verify(context.Background(), resource.VerifyRequest{Method: "GET", URL: target, Authorization: "Bearer token", PeerCertificate: cert}) + return err +} diff --git a/resource/verify.go b/resource/verify.go index fc95ab80..6c7727d3 100644 --- a/resource/verify.go +++ b/resource/verify.go @@ -496,16 +496,30 @@ func (v *Verifier) checkNotRevoked(ctx context.Context, resolved ResolvedAccessT // checkEachNotRevoked is checkNotRevoked one IsRevoked call at a time: // the token's own key, then each of its grants' keys. func (v *Verifier) checkEachNotRevoked(ctx context.Context, resolved ResolvedAccessToken) *Error { - revoked, err := v.deps.Revocation.IsRevoked(ctx, resolved.Key) - if err != nil { - return newError(ErrorServerError, 500, "failed to check token revocation", err) - } - if revoked { - return newError(ErrorInvalidToken, 401, "access token has been revoked", nil) + for _, key := range tokenRevocationKeys(resolved) { + revoked, err := v.deps.Revocation.IsRevoked(ctx, key) + if err != nil { + return newError(ErrorServerError, 500, "failed to check token revocation", err) + } + if revoked { + return newError(ErrorInvalidToken, 401, "access token has been revoked", nil) + } } return v.checkGrantNotRevoked(ctx, resolved.Issuer, resolved.Claims) } +// tokenRevocationKeys are the keys resolved itself may be revoked +// under: its Key namespaced by its Issuer, as a server since v0.84.0 +// writes it, and Key itself, as older servers wrote it +// (grantrevocation.AccessTokenKeys). A resolver reporting no Issuer +// gets the raw Key alone: there is no issuer to namespace it by. +func tokenRevocationKeys(resolved ResolvedAccessToken) []string { + if resolved.Issuer == "" { + return []string{resolved.Key} + } + return grantrevocation.AccessTokenKeys(resolved.Issuer, resolved.Key) +} + // resolveCredential verifies whichever sender-constraining credential // scheme (the Authorization header's own DPoP/Bearer distinction — // RFC 8705 §3 presents an mTLS-bound token as RFC 6750 does) demands, and @@ -639,7 +653,7 @@ func (v *Verifier) checkAnyRevoked(ctx context.Context, resolved ResolvedAccessT if !ok { return false, false } - revoked, err := batch.IsAnyRevoked(ctx, append([]string{resolved.Key}, keys...)) + revoked, err := batch.IsAnyRevoked(ctx, append(tokenRevocationKeys(resolved), keys...)) if err != nil { return false, false } diff --git a/server/backchannel_auth_req_id_test.go b/server/backchannel_auth_req_id_test.go index 462befe4..a2248f3b 100644 --- a/server/backchannel_auth_req_id_test.go +++ b/server/backchannel_auth_req_id_test.go @@ -24,13 +24,16 @@ const unknownAuthReqID = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" // boundDigestPreimage is the auth_req_id an attacker holding the // client's assertion key, but not the client instance or DPoP key, // crafts for the request authReqID names, bound to instanceKey and -// dpopJKT: the string the request's digest is taken over, whose own -// unbound digest is that digest. +// dpopJKT: the string the request's digest is taken over, presented as +// an unbound auth_req_id. The length-prefixed +// binding keeps its digest from being the request's; the token endpoint +// refuses it before any poll in any case, as not of the form this +// server issues. func boundDigestPreimage(t *testing.T, authReqID, instanceKey, dpopJKT string) string { t.Helper() - preimage, ok := server.BoundAuthReqIDPreimage(authReqID, instanceKey, dpopJKT) - if !ok { - t.Fatal("the bound digest's preimage has another unbound digest, so there's nothing left to refuse") + preimage, collides := server.BoundAuthReqIDPreimage(testIssuer, authReqID, instanceKey, dpopJKT) + if collides { + t.Fatal("the bound digest's preimage has the bound request's digest as an unbound auth_req_id") } return preimage } @@ -165,11 +168,12 @@ func TestExchangeBackchannelAuthenticationRefusesMalformedAuthReqID(t *testing.T // TestCraftedAuthReqIDLeavesTheBoundApproval: the client's own // assertion key, without the client instance or DPoP key an approved // request is bound to, can't spend its approval by presenting the -// string the request's digest is taken over, whose unbound digest is -// the same: it's refused as an unknown auth_req_id, before any poll, so +// string the request's digest is taken over: it's refused as an +// unknown auth_req_id, before any poll (and its unbound digest isn't +// the request's in any case), so // the instance and key the request is bound to still redeem it. That // holds for a dpop_jkt, for the key of a DPoP proof sent with the -// request, with the NUL the string starts with sent as %00 over HTTP, +// request, with the NUL the string's prefix holds sent as %00 over HTTP, // and for a client instance. func TestCraftedAuthReqIDLeavesTheBoundApproval(t *testing.T) { for name, tc := range map[string]struct { diff --git a/server/backchannel_authentication.go b/server/backchannel_authentication.go index be353308..a2f555d2 100644 --- a/server/backchannel_authentication.go +++ b/server/backchannel_authentication.go @@ -256,7 +256,7 @@ func (s *Server) BeginBackchannelAuthentication(ctx context.Context, req BeginBa return s.backchannelBeginFail(ctx, client.ID(), newError(ErrorServerError, 500, "failed to encode backchannel authentication request", err)), nil } if storeErr := s.storeBackchannelRequest(ctx, handleRaw, resolvedSubject, storage.NewBackchannelAuthentication{ - AuthReqIDHash: backchannelAuthReqIDHash(authReqIDRaw, authn.InstanceKey, dpopJKT), + AuthReqIDHash: backchannelAuthReqIDHash(s.cfg.Issuer.String(), authReqIDRaw, authn.InstanceKey, dpopJKT), AuthReqID: authReqIDForNotification, HandleHash: sha256.Sum256([]byte(handleRaw)), ClientID: client.ID(), diff --git a/server/backchannel_token.go b/server/backchannel_token.go index f9e7612e..7ef9f234 100644 --- a/server/backchannel_token.go +++ b/server/backchannel_token.go @@ -5,7 +5,6 @@ import ( "crypto/sha256" "crypto/x509" "errors" - "strconv" "strings" "time" @@ -190,11 +189,7 @@ func (s *Server) backchannelTokenParameters(client storage.RegisteredClient, par return "", requestedAuthorizationDetails{}, newError(ErrorInvalidRequest, 400, "auth_req_id is required", nil) } // A value of another form names no request, so it's answered as an - // unknown one is, without a poll. A poll could find a request all - // the same: the string a bound request's digest is taken over - // (backchannelAuthReqIDHash) has that digest as its own unbound one, - // and would spend the approval without the client instance or DPoP - // key the request is bound to. + // unknown one is, without a poll. if !isWellFormedAuthReqID(authReqID) { return "", requestedAuthorizationDetails{}, newError(ErrorInvalidGrant, 400, authReqIDUnknownDescription, nil) } @@ -205,46 +200,39 @@ func (s *Server) backchannelTokenParameters(client storage.RegisteredClient, par return authReqID, details, nil } -// backchannelAuthReqIDHashPrefix starts the string the digest of an -// auth_req_id bound to a client instance or a DPoP key is taken over. -// No auth_req_id this server issues starts with it (it has a space and -// a NUL), so it separates that digest from the plain SHA-256 of every -// unbound one, though not from that of an arbitrary string: see -// backchannelAuthReqIDHash. -const backchannelAuthReqIDHashPrefix = "fapigo bound auth_req_id\x00" +// backchannelAuthReqIDHashPrefix starts the string an auth_req_id's +// digest is taken over (backchannelAuthReqIDHash), separating it from +// an authorization code's (authorizationCodeHash) and a refresh +// token's (refreshTokenHash) of the same value. +const backchannelAuthReqIDHashPrefix = "fapigo auth_req_id v2\x00" // backchannelAuthReqIDHash is the digest a CIBA request is stored and // polled under (storage.NewBackchannelAuthentication.AuthReqIDHash): -// the plain SHA-256 of authReqID for a request bound to neither a -// client instance nor a DPoP key, as before such bindings existed, and -// otherwise the SHA-256 of authReqID bound to instanceKey (the -// thumbprint of the Client Instance Key of a client authenticated by -// Client Attestation) and dpopJKT (the thumbprint of the DPoP key the -// request is bound to: its dpop_jkt, or the key of the DPoP proof sent -// with it). +// the SHA-256 of backchannelAuthReqIDHashPrefix, then issuer, +// instanceKey (the thumbprint of the Client Instance Key of a client +// authenticated by Client Attestation, or empty) and dpopJKT (the +// thumbprint of the DPoP key the request is bound to: its dpop_jkt, or +// the key of the DPoP proof sent with it; or empty), each +// length-prefixed, then authReqID. The length prefixes keep any two +// different bindings of one auth_req_id apart. // // The store spends an approval in the poll that observes it, before the -// server can compare the poll's client instance or DPoP key with the -// request's, and every installation of a wallet app shares one -// client_id. Keyed by both, an auth_req_id presented by another -// instance, or with another DPoP key, is simply unknown to the store, -// as authorizationCodeHash makes another instance's code: the poll -// neither spends the approval nor sees the request, so the poll from -// the instance and key it was issued to still succeeds. Each part is -// length-prefixed, so no two different bindings of one auth_req_id -// share a digest. The plain digest of an arbitrary string can equal a -// bound one, though: the string a bound digest is taken over, presented -// as an unbound auth_req_id, has that same digest, and would find the -// bound request. So the token endpoint polls only for an auth_req_id of -// the form this server issues (isWellFormedAuthReqID), which that -// string, starting with backchannelAuthReqIDHashPrefix, never has. -func backchannelAuthReqIDHash(authReqID, instanceKey, dpopJKT string) [32]byte { - if instanceKey == "" && dpopJKT == "" { - return sha256.Sum256([]byte(authReqID)) - } - return sha256.Sum256([]byte(backchannelAuthReqIDHashPrefix + - strconv.Itoa(len(instanceKey)) + ":" + instanceKey + - strconv.Itoa(len(dpopJKT)) + ":" + dpopJKT + authReqID)) +// server can compare the poll's issuer, client instance or DPoP key +// with the request's, and every installation of a wallet app shares +// one client_id. Keyed by all three, an auth_req_id presented to a +// server of another issuer sharing the store, by another instance, or +// with another DPoP key, is simply unknown to the store, as +// authorizationCodeHash makes another issuer's or instance's code: the +// poll neither spends the approval nor sees the request, so the poll +// from the server, instance and key it was issued to still succeeds. +// +// A server before v0.84.0 stored an unbound request under the plain +// SHA-256 of its auth_req_id and a bound one under a digest without the +// issuer; this digest is neither, so those requests are unknown after +// the upgrade. +func backchannelAuthReqIDHash(issuer, authReqID, instanceKey, dpopJKT string) [32]byte { + return sha256.Sum256([]byte(backchannelAuthReqIDHashPrefix + lengthPrefixed(issuer) + + lengthPrefixed(instanceKey) + lengthPrefixed(dpopJKT) + authReqID)) } // pollBackchannelAuthentication polls the CIBA request authReqID names @@ -257,10 +245,6 @@ func backchannelAuthReqIDHash(authReqID, instanceKey, dpopJKT string) [32]byte { // polled as if it were the only one. A store that couldn't answer the // first isn't asked the second: had it recovered, the second would miss // a request stored under the DPoP key, and answer it as unknown. -// Without an instanceKey, the lookup under no DPoP key is the plain -// SHA-256 of authReqID, which the string a bound digest is taken over -// would share with that bound request; backchannelTokenParameters has -// refused every such string, as not of the form this server issues. func (s *Server) pollBackchannelAuthentication(ctx context.Context, client storage.RegisteredClient, authReqID, instanceKey, thumbprint string, now time.Time) (storage.PolledBackchannelAuthentication, [32]byte, error) { poll := func(hash [32]byte) (storage.PolledBackchannelAuthentication, error) { return s.deps.Backchannel.PollBackchannelAuthentication(ctx, storage.PollBackchannelAuthentication{ @@ -270,13 +254,13 @@ func (s *Server) pollBackchannelAuthentication(ctx context.Context, client stora }) } if client.SenderConstrain() != storage.SenderConstrainMTLS { - hash := backchannelAuthReqIDHash(authReqID, instanceKey, thumbprint) + hash := backchannelAuthReqIDHash(s.cfg.Issuer.String(), authReqID, instanceKey, thumbprint) polled, err := poll(hash) if err == nil || isBackchannelPollOutcome(err) || storeOutage(ctx, err) { return polled, hash, err } } - hash := backchannelAuthReqIDHash(authReqID, instanceKey, "") + hash := backchannelAuthReqIDHash(s.cfg.Issuer.String(), authReqID, instanceKey, "") polled, err := poll(hash) return polled, hash, err } diff --git a/server/backchannel_token_internal_test.go b/server/backchannel_token_internal_test.go index 46221115..1b13756d 100644 --- a/server/backchannel_token_internal_test.go +++ b/server/backchannel_token_internal_test.go @@ -53,22 +53,28 @@ func TestBackchannelStatusError(t *testing.T) { } // TestBackchannelAuthReqIDHash covers the digest a CIBA request is -// stored under: the plain SHA-256 of an unbound auth_req_id, as before -// bindings existed, and one per client instance and dpop_jkt otherwise, -// so a poll from another instance or with another key finds nothing. +// stored under: one per issuer, client instance and dpop_jkt, so a +// poll to another issuer's server sharing the store, from another +// instance or with another key finds nothing, and never the plain +// SHA-256 a server before v0.84.0 stored an unbound request under. func TestBackchannelAuthReqIDHash(t *testing.T) { const id = "auth-req-id" - if backchannelAuthReqIDHash(id, "", "") != sha256.Sum256([]byte(id)) { - t.Error("an unbound auth_req_id's digest isn't its plain SHA-256") + if backchannelAuthReqIDHash("https://as.example", id, "", "") == sha256.Sum256([]byte(id)) { + t.Error("an unbound auth_req_id's digest is its plain SHA-256") } seen := map[[32]byte]string{} - for _, b := range [][2]string{{"", ""}, {"inst-a", ""}, {"inst-b", ""}, {"", "jkt-a"}, {"inst-a", "jkt-a"}, {"inst-a", "jkt-b"}, {"inst-aj", "kt-a"}, {"", "inst-a"}} { - h := backchannelAuthReqIDHash(id, b[0], b[1]) + for _, b := range [][3]string{ + {"https://as.example", "", ""}, {"https://other.example", "", ""}, {"https://as.example", "inst-a", ""}, + {"https://as.example", "inst-b", ""}, {"https://as.example", "", "jkt-a"}, {"https://as.example", "inst-a", "jkt-a"}, + {"https://as.example", "inst-a", "jkt-b"}, {"https://as.example", "inst-aj", "kt-a"}, {"https://as.example", "", "inst-a"}, + {"https://as.exampleinst-a", "", ""}, {"", "https://as.example", ""}, + } { + h := backchannelAuthReqIDHash(b[0], id, b[1], b[2]) if prev, ok := seen[h]; ok { t.Errorf("binding %q shares a digest with %q", b, prev) } - seen[h] = b[0] + "|" + b[1] - if h != backchannelAuthReqIDHash(id, b[0], b[1]) { + seen[h] = b[0] + "|" + b[1] + "|" + b[2] + if h != backchannelAuthReqIDHash(b[0], id, b[1], b[2]) { t.Errorf("binding %q isn't deterministic", b) } } @@ -76,8 +82,8 @@ func TestBackchannelAuthReqIDHash(t *testing.T) { // TestIsWellFormedAuthReqID: only the form generateAuthReqID gives an // auth_req_id is well-formed. The string a bound request's digest is -// taken over, whose own unbound digest is that same digest, never is, -// whatever the binding. +// taken over never is, whatever the binding, and +// its digest as an unbound auth_req_id isn't the bound request's. func TestIsWellFormedAuthReqID(t *testing.T) { id, err := generateAuthReqID(nil) if err != nil { @@ -108,9 +114,9 @@ func TestIsWellFormedAuthReqID(t *testing.T) { "client instance": {thumbprint, ""}, "both": {thumbprint, thumbprint}, } { - preimage, collides := BoundAuthReqIDPreimage(id, binding[0], binding[1]) - if !collides { - t.Fatalf("%s: the bound digest's preimage has another unbound digest", name) + preimage, collides := BoundAuthReqIDPreimage("https://as.example", id, binding[0], binding[1]) + if collides { + t.Errorf("%s: the bound digest's preimage has the bound request's digest unbound", name) } if isWellFormedAuthReqID(preimage) { t.Errorf("%s: the bound digest's preimage %q is well-formed", name, preimage) diff --git a/server/code_instance_internal_test.go b/server/code_instance_internal_test.go index 228a223a..7d648f5c 100644 --- a/server/code_instance_internal_test.go +++ b/server/code_instance_internal_test.go @@ -9,24 +9,30 @@ import ( ) // TestAuthorizationCodeHash covers the digest a code is stored under: -// never the plain SHA-256 a refresh token with the same value is stored -// under, and the SHA-256 of the prefix, each part of the binding -// length-prefixed, and the code. +// never a refresh token's or an auth_req_id's digest of the same value, +// never the plain SHA-256 a server before v0.84.0 stored a refresh +// token under, and the SHA-256 of the prefix, the issuer and each part +// of the binding length-prefixed, and the code. func TestAuthorizationCodeHash(t *testing.T) { - const code = "code-value" + const code, issuer = "code-value", "https://as.example" bound := codeBinding{codeChallenge: "challenge", redirectURI: "https://rp.example/cb"} for _, binding := range []codeBinding{{}, bound, {instanceKey: "instance-a", codeChallenge: "challenge", dpopJKT: "jkt"}} { - if authorizationCodeHash(code, binding) == sha256.Sum256([]byte(code)) { - t.Errorf("authorizationCodeHash(%+v) is a refresh token's digest of the same value", binding) + got := authorizationCodeHash(issuer, code, binding) + if got == sha256.Sum256([]byte(code)) || got == refreshTokenHash(issuer, code) || + got == backchannelAuthReqIDHash(issuer, code, binding.instanceKey, binding.dpopJKT) { + t.Errorf("authorizationCodeHash(%+v) is another kind of token's digest of the same value", binding) } } - got := authorizationCodeHash(code, bound) - if got != sha256.Sum256([]byte(codeHashPrefix+"0:"+"9:challenge"+"21:https://rp.example/cb"+"0:"+code)) { - t.Error("authorizationCodeHash isn't the SHA-256 of the prefix, the length-prefixed binding and the code") + got := authorizationCodeHash(issuer, code, bound) + if got != sha256.Sum256([]byte(codeHashPrefix+"18:https://as.example"+"0:"+"9:challenge"+"21:https://rp.example/cb"+"0:"+code)) { + t.Error("authorizationCodeHash isn't the SHA-256 of the prefix, the length-prefixed issuer and binding, and the code") } - if authorizationCodeHash(code, bound) != got { + if authorizationCodeHash(issuer, code, bound) != got { t.Error("authorizationCodeHash isn't deterministic") } + if authorizationCodeHash("https://other.example", code, bound) == got { + t.Error("two issuers' codes of one value and binding share a digest") + } } // TestAuthorizationCodeHashSeparatesBindings covers one digest per @@ -40,7 +46,7 @@ func TestAuthorizationCodeHashSeparatesBindings(t *testing.T) { code string binding codeBinding } - const code = "code-value" + const code, issuer = "code-value", "https://as.example" issued := presented{code, codeBinding{instanceKey: "instance-a", codeChallenge: "challenge", redirectURI: "https://rp.example/cb", dpopJKT: "jkt"}} for name, other := range map[string]presented{ "another instance": {code, codeBinding{instanceKey: "instance-b", codeChallenge: "challenge", redirectURI: "https://rp.example/cb", dpopJKT: "jkt"}}, @@ -54,7 +60,7 @@ func TestAuthorizationCodeHashSeparatesBindings(t *testing.T) { "redirect URI into DPoP key": {code, codeBinding{instanceKey: "instance-a", codeChallenge: "challenge", redirectURI: "https://rp.example/c", dpopJKT: "bjkt"}}, "DPoP key into code": {"t" + code, codeBinding{instanceKey: "instance-a", codeChallenge: "challenge", redirectURI: "https://rp.example/cb", dpopJKT: "jk"}}, } { - if authorizationCodeHash(other.code, other.binding) == authorizationCodeHash(issued.code, issued.binding) { + if authorizationCodeHash(issuer, other.code, other.binding) == authorizationCodeHash(issuer, issued.code, issued.binding) { t.Errorf("authorizationCodeHash doesn't separate %s", name) } } diff --git a/server/code_reuse_audit_test.go b/server/code_reuse_audit_test.go index 3ca3820b..91e7c9c7 100644 --- a/server/code_reuse_audit_test.go +++ b/server/code_reuse_audit_test.go @@ -2,7 +2,6 @@ package server_test import ( "context" - "crypto/sha256" "slices" "strings" "testing" @@ -192,7 +191,7 @@ func newReuseRevocationStores(t *testing.T) reuseRevocationStores { // redeemable reports whether the GrantStore still redeems refreshToken. func (s reuseRevocationStores) redeemable(refreshToken string) bool { - _, err := s.grants.RedeemRefreshToken(context.Background(), storage.RefreshTokenRedemption{TokenHash: sha256.Sum256([]byte(refreshToken))}) + _, err := s.grants.RedeemRefreshToken(context.Background(), storage.RefreshTokenRedemption{TokenHash: server.RefreshTokenHash(testIssuer, refreshToken)}) return err == nil } diff --git a/server/code_reuse_grant_test.go b/server/code_reuse_grant_test.go index 4124b254..cc8b4c2f 100644 --- a/server/code_reuse_grant_test.go +++ b/server/code_reuse_grant_test.go @@ -126,7 +126,7 @@ func TestRefreshRefusesARevokedCodeGrant(t *testing.T) { t.Fatalf("RefreshAccessToken before revocation: %v", err) } // The digest the server stores a code under (authorizationCodeHash). - codeHash := server.AuthorizationCodeHash(code, testCodeChallenge, testRedirectURI) + codeHash := server.AuthorizationCodeHash(testIssuer, code, testCodeChallenge, testRedirectURI) if err := h.revocation.Revoke(context.Background(), grantrevocation.CodeKey(testIssuer, grantrevocation.CodeGrantID(codeHash)), h.now.Add(time.Hour)); err != nil { t.Fatalf("Revoke: %v", err) } diff --git a/server/complete_authorization.go b/server/complete_authorization.go index 31d14440..5e9ddd33 100644 --- a/server/complete_authorization.go +++ b/server/complete_authorization.go @@ -240,7 +240,7 @@ func (s *Server) completeAuthorize(ctx context.Context, clientID fapi.ClientID, // Stored under a digest of everything the token request must present // with the code: one presenting anything else finds no code, and // neither spends it nor revokes what it issued. - codeHash := authorizationCodeHash(code, codeBinding{ + codeHash := authorizationCodeHash(s.cfg.Issuer.String(), code, codeBinding{ instanceKey: request.ClientInstanceKey, codeChallenge: codeChallenge, redirectURI: redirectURI, dpopJKT: dpopJKT, }) if err := s.deps.Grants.CreateAuthorizationCode(ctx, storage.NewAuthorizationCode{ diff --git a/server/export_backchannel_test.go b/server/export_backchannel_test.go index 1b66556e..3a640454 100644 --- a/server/export_backchannel_test.go +++ b/server/export_backchannel_test.go @@ -1,15 +1,12 @@ package server -import "strconv" - // BoundAuthReqIDPreimage is the string backchannelAuthReqIDHash takes -// the digest of for authReqID bound to instanceKey and dpopJKT, for a -// test to present as an auth_req_id, as an attacker would. ok reports -// that the string's own unbound digest is that bound one, which is what -// makes it worth presenting. -func BoundAuthReqIDPreimage(authReqID, instanceKey, dpopJKT string) (preimage string, ok bool) { - preimage = backchannelAuthReqIDHashPrefix + - strconv.Itoa(len(instanceKey)) + ":" + instanceKey + - strconv.Itoa(len(dpopJKT)) + ":" + dpopJKT + authReqID - return preimage, backchannelAuthReqIDHash(preimage, "", "") == backchannelAuthReqIDHash(authReqID, instanceKey, dpopJKT) +// the digest of for authReqID bound, at a server of issuer, to +// instanceKey and dpopJKT: what a test presents as an auth_req_id, as +// an attacker would, hoping its digest as an unbound auth_req_id is the +// bound request's. collides reports whether it is; the length-prefixed +// binding keeps it from being. +func BoundAuthReqIDPreimage(issuer, authReqID, instanceKey, dpopJKT string) (preimage string, collides bool) { + preimage = backchannelAuthReqIDHashPrefix + lengthPrefixed(issuer) + lengthPrefixed(instanceKey) + lengthPrefixed(dpopJKT) + authReqID + return preimage, backchannelAuthReqIDHash(issuer, preimage, "", "") == backchannelAuthReqIDHash(issuer, authReqID, instanceKey, dpopJKT) } diff --git a/server/export_test.go b/server/export_test.go index 73d32f60..c4dd6403 100644 --- a/server/export_test.go +++ b/server/export_test.go @@ -8,10 +8,16 @@ func GrantEntryKey(refreshTokenHash [32]byte) string { return grantEntryKey(refr // package, so a test can hold FormRequestFromHTTP to the bound itself. const MaxFormParameters = maxFormParameters +// RefreshTokenHash exposes refreshTokenHash to the server_test package: +// the digest a server of issuer stores refreshToken under. +func RefreshTokenHash(issuer, refreshToken string) [32]byte { + return refreshTokenHash(issuer, refreshToken) +} + // AuthorizationCodeHash exposes authorizationCodeHash to the // server_test package for a code issued to a client that didn't // authenticate by Client Attestation, bound to no DPoP key: the digest // the server stores it under, from which a test names its grant. -func AuthorizationCodeHash(code, codeChallenge, redirectURI string) [32]byte { - return authorizationCodeHash(code, codeBinding{codeChallenge: codeChallenge, redirectURI: redirectURI}) +func AuthorizationCodeHash(issuer, code, codeChallenge, redirectURI string) [32]byte { + return authorizationCodeHash(issuer, code, codeBinding{codeChallenge: codeChallenge, redirectURI: redirectURI}) } diff --git a/server/grant_registry_sweep_test.go b/server/grant_registry_sweep_test.go index 1147eece..62c5cdd3 100644 --- a/server/grant_registry_sweep_test.go +++ b/server/grant_registry_sweep_test.go @@ -65,7 +65,7 @@ func newRecordedLifetimeChanges(t *testing.T, grants storage.GrantStore) (*lifet func (c *lifetimeChanges) issueGrant(grantID string, refreshLifetime time.Duration) (refreshToken, id string) { c.t.Helper() refreshToken = exchangeWithGrantID(c.t, c.at(0, refreshLifetime), grantID) - return refreshToken, server.GrantEntryKey(sha256.Sum256([]byte(refreshToken))) + return refreshToken, server.GrantEntryKey(server.RefreshTokenHash(testIssuer, refreshToken)) } // revokeGrantAt revokes grantID a minute in, under a 1h refresh token @@ -243,7 +243,7 @@ func testSweepBesideAListedGrant(t *testing.T) { revoked, _ := c.issueGrant("grant-1", longRefreshLifetime) listed, listedID := c.issueGrant("grant-2", longRefreshLifetime) h := c.revokeGrantAt("grant-1") - grants.downTokens = map[[32]byte]bool{sha256.Sum256([]byte(revoked)): true} + grants.downTokens = map[[32]byte]bool{server.RefreshTokenHash(testIssuer, revoked): true} if err := h.server.RevokeListedGrant(context.Background(), mustSubjectID(t, "user-1"), listedID); err != nil { t.Fatalf("RevokeListedGrant(a listed grant), a revoked grant's refresh token failing to revoke = %v, want nil", err) } diff --git a/server/issued_tokens_recorder_test.go b/server/issued_tokens_recorder_test.go index 3862967e..7cbb7f82 100644 --- a/server/issued_tokens_recorder_test.go +++ b/server/issued_tokens_recorder_test.go @@ -3,7 +3,6 @@ package server_test import ( "context" "crypto/ecdsa" - "crypto/sha256" "errors" "slices" "sync" @@ -170,9 +169,9 @@ func TestExchangeAuthorizationCodeRecordsBothTokensInOneWrite(t *testing.T) { func requireRecordedTokens(t *testing.T, h harness, store *recordingGrantStore, code string, result server.TokenResult) { t.Helper() got := store.recorded - wantCodeHash := server.AuthorizationCodeHash(code, testCodeChallenge, testRedirectURI) + wantCodeHash := server.AuthorizationCodeHash(testIssuer, code, testCodeChallenge, testRedirectURI) if got.codeHash != wantCodeHash || got.accessKey != accessTokenJTI(t, h, result.AccessToken.Reveal()) || - got.refreshHash != sha256.Sum256([]byte(result.RefreshToken.Reveal())) { + got.refreshHash != server.RefreshTokenHash(testIssuer, result.RefreshToken.Reveal()) { t.Fatalf("RecordIssuedTokens recorded code %x, access key %q, refresh hash %x; want the exchange's code and tokens", got.codeHash, got.accessKey, got.refreshHash) } if !got.accessExpiresAt.Equal(h.now.Add(h.cfg.Limits.AccessTokenLifetime)) || !got.refreshExpireAt.Equal(h.now.Add(h.cfg.Limits.RefreshTokenLifetime)) { @@ -198,7 +197,7 @@ func TestCodeReuseRevokesTokensRecordedInOneWrite(t *testing.T) { if jti := accessTokenJTI(t, h, first.AccessToken.Reveal()); !slices.Contains(h.revocation.all(), jti) { t.Fatalf("Revoke calls = %v, want the first access token's jti %q among them", h.revocation.all(), jti) } - refreshHash := sha256.Sum256([]byte(first.RefreshToken.Reveal())) + refreshHash := server.RefreshTokenHash(testIssuer, first.RefreshToken.Reveal()) h.grants.mu.Lock() revoked := h.grants.refreshRevoked[refreshHash] h.grants.mu.Unlock() diff --git a/server/records_issuer_digest_test.go b/server/records_issuer_digest_test.go new file mode 100644 index 00000000..da7af733 --- /dev/null +++ b/server/records_issuer_digest_test.go @@ -0,0 +1,138 @@ +package server_test + +import ( + "context" + "errors" + "testing" + + "github.com/idfoundry/fapigo/internal/clientassertion" + "github.com/idfoundry/fapigo/server" + "github.com/idfoundry/fapigo/storage" +) + +// foundGrantStore is a GrantStore that counts the codes and refresh +// tokens it found (redeemed, or reported reused) for one server. +type foundGrantStore struct { + storage.GrantStore + codes, refreshTokens int +} + +func (s *foundGrantStore) RedeemAuthorizationCode(ctx context.Context, r storage.AuthorizationCodeRedemption) (storage.RedeemedAuthorizationCode, error) { + redeemed, err := s.GrantStore.RedeemAuthorizationCode(ctx, r) + var reused *storage.AuthorizationCodeAlreadyRedeemedError + if err == nil || errors.As(err, &reused) { + s.codes++ + } + return redeemed, err +} + +func (s *foundGrantStore) RedeemRefreshToken(ctx context.Context, r storage.RefreshTokenRedemption) (storage.RedeemedRefreshToken, error) { + redeemed, err := s.GrantStore.RedeemRefreshToken(ctx, r) + if err == nil { + s.refreshTokens++ + } + return redeemed, err +} + +// otherTenantSeeing is otherTenant whose GrantStore, the same one h +// uses, counts what tenant B finds in it. +func otherTenantSeeing(t *testing.T, h harness) (*server.Server, func() string, *foundGrantStore) { + t.Helper() + found := &foundGrantStore{GrantStore: h.deps.Grants} + h.deps.Grants = found + srv, assertion := otherTenant(t, h) + return srv, assertion, found +} + +// TestAnotherIssuersCodeIsLeftUnspent: a code presented to a server of +// another issuer over the same store isn't found there, so isn't spent: +// the server that issued it still exchanges it. +func TestAnotherIssuersCodeIsLeftUnspent(t *testing.T) { + h := newHarness(t, server.ProfileFAPISecurity, true) + tenantB, assertionB, found := otherTenantSeeing(t, h) + code := completeSuccessfulAuthorization(t, h, []string{"openid", "accounts"}) + _, err := tenantB.ExchangeAuthorizationCode(context.Background(), server.AuthorizationCodeExchangeRequest{ + HTTP: server.FormRequest{Parameters: exchangeFormParams(assertionB(), code, testRedirectURI, testCodeVerifier)}, + DPoPProofs: []string{createDPoPProof(t, generateKey(t), h.now)}, + }) + if code := serverErrorCode(t, err); code != server.ErrorInvalidGrant { + t.Fatalf("tenant B redeeming tenant A's code: error code %q, want %q", code, server.ErrorInvalidGrant) + } + if found.codes != 0 { + t.Fatalf("tenant B's exchange found tenant A's code in the store %d times, want none", found.codes) + } + if _, err := exchangeCode(t, h, code, generateKey(t)); err != nil { + t.Fatalf("tenant A exchanging its own code afterwards: %v, want tokens", err) + } +} + +// TestAnotherIssuersRefreshTokenIsNotFound: a refresh token presented +// to a server of another issuer over the same store isn't found there, +// by a refresh or a revocation, and still works at the server that +// issued it. +func TestAnotherIssuersRefreshTokenIsNotFound(t *testing.T) { + ctx := context.Background() + h := newHarness(t, server.ProfileFAPISecurity, true) + tenantB, assertionB, found := otherTenantSeeing(t, h) + code := completeSuccessfulAuthorization(t, h, []string{"openid", "accounts", "offline_access"}) + tokens, err := exchangeCode(t, h, code, generateKey(t)) + if err != nil || !tokens.HasRefreshToken { + t.Fatalf("ExchangeAuthorizationCode = %v (refresh token %v)", err, tokens.HasRefreshToken) + } + refreshToken := tokens.RefreshToken.Reveal() + _, err = tenantB.RefreshAccessToken(ctx, server.RefreshTokenRequest{ + HTTP: server.FormRequest{Parameters: refreshFormParams(assertionB(), refreshToken, "")}, + DPoPProofs: []string{createDPoPProof(t, generateKey(t), h.now)}, + }) + if code := serverErrorCode(t, err); code != server.ErrorInvalidGrant { + t.Fatalf("tenant B refreshing tenant A's refresh token: error code %q, want %q", code, server.ErrorInvalidGrant) + } + if found.refreshTokens != 0 { + t.Fatalf("tenant B's refresh found tenant A's refresh token in the store %d times, want none", found.refreshTokens) + } + if _, err := h.server.RefreshAccessToken(ctx, server.RefreshTokenRequest{ + HTTP: server.FormRequest{Parameters: refreshFormParams(h.clientAssertion(t), refreshToken, "")}, + DPoPProofs: []string{createDPoPProof(t, generateKey(t), h.now)}, + }); err != nil { + t.Fatalf("tenant A refreshing its own refresh token afterwards: %v", err) + } +} + +// TestAnotherIssuersAuthReqIDIsLeftUnspent: an auth_req_id polled at a +// server of another issuer over the same store isn't found there, so +// neither counts as a poll of the pending request nor spends its +// approval: the server that issued it still answers its own client's +// polls as if tenant B's never happened. +func TestAnotherIssuersAuthReqIDIsLeftUnspent(t *testing.T) { + h, _ := newHarnessWithBackchannel(t) + tenantB, assertionB := otherTenant(t, h) + pollB := func(authReqID server.AuthReqID) error { + _, err := tenantB.ExchangeBackchannelAuthentication(context.Background(), server.BackchannelTokenExchangeRequest{ + HTTP: server.FormRequest{Parameters: []server.FormParameter{ + formParam("client_assertion", assertionB()), + formParam("client_assertion_type", clientassertion.AssertionType), + formParam("grant_type", server.CIBAGrantType), + formParam("auth_req_id", authReqID.String()), + }}, + DPoPProofs: []string{createDPoPProof(t, generateKey(t), h.now)}, + }) + return err + } + + pending := beginBackchannel(t, h, standardBackchannelParams(t)) + if code := serverErrorCode(t, pollB(pending.AuthReqID)); code != server.ErrorInvalidGrant { + t.Fatalf("tenant B polling tenant A's pending auth_req_id: error code %q, want %q", code, server.ErrorInvalidGrant) + } + if code := serverErrorCode(t, exchangeBackchannelWithKey(t, h, pending.AuthReqID.String(), generateKey(t))); code != server.ErrorAuthorizationPending { + t.Fatalf("tenant A's first poll after tenant B's: %q, want %q, not slow_down", code, server.ErrorAuthorizationPending) + } + + approved := beginBackchannel(t, h, standardBackchannelParams(t)) + approveBackchannel(t, h, approved.Handle) + if code := serverErrorCode(t, pollB(approved.AuthReqID)); code != server.ErrorInvalidGrant { + t.Fatalf("tenant B redeeming tenant A's approved auth_req_id: error code %q, want %q", code, server.ErrorInvalidGrant) + } + if err := exchangeBackchannelWithKey(t, h, approved.AuthReqID.String(), generateKey(t)); err != nil { + t.Fatalf("tenant A redeeming its own approved auth_req_id afterwards: %v, want tokens", err) + } +} diff --git a/server/refresh.go b/server/refresh.go index cf21d1b4..e5d01f65 100644 --- a/server/refresh.go +++ b/server/refresh.go @@ -2,7 +2,6 @@ package server import ( "context" - "crypto/sha256" "crypto/x509" "encoding/json" "slices" @@ -295,7 +294,7 @@ const refreshTokenUnknownDescription = "refresh_token is invalid, expired, or al // (empty unless it authenticated by Client Attestation); see // checkRefreshInstance for how it must match the grant's. func (s *Server) redeemRefreshGrant(ctx context.Context, clientID fapi.ClientID, instanceKey, rawToken string) (grantRecord, time.Time, *Error) { - tokenHash := sha256.Sum256([]byte(rawToken)) + tokenHash := refreshTokenHash(s.cfg.Issuer.String(), rawToken) redeemed, err := s.deps.Grants.RedeemRefreshToken(ctx, storage.RefreshTokenRedemption{ TokenHash: tokenHash, }) diff --git a/server/revocation.go b/server/revocation.go index d7e1b5db..ae840669 100644 --- a/server/revocation.go +++ b/server/revocation.go @@ -13,10 +13,16 @@ import ( // or NoRevocation{} to explicitly decline — see NoRevocation's own doc // comment for why declining must be a visible choice, not a silent one. type RevocationSink interface { - // Revoke marks key as revoked — a JWT's jti claim when the active - // AccessTokenIssuer is JWTAccessTokens, an opaque token's own hash - // when it's OpaqueAccessTokens; opaque either way from this - // interface's point of view. expiresAt is a conservative upper + // Revoke marks key as revoked. For an access token the server + // revokes it twice: under the token's own key — a JWT's jti claim + // when the active AccessTokenIssuer is JWTAccessTokens, an opaque + // token's own hash when it's OpaqueAccessTokens — namespaced by the + // server's issuer ("access-token:", the issuer's length in bytes, + // ":", the issuer, then the token's key), and under the token's key + // itself, the only form servers before v0.84.0 wrote, which + // resource servers not yet upgraded look for; a later release will + // stop writing it. Opaque either way from this interface's point of + // view. expiresAt is a conservative upper // bound on the access token's own expiry (the server no longer has // the token's real exp claim at this point in the flow) — a // backend with native per-key TTL support (Redis EXPIRE, a diff --git a/server/revocation_batch_test.go b/server/revocation_batch_test.go index fd0182f6..3e9c0fb6 100644 --- a/server/revocation_batch_test.go +++ b/server/revocation_batch_test.go @@ -125,7 +125,7 @@ func exchangeForRefreshToken(t *testing.T, h harness, dpopKey *ecdsa.PrivateKey) t.Fatalf("ExchangeAuthorizationCode: %v", err) } // The digest the server stores a code under (authorizationCodeHash). - return result.RefreshToken.Reveal(), grantrevocation.CodeGrantID(server.AuthorizationCodeHash(code, testCodeChallenge, testRedirectURI)) + return result.RefreshToken.Reveal(), grantrevocation.CodeGrantID(server.AuthorizationCodeHash(testIssuer, code, testCodeChallenge, testRedirectURI)) } // requireTokenOutcome fails unless err is nil when want is empty, or a diff --git a/server/revoked_grant_lifetime_test.go b/server/revoked_grant_lifetime_test.go index d99a359f..aa1ffa00 100644 --- a/server/revoked_grant_lifetime_test.go +++ b/server/revoked_grant_lifetime_test.go @@ -2,7 +2,6 @@ package server_test import ( "context" - "crypto/sha256" "errors" "fmt" "slices" @@ -98,7 +97,7 @@ func (c *lifetimeChanges) at(offset, refreshLifetime time.Duration) harness { // stored reports whether the GrantStore still redeems refreshToken. func (c *lifetimeChanges) stored(refreshToken string) bool { - _, err := c.h.deps.Grants.RedeemRefreshToken(context.Background(), storage.RefreshTokenRedemption{TokenHash: sha256.Sum256([]byte(refreshToken))}) + _, err := c.h.deps.Grants.RedeemRefreshToken(context.Background(), storage.RefreshTokenRedemption{TokenHash: server.RefreshTokenHash(testIssuer, refreshToken)}) return err == nil } diff --git a/server/token.go b/server/token.go index c625c801..cb7ba08e 100644 --- a/server/token.go +++ b/server/token.go @@ -338,21 +338,30 @@ type codeBinding struct { } // codeHashPrefix starts the string an authorization code's digest is -// taken over (authorizationCodeHash), separating that digest from the -// plain SHA-256 a refresh token is stored under (issueRefreshToken). -const codeHashPrefix = "fapigo authorization code\x00" +// taken over (authorizationCodeHash), separating that digest from a +// refresh token's (refreshTokenHash) and an auth_req_id's +// (backchannelAuthReqIDHash) of the same value. The "v2" marks the +// digests that cover the issuer: no code a server before v0.84.0 +// stored, under a digest without it, shares one with any code stored +// since. +const codeHashPrefix = "fapigo authorization code v2\x00" // authorizationCodeHash is the digest an authorization code is stored // and redeemed under (storage.NewAuthorizationCode.CodeHash): the -// SHA-256 of codeHashPrefix, each part of binding length-prefixed, and -// the code. The prefix keeps it from being a refresh token's digest -// (the plain SHA-256 of the token, unprefixed so the refresh tokens -// already stored stay valid) of the same value, so a store keeping -// codes and refresh tokens in one table keyed by digest can't return -// one for the other; the record's own grantRecord.Kind refuses it as -// well. The length prefixes keep any two bindings apart, whatever their -// parts hold: a code_challenge or redirect_uri is the client's to -// choose. +// SHA-256 of codeHashPrefix, issuer and each part of binding, each +// length-prefixed, and the code. The prefix keeps it from being a +// refresh token's digest of the same value, so a store keeping codes +// and refresh tokens in one table keyed by digest can't return one for +// the other; the record's own grantRecord.Kind refuses it as well. The +// length prefixes keep any two bindings apart, whatever their parts +// hold: a code_challenge or redirect_uri is the client's to choose. +// +// The issuer keeps servers of different issuers sharing one store +// apart: a code one issued, presented to the other, is unknown to the +// store, so it is neither spent nor treated as reused there. Without +// it, the other server's store would spend the code (or report it +// reused, revoking what it issued) before ownsRecord could refuse the +// record as another issuer's. // // The store spends a code, or reports it reused, before the exchange // can check what the token request presented with it, and a reuse by @@ -373,12 +382,31 @@ const codeHashPrefix = "fapigo authorization code\x00" // is different. And every installation of a wallet app shares one // client_id, so client_id alone can't keep one installation from // presenting a code another's user authorized. -func authorizationCodeHash(code string, binding codeBinding) [32]byte { - return sha256.Sum256([]byte(codeHashPrefix + +func authorizationCodeHash(issuer, code string, binding codeBinding) [32]byte { + return sha256.Sum256([]byte(codeHashPrefix + lengthPrefixed(issuer) + lengthPrefixed(binding.instanceKey) + lengthPrefixed(binding.codeChallenge) + lengthPrefixed(binding.redirectURI) + lengthPrefixed(binding.dpopJKT) + code)) } +// refreshHashPrefix starts the string a refresh token's digest is +// taken over (refreshTokenHash), separating it from an authorization +// code's (authorizationCodeHash) and an auth_req_id's +// (backchannelAuthReqIDHash). +const refreshHashPrefix = "fapigo refresh token\x00" + +// refreshTokenHash is the digest a refresh token is stored and redeemed +// under (storage.NewRefreshToken.TokenHash): the SHA-256 of +// refreshHashPrefix, the length-prefixed issuer and the token. The +// issuer keeps servers of different issuers sharing one store apart, as +// it does for a code (authorizationCodeHash): another issuer's refresh +// token is unknown to this server's lookup, so it is never redeemed, +// rotated or revoked here. A server before v0.84.0 stored each refresh +// token under the plain SHA-256 of the token, which this digest never +// equals, so those tokens are unknown after the upgrade. +func refreshTokenHash(issuer, token string) [32]byte { + return sha256.Sum256([]byte(refreshHashPrefix + lengthPrefixed(issuer) + token)) +} + // lengthPrefixed is part after its length in bytes and a colon: a // sequence of such strings splits into its parts one way only. func lengthPrefixed(part string) string { @@ -398,7 +426,7 @@ func lengthPrefixed(part string) string { // and answer it as unknown. func (s *Server) redeemAuthorizationCode(ctx context.Context, client storage.RegisteredClient, code string, presented codeExchange) (storage.RedeemedAuthorizationCode, [32]byte, error) { redeem := func(dpopJKT string) (storage.RedeemedAuthorizationCode, [32]byte, error) { - hash := authorizationCodeHash(code, presented.binding(dpopJKT)) + hash := authorizationCodeHash(s.cfg.Issuer.String(), code, presented.binding(dpopJKT)) redeemed, err := s.deps.Grants.RedeemAuthorizationCode(ctx, storage.AuthorizationCodeRedemption{ CodeHash: hash, ClientID: client.ID(), @@ -657,8 +685,15 @@ func (s *Server) revokeReusedCodeTokens(ctx context.Context, reused *storage.Aut if reused.IssuedAccessTokenKey != "" { // Resource servers accept the token until exp+MaxClockSkew by // their own clocks, which may lag this one's by another - // MaxClockSkew: the record must outlast both. - failures = append(failures, s.deps.Revocation.Revoke(ctx, reused.IssuedAccessTokenKey, s.deps.Clock.Now().Add(timeutil.SaturatingAdd(s.cfg.Limits.AccessTokenLifetime, s.cfg.Limits.MaxClockSkew, s.cfg.Limits.MaxClockSkew)))) + // MaxClockSkew: the record must outlast both. The store recorded + // the token's own key; it is revoked under that key namespaced + // by this server's issuer and, for resource servers and + // checkers that look only for it, the key itself + // (grantrevocation.AccessTokenKeys). + until := s.deps.Clock.Now().Add(timeutil.SaturatingAdd(s.cfg.Limits.AccessTokenLifetime, s.cfg.Limits.MaxClockSkew, s.cfg.Limits.MaxClockSkew)) + for _, key := range grantrevocation.AccessTokenKeys(s.cfg.Issuer.String(), reused.IssuedAccessTokenKey) { + failures = append(failures, s.deps.Revocation.Revoke(ctx, key, until)) + } } if reused.IssuedRefreshTokenHash != nil { revokeErr := s.deps.Grants.RevokeRefreshToken(ctx, *reused.IssuedRefreshTokenHash) @@ -726,7 +761,7 @@ func (s *Server) issueCodeExchangeTokens(ctx context.Context, client storage.Reg return issueErr } _ = recorder.RecordIssuedTokens(ctx, codeHash, accessKey, params.Now.Add(s.cfg.Limits.AccessTokenLifetime), - sha256.Sum256([]byte(refreshToken)), params.Now.Add(s.cfg.Limits.RefreshTokenLifetime)) + refreshTokenHash(s.cfg.Issuer.String(), refreshToken), params.Now.Add(s.cfg.Limits.RefreshTokenLifetime)) result.AccessToken = fapi.NewSecret(accessToken) result.RefreshToken = fapi.NewSecret(refreshToken) result.HasRefreshToken = true @@ -767,8 +802,8 @@ func (s *Server) issueOptionalRefreshToken(ctx context.Context, client storage.R // is the exact same hash CreateRefreshToken itself used to key // the stored record — see RecordIssuedRefreshToken's own doc // comment for why this association is recorded at all. - refreshTokenHash := sha256.Sum256([]byte(refreshToken)) - _ = s.deps.Grants.RecordIssuedRefreshToken(ctx, codeHash, refreshTokenHash, now.Add(s.cfg.Limits.RefreshTokenLifetime)) + tokenHash := refreshTokenHash(s.cfg.Issuer.String(), refreshToken) + _ = s.deps.Grants.RecordIssuedRefreshToken(ctx, codeHash, tokenHash, now.Add(s.cfg.Limits.RefreshTokenLifetime)) result.RefreshToken = fapi.NewSecret(refreshToken) result.HasRefreshToken = true return nil @@ -1076,7 +1111,7 @@ func (s *Server) issueRefreshToken(ctx context.Context, clientID fapi.ClientID, if err != nil { return "", err } - hash := sha256.Sum256([]byte(raw)) + hash := refreshTokenHash(s.cfg.Issuer.String(), raw) expiresAt := now.Add(s.cfg.Limits.RefreshTokenLifetime) if err := s.recordGrant(ctx, clientID, grant, hash, now, expiresAt); err != nil { return "", fmt.Errorf("record the grant: %w", err) diff --git a/server/token_revocation.go b/server/token_revocation.go index df17607d..261fc0b5 100644 --- a/server/token_revocation.go +++ b/server/token_revocation.go @@ -298,7 +298,7 @@ func (s *Server) revokeRefreshToken(ctx context.Context, clientID fapi.ClientID, if revokeErr := s.revokeCodeGrant(ctx, grant.CodeGrantID); revokeErr != nil { return TokenRevocationResult{}, revokeErr } - hash := sha256.Sum256([]byte(rawToken)) + hash := refreshTokenHash(s.cfg.Issuer.String(), rawToken) if err := s.deps.Grants.RevokeRefreshToken(ctx, hash); err != nil { return TokenRevocationResult{}, newError(ErrorServerError, 500, "failed to revoke the refresh token", err) } diff --git a/server/token_test.go b/server/token_test.go index 533bfd34..76c09726 100644 --- a/server/token_test.go +++ b/server/token_test.go @@ -14,6 +14,7 @@ import ( fapi "github.com/idfoundry/fapigo" "github.com/idfoundry/fapigo/internal/clientassertion" "github.com/idfoundry/fapigo/internal/dpop" + "github.com/idfoundry/fapigo/internal/grantrevocation" "github.com/idfoundry/fapigo/internal/jose" "github.com/idfoundry/fapigo/internal/token" "github.com/idfoundry/fapigo/keys" @@ -527,11 +528,20 @@ func TestExchangeAuthorizationCodeReuseRevokesAccessToken(t *testing.T) { t.Fatalf("second ExchangeAuthorizationCode (replayed code) = nil error, want error") } - // The first access token, and the code's grant (whatever else was - // issued from it). - revoked := h.revocation.all() - if len(revoked) != 2 || revoked[0] != validatedAT.JTI || !strings.HasPrefix(revoked[1], "code-grant:") { - t.Fatalf("Revoke calls = %v, want [%q code-grant:...]", revoked, validatedAT.JTI) + // The first access token, under its jti namespaced by the issuer + // and its bare jti, and the code's grant (whatever else was issued + // from it). + requireReuseRevocations(t, h.revocation.all(), validatedAT.JTI) +} + +// requireReuseRevocations fails unless revoked, a code reuse's Revoke +// calls, revoke the first access token, whose own key is key, under +// that key namespaced by the issuer and as is, then the code's grant. +func requireReuseRevocations(t *testing.T, revoked []string, key string) { + t.Helper() + want := grantrevocation.AccessTokenKeys(testIssuer, key) + if len(revoked) != 3 || revoked[0] != want[0] || revoked[1] != want[1] || !strings.HasPrefix(revoked[2], "code-grant:") { + t.Fatalf("Revoke calls = %v, want %q, code-grant:...", revoked, want) } } @@ -775,11 +785,7 @@ func TestExchangeAuthorizationCodeReuseRevokesOpaqueAccessToken(t *testing.T) { t.Fatalf("second ExchangeAuthorizationCode (replayed code) = nil error, want error") } - wantKey := hex.EncodeToString(tokenHash[:]) - revoked := h.revocation.all() - if len(revoked) != 2 || revoked[0] != wantKey || !strings.HasPrefix(revoked[1], "code-grant:") { - t.Fatalf("Revoke calls = %v, want [%q code-grant:...]", revoked, wantKey) - } + requireReuseRevocations(t, h.revocation.all(), hex.EncodeToString(tokenHash[:])) // ... and confirm the exact same verifier now rejects it (a fresh // DPoP proof each call — proofs are single-use). diff --git a/server/transaction_keys.go b/server/transaction_keys.go index 67f7f52e..0bed6261 100644 --- a/server/transaction_keys.go +++ b/server/transaction_keys.go @@ -11,7 +11,7 @@ import ( // parReferenceKeyPrefix and interactionHandleKeyPrefix separate the // digests a pushed authorization request and an interaction are stored // under from each other and from every other digest this server stores -// (authorizationCodeHash's, a refresh token's). +// (authorizationCodeHash's, refreshTokenHash's, backchannelAuthReqIDHash's). const ( parReferenceKeyPrefix = "fapigo pushed authorization request\x00" interactionHandleKeyPrefix = "fapigo interaction handle\x00" diff --git a/sqlstore/grant_revoker_test.go b/sqlstore/grant_revoker_test.go index 1a11c2ba..220c69cf 100644 --- a/sqlstore/grant_revoker_test.go +++ b/sqlstore/grant_revoker_test.go @@ -7,6 +7,7 @@ import ( "encoding/base64" "errors" "slices" + "strconv" "strings" "testing" "time" @@ -33,6 +34,37 @@ func newIndexedToken(t *testing.T, g storage.GrantStore, name string, expires ti return hash } +// productionIssuer is the issuer productionServer and productionClient +// configure. +const productionIssuer = "https://as.example" + +// serverRefreshTokenHashes are the digests a server of issuer may store +// refreshToken under: the issuer-bound one current servers use (the +// SHA-256 of a fixed prefix, the length-prefixed issuer and the token, +// following the server package's own, unexported derivation), then the +// plain SHA-256 a fapigo release before it used. sqlstore's tests also +// run against the fapigo release its go.mod requires (CI's "go test +// against the required FAPIgo release" step), so they look a token up +// under both rather than tie themselves to one release's derivation. +func serverRefreshTokenHashes(issuer, refreshToken string) [][32]byte { + return [][32]byte{ + sha256.Sum256([]byte("fapigo refresh token\x00" + strconv.Itoa(len(issuer)) + ":" + issuer + refreshToken)), + sha256.Sum256([]byte(refreshToken)), + } +} + +// redeemableUnderAny reports whether g can redeem a refresh token stored +// under any of hashes. +func redeemableUnderAny(t *testing.T, g storage.GrantStore, hashes [][32]byte) bool { + t.Helper() + for _, hash := range hashes { + if redeemable(t, g, hash) { + return true + } + } + return false +} + // redeemable reports whether g redeems the refresh token stored under // hash, failing the test on an error other than an unknown token. func redeemable(t *testing.T, g storage.GrantStore, hash [32]byte) bool { diff --git a/sqlstore/production_test.go b/sqlstore/production_test.go index 087294d7..0ae95a1f 100644 --- a/sqlstore/production_test.go +++ b/sqlstore/production_test.go @@ -38,7 +38,7 @@ func (discardAudit) Record(context.Context, server.AuditEvent) error { return ni func productionServer(t *testing.T, d *sqlstore.DB, deployment server.Deployment) (server.Config, server.Dependencies) { t.Helper() url := func(raw string) fapi.URL { return mustURL(t, raw) } - issuer, err := fapi.ParseIssuerURL("https://as.example") + issuer, err := fapi.ParseIssuerURL(productionIssuer) if err != nil { t.Fatal(err) } @@ -228,7 +228,7 @@ func checkProductionPushedRequestLookup(t *testing.T, d *sqlstore.DB, deployment func productionClient(t *testing.T, d *sqlstore.DB) (client.Config, client.Dependencies) { t.Helper() url := func(raw string) fapi.URL { return mustURL(t, raw) } - issuer, err := fapi.ParseIssuerURL("https://as.example") + issuer, err := fapi.ParseIssuerURL(productionIssuer) if err != nil { t.Fatal(err) } diff --git a/sqlstore/registry_race_test.go b/sqlstore/registry_race_test.go index 4252e0c0..166396a9 100644 --- a/sqlstore/registry_race_test.go +++ b/sqlstore/registry_race_test.go @@ -2,7 +2,6 @@ package sqlstore_test import ( "context" - "crypto/sha256" "errors" "sync" "testing" @@ -245,10 +244,12 @@ func raced(t *testing.T, srv *server.Server, grants storage.GrantStore, app flow out.refreshToken, out.exchangeErr = app.exchange(ctx, srv, code) if out.exchangeErr == nil { await(ctx, race.revoked) - _, err := grants.RedeemRefreshToken(context.Background(), storage.RefreshTokenRedemption{TokenHash: sha256.Sum256([]byte(out.refreshToken))}) - out.liveAfter = err == nil - if err != nil && !isNotFound(err) { - out.checkErr = err + for _, hash := range serverRefreshTokenHashes(productionIssuer, out.refreshToken) { + _, err := grants.RedeemRefreshToken(context.Background(), storage.RefreshTokenRedemption{TokenHash: hash}) + out.liveAfter = out.liveAfter || err == nil + if err != nil && !isNotFound(err) { + out.checkErr = err + } } } }) diff --git a/sqlstore/server_flow_test.go b/sqlstore/server_flow_test.go index d900eb8c..7cd24930 100644 --- a/sqlstore/server_flow_test.go +++ b/sqlstore/server_flow_test.go @@ -235,9 +235,14 @@ func checkRevokedGrantStaysRevoked(t *testing.T, dialect sqlstore.Dialect, grant refreshToken, err := app.exchange(ctx, long, app.code(ctx, long, clock.Now(), "grant-1")) must(t, err) + hashes := serverRefreshTokenHashes(productionIssuer, refreshToken) + if !redeemableUnderAny(t, d.Grants(), hashes) { + t.Fatal("setup: the issued refresh token isn't in the store under the digest the server stores it under") + } + clock.advance(time.Minute) must(t, short.RevokeGrant(ctx, "grant-1")) - if redeemable(t, d.Grants(), sha256.Sum256([]byte(refreshToken))) { + if redeemableUnderAny(t, d.Grants(), hashes) { t.Fatal("RevokeGrant left the grant's refresh token in the store") } diff --git a/storage/backchannel.go b/storage/backchannel.go index ecd7afae..1db77ce6 100644 --- a/storage/backchannel.go +++ b/storage/backchannel.go @@ -37,8 +37,10 @@ const ( // NewBackchannelAuthentication is what CreateBackchannelAuthentication // persists for one client-initiated backchannel authentication request. type NewBackchannelAuthentication struct { - // AuthReqIDHash is the SHA-256 digest of the raw auth_req_id value - // handed to the client — matching NewAuthorizationCode.CodeHash's + // AuthReqIDHash is a SHA-256 digest of the raw auth_req_id value + // handed to the client and the issuer of the server that issued it + // (so a server of another issuer sharing the store finds no record) + // — matching NewAuthorizationCode.CodeHash's // digest-only discipline, used to look this record up by the value a // client presents back. Required unconditionally, regardless of // DeliveryMode. For a request made by a client authenticated by diff --git a/storage/grant.go b/storage/grant.go index d4a1ba74..1d379e24 100644 --- a/storage/grant.go +++ b/storage/grant.go @@ -105,7 +105,9 @@ type AuthorizationCodeAlreadyRedeemedError struct { // IssuedAccessTokenKey is the revocation-lookup key of the access // token issued on the original (first) redemption (a JWT's jti // claim, or an opaque token's own hash — see - // server.AccessTokenIssuer.IssueAccessToken) — "" if + // server.AccessTokenIssuer.IssueAccessToken), as the server recorded + // it; the server revokes it both namespaced by its issuer and as is + // (see server.RevocationSink) — "" if // RecordIssuedAccessToken was never called for this code (e.g. no // revocation support wired in). IssuedAccessTokenKey string @@ -132,8 +134,9 @@ func (e *AuthorizationCodeAlreadyRedeemedError) Error() string { // NewAuthorizationCode is what CreateAuthorizationCode persists for one // issued authorization code. CodeHash is a SHA-256 digest of the raw -// code value, domain-separated so it never equals a refresh token's -// digest (NewRefreshToken.TokenHash) of the same value — matching +// code value and the issuer of the server that issued it, +// domain-separated so it never equals a refresh token's digest +// (NewRefreshToken.TokenHash) of the same value — matching // ReplayStore's digest-only philosophy — never the code itself; the raw value exists only long enough to be hashed // here and returned to the client in the redirect response. The digest // also covers the code's PKCE challenge, its redirect URI and the DPoP @@ -141,8 +144,9 @@ func (e *AuthorizationCodeAlreadyRedeemedError) Error() string { // authenticated by Client Attestation, the client instance it was // issued to, so a token request presenting the code with another // code_verifier, redirect_uri or DPoP key, or from another instance of -// the same client, finds none. A store just keys the record by it -// either way. The server may look for a code under two digests, with +// the same client, finds none, and a server of another issuer sharing +// the store finds none either, so can't spend it. A store just keys the +// record by it either way. The server may look for a code under two digests, with // the presented DPoP key and without, since it can't tell which the // code is bound to: a CodeHash the store doesn't know is only an error // (see RedeemAuthorizationCode), changing nothing. @@ -190,9 +194,12 @@ type RedeemedAuthorizationCode struct { } // NewRefreshToken is what CreateRefreshToken persists for one issued -// refresh token. TokenHash is the SHA-256 digest of the raw token value, -// never the value itself — the same digest-only discipline as -// NewAuthorizationCode.CodeHash. +// refresh token. TokenHash is a SHA-256 digest of the raw token value +// and the issuer of the server that issued it, never the value itself — +// the same digest-only discipline as NewAuthorizationCode.CodeHash. As +// for a code, the issuer keeps servers of different issuers sharing one +// store apart: one's refresh token, presented to another, is unknown to +// it. (A server before v0.84.0 stored the plain SHA-256 of the token.) type NewRefreshToken struct { TokenHash [32]byte @@ -218,8 +225,8 @@ type NewRefreshToken struct { // RefreshTokenRedemption is the input to GrantStore.RedeemRefreshToken. type RefreshTokenRedemption struct { - // TokenHash is the SHA-256 digest of the presented refresh token - // value — the same digest CreateRefreshToken stored it under. + // TokenHash is the digest of the presented refresh token value — + // the same digest CreateRefreshToken stored it under. TokenHash [32]byte } diff --git a/storage/revocation.go b/storage/revocation.go index ec50fa77..105f229d 100644 --- a/storage/revocation.go +++ b/storage/revocation.go @@ -37,8 +37,8 @@ type RevocationStore interface { // resource.RevocationChecker) may implement to answer several IsRevoked // questions in one round trip. The server and resource.Verifier each // check a handful of keys per request — an access token's own key, its -// grant's key and its code grant's key, each also in the form a server -// before v0.61.0 wrote — and use IsAnyRevoked, when the store has it, +// grant's key and its code grant's key, each namespaced by issuer and +// also in the un-namespaced form older servers wrote — and use IsAnyRevoked, when the store has it, // instead of one IsRevoked call per key. A store without it gets exactly // those IsRevoked calls. // @@ -47,7 +47,7 @@ type RevocationStore interface { // first that is. An empty keys is false, nil. Keys are compared exactly, // as IsRevoked compares them. An error means the answer isn't known, as // for IsRevoked: the caller fails closed. Callers pass a few keys (at -// most five today); a store may refuse an unreasonably long keys with an +// most six today); a store may refuse an unreasonably long keys with an // error. TestRevocationStoreContract checks a store that implements it // against IsRevoked. //