From 41949076d37d3dae7a80fe1d067b64995850ff7b Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 19 Nov 2026 00:19:59 +0800 Subject: [PATCH] fix(server): confirm a refresh token's grant by its key Each refresh token issued with a GrantRegistry set listed all of its end user's grant entries to confirm its own was still recorded, so the cost of issuance grew with the user's grants. In sqlstore that meant fetching and unsealing every row. memstore scanned every subject's entries. storage.GrantListing gains Key. With it set, a store may return only that entry, which the server now asks for. A store that ignores Key and lists the subject's entries as before is still correct, only slower. memstore honours it with one map lookup. The registry contract checks the entry is listed by key and never another subject's. Co-Authored-By: Claude Opus 5.5 --- server/grant_registry.go | 7 ++++-- server/grant_registry_test.go | 38 ++++++++++++++++++++++++++++ storage/contract.go | 40 ++++++++++++++++++++++++++++++ storage/grant_registry.go | 11 +++++++- storage/memstore/grant_registry.go | 18 +++++++++++--- storage/memstore/memstore_test.go | 17 +++++++++++++ 6 files changed, 125 insertions(+), 6 deletions(-) diff --git a/server/grant_registry.go b/server/grant_registry.go index 501b7486..88f19eaf 100644 --- a/server/grant_registry.go +++ b/server/grant_registry.go @@ -127,11 +127,14 @@ func (s *Server) confirmGrantRecorded(ctx context.Context, subject string, refre if s.deps.GrantRegistry == nil { return nil } - entries, err := s.deps.GrantRegistry.ListGrants(ctx, storage.GrantListing{SubjectKey: s.grantSubjectKey(subject), Now: s.deps.Clock.Now()}) + // Key asks for this entry alone, so the cost doesn't grow with the + // subject's other grants; a store that lists them all anyway is + // searched below. + key := grantEntryKey(refreshTokenHash) + entries, err := s.deps.GrantRegistry.ListGrants(ctx, storage.GrantListing{SubjectKey: s.grantSubjectKey(subject), Now: s.deps.Clock.Now(), Key: key}) if err != nil { return s.withdrawRefreshToken(ctx, refreshTokenHash, fmt.Errorf("confirm the grant is recorded: %w", err)) } - key := grantEntryKey(refreshTokenHash) if slices.ContainsFunc(entries, func(e storage.GrantEntry) bool { return e.Key == key }) { return nil } diff --git a/server/grant_registry_test.go b/server/grant_registry_test.go index e634cf3c..32ed2e00 100644 --- a/server/grant_registry_test.go +++ b/server/grant_registry_test.go @@ -595,3 +595,41 @@ func TestGrantRevokedWhileIssuedWithdrawalFails(t *testing.T) { t.Fatalf("IssueRefreshToken = %v, want the withdrawal failure reported", err) } } + +// keyRecordingRegistry records the GrantListing.Key of each listing, +// and with ignoreKey lists every one of the subject's entries anyway, as +// a store written before Key existed would. +type keyRecordingRegistry struct { + *memstore.GrantRegistry + ignoreKey bool + keys *[]string +} + +func (r keyRecordingRegistry) ListGrants(ctx context.Context, listing storage.GrantListing) ([]storage.GrantEntry, error) { + *r.keys = append(*r.keys, listing.Key) + if r.ignoreKey { + listing.Key = "" + } + return r.GrantRegistry.ListGrants(ctx, listing) +} + +// TestRefreshTokenIssuanceConfirmsItsOwnEntry: confirming a refresh +// token's grant is still recorded asks for its own entry by key, so its +// cost doesn't grow with the user's other grants, and still issues the +// token from a store that ignores the key and lists them all. +func TestRefreshTokenIssuanceConfirmsItsOwnEntry(t *testing.T) { + for name, ignoreKey := range map[string]bool{"store honours Key": false, "store ignores Key": true} { + t.Run(name, func(t *testing.T) { + var keys []string + h, owner := registryHarness(t, keyRecordingRegistry{memstore.NewGrantRegistry(), ignoreKey, &keys}) + owner.issueRefreshToken() + owner.issueRefreshToken() + if len(keys) != 2 || keys[0] == "" || keys[1] == "" || keys[0] == keys[1] { + t.Fatalf("issuance listed with keys %q, want each its own entry's key", keys) + } + if grants := listGrants(t, h, "user-1"); len(grants) != 2 { + t.Fatalf("ListGrants(user-1) = %d grants, want 2", len(grants)) + } + }) + } +} diff --git a/storage/contract.go b/storage/contract.go index f173b397..26b4f7aa 100644 --- a/storage/contract.go +++ b/storage/contract.go @@ -2022,6 +2022,7 @@ func TestGrantRegistryContract(t *testing.T, factory func() GrantRegistry) { t.Run("ListOnlyUnexpired", func(t *testing.T) { testGrantRegistryListOnlyUnexpired(t, factory) }) t.Run("RecordReplacesByKey", func(t *testing.T) { testGrantRegistryRecordReplacesByKey(t, factory) }) t.Run("Delete", func(t *testing.T) { testGrantRegistryDelete(t, factory) }) + t.Run("ListByKey", func(t *testing.T) { testGrantRegistryListByKey(t, factory) }) } func recordGrantEntry(t *testing.T, registry GrantRegistry, entry NewGrantEntry) { @@ -2122,6 +2123,45 @@ func testGrantRegistryDelete(t *testing.T, factory func() GrantRegistry) { } } +// testGrantRegistryListByKey covers GrantListing.Key: the entry with +// that key is listed while it's the subject's and unexpired, and never +// another subject's entry. A store may list the subject's other entries +// too, so only their absence from another subject's listing is checked. +func testGrantRegistryListByKey(t *testing.T, factory func() GrantRegistry) { + registry := factory() + expires := time.Now().Add(time.Hour) + recordGrantEntry(t, registry, NewGrantEntry{Key: "g1", SubjectKey: "s1", ClientID: "client-1", Record: contractPayload, ExpiresAt: expires}) + recordGrantEntry(t, registry, NewGrantEntry{Key: "g2", SubjectKey: "s1", ClientID: "client-2", Record: contractPayload, ExpiresAt: expires}) + recordGrantEntry(t, registry, NewGrantEntry{Key: "g3", SubjectKey: "s2", ClientID: "client-1", Record: contractPayload, ExpiresAt: expires}) + keyed := func(subjectKey, key string, now time.Time) []string { + t.Helper() + entries, err := registry.ListGrants(context.Background(), GrantListing{SubjectKey: subjectKey, Now: now, Key: key}) + if err != nil { + t.Fatalf("ListGrants(%q, key %q): %v", subjectKey, key, err) + } + keys := make([]string, 0, len(entries)) + for _, e := range entries { + keys = append(keys, e.Key) + } + return keys + } + if got := keyed("s1", "g1", time.Now()); !slices.Contains(got, "g1") || slices.Contains(got, "g3") { + t.Errorf("ListGrants(s1, key g1) = %v, want g1 and nothing of s2's", got) + } + if got := keyed("s2", "g1", time.Now()); slices.Contains(got, "g1") { + t.Errorf("ListGrants(s2, key g1) = %v, want no entry of s1's", got) + } + if got := keyed("s1", "g1", expires); slices.Contains(got, "g1") { + t.Errorf("ListGrants(s1, key g1) at expiry = %v, want g1 not listed", got) + } + if err := registry.DeleteGrant(context.Background(), "g1"); err != nil { + t.Fatalf("DeleteGrant(g1): %v", err) + } + if got := keyed("s1", "g1", time.Now()); slices.Contains(got, "g1") { + t.Errorf("ListGrants(s1, key g1) after deleting it = %v, want g1 not listed", got) + } +} + // TestBackchannelInboxContract exercises factory()'s behavior against // the guarantees BackchannelInbox's documentation promises: entries // round-trip unmodified, are listed only for their own subject and only diff --git a/storage/grant_registry.go b/storage/grant_registry.go index 432849ab..0134ac95 100644 --- a/storage/grant_registry.go +++ b/storage/grant_registry.go @@ -43,6 +43,14 @@ type GrantListing struct { // Now is the server's current time (server.Dependencies.Clock): an // entry whose ExpiresAt isn't after it is not listed. Now time.Time + + // Key, when set, asks only whether the entry with that Key is + // listed: the server sets it to confirm a grant it just recorded is + // still there, on each refresh token it issues. A store should then + // return at most that entry, found by its key, so the cost doesn't + // grow with the subject's other grants. A store that ignores Key and + // lists all of the subject's entries is still correct, only slower. + Key string } // GrantEntry is one entry ListGrants returns. @@ -65,7 +73,8 @@ type GrantEntry struct { // // RecordGrant stores entry, replacing any entry with the same Key. // ListGrants returns every entry with listing.SubjectKey whose ExpiresAt -// is after listing.Now, in any order. DeleteGrant deletes the entry with +// is after listing.Now, in any order; with listing.Key set, it may return +// only the entry with that Key. DeleteGrant deletes the entry with // key, and succeeds when there is none. A store that couldn't answer // wraps ErrStoreUnavailable. Run TestGrantRegistryContract against an // implementation. diff --git a/storage/memstore/grant_registry.go b/storage/memstore/grant_registry.go index fd2d2c16..365ad462 100644 --- a/storage/memstore/grant_registry.go +++ b/storage/memstore/grant_registry.go @@ -32,16 +32,28 @@ func (r *GrantRegistry) RecordGrant(_ context.Context, entry storage.NewGrantEnt func (r *GrantRegistry) ListGrants(_ context.Context, listing storage.GrantListing) ([]storage.GrantEntry, error) { r.mu.Lock() defer r.mu.Unlock() + listed := func(e storage.NewGrantEntry) bool { + return e.SubjectKey == listing.SubjectKey && listing.Now.Before(e.ExpiresAt) + } var out []storage.GrantEntry + if listing.Key != "" { + if e, ok := r.entries[listing.Key]; ok && listed(e) { + out = append(out, grantEntryOf(e)) + } + return out, nil + } for _, e := range r.entries { - if e.SubjectKey != listing.SubjectKey || !listing.Now.Before(e.ExpiresAt) { - continue + if listed(e) { + out = append(out, grantEntryOf(e)) } - out = append(out, storage.GrantEntry{Key: e.Key, ClientID: e.ClientID, Record: cloneRawMessage(e.Record), ExpiresAt: e.ExpiresAt}) } return out, nil } +func grantEntryOf(e storage.NewGrantEntry) storage.GrantEntry { + return storage.GrantEntry{Key: e.Key, ClientID: e.ClientID, Record: cloneRawMessage(e.Record), ExpiresAt: e.ExpiresAt} +} + // DeleteGrant implements storage.GrantRegistry. func (r *GrantRegistry) DeleteGrant(_ context.Context, key string) error { r.mu.Lock() diff --git a/storage/memstore/memstore_test.go b/storage/memstore/memstore_test.go index e9e0219f..d87cab31 100644 --- a/storage/memstore/memstore_test.go +++ b/storage/memstore/memstore_test.go @@ -28,6 +28,23 @@ func TestGrantRegistryContract(t *testing.T) { storage.TestGrantRegistryContract(t, func() storage.GrantRegistry { return NewGrantRegistry() }) } +// GrantRegistry honours GrantListing.Key: only that entry is listed, +// not the subject's others. +func TestGrantRegistryListsByKeyAlone(t *testing.T) { + r := NewGrantRegistry() + ctx := context.Background() + expires := time.Now().Add(time.Hour) + for _, key := range []string{"g1", "g2"} { + if err := r.RecordGrant(ctx, storage.NewGrantEntry{Key: key, SubjectKey: "s1", ClientID: "c", ExpiresAt: expires}); err != nil { + t.Fatal(err) + } + } + entries, err := r.ListGrants(ctx, storage.GrantListing{SubjectKey: "s1", Now: time.Now(), Key: "g1"}) + if err != nil || len(entries) != 1 || entries[0].Key != "g1" { + t.Fatalf("ListGrants(s1, key g1) = %+v, %v, want g1 alone", entries, err) + } +} + func TestBackchannelInboxContract(t *testing.T) { storage.TestBackchannelInboxContract(t, func() storage.BackchannelInbox { return NewBackchannelInbox() }) }