From c05bc82f82747280ec098d5d4419d5d004315290 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Wed, 25 Nov 2026 22:33:13 +0800 Subject: [PATCH 1/4] fix(server): answer invalid_grant for a grant revoked during issuance When a grant was revoked while its refresh token was being stored, typically a reused authorization code racing the exchange that redeemed it, the server withdrew the token but answered server_error (HTTP 500) "failed to issue refresh token". Nothing was issued, but the client saw a store outage for what is a refused grant. Both checks that run after the token is stored now mark that outcome with errGrantRevokedWhileIssued: confirmGrantNotRevoked when the revocation check finds the grant revoked, and confirmGrantRecorded when the grant registry no longer lists it. A new refreshTokenIssueFailure maps it to invalid_grant (HTTP 400) "the grant has been revoked" for the authorization code exchange, the CIBA token request and IssueRefreshToken alike, so their audit events record invalid_grant too. Everything else stays server_error: a revocation store or registry that can't answer, and a revoked grant whose token then can't be withdrawn (withdrawRefreshToken now marks that failure), since a live token may remain. Co-Authored-By: Claude Opus 5.5 --- GETTING_STARTED.md | 2 +- UPGRADING.md | 23 ++ server/backchannel_token.go | 2 +- server/embedder_refresh.go | 2 +- server/grant_registry.go | 26 ++- server/grant_revocation.go | 16 +- server/grant_revoked_while_issued_test.go | 265 ++++++++++++++++++++++ server/issued_tokens_recorder_test.go | 6 +- server/revoked_grant_records_test.go | 12 +- server/token.go | 4 +- 10 files changed, 338 insertions(+), 20 deletions(-) create mode 100644 server/grant_revoked_while_issued_test.go diff --git a/GETTING_STARTED.md b/GETTING_STARTED.md index 0637094e..b725d9f0 100644 --- a/GETTING_STARTED.md +++ b/GETTING_STARTED.md @@ -974,7 +974,7 @@ stored before the store had it, only the record refuses them (one issued while `RevokeGrant` runs isn't left to the record alone unless the grant's others are: the issuance checks the grant's revocation again once it has stored the token, and withdraws it instead if the -record is there by then): raising +record is there by then, answering the token request `invalid_grant`): raising `Limits.RefreshTokenLifetime` later, or running instances with longer `Limits`, can't bring a revoked grant back unless a refresh token lifetime over 400 days applies. With sqlstore, refresh tokens stored diff --git a/UPGRADING.md b/UPGRADING.md index 5e625e03..af61d406 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -55,6 +55,29 @@ federation relied on Relying Parties that leave the parameter out getting every type, list those types in the Trust Anchor's or Intermediate's `one_of`, or have the Relying Parties publish the types they use. +### A grant revoked while its refresh token is issued is `invalid_grant`, not `server_error` (server) + +**Affects:** servers issuing refresh tokens (`offline_access`, CIBA, +`IssueRefreshToken`), and clients or monitoring that count their +token errors. No code changes. + +**Why:** when the grant was revoked while its refresh token was being +stored, most often a reused authorization code racing the exchange +that redeemed it, the server withdrew the token and answered +`server_error` (HTTP 500) "failed to issue refresh token": nothing was +issued, but the client saw a store outage for what is a refused grant. + +**What fails:** nothing is refused that wasn't before. That token +request now answers `invalid_grant` (HTTP 400) "the grant has been +revoked", from the authorization code exchange, the CIBA token +request and `IssueRefreshToken` alike, and its audit event records +`invalid_grant`. A genuine store failure there, including a failure to +withdraw the token, still answers `server_error`. + +**What to change:** nothing, unless an alert or client keys on the +500: expect a 400 `invalid_grant` instead, and the client starts a new +authorization as for any other refused grant. + ## v0.85.0 ### Codes, refresh tokens and `auth_req_id`s are stored under digests covering the issuer (server, storage) diff --git a/server/backchannel_token.go b/server/backchannel_token.go index 7ef9f234..a63144e9 100644 --- a/server/backchannel_token.go +++ b/server/backchannel_token.go @@ -366,7 +366,7 @@ func (s *Server) issueBackchannelOptionalTokens(ctx context.Context, client stor if containsScope(grant.Scope, "offline_access") { refreshToken, err := s.issueRefreshToken(ctx, client.ID(), grant, binding) if err != nil { - return newError(ErrorServerError, 500, "failed to issue refresh token", err) + return refreshTokenIssueFailure(err) } result.RefreshToken = fapi.NewSecret(refreshToken) result.HasRefreshToken = true diff --git a/server/embedder_refresh.go b/server/embedder_refresh.go index 8cdeaa42..5672ba77 100644 --- a/server/embedder_refresh.go +++ b/server/embedder_refresh.go @@ -99,7 +99,7 @@ func (s *Server) IssueRefreshToken(ctx context.Context, req IssueRefreshTokenReq } raw, issueErr := s.issueRefreshToken(ctx, client.ID(), grant, refreshBinding{Thumbprint: req.Binding.Thumbprint, InstanceKey: req.Client.instanceKey}) if issueErr != nil { - err := newError(ErrorServerError, 500, "failed to issue refresh token", issueErr) + err := refreshTokenIssueFailure(issueErr) s.audit(ctx, AuditEventIssueRefreshToken, client.ID(), AuditOutcomeFailure, string(err.Code())) return fapi.Secret{}, err } diff --git a/server/grant_registry.go b/server/grant_registry.go index 14e6eb96..634d4323 100644 --- a/server/grant_registry.go +++ b/server/grant_registry.go @@ -115,9 +115,31 @@ func (s *Server) recordGrant(ctx context.Context, clientID fapi.ClientID, grant } // errGrantRevokedWhileIssued is issueRefreshToken's failure when the -// grant was revoked while its refresh token was being issued. +// grant was revoked while its refresh token was being issued: either +// check after storing the token, confirmGrantRecorded's or +// confirmGrantNotRevoked's, found the revocation, and the token was +// withdrawn. refreshTokenIssueFailure answers it invalid_grant. var errGrantRevokedWhileIssued = errors.New("the grant was revoked while its refresh token was being issued") +// errRefreshTokenNotWithdrawn marks withdrawRefreshToken's failure to +// revoke the token it withdraws: a store failure, which may leave a live +// token behind, whatever the cause it's joined to. +var errRefreshTokenNotWithdrawn = errors.New("withdraw the refresh token") + +// refreshTokenIssueFailure is the token request's answer when +// issueRefreshToken fails with err: invalid_grant (RFC 6749 §5.2) when +// the grant was revoked while the token was being issued, the token +// withdrawn, as a reused authorization code's racing exchange is; and +// server_error for any other failure, a store's included, and for a +// revocation found when the token couldn't then be withdrawn, which is +// a store failure too. +func refreshTokenIssueFailure(err error) *Error { + if errors.Is(err, errGrantRevokedWhileIssued) && !errors.Is(err, errRefreshTokenNotWithdrawn) { + return newError(ErrorInvalidGrant, 400, "the grant has been revoked", err) + } + return newError(ErrorServerError, 500, "failed to issue refresh token", err) +} + // confirmGrantRecorded checks, after the refresh token stored under // refreshTokenHash was created, that its grant is still in // Dependencies.GrantRegistry, when one is set. A revocation that lists @@ -161,7 +183,7 @@ func (s *Server) confirmGrantRecorded(ctx context.Context, subject string, refre // RevokeListedGrant or RevokeSubjectGrants to revoke the token by. func (s *Server) withdrawRefreshToken(ctx context.Context, refreshTokenHash [32]byte, cause error) error { if err := s.deps.Grants.RevokeRefreshToken(ctx, refreshTokenHash); err != nil { - return errors.Join(cause, fmt.Errorf("withdraw the refresh token: %w", err)) + return errors.Join(cause, fmt.Errorf("%w: %w", errRefreshTokenNotWithdrawn, err)) } _ = s.forgetRevokedRefreshToken(ctx, refreshTokenHash) return cause diff --git a/server/grant_revocation.go b/server/grant_revocation.go index fdb46b25..a7ef3a4c 100644 --- a/server/grant_revocation.go +++ b/server/grant_revocation.go @@ -198,7 +198,10 @@ func (s *Server) revokeGrantRefreshTokens(ctx context.Context, revocationKey str // refreshTokenHash has been created, that grant, the grant it's issued // from, still isn't revoked, and withdraws the token if it is, or if // that can't be checked (withdrawRefreshToken), so the token isn't -// issued. The token request checked the grant before, but it may have +// issued: a revocation found is errGrantRevokedWhileIssued, which the +// token request answers invalid_grant (refreshTokenIssueFailure), a +// failure to check the revocation the server_error it is. The token +// request checked the grant before, but it may have // been revoked since: RevokeGrant, or a reuse of the authorization code, // records the grant as revoked, then revokes the grant's refresh tokens // in a GrantStore that can find them (storage.GrantRefreshTokenRevoker), @@ -210,10 +213,15 @@ func (s *Server) revokeGrantRefreshTokens(ctx context.Context, revocationKey str // revocation store only for a grant with a GrantID or code grant ID, as // checkGrantNotRevoked does. func (s *Server) confirmGrantNotRevoked(ctx context.Context, grant grantRecord, refreshTokenHash [32]byte) error { - if revErr := s.checkGrantNotRevoked(ctx, grant); revErr != nil { - return s.withdrawRefreshToken(ctx, refreshTokenHash, fmt.Errorf("confirm the grant isn't revoked: %w", revErr)) + revErr := s.checkGrantNotRevoked(ctx, grant) + if revErr == nil { + return nil } - return nil + cause := fmt.Errorf("confirm the grant isn't revoked: %w", revErr) + if revErr.Code() == ErrorInvalidGrant { + cause = fmt.Errorf("%w: %w", errGrantRevokedWhileIssued, cause) + } + return s.withdrawRefreshToken(ctx, refreshTokenHash, cause) } // refreshTokenGrantKeys are the storage.NewRefreshToken.GrantKeys of a diff --git a/server/grant_revoked_while_issued_test.go b/server/grant_revoked_while_issued_test.go new file mode 100644 index 00000000..0bc840f8 --- /dev/null +++ b/server/grant_revoked_while_issued_test.go @@ -0,0 +1,265 @@ +package server_test + +import ( + "context" + "encoding/json" + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/idfoundry/fapigo/internal/clientassertion" + "github.com/idfoundry/fapigo/server" + "github.com/idfoundry/fapigo/storage" + "github.com/idfoundry/fapigo/storage/memstore" +) + +// A grant revoked while its refresh token is being stored, after the +// token request checked it, gets no refresh token, and the token request +// answers invalid_grant, the grant being refused, not the server_error of +// a store failure — whichever of the two checks after storing the token +// finds the revocation. A store failing in those checks, or failing to +// withdraw the token, is still server_error. + +// afterCreateGrants is a fakeGrantStore that runs after once a refresh +// token has been created, as a revocation racing the issuance would run +// between the token's store write and the checks after it. +type afterCreateGrants struct { + *fakeGrantStore + after func(context.Context) +} + +func (g afterCreateGrants) CreateRefreshToken(ctx context.Context, tok storage.NewRefreshToken) error { + err := g.fakeGrantStore.CreateRefreshToken(ctx, tok) + if err == nil { + g.after(ctx) + } + return err +} + +// downAfterCreateRevocation is a fakeRevocationSink whose IsRevoked fails +// once down is set. +type downAfterCreateRevocation struct { + *fakeRevocationSink + down *atomic.Bool +} + +func (r downAfterCreateRevocation) IsRevoked(ctx context.Context, key string) (bool, error) { + if r.down.Load() { + return false, errStoreDown + } + return r.fakeRevocationSink.IsRevoked(ctx, key) +} + +// wantTokenError fails t unless err is an *server.Error of code. +func wantTokenError(t *testing.T, what string, err error, code server.ErrorCode) { + t.Helper() + var serverErr *server.Error + if !errors.As(err, &serverErr) || serverErr.Code() != code { + t.Fatalf("%s = %v, want %s", what, err, code) + } +} + +// revokedGrantIssuance is a harness, without a GrantRegistry, whose +// GrantStore runs after once each refresh token is created, and an +// attested instance of its client. +func revokedGrantIssuance(t *testing.T, after func(h *harness, ctx context.Context), mutate ...func(*server.Dependencies)) (*harness, *attestedInstance) { + t.Helper() + var hp *harness + h, owner := registryHarness(t, nil, append([]func(*server.Dependencies){func(deps *server.Dependencies) { + deps.Grants = afterCreateGrants{deps.Grants.(*fakeGrantStore), func(ctx context.Context) { after(hp, ctx) }} + }}, mutate...)...) + hp = &h + return hp, owner +} + +// issueGrantRefreshToken is IssueRefreshToken of grant-1 for owner. +func issueGrantRefreshToken(t *testing.T, h *harness, owner *attestedInstance) error { + t.Helper() + attested, binding := embedderTokenRequest(t, owner) + _, err := h.server.IssueRefreshToken(context.Background(), server.IssueRefreshTokenRequest{ + GrantType: preAuthorizedCodeGrant, Client: attested, Binding: binding, + Subject: mustSubjectID(t, "holder-1"), Scope: []string{"accounts"}, GrantID: "grant-1", + }) + return err +} + +// TestGrantRevokedWhileIssuedIsInvalidGrant: RevokeGrant landing once +// IssueRefreshToken has stored the refresh token is found by the check +// that the grant isn't revoked: the token is withdrawn and the issuance +// is invalid_grant, audited as such. +func TestGrantRevokedWhileIssuedIsInvalidGrant(t *testing.T) { + var once sync.Once + h, owner := revokedGrantIssuance(t, func(h *harness, ctx context.Context) { + once.Do(func() { + if err := h.server.RevokeGrant(ctx, "grant-1"); err != nil { + t.Errorf("RevokeGrant: %v", err) + } + }) + }) + before := len(h.grants.refreshTokens) + wantTokenError(t, "IssueRefreshToken of a grant revoked meanwhile", issueGrantRefreshToken(t, h, owner), server.ErrorInvalidGrant) + checkNoLiveRefreshTokenSince(t, *h, before) + wantLastAudit(t, h, server.AuditEventIssueRefreshToken, string(server.ErrorInvalidGrant)) +} + +// TestGrantRevocationUncheckableWhileIssuedIsServerError: a revocation +// store failing the check after the refresh token is stored is a store +// failure, server_error, and the token is withdrawn. +func TestGrantRevocationUncheckableWhileIssuedIsServerError(t *testing.T) { + var down atomic.Bool + h, owner := revokedGrantIssuance(t, func(*harness, context.Context) { down.Store(true) }, func(deps *server.Dependencies) { + deps.Revocation = downAfterCreateRevocation{deps.Revocation.(*fakeRevocationSink), &down} + }) + before := len(h.grants.refreshTokens) + wantTokenError(t, "IssueRefreshToken whose revocation check fails", issueGrantRefreshToken(t, h, owner), server.ErrorServerError) + checkNoLiveRefreshTokenSince(t, *h, before) +} + +// TestGrantRevokedWhileIssuedWithdrawalFailsIsServerError: a grant found +// revoked whose refresh token then can't be withdrawn is a store +// failure, server_error: the token may still be live. +func TestGrantRevokedWhileIssuedWithdrawalFailsIsServerError(t *testing.T) { + var once sync.Once + h, owner := revokedGrantIssuance(t, func(h *harness, ctx context.Context) { + once.Do(func() { + // The revocation record is written; the store then refuses to + // revoke the grant's refresh tokens, and the withdrawal. + h.grants.failRevokeRefresh = errStoreDown + _ = h.server.RevokeGrant(ctx, "grant-1") + }) + }) + wantTokenError(t, "IssueRefreshToken of a revoked grant whose token can't be withdrawn", issueGrantRefreshToken(t, h, owner), server.ErrorServerError) +} + +// tokensRecorderGrants is an afterCreateGrants that is a +// storage.IssuedTokensRecorder, so a code exchange stores its refresh +// token before its access token. +type tokensRecorderGrants struct{ afterCreateGrants } + +func (g tokensRecorderGrants) RecordIssuedTokens(ctx context.Context, codeHash [32]byte, accessKey string, accessExpiresAt time.Time, refreshHash [32]byte, refreshExpiresAt time.Time) error { + if err := g.RecordIssuedAccessToken(ctx, codeHash, accessKey, accessExpiresAt); err != nil { + return err + } + return g.RecordIssuedRefreshToken(ctx, codeHash, refreshHash, refreshExpiresAt) +} + +// TestCodeReuseWhileIssuedIsInvalidGrant: a reuse of an authorization +// code landing once its exchange has stored the refresh token revokes +// the code's grant, and the exchange answers invalid_grant, as the reuse +// does, issuing nothing live — with a GrantStore that records the +// exchange's tokens together (storage.IssuedTokensRecorder) and one that +// doesn't. +func TestCodeReuseWhileIssuedIsInvalidGrant(t *testing.T) { + for name, recorder := range map[string]bool{"IssuedTokensRecorder": true, "no IssuedTokensRecorder": false} { + t.Run(name, func(t *testing.T) { + var once sync.Once + var owner *attestedInstance + var code string + var reuseErr error + h, owner := revokedGrantIssuance(t, func(h *harness, ctx context.Context) { + once.Do(func() { + _, reuseErr = h.server.ExchangeAuthorizationCode(ctx, owner.exchangeCodeRequest(code, testCodeVerifier)) + }) + }, func(deps *server.Dependencies) { + if recorder { + deps.Grants = tokensRecorderGrants{deps.Grants.(afterCreateGrants)} + } + }) + code = owner.attestedCode() + before := len(h.grants.refreshTokens) + _, err := owner.exchangeCode(code, testCodeVerifier) + wantTokenError(t, "the exchange whose code was reused while it issued", err, server.ErrorInvalidGrant) + wantTokenError(t, "the reuse", reuseErr, server.ErrorInvalidGrant) + checkNoLiveRefreshTokenSince(t, *h, before) + wantLastAudit(t, h, server.AuditEventExchangeAuthorizationCode, string(server.ErrorInvalidGrant)) + }) + } +} + +// TestGrantEntryGoneWhileIssuedIsInvalidGrant: a grant whose registry +// entry is gone by the time its refresh token is stored, deleted by a +// revocation in between, is invalid_grant; a registry that can't say +// whether it's there is server_error; and so is an entry gone whose +// refresh token can't then be withdrawn. +func TestGrantEntryGoneWhileIssuedIsInvalidGrant(t *testing.T) { + for name, tc := range map[string]struct { + registry storage.GrantRegistry + withdrawFails bool + want server.ErrorCode + }{ + "entry gone": {racingRegistry{memstore.NewGrantRegistry()}, false, server.ErrorInvalidGrant}, + "registry can't say": {listFailsAfterRecord{memstore.NewGrantRegistry()}, false, server.ErrorServerError}, + "entry gone, token can't be withdrawn": {racingRegistry{memstore.NewGrantRegistry()}, true, server.ErrorServerError}, + } { + t.Run(name, func(t *testing.T) { + h, owner := registryHarness(t, tc.registry) + if tc.withdrawFails { + h.grants.failRevokeRefresh = errStoreDown + } + err := issueGrantRefreshToken(t, &h, owner) + wantTokenError(t, "IssueRefreshToken", err, tc.want) + wantLastAudit(t, &h, server.AuditEventIssueRefreshToken, string(tc.want)) + }) + } +} + +// wantLastAudit fails t unless h's last audit event is a failure of +// eventType with reason. +func wantLastAudit(t *testing.T, h *harness, eventType server.AuditEventType, reason string) { + t.Helper() + events := h.audit.all() + if len(events) == 0 { + t.Fatal("no audit event recorded") + } + last := events[len(events)-1] + if last.Type != eventType || last.Outcome != server.AuditOutcomeFailure || last.Description != reason { + t.Fatalf("last audit event = %+v, want a %v failure with reason %s", last, eventType, reason) + } +} + +// TestCIBAGrantRevokedWhileIssuedIsInvalidGrant: RevokeGrant landing +// once a CIBA token request has stored the refresh token makes that +// request invalid_grant too. +func TestCIBAGrantRevokedWhileIssuedIsInvalidGrant(t *testing.T) { + var once sync.Once + var srv *server.Server + grants, audit := &fakeGrantStore{}, &fakeAuditSink{} + h := newHarnessWithBackchannelOptions(t, memstore.NewBackchannelAuthenticationStore(), nil, func(d *server.Dependencies) { + d.Revocation, d.Audit = &fakeRevocationSink{}, audit + d.Grants = afterCreateGrants{grants, func(ctx context.Context) { + once.Do(func() { + if err := srv.RevokeGrant(ctx, "ciba-grant"); err != nil { + t.Errorf("RevokeGrant: %v", err) + } + }) + }} + }) + srv, h.grants, h.audit = h.server, grants, audit + params := standardBackchannelParams(t) + params["scope"] = json.RawMessage(`"openid accounts offline_access"`) + required := beginBackchannel(t, h, params) + subject, _ := server.NewSubjectID("user-1") + authenticated, _ := server.NewAuthenticatedSubject(subject) + authCtx, _ := server.NewAuthenticationContext(h.now, "", nil) + if err := h.server.CompleteBackchannelAuthentication(context.Background(), server.CompleteBackchannelAuthenticationRequest{ + Handle: required.Handle, + Result: server.Authorize(authenticated, authCtx, server.GrantedAuthorization{Scope: []string{"openid", "accounts", "offline_access"}, GrantID: "ciba-grant"}), + }); err != nil { + t.Fatalf("CompleteBackchannelAuthentication: %v", err) + } + before := len(h.grants.refreshTokens) + _, err := h.server.ExchangeBackchannelAuthentication(context.Background(), server.BackchannelTokenExchangeRequest{ + HTTP: server.FormRequest{Parameters: []server.FormParameter{ + formParam("client_assertion", h.clientAssertion(t)), + formParam("client_assertion_type", clientassertion.AssertionType), + formParam("grant_type", server.CIBAGrantType), + formParam("auth_req_id", required.AuthReqID.String()), + }}, + DPoPProofs: []string{createDPoPProof(t, generateKey(t), h.now)}, + }) + wantTokenError(t, "the CIBA token request whose grant was revoked while it issued", err, server.ErrorInvalidGrant) + checkNoLiveRefreshTokenSince(t, h, before) + wantLastAudit(t, &h, server.AuditEventExchangeBackchannelAuthentication, string(server.ErrorInvalidGrant)) +} diff --git a/server/issued_tokens_recorder_test.go b/server/issued_tokens_recorder_test.go index 7cbb7f82..afe68311 100644 --- a/server/issued_tokens_recorder_test.go +++ b/server/issued_tokens_recorder_test.go @@ -235,7 +235,7 @@ func TestCodeReuseBeforeTheRecordStillEndsTheTokens(t *testing.T) { // testReuseMidExchange reuses a code mid-exchange, between its // redemption and RecordIssuedTokens, and checks the exchange fails with -// server_error, recording nothing, and withdraws the refresh token it +// invalid_grant, recording nothing, and withdraws the refresh token it // stored. func testReuseMidExchange(t *testing.T) { h, store := newRecordingHarness(t) @@ -248,8 +248,8 @@ func testReuseMidExchange(t *testing.T) { if reuseErr == nil { t.Fatal("ExchangeAuthorizationCode reusing the code mid-exchange = nil error, want error") } - if err == nil || serverErrorCode(t, err) != server.ErrorServerError { - t.Fatalf("ExchangeAuthorizationCode with its code reused mid-exchange = %v, want server_error, issuing nothing", err) + if err == nil || serverErrorCode(t, err) != server.ErrorInvalidGrant { + t.Fatalf("ExchangeAuthorizationCode with its code reused mid-exchange = %v, want invalid_grant, issuing nothing", err) } if got := store.loggedCalls(); !slices.Equal(got, []string{"CreateRefreshToken"}) { t.Fatalf("grant store calls = %v, want the refresh token stored, and nothing recorded", got) diff --git a/server/revoked_grant_records_test.go b/server/revoked_grant_records_test.go index dd83518c..ce06201f 100644 --- a/server/revoked_grant_records_test.go +++ b/server/revoked_grant_records_test.go @@ -151,12 +151,12 @@ func exchangeRevokedMeanwhile(t *testing.T, h harness, grants *revokingGrantStor // between a code exchange's check of the grant and the storage of its // refresh token revokes the grant's refresh tokens before this one // exists, so misses it. The exchange checks the grant again once the -// token is stored, and fails with server_error, withdrawing the token and +// token is stored, and fails with invalid_grant, withdrawing the token and // deleting its registry entry, rather than issuing one only the grant's // revocation record refuses, whether or not the GrantStore revokes a // grant's refresh tokens itself. A withdrawal that fails is reported with -// it, and the token still isn't issued; it keeps its entry, by which -// RevokeSubjectGrants revokes it. +// it, as server_error, and the token still isn't issued; it keeps its +// entry, by which RevokeSubjectGrants revokes it. func TestRefreshTokenIsntIssuedForAGrantRevokedMeanwhile(t *testing.T) { for _, kind := range grantStoreKinds { t.Run(kind.name, func(t *testing.T) { testRevokedMeanwhile(t, kind) }) @@ -165,15 +165,15 @@ func TestRefreshTokenIsntIssuedForAGrantRevokedMeanwhile(t *testing.T) { } // testRevokedMeanwhile runs exchangeRevokedMeanwhile over a GrantStore of -// kind, and checks the exchange fails with server_error, withdrawing the +// kind, and checks the exchange fails with invalid_grant, withdrawing the // one refresh token it stored and deleting that token's entry alone, and // lists nothing. func testRevokedMeanwhile(t *testing.T, kind grantStoreKind) { grants := &revokingGrantStore{GrantStore: memstore.NewGrantStore()} c, deleted := newRecordedLifetimeChanges(t, kind.of(grants)) h := c.at(0, 24*time.Hour) - if err := exchangeRevokedMeanwhile(t, h, grants); serverErrorCode(t, err) != server.ErrorServerError { - t.Fatalf("ExchangeAuthorizationCode, its grant revoked mid-exchange = %v, want server_error", err) + if err := exchangeRevokedMeanwhile(t, h, grants); serverErrorCode(t, err) != server.ErrorInvalidGrant { + t.Fatalf("ExchangeAuthorizationCode, its grant revoked mid-exchange = %v, want invalid_grant", err) } if len(grants.created) != 1 || redeemable(grants, grants.created[0]) { t.Fatalf("%d refresh tokens created, the first still redeemable; want the one created withdrawn", len(grants.created)) diff --git a/server/token.go b/server/token.go index cb7ba08e..41596d5c 100644 --- a/server/token.go +++ b/server/token.go @@ -754,7 +754,7 @@ func (s *Server) issueCodeExchangeTokens(ctx context.Context, client storage.Reg } refreshToken, err := s.issueRefreshToken(ctx, client.ID(), grant, binding) if err != nil { - return newError(ErrorServerError, 500, "failed to issue refresh token", err) + return refreshTokenIssueFailure(err) } accessToken, accessKey, issueErr := s.issueAccessToken(ctx, params) if issueErr != nil { @@ -795,7 +795,7 @@ func (s *Server) issueOptionalRefreshToken(ctx context.Context, client storage.R } refreshToken, err := s.issueRefreshToken(ctx, client.ID(), grant, binding) if err != nil { - return newError(ErrorServerError, 500, "failed to issue refresh token", err) + return refreshTokenIssueFailure(err) } // Recomputed rather than threaded through issueRefreshToken's // return: the caller already gets the raw value back, and this From 7e776044c4a467da8bb3288d9528e2523e6c1909 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Wed, 25 Nov 2026 22:41:31 +0800 Subject: [PATCH 2/4] test(sqlstore): expect invalid_grant from a code exchange losing the race A code exchange whose grant a racing reuse revokes while it stores its refresh token now answers invalid_grant rather than server_error. The race tests accept that answer, and TestServerCodeReuseRacingIssuanceIsInvalidGrant is no longer skipped. The server_error shapes FAPIgo answered before are still accepted, but only when the tests are built against a released FAPIgo rather than the tree beside this module (go.mod's replace dropped, as CI's run against the required release does), since that release may predate the change. Co-Authored-By: Claude Opus 5.5 --- sqlstore/server_concurrency_test.go | 64 ++++++++++++++++++++--------- 1 file changed, 45 insertions(+), 19 deletions(-) diff --git a/sqlstore/server_concurrency_test.go b/sqlstore/server_concurrency_test.go index 33d2ac50..2dc112f2 100644 --- a/sqlstore/server_concurrency_test.go +++ b/sqlstore/server_concurrency_test.go @@ -4,6 +4,8 @@ import ( "context" "errors" "net/url" + "os" + "strings" "sync" "testing" "time" @@ -135,19 +137,26 @@ func (r *serverRace) wantRefused(what string, issued server.TokenResult) { // isRevokedWhileIssued reports whether err is a token request refused // because its grant was revoked while its refresh token was being -// stored. Today that is a server_error, in one of two forms, depending +// stored: invalid_grant, "the grant has been revoked". FAPIgo before +// v0.86.0 answered server_error instead, in one of two forms, depending // on which of the server's two checks after storing the token saw the -// revocation: -// - the check that the grant isn't revoked: its cause is the -// invalid_grant that check found; -// - the check that the grant registry still lists the grant: its -// cause is the server's (unexported) "revoked while its refresh -// token was being issued" error, matched here by its text. -// -// See TestServerCodeReuseRacingIssuanceIsInvalidGrant. +// revocation (the check that the grant isn't revoked: its cause is the +// invalid_grant that check found; the check that the grant registry +// still lists the grant: its cause is the server's "revoked while its +// refresh token was being issued" error, matched by its text). Those +// forms are accepted only when these tests are built against a released +// FAPIgo (fapigoFromTree): CI also runs them against the release this +// module's go.mod requires, which may predate v0.86.0. Built against the +// tree beside it, as they are otherwise, only invalid_grant is. func isRevokedWhileIssued(err error) bool { var outer *server.Error - if !errors.As(err, &outer) || outer.Code() != server.ErrorServerError { + if !errors.As(err, &outer) { + return false + } + if outer.Code() == server.ErrorInvalidGrant { + return outer.PublicDescription() == "the grant has been revoked" + } + if fapigoFromTree || outer.Code() != server.ErrorServerError { return false } cause := errors.Unwrap(outer) @@ -158,14 +167,33 @@ func isRevokedWhileIssued(err error) bool { return cause != nil && cause.Error() == "the grant was revoked while its refresh token was being issued" } +// fapigoFromTree reports whether this module's go.mod replaces FAPIgo +// with the tree beside it, so these tests are built against that tree, +// not a released version (CI's run against the release drops the +// replace with go mod edit). A test binary carries no build info about +// its dependencies, so go.mod is read instead. +var fapigoFromTree = func() bool { + mod, err := os.ReadFile("go.mod") + if err != nil { + return false + } + for line := range strings.Lines(string(mod)) { + if strings.HasPrefix(strings.TrimSpace(line), "replace github.com/idfoundry/fapigo =>") { + return true + } + } + return false +}() + // Concurrent exchanges of one authorization code: at most one issues // tokens and every other is invalid_grant, and the others' reuse of the // code revokes what the one issued (RFC 6749 §4.1.2) — its access token // at the resource server and its refresh token at the server — however // the reuse and the issuance interleave. None may issue: the exchange // that redeemed the code stores its refresh token and then confirms the -// code's grant isn't revoked, and a reuse may have revoked it by then -// (isRevokedWhileIssued), so nothing is issued. +// code's grant isn't revoked, and a reuse may have revoked it by then, +// so it withdraws the token and is invalid_grant too +// (isRevokedWhileIssued). func TestServerConcurrentCodeExchanges(t *testing.T) { forEachDialect(t, func(t *testing.T, dialect sqlstore.Dialect) { for name, grants := range grantStores { @@ -187,17 +215,15 @@ func TestServerConcurrentCodeExchanges(t *testing.T) { // When a reuse of an authorization code revokes its grant while the // exchange that redeemed it is storing its refresh token, that exchange -// issues nothing, as it must — but it answers server_error (500), a -// store failure to the client, rather than invalid_grant: the -// confirmation that the grant isn't revoked (confirmGrantNotRevoked) -// finds invalid_grant, and the exchange wraps every failure to issue a -// refresh token as server_error. +// issues nothing and answers invalid_grant (400), the grant refused, not +// the server_error (500) of a store failure: every loser of the race is +// invalid_grant. (Against a FAPIgo release before v0.86.0, which +// answered server_error, isRevokedWhileIssued accepts that too.) func TestServerCodeReuseRacingIssuanceIsInvalidGrant(t *testing.T) { - t.Skip("the exchange whose grant a racing reuse revokes answers server_error, not invalid_grant; awaiting a decision") forEachDialect(t, func(t *testing.T, dialect sqlstore.Dialect) { r := newServerRace(t, dialect, grantStores["Grants"], false) for range serverRaceIterations { - r.checkCodeExchanges(r.raceCodeExchanges(), isInvalidGrant) + r.checkCodeExchanges(r.raceCodeExchanges(), isInvalidGrant, isRevokedWhileIssued) } }) } From a0575f7278ca73f76d38799512dc6b8f24df988e Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Wed, 25 Nov 2026 22:41:31 +0800 Subject: [PATCH 3/4] test: add mutants for invalid_grant on a grant revoked during issuance Covers the mapping of a grant revoked while its refresh token was issued to invalid_grant, server_error for a store failure or a token that couldn't be withdrawn, and each token path's use of it. Updates the anchors of three existing mutants on the code it changed. Co-Authored-By: Claude Opus 5.5 --- .github/mutation/mutants.json | 120 ++++++++++++++++++++++++++++++++-- 1 file changed, 114 insertions(+), 6 deletions(-) diff --git a/.github/mutation/mutants.json b/.github/mutation/mutants.json index ef091972..ea66c636 100644 --- a/.github/mutation/mutants.json +++ b/.github/mutation/mutants.json @@ -1563,8 +1563,8 @@ { "id": "srv-issuance-rechecks-revocation", "file": "server/grant_revocation.go", - "old": "if revErr := s.checkGrantNotRevoked(ctx, grant); revErr != nil {\n\t\treturn s.withdrawRefreshToken(", - "new": "if revErr := s.checkGrantNotRevoked(ctx, grant); revErr != nil && false {\n\t\treturn s.withdrawRefreshToken(", + "old": "if revErr == nil {\n\t\treturn nil\n\t}\n\tcause := fmt.Errorf(\"confirm the grant isn't revoked", + "new": "if revErr == nil || true {\n\t\treturn nil\n\t}\n\tcause := fmt.Errorf(\"confirm the grant isn't revoked", "module": "root", "packages": [ "./server" @@ -1575,8 +1575,8 @@ { "id": "srv-issuance-recheck-fails-closed", "file": "server/grant_revocation.go", - "old": "if revErr := s.checkGrantNotRevoked(ctx, grant); revErr != nil {\n\t\treturn s.withdrawRefreshToken(", - "new": "if revErr := s.checkGrantNotRevoked(ctx, grant); revErr != nil && revErr.Code() == ErrorInvalidGrant {\n\t\treturn s.withdrawRefreshToken(", + "old": "if revErr == nil {\n\t\treturn nil\n\t}\n\tcause := fmt.Errorf(\"confirm the grant isn't revoked", + "new": "if revErr == nil || revErr.Code() != ErrorInvalidGrant {\n\t\treturn nil\n\t}\n\tcause := fmt.Errorf(\"confirm the grant isn't revoked", "module": "root", "packages": [ "./server" @@ -1599,8 +1599,8 @@ { "id": "srv-withdrawal-failure-keeps-entry", "file": "server/grant_registry.go", - "old": "if err := s.deps.Grants.RevokeRefreshToken(ctx, refreshTokenHash); err != nil {\n\t\treturn errors.Join(cause, fmt.Errorf(\"withdraw the refresh token: %w\", err))", - "new": "if err := s.deps.Grants.RevokeRefreshToken(ctx, refreshTokenHash); err != nil {\n\t\t_ = s.forgetRevokedRefreshToken(ctx, refreshTokenHash)\n\t\treturn errors.Join(cause, fmt.Errorf(\"withdraw the refresh token: %w\", err))", + "old": "if err := s.deps.Grants.RevokeRefreshToken(ctx, refreshTokenHash); err != nil {\n\t\treturn errors.Join(cause, fmt.Errorf(\"%w: %w\", errRefreshTokenNotWithdrawn, err))", + "new": "if err := s.deps.Grants.RevokeRefreshToken(ctx, refreshTokenHash); err != nil {\n\t\t_ = s.forgetRevokedRefreshToken(ctx, refreshTokenHash)\n\t\treturn errors.Join(cause, fmt.Errorf(\"%w: %w\", errRefreshTokenNotWithdrawn, err))", "module": "root", "packages": [ "./server" @@ -5070,5 +5070,113 @@ ], "run": "^(TestPermittedArrayStrings|TestAutomaticRegistrationRARTypesAbsentUnderEachOperator)$", "why": "a one_of alone bounds an omitted array parameter to its listed values, not to nothing" + }, + { + "id": "race-invalid-grant-mapping", + "file": "server/grant_registry.go", + "old": "if errors.Is(err, errGrantRevokedWhileIssued) && !errors.Is(err, errRefreshTokenNotWithdrawn) {", + "new": "if errors.Is(err, errGrantRevokedWhileIssued) && !errors.Is(err, errRefreshTokenNotWithdrawn) && false {", + "module": "root", + "packages": [ + "./server" + ], + "run": "^(TestGrantRevokedWhileIssuedIsInvalidGrant|TestGrantEntryGoneWhileIssuedIsInvalidGrant)$", + "why": "a grant revoked while its refresh token was issued is invalid_grant, not server_error" + }, + { + "id": "race-invalid-grant-only-revoked", + "file": "server/grant_registry.go", + "old": "if errors.Is(err, errGrantRevokedWhileIssued) && !errors.Is(err, errRefreshTokenNotWithdrawn) {", + "new": "if (true || errors.Is(err, errGrantRevokedWhileIssued)) && !errors.Is(err, errRefreshTokenNotWithdrawn) {", + "module": "root", + "packages": [ + "./server" + ], + "run": "^(TestGrantRevocationUncheckableWhileIssuedIsServerError|TestGrantEntryGoneWhileIssuedIsInvalidGrant)$", + "why": "a store failure while issuing a refresh token stays server_error" + }, + { + "id": "race-invalid-grant-withdraw-failure", + "file": "server/grant_registry.go", + "old": "if errors.Is(err, errGrantRevokedWhileIssued) && !errors.Is(err, errRefreshTokenNotWithdrawn) {", + "new": "if errors.Is(err, errGrantRevokedWhileIssued) && (true || !errors.Is(err, errRefreshTokenNotWithdrawn)) {", + "module": "root", + "packages": [ + "./server" + ], + "run": "^(TestGrantRevokedWhileIssuedWithdrawalFailsIsServerError|TestGrantEntryGoneWhileIssuedIsInvalidGrant)$", + "why": "a revoked grant whose refresh token can't be withdrawn is a store failure, server_error: a live token may remain" + }, + { + "id": "race-invalid-grant-revocation-found", + "file": "server/grant_revocation.go", + "old": "if revErr.Code() == ErrorInvalidGrant {", + "new": "if revErr.Code() == ErrorInvalidGrant && false {", + "module": "root", + "packages": [ + "./server" + ], + "run": "^(TestGrantRevokedWhileIssuedIsInvalidGrant|TestCodeReuseWhileIssuedIsInvalidGrant|TestCIBAGrantRevokedWhileIssuedIsInvalidGrant)$", + "why": "the check that the grant isn't revoked marks a revocation found after storing the token as revoked-while-issued" + }, + { + "id": "race-invalid-grant-revocation-uncheckable", + "file": "server/grant_revocation.go", + "old": "if revErr.Code() == ErrorInvalidGrant {", + "new": "if revErr.Code() == ErrorInvalidGrant || true {", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestGrantRevocationUncheckableWhileIssuedIsServerError$", + "why": "a revocation store that can't answer after the token is stored is server_error, not invalid_grant" + }, + { + "id": "race-invalid-grant-ciba", + "file": "server/backchannel_token.go", + "old": "return refreshTokenIssueFailure(err)", + "new": "return newError(ErrorServerError, 500, \"failed to issue refresh token\", err)", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestCIBAGrantRevokedWhileIssuedIsInvalidGrant$", + "why": "the CIBA token request answers invalid_grant for a grant revoked while its refresh token was issued" + }, + { + "id": "race-invalid-grant-embedder", + "file": "server/embedder_refresh.go", + "old": "err := refreshTokenIssueFailure(issueErr)", + "new": "err := newError(ErrorServerError, 500, \"failed to issue refresh token\", issueErr)", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestGrantRevokedWhileIssuedIsInvalidGrant$", + "why": "IssueRefreshToken answers invalid_grant for a grant revoked while its refresh token was issued" + }, + { + "id": "race-invalid-grant-code-recorder", + "file": "server/token.go", + "old": "\t\treturn refreshTokenIssueFailure(err)\n\t}\n\taccessToken, accessKey, issueErr", + "new": "\t\treturn newError(ErrorServerError, 500, \"failed to issue refresh token\", err)\n\t}\n\taccessToken, accessKey, issueErr", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestCodeReuseWhileIssuedIsInvalidGrant$", + "why": "a code exchange recording its tokens together answers invalid_grant when a reuse revokes the grant mid-issuance" + }, + { + "id": "race-invalid-grant-code-optional", + "file": "server/token.go", + "old": "\t\treturn refreshTokenIssueFailure(err)\n\t}\n\t// Recomputed", + "new": "\t\treturn newError(ErrorServerError, 500, \"failed to issue refresh token\", err)\n\t}\n\t// Recomputed", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestCodeReuseWhileIssuedIsInvalidGrant$", + "why": "a code exchange issuing its refresh token last answers invalid_grant when a reuse revokes the grant mid-issuance" } ] From b9943e21352318e2bda0e8c408254d6a44a14343 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Wed, 25 Nov 2026 23:40:04 +0800 Subject: [PATCH 4/4] test(fapitest): refuse a revoked grant's code that issues no refresh token The server now answers a grant revoked while its refresh token is issued with invalid_grant, so a code exchange whose grant was revoked before redemption is refused with the same code whether the check before issuance or the re-check after it refuses it. The test of the check before issuance asked for a refresh token, so it no longer told the two apart. This adds the same exchange without offline_access, where nothing after redemption re-checks the grant, and runs the check's mutant against it too. Co-Authored-By: Claude Opus 5.5 --- .github/mutation/mutants.json | 2 +- fapitest/grant_revocation_test.go | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/.github/mutation/mutants.json b/.github/mutation/mutants.json index ea66c636..e4be4da1 100644 --- a/.github/mutation/mutants.json +++ b/.github/mutation/mutants.json @@ -1076,7 +1076,7 @@ "packages": [ "./fapitest" ], - "run": "^TestRevokeGrantBeforeTheCodeIsRedeemed$", + "run": "^(TestRevokeGrantBeforeTheCodeIsRedeemed|TestRevokeGrantBeforeAnOnlineCodeIsRedeemed)$", "why": "a code whose grant was revoked before redemption is refused" }, { diff --git a/fapitest/grant_revocation_test.go b/fapitest/grant_revocation_test.go index 5d2706cb..e21d585e 100644 --- a/fapitest/grant_revocation_test.go +++ b/fapitest/grant_revocation_test.go @@ -123,6 +123,29 @@ func TestRevokeGrantBeforeTheCodeIsRedeemed(t *testing.T) { } } +// TestRevokeGrantBeforeAnOnlineCodeIsRedeemed: a code whose grant was +// revoked before redemption is refused even when the exchange would +// issue no refresh token, so nothing after redemption re-checks the +// grant: the check before issuance is all that refuses it. +func TestRevokeGrantBeforeAnOnlineCodeIsRedeemed(t *testing.T) { + h := fapitest.New(t, fapitest.Config{Profile: server.ProfileFAPISecurity, GrantID: "grant-1"}) + ctx := context.Background() + session, err := h.Client.BeginAuthorization(ctx, client.BeginAuthorizationRequest{Scope: []string{"openid", "accounts"}}) + if err != nil { + t.Fatalf("BeginAuthorization: %v", err) + } + callback, err := h.CaptureCallback(ctx, session) + if err != nil { + t.Fatalf("CaptureCallback: %v", err) + } + if err := h.RevokeGrant(ctx, "grant-1"); err != nil { + t.Fatalf("RevokeGrant: %v", err) + } + if _, err := h.RunAuthorizationCodeFlowWithCallback(ctx, session.Handle(), callback); serverErrorCodeOf(err) != "invalid_grant" { + t.Fatalf("code exchange after revocation = %v, want invalid_grant", err) + } +} + // TestRevokeGrantLeavesOtherGrantsAlone covers tokens from a grant with // no grant ID: revoking a grant ID doesn't touch them, and they carry no // grant_id claim.