Skip to content

Make Redis per-provider upstream delete atomic - #7303

Merged
jhrozek merged 1 commit into
mainfrom
redis-atomic-provider-delete
Nov 25, 2026
Merged

jhrozek merged 1 commit into
mainfrom
redis-atomic-provider-delete

Conversation

@jhrozek

@jhrozek jhrozek commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Summary

RedisStorage.DeleteUpstreamTokensForProvider sent four separate commands: GET the row to learn its user ID, DEL the row, then SREM it from the session index and from the user's reverse-index set. If a write to the same row landed between the DEL and the SREMs, the result was a live row missing from both index sets. GetAllUpstreamTokens and GetLatestUpstreamTokensForUser could not see it, and DeleteUser would not delete it, until the next write of that row. With session-keyed storage a concurrent write to the same key is unlikely, but with user-keyed storage ("User-keyed upstream storage behind the embedder option" (#7263)) every client of a user writes the same key. The write paths were already atomic Lua scripts; the delete was the odd one out.

  • The GET/DEL/SREM/SREM sequence is replaced by one Lua script, in the same style as storeUpstreamTokensScript.
  • Rows with no usable user ID (the null placeholder, undecodable JSON, empty, missing or JSON-null user_id) are still deleted and removed from the session index; only the user-set removal is skipped, as before.
  • Before changing anything, the script checks that the session index and the user set are sets (or absent) and otherwise fails with WRONGTYPE. Redis does not roll back a script that fails partway, and the row is the only record of which user set to clean up, so deleting it first and then failing would leave a stale user-set member that DeleteUser later trusts.
  • Any Redis error now fails the call. Previously a failed GET was ignored and failed SREMs were only logged.

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (go test -race ./pkg/authserver/storage/)
  • E2E tests (task test-e2e)
  • Linting (task lint-fix)
  • Manual testing (describe below)

New tests in redis_test.go (miniredis):

  • the row leaves both index sets, and a sibling provider's row and index member stay;
  • each unusable-row variant is deleted without error, and the user set is left alone;
  • a wrong-type session index or user set fails the call with nothing changed, and a retry after repairing the key removes everything;
  • a go-redis hook stores the row under a different user right after any standalone command that names the row. It must never fire. Run against the old four-command code, and against a variant that GETs the owner before running the script, the test fails; against the script it passes.

Does this introduce a user-facing change?

No change visible to MCP clients. Both in-tree callers (the refresher after a failed persist of a rotated refresh token, and cleanupUpstreamTokens in the callback handler) already log a delete error and carry on, so on a Redis fault operators may now see that caller's warning where before they saw a cleanup warning from storage, or nothing for a failed GET.

Special notes for reviewers

  • The script type-checks the index keys and requires user_id to be a non-empty string. The store and CAS scripts do neither; they are left unchanged here.
  • Like the write scripts, the user-set key is built inside the script from the {ns:name}-tagged key prefix rather than declared in KEYS, so it lands in the same cluster slot. Declaring it in KEYS would be a separate change covering all three scripts.
  • DeleteUpstreamTokens and DeleteUser are still multi-command and have the same class of race. They are a separate change.
  • No docs change: neither docs/redis-storage.md nor docs/arch/11-auth-server-storage.md describes the delete steps.

@jhrozek
jhrozek requested a review from ChrisJBurns as a code owner November 25, 2026 13:27
@github-actions github-actions Bot added the size/S Small PR: 100-299 lines changed label Nov 25, 2026
rdimitrov
rdimitrov previously approved these changes Nov 25, 2026

@rdimitrov rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve: the single Lua script is the right fix for the delete/index race.

Design: The row delete and both index SREMs now run atomically in redis.go, the owner of row/index consistency, in the same style as the existing store and CAS scripts. The user-set key built inside the script matches redisSetKey exactly and shares the {ns:name} hash tag in the prefix, so Cluster slot consistency holds. Both non-test callers (refresher.go:269, callback.go:837) only log errors, so they are covered, and there is no API, CLI or persisted-format change. DeleteUpstreamTokens and DeleteUser keep the same race; the PR says it defers them, which is fine.

Non-blocking notes (not required for approval):

  1. redis.go, WRONGTYPE precheck: if an index key (or the row key itself) holds the wrong type, the delete now fails and leaves the row. Before, the row was deleted and only the SREM warned. In the refresher path (refresher.go:269) that row is the dead rotated refresh token, so a corrupted index plus a persist failure leaves it to be replayed and trip the IdP's reuse detection. This needs prior key corruption, so it is rare. Either state the fail-closed behaviour in the PR body, or skip the SREM on a wrong-type index key, still DEL the row, and return a distinct status that Go logs.
  2. The new tests run on miniredis only. redis_integration_test.go already runs real Redis, so one delete plus WRONGTYPE case there would pin the real TYPE/error_reply behaviour.

🤖 Reviewed with Claude Code

@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.99%. Comparing base (1082992) to head (ad5f00d).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7303      +/-   ##
==========================================
+ Coverage   81.95%   81.99%   +0.04%     
==========================================
  Files         922      923       +1     
  Lines       93367    93575     +208     
==========================================
+ Hits        76521    76730     +209     
+ Misses      16841    16840       -1     
  Partials        5        5              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

DeleteUpstreamTokensForProvider ran GET, DEL and two SREMs as separate
commands. A write to the same row landing between the DEL and the SREMs
left a live row missing from the session index and the user set, so
GetAllUpstreamTokens, GetLatestUpstreamTokensForUser and DeleteUser
could not see it until the next write. Writes were already atomic Lua
scripts; the delete was the odd one out.

Replace the sequence with one Lua script that reads the stored user ID,
deletes the row and removes it from both index sets. Rows with no
usable user ID (placeholder, undecodable, empty or null user_id) are
still deleted and removed from the session index. Any Redis error now
fails the call instead of being logged.

The script checks that both index keys are sets (or absent) before
changing anything and fails with WRONGTYPE otherwise. Redis does not
roll back a script that errors partway, and the row is the only record
of which user set to clean up, so deleting it first would leave a stale
user-set member that DeleteUser later trusts.

Tests cover both index sets, the unusable-row cases, a wrong-type
index key on each side, and a go-redis hook that stores the row under
another user right after any standalone command on it. The hook fails
on the old implementation and on one that reads the owner before the
script, and never fires on the script itself.

Co-authored-by: Mecatl <[email protected]>
@jhrozek

jhrozek commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

@rdimitrov @ChrisJBurns the lint job on this PR was failing, so I amended the commit and force-pushed. The branch is now ad5f00db0, replacing dcf59e02e. The code change is the same.

The failure was golangci-lint's unparam check on the test helper upstreamRowInvariant in pkg/authserver/storage/redis_test.go. Every caller passed the same sessionID and providerName, so I removed those two parameters and hardcoded "session-1" and "provider-a" inside the helper. userID stays a parameter because the tests use both user-1 and user-2. Nothing in redis.go changed.

task lint is clean now. I haven't rerun the Redis tests locally, so CI is the first run of them on the amended commit.

Because the commit changed, GitHub may have dismissed the earlier approval, so it may need a re-approval.

@github-actions github-actions Bot added size/S Small PR: 100-299 lines changed and removed size/S Small PR: 100-299 lines changed labels Nov 25, 2026
@jhrozek
jhrozek merged commit 8eccc0f into main Nov 25, 2026
47 checks passed
@jhrozek
jhrozek deleted the redis-atomic-provider-delete branch November 25, 2026 15:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/S Small PR: 100-299 lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants