Skip to content

Bound per-user upstream token reads by context - #7351

Merged
jhrozek merged 1 commit into
stacklok:mainfrom
jhrozek:credential-read-2-bounded-reads
Nov 27, 2026
Merged

jhrozek merged 1 commit into
stacklok:mainfrom
jhrozek:credential-read-2-bounded-reads

Conversation

@jhrozek

@jhrozek jhrozek commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Summary

  • The per-user upstream token read (GetValidTokensForUser) kept waiting on the refresher after the caller's context ended, up to the refresher's 30s timeout. The refresh-grant guard worked around that with its own goroutine and select, so any other caller of the reader would have hung. This moves the bound into the reader.
  • GetValidTokensForUser returns when the caller's context ends. The refresh runs in a worker detached from the caller's cancellation, so a refresh that has started can still save the rotated row. If the context ends while an expired access token refreshes, the error matches both ErrRefreshFailed and the context error.
  • Session reads (GetValidTokens, GetAllUpstreamCredentials) still wait for the refresher, because their callers hold a generation lease on the context until the read returns.
  • The user-keyed refresh-grant guard drops its goroutine and relies on the reader. An error that arrives after the guard's deadline is treated as uncertain, so the grant goes through and is not revoked on a late answer.
  • When the caller leaves during an ID-token-only refresh (access token live, ID token expired) the read returns the stored credential. The worker records the ID-token refresh suppression itself (owner's row only), and if that refresh fails it records the failure backoff and logs one WARN. Otherwise every later read would call the provider again.
  • The unexpected token_type error no longer includes the provider's value.

Docs: docs/arch/11-auth-server-storage.md and the reader's doc comments describe the new contract, including that callers should log a failure category, not err.Error().

Type of change

  • Bug fix

Test plan

  • Unit tests (task test): run on the touched packages (./pkg/auth/upstreamtoken/, ./pkg/authserver/) with -race and the Taskfile's flags, not the whole repo
  • E2E tests (task test-e2e)
  • Linting (task lint-fix)
  • Manual testing (describe below)

New tests cover: cancel during an expired-access-token refresh (returns promptly, row still saved), cancel during an ID-token-only refresh that then fails (one WARN, no second provider call), cancel during one where the refresher clears the row (first read returns the credential, the next needs authorization), a context that has already ended before the read, and session reads still waiting.

Changes

File Change
pkg/auth/upstreamtoken/service.go refreshDetached bounds the wait for per-user reads; the worker runs detached, sends its result first, then records suppression or the failure backoff
pkg/auth/upstreamtoken/types.go Reader contract: prompt return on context end, error matching, log-a-category rule
pkg/authserver/refresh_grant_guard_user_keyed.go Guard calls the reader inline; a late failure becomes the context error
pkg/authserver/upstream/oauth2.go token_type error omits the provider's value
docs/arch/11-auth-server-storage.md Describes the above
*_test.go New and updated tests

Does this introduce a user-facing change?

For operators:

  • Before: a refresh-grant check against a slow identity provider could keep a goroutine and the reader blocked for up to 30s after the guard gave up. After: the reader returns when its context ends. The refresh still finishes in the background.
  • Before: an ID-token-only refresh that failed after the caller left logged nothing and was retried on the next read. After: one WARN ("upstream ID token refresh failed after the caller left") and a one-minute backoff, as for a failure the caller saw.
  • The unexpected token_type error text no longer contains the provider's value.

No change for clients of the token endpoint.

Special notes for reviewers

  • Deliberate difference from the session reads: only the per-user path stops waiting. Session reads keep waiting because of the generation lease. This is why refreshOrFail branches on expectedUserID.
  • One-read window: if the caller leaves during an ID-token-only refresh and the refresher then clears the row (rotated refresh token could not be saved), that read still returns the stored credential and the next read reports needs-authorization. Waiting for the refresher would undo the point of this change. The refresh-grant guard never sees this case, because it skips the reader when the access token is live.
  • Guard bound: the guard no longer has its own timeout. A check can run up to the storage client's own timeout (about 3s for Redis, because go-redis ignores context deadlines on socket I/O) past the guard's 10s check timeout.
  • Two narrow races, left as they are: if the context ends between the worker's check and the caller's, either no backoff is recorded (one extra provider call) or the failure is logged twice. Neither can produce a wrong grant.
  • Unrelated cleanup: userRowSession in user_reader_test.go lost its parameter because every caller passed the same user. It is test-only and unexported, so it does not affect embedders.
  • SEP and mecatl are not affected today: they pin ToolHive tags that do not contain the per-user reader or the user-keyed guard.

Before, GetValidTokensForUser waited for the refresher even after the caller context ended. Now it returns promptly while an in-flight refresh can still persist the row. Keep session reads synchronous so the caller can hold its generation lease until refresh completes.

Let the user-keyed grant guard rely on the reader for cancellation. A failure that reaches the guard after its deadline is treated as uncertain, so the grant goes through instead of being revoked on a late not-found answer. Omit the provider-supplied token type from errors that reach operator logs.

Run the refresh worker detached from the caller's cancellation, so a caller that leaves early cannot abort a refresh before the provider is called. Record the ID-token refresh suppression from the worker, for the owner's row only, after it sends its result, so a refresh that finishes after the caller left does not make the next read call the provider again. When that refresh fails after the caller left, record the failure backoff and log it once, so a failing provider is not called on every read. Document that callers should log a failure category, not error text, and what a read returns when the context ends during an ID-token-only refresh, including that a row the refresher clears in the meantime is reported on the next read.

Co-authored-by: Mecatl <[email protected]>
@jhrozek
jhrozek requested a review from ChrisJBurns as a code owner November 27, 2026 09:25
@codecov

codecov Bot commented Nov 27, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.65217% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.57%. Comparing base (4b9f678) to head (2b539cd).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pkg/auth/upstreamtoken/service.go 95.23% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7351      +/-   ##
==========================================
- Coverage   82.57%   82.57%   -0.01%     
==========================================
  Files         940      941       +1     
  Lines       96639    96722      +83     
==========================================
+ Hits        79802    79866      +64     
- Misses      16832    16851      +19     
  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.

@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.

Approving. This matches the reader contract in #7263 and what #6407 needs from it: when a client leaves a vMCP tool call during a refresh, the read no longer blocks, and a rotated refresh token is still saved.

Verified locally (merged with main, -race):

  • The touched packages plus ./pkg/auth/..., ./pkg/authserver/... and ./pkg/vmcp/auth/... pass.
  • The new and changed reader and guard tests pass 10 runs in a row with no flakes.
  • The hung-IdP guard case, which uses the real refresher, is still cut off at the check timeout now that the guard has no goroutine of its own.
  • WithoutCancel keeps the remembered-rejection marker the guard sets on its context.

The trade-offs in the description look right to me: the one-read window, the guard running past its timeout by up to the Redis client's own timeout, and the two narrow races. None of them can produce a wrong grant.

@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.

LGTM. GetValidTokensForUser is the only path that stops waiting. The session reads keep waiting because they pass an empty expectedUserID, and the user-keyed guard is the only non-test caller of the per-user reader. The detached worker can't leak or double-spend a refresh token:

  • its result channel is buffered;
  • the refresher's shared in-flight call is keyed by row ID, so a second read joins the running refresh;
  • suppression and backoff are keyed by row ID plus ID token, so they can't attach to a row that a new sign-in replaced.

go test -race -count=3 ./pkg/auth/upstreamtoken/ ./pkg/authserver/ passes, and so do the new cancellation tests at -count=30. A downstream embedder builds against this head, and its broker tests pass.

Not blocking: the detached worker isn't tracked by shutdown, so it can touch storage up to about 30s after Close. Main's guard goroutine already outlived its caller the same way, so this is not a regression.

@jhrozek
jhrozek merged commit 8863605 into stacklok:main Nov 27, 2026
44 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants