Repository navigation
Add per-user upstream credential reads - #7323
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
rdimitrov
left a comment
There was a problem hiding this comment.
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:
pkg/auth/token.go:~1490(the!interactive && ErrNoCanonicalUserbranch): the tolerance is not limited to a validator bound to the embedded issuer. On an unbound validatorCanonicalUserFromContextfalls back toPlatformUserID, soErrNoCanonicalUsercan only come from the user-keyed wrapper. If an operator turns on user-keyed storage but the validator is unbound (issuer mismatch,EmbeddedAuthServerIssuerunset), every request loads no upstream tokens and logs only at DEBUG. Before, it was a 503. Suggested fix: tolerate the error only whenboundToEmbeddedIssuer(); otherwise keep the error.pkg/auth/token.go:~1606(classifyRouteaudience 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.pkg/authserver/refresher.go:~347/refresh_grant_guard.go:290: wrappingErrNotFoundafter the "persist failed after rotation" row deletion makes the guard'scheckRowrefuse the client'srefresh_tokengrant 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
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]>
9e47b36 to
a28cdaa
Compare
|
Thanks, all three taken.
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
left a comment
There was a problem hiding this comment.
Re-review of a28cdaa: approve. The earlier blocking finding is fixed and the refresher change moved out of this PR.
- Validator tolerated
ErrNoCanonicalUserwhen not bound to the embedded issuer: resolved.token.gonow tolerates it only when!interactive && v.boundToEmbeddedIssuer(), so an unbound validator returns a 503 again. Bare and wrapped error cases are covered inTestLoadUpstreamTokens_UserKeying, and the unbound 503 inTestMiddleware_UserKeying. - 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.
ErrNotFoundwrap 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
left a comment
There was a problem hiding this comment.
-
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. OnlRecommendation: 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.
|
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. |
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.
upstreamtoken.UserCredentialReaderandInProcessService.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:ErrNeedsAuthorizationwhen the user must connect again (no row, a placeholder, no access token, an expired row that cannot be refreshed,invalid_grant);ErrInvalidBindingfor another user's row;ErrNoCanonicalUserpassed through; anything else is an infrastructure error. The session paths (GetValidTokens,GetAllUpstreamCredentials) behave as before.loadUpstreamTokensputs the token'ssubin 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.tsidis never a sessionless grant. Without this, a non-interactive load that loaded nothing would let a token with both atsidandactorno_upstream_sessionreach 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
Test plan
pkg/auth/...,pkg/authserver/...,pkg/authz/authorizers/cedar/...) with-racegolangci-lintandgo veton 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
ErrNoCanonicalUseranswers 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 bytsid.Changes
pkg/auth/upstreamtoken/service.go,types.go,errors.goUserCredentialReader,GetValidTokensForUser,ErrNeedsAuthorization,ErrNoCanonicalUseralias; owner check on refreshed rowspkg/auth/token.go,pkg/auth/context.gotsidin the sessionless gatedocs/arch/17-token-exchange-delegation.md*_test.goDoes 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
GetValidTokensForUserhas 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 aninvalid_grantwith the existing recheck before refusing.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.ErrNoCanonicalUser. A validator not bound to the embedded issuer leaves the key alone, so storage that reads the user from theIdentity(viaauth.CanonicalUserFromContext) keeps working. If it still getsErrNoCanonicalUser, the storage reads only the auth server's own key, which is a misconfiguration, and the request gets a 503 as before.tsidalready ended with upstream tokens or a 401 before the check. Without a reader the rule does not apply.UserCredentialReader,ErrNeedsAuthorization, andErrNoCanonicalUser(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.