Skip to content

Add per-user upstream credential reads - #7323

Merged
jhrozek merged 2 commits into
mainfrom
user-keyed-storage-v2-2-readers
Nov 26, 2026
Merged

jhrozek merged 2 commits into
mainfrom
user-keyed-storage-v2-2-readers

Conversation

@jhrozek

@jhrozek jhrozek commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

"User-keyed upstream storage behind the embedder option" (#7263) moves upstream tokens from one row per login session to one row per user and provider. #7308 added the storage wrapper. Two read paths still have to cope with it before anything can turn it on: a caller with no login session, starting with the refresh grant guard, needs to read one user's credential for one provider; and the token validator must name a user to storage only for a token it can trust, because user-keyed storage hands a user's connections to whoever presents that user's ID. This PR adds both. Nothing applies the wrapper yet.

  • Per-user read. upstreamtoken.UserCredentialReader and InProcessService.GetValidTokensForUser(ctx, userID, provider) set the canonical user, check the row's owner before any refresh and again on the refreshed row, and refresh through the shared refresher. Results: ErrNeedsAuthorization when the user must connect again (no row, a placeholder, no access token, an expired row that cannot be refreshed, invalid_grant); ErrInvalidBinding for another user's row; ErrNoCanonicalUser passed through; anything else is an infrastructure error. The session paths (GetValidTokens, GetAllUpstreamCredentials) behave as before.
  • Validator. On a validator bound to the embedded issuer, loadUpstreamTokens puts the token's sub in the load context as the canonical user only when the admission route is interactive. Every other token gets an explicit empty user, so a user set earlier on the request cannot leak into the load, and a missing user loads nothing instead of failing the request. A validator not bound to the embedded issuer does not touch the key, and it does not tolerate a missing user: that can only mean user-keyed storage behind a validator that is not bound to the embedded issuer, so it stays a 503.
  • Sessionless gate. With an upstream token reader configured, a token that carries a tsid is never a sessionless grant. Without this, a non-interactive load that loaded nothing would let a token with both a tsid and act or no_upstream_session reach Cedar's request-claims path.

Part of #7263. The refresher change that lets the reader recognise a row deleted after a failed persist is in its own PR, #7324.

Type of change

  • New feature

Test plan

  • Unit tests, scoped to the touched packages (pkg/auth/..., pkg/authserver/..., pkg/authz/authorizers/cedar/...) with -race
  • Linting (golangci-lint and go vet on the touched packages)

The reader tests cover every result above, including the owner check on a refreshed row owned by someone else, a row deleted after a failed persist (on both the expired-access-token and the ID-token paths), and log levels. The validator tests cover each admission route on bound and unbound validators (an unbound validator that gets ErrNoCanonicalUser answers 503), over a mock reader and over the real user-keyed wrapper (two users, each sees only their own row), plus a bound validator with no audience over session-keyed storage, which still loads by tsid.

Changes

File Change
pkg/auth/upstreamtoken/service.go, types.go, errors.go UserCredentialReader, GetValidTokensForUser, ErrNeedsAuthorization, ErrNoCanonicalUser alias; owner check on refreshed rows
pkg/auth/token.go, pkg/auth/context.go Canonical user on the load context by admission route; tsid in the sessionless gate
docs/arch/17-token-exchange-delegation.md Sessionless rule
*_test.go Reader and validator tests

Does this introduce a user-facing change?

No. Nothing applies user-keyed storage yet. A validator bound to the embedded issuer now always sets the canonical-user key on its upstream-token load, and the session-keyed storage in this repo ignores it.

Special notes for reviewers

  • GetValidTokensForUser has no caller yet. Its first caller is the user-keyed refresh grant guard in the next PR of User-keyed upstream storage behind the embedder option #7263, which also confirms an invalid_grant with the existing recheck before refusing.
  • The ID-token refresh keeps today's behaviour. When only the ID token has expired and the access token is still live, a failed refresh, including invalid_grant, returns the stored credential, as the session path does. The reader's caller never sees that failure, so the reader logs it once at WARN. Needs-authorization follows once the access token expires.
  • The bulk session path does not check the refreshed row's owner. It passes an empty user ID and behaves as before; the owner check moves into the refresher when the option is wired.
  • Only a bound validator tolerates ErrNoCanonicalUser. A validator not bound to the embedded issuer leaves the key alone, so storage that reads the user from the Identity (via auth.CanonicalUserFromContext) keeps working. If it still gets ErrNoCanonicalUser, the storage reads only the auth server's own key, which is a misconfiguration, and the request gets a 503 as before.
  • A bound validator without an audience assigns no route, so under user-keyed storage even an interactive token loads nothing. The PR that adds the option checks for this at startup.
  • The sessionless rule changes nothing with the in-tree reader: with a reader configured, a token with a tsid already ended with upstream tokens or a 401 before the check. Without a reader the rule does not apply.
  • New exports: UserCredentialReader, ErrNeedsAuthorization, and ErrNoCanonicalUser (the storage sentinel, re-exported so callers outside the auth server can match it). The method ignores the caller's deadline only for the refresh call itself.

@jhrozek
jhrozek requested a review from ChrisJBurns as a code owner November 26, 2026 10:17
@github-actions github-actions Bot added the size/XL Extra large PR: 1000+ lines changed label Nov 26, 2026
@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.17%. Comparing base (ac27d5e) to head (a28cdaa).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7323      +/-   ##
==========================================
- Coverage   82.18%   82.17%   -0.01%     
==========================================
  Files         932      932              
  Lines       94564    94635      +71     
==========================================
+ Hits        77715    77769      +54     
- Misses      16844    16861      +17     
  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.

Design is right, but two things should change before the option gets wired: the silent "no upstream tokens" fallback and the bundled scope.

Design: Keying admission by route in TokenValidator (sub only for interactive tokens, explicit empty user otherwise) and checking the row owner in the storage wrapper is the right place and a safe default. GetValidTokensForUser has no caller yet; the PR says the refresh grant guard will be its first consumer, which makes it dead code until then. Existing session-keyed deployments see no change from the validator keying. The one live behaviour change is the refresher/guard flip in finding 3.

Findings:

  1. pkg/auth/token.go:~1490 (the !interactive && ErrNoCanonicalUser branch): the tolerance is not limited to a validator bound to the embedded issuer. On an unbound validator CanonicalUserFromContext falls back to PlatformUserID, so ErrNoCanonicalUser can only come from the user-keyed wrapper. If an operator turns on user-keyed storage but the validator is unbound (issuer mismatch, EmbeddedAuthServerIssuer unset), every request loads no upstream tokens and logs only at DEBUG. Before, it was a 503. Suggested fix: tolerate the error only when boundToEmbeddedIssuer(); otherwise keep the error.
  2. pkg/auth/token.go:~1606 (classifyRoute audience gate): a bound validator with no audience classifies every token as unspecified, so legitimate interactive tokens silently load nothing under user-keyed storage. Suggested fix: fail startup, or WARN once, when user-keyed storage is wired without an audience or key provider.
  3. pkg/authserver/refresher.go:~347 / refresh_grant_guard.go:290: wrapping ErrNotFound after the "persist failed after rotation" row deletion makes the guard's checkRow refuse the client's refresh_token grant where it used to grant. This is the only change that alters live session-keyed behaviour, and it is independent of the per-user API. Suggested fix: land it as its own PR with the guard test, so it can be reverted separately.

Simpler alternative: split into (1) the refresher ErrNotFound wrap plus guard test, and (2) GetValidTokensForUser, the validator keying and the isSessionlessGrant gate, together with their first consumer. The isSessionlessGrant gate itself is correct and small.

When the follow-up guard adopts GetValidTokensForUser, classifyUserRefreshError treats the first invalid_grant as final without the guard's rejectionConfirmed recheck. The cost is a reconnect prompt, so it is fine to settle there.

🤖 Reviewed with Claude Code

jhrozek and others added 2 commits November 26, 2026 11:49
Callers without a login session, starting with the refresh-grant guard,
need one provider's credential for one user. Add UserCredentialReader
and implement GetValidTokensForUser on InProcessService. It sets the
canonical user, checks the row's owner itself, and refreshes an expired
row through the shared refresher.

No row, a placeholder, an empty access token (stored, or left by a
refresh that otherwise succeeded), a missing refresh token or an
invalid_grant rejection return ErrNeedsAuthorization; another user's
row returns ErrInvalidBinding; ErrNoCanonicalUser passes through;
anything else is an infrastructure error. For a failed refresh of an
expired access token the reader adds no WARN of its own, so the caller
decides how loudly to log it.

When only the ID token needs refreshing and the access token is still
live, a failed refresh, including invalid_grant, returns the stored
credential, as the session path does today. The caller never sees that
failure, so the reader logs one WARN with the provider and error only.

A refresh can return a different row than the one first read, for
example after another replica rotated the token, so refreshOrFail and
refreshForIDToken take the expected user ID and check the owner of the
refreshed row too. The ID token fallback returns a binding error,
whether it is the upstreamtoken or the storage sentinel, instead of
serving the stored credential. The session-level paths pass an empty
user ID and behave as before; their per-row logic moves into
credentialFor without changing what it does.

The ID-token fallback re-reads the row after a failed refresh. When the
row is gone it returns the refresh error with the missing-row cause, so
the caller gets ErrNeedsAuthorization; on the user path a binding error
from that re-read is returned as ErrInvalidBinding instead of falling
back to the stored credential.

Only the refresh call is detached from the caller's deadline; the
initial read, the row-ID lookup and the ID-token re-read use the
caller's context.

Co-authored-by: Mecatl <[email protected]>
User-keyed storage serves a user's connections to whoever presents
that user's ID, so the validator must name the user only for tokens it
can trust: an interactive login at the embedded authorization server.

On a validator bound to the embedded issuer, loadUpstreamTokens puts sub
in the load context as the canonical user when the token's admission
route is interactive. Any other token gets an explicit empty canonical
user, so a user set earlier on the request cannot leak into the load,
and a missing canonical user loads nothing instead of failing the
request; that case is logged at DEBUG. A validator without an audience
or an in-process key provider assigns no route, so under user-keyed
storage it loads nothing.

Because such a load can now leave UpstreamTokens nil for a token that
carries a tsid, a token with a tsid is never a sessionless grant when
an upstream token reader is configured, even if it also carries act or
no_upstream_session. Otherwise Cedar would evaluate the request token's
own claims. The authorization server never mints that combination, and
with the in-tree reader nothing changes on main: such a token already
ended with upstream tokens or a 401 before this check.

A validator not bound to the embedded issuer does not touch the
canonical-user key, so storage that falls back to the Identity keeps
working as today. The missing-user tolerance applies only to a bound
validator: on an unbound one ErrNoCanonicalUser is returned like any
other reader error (a 503), because it can only come from storage that
reads just the authorization server's key behind a validator that is
not bound to the embedded issuer, a misconfiguration that must not turn
into silent "no upstream tokens". The comments on the load context,
WithPlatformUser and CanonicalUserFromContext now describe the bound
validator as the exception.

A bound validator sets the key even while no storage is user-keyed.
The in-tree session-keyed storage ignores it and still loads by tsid,
which a test with no audience over session-keyed storage pins, so
nothing changes until the option exists.

Co-authored-by: Mecatl <[email protected]>
@jhrozek
jhrozek force-pushed the user-keyed-storage-v2-2-readers branch from 9e47b36 to a28cdaa Compare November 26, 2026 10:53
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Nov 26, 2026
@jhrozek

jhrozek commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, all three taken.

  1. Agreed. Only a validator bound to the embedded issuer tolerates ErrNoCanonicalUser now. An unbound one returns it as before, so it is a 503 again instead of silently loading nothing. Tests updated, including the Cedar-package e2e case that used to expect "loads nothing".

  2. Agreed, but it lands in the PR that adds the option, since that is where we know user-keyed storage is on. This PR has nothing to check against yet. I'll do it there as a startup check for a bound validator without an audience or key provider.

  3. Split out into Report the upstream row deleted after a failed persist #7324 (refresher change, guard test, and the guard table row in docs/arch/11). This PR is now two commits: the reader and the validator. The reader still treats a row deleted after a failed persist as needs-authorization, its tests mock the error shape, so it works with or without Report the upstream row deleted after a failed persist #7324; until that lands the case is reported as an infrastructure error.

On folding the reader and validator into the PR with their first consumer: that would be the guard PR, which is already large, so I'd rather keep them separate and open the guard PR on top of this one so you can see the caller. The invalid_grant point is covered there: the user-keyed guard checks ErrGrantRejected before ErrNeedsAuthorization and runs rejectionConfirmed, and it also skips remembered rejections like the field-off guard does.

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

Re-review of a28cdaa: approve. The earlier blocking finding is fixed and the refresher change moved out of this PR.

  1. Validator tolerated ErrNoCanonicalUser when not bound to the embedded issuer: resolved. token.go now tolerates it only when !interactive && v.boundToEmbeddedIssuer(), so an unbound validator returns a 503 again. Bare and wrapped error cases are covered in TestLoadUpstreamTokens_UserKeying, and the unbound 503 in TestMiddleware_UserKeying.
  2. Audience gate loads nothing under user-keyed storage, with no startup check: settled by deferral. This PR doesn't wire the user-keyed option, so the failure can't occur yet. The startup check (or WARN) for the audience/key-provider mismatch has to land in the PR that adds the option or the guard PR; please treat it as blocking there.
  3. ErrNotFound wrap on the refresher and the guard-test flip: resolved for this PR. The behaviour change is reverted here and lives in #7324.

Design: unchanged. Route-keyed admission in the validator and the owner check in the storage wrapper stay as before, and the reader and validator still ship without their first caller, which is fine while the stacked PRs follow.

🤖 Reviewed with Claude Code

@ChrisJBurns ChrisJBurns left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

  • Possibly important · correctness — A failed refresh token rotation on the expired path is reported as a transient error, not ErrNeedsAuthorization (pkg/auth/upstreamtoken/service.go:1129)

    classifyUserRefreshError's doc says a row "the refresher deleted after it could not save a rotated refresh token ... carries storage.ErrNotFound". On the expired-access-token path, the real refresher does not wrap ErrNotFound. It deletes the row, then returns fmt.Errorf("failed to persist rotated upstream refresh token for provider %q: %w", ..., err), which wraps only the CAS/store error (checkout/pkg/authserver/refresher.go:343-346). GetValidTokensForUser therefore returns a generic infrastructure error rather than ErrNeedsAuthorization, even though the credential can no longer be used. Onl

    Recommendation: Pick one: (a) make the refresher wrap storage.ErrNotFound in its rotated-persist-failure error after a successful delete, or (b) on the per-user expired path, re-read the row after a refresh failure (as refreshForIDToken does) and add ErrNotFound when the row is gone. Change the test mock to return the refresher's real error string, or drive the case through the real refresher.

@jhrozek
jhrozek merged commit 96ca697 into main Nov 26, 2026
48 of 49 checks passed
@jhrozek
jhrozek deleted the user-keyed-storage-v2-2-readers branch November 26, 2026 12:12
@jhrozek

jhrozek commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Thanks Chris. This is covered. It's the same case, fixed at the source in #7324 (your option a): the refresher now wraps storage.ErrNotFound when it deleted the row after failing to save a rotated refresh token, so the per-user read returns ErrNeedsAuthorization on the expired-access-token path as well. #7324 landed just before this PR, and the reader test now uses the refresher's real error format. The end-to-end case through the real refresher (IdP rotates, save fails, row deleted, guard refuses and revokes) is in the next PR of the stack, where the first caller is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Extra large PR: 1000+ lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants