Repository navigation
Compare the owner on upstream token reads - #7219
hellouz818 wants to merge 1 commit into
Conversation
Upstream rows are addressed by token session ID, which travels in the token as a claim. Whoever presented that claim got the credentials filed under it, and nothing checked that they were the user those credentials were stored for. storage.ErrInvalidBinding documented the check as if it happened, but no backend returned it and the reads it guarded took no subject to compare with. Give both session-keyed reads the expected owner and compare it with the row's UserID. The comparison runs before the expiry check, because ErrExpired hands the row back so the caller can refresh it, and that row carries the refresh token. An empty owner is refused rather than taken as permission to skip the comparison. A row recording no owner belongs to nobody. One foreign row fails a bulk read entirely rather than returning a partial view of another user's session. A null-marker row still reads as no row: it records no owner because it carries no credentials. Every caller passes an owner and there is no bypass: the request path passes the validated token's subject, the guard the session's, the refresher the owner of the row it snapshotted, and the interactive chain walk the user it is authenticating. A shared contract suite runs the rules against both backends, since a deployment moving from memory to Redis must not quietly lose them. First of two changes. What each caller does with a mismatch follows separately. Refs: stacklok#6176 Signed-off-by: hellouz818 <[email protected]>
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #7219 +/- ##
==========================================
- Coverage 81.64% 81.60% -0.04%
==========================================
Files 898 898
Lines 91621 91659 +38
==========================================
- Hits 74805 74800 -5
- Misses 16811 16854 +43
Partials 5 5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
ChrisJBurns
left a comment
There was a problem hiding this comment.
See the inline comments.
| } | ||
|
|
||
| nextProvider, err := h.nextMissingUpstream(ctx, sessionID, chain) | ||
| nextProvider, err := h.nextMissingUpstream(ctx, sessionID, subject, chain) |
There was a problem hiding this comment.
Important · correctness — Callback chain no longer deletes tokens on a confirmed identity mismatch: storage now returns ErrInvalidBinding, which the callback treats as a transient read e
Today, a first-leg row whose UserID differs from the chain subject reaches verifyChainIdentity (callback.go:1028). That function returns errChainIdentityMismatch, which triggers cleanupUpstreamTokens and the structured "identity mismatch between chain state and stored tokens" error log. With this PR, both nextMissingUpstream (handler.go:1683) and verifyChainIdentity (callback.go:1022) pass subject to GetAllUpstreamTokens, so real storage returns ErrInvalidBinding for that foreign row before either comparison runs. The error goes down the "transient chain-state read failure — preserve upstrea
Recommendation: In continueChainOrComplete, check errors.Is(err, storage.ErrInvalidBinding) on the results of both nextMissingUpstream and verifyChainIdentity. Treat it as a confirmed mismatch: emit the identity-mismatch log and call cleanupUpstreamTokens. Alternatively, have verifyChainIdentity map ErrInvalidBinding to errChainIdentityMismatch. Make the helpers_test mock apply the same owner comparison (or use MemoryStorage) so the mismatch tests exercise the real contract.
| require.NoError(t, s.StoreUpstreamTokens(ctx, "sess-up-1", "provider-a", tokens)) | ||
|
|
||
| retrieved, err := s.GetUpstreamTokens(ctx, "sess-up-1", "provider-a") | ||
| retrieved, err := s.GetUpstreamTokens(ctx, "sess-up-1", "provider-a", testOwner) |
There was a problem hiding this comment.
Possibly important · maintainability · tests — Redis integration tests still read rows with an owner that does not match, so the integration suite will fail
The PR replaced every read with testOwner ("test-owner") but did not change the stored rows. Their UserIDs are "user-up-1" (L622), "user2" (L651), empty (sess-exp, L662), "migrate-user" (L1267/1303), "u1" (L1354/1360/1368, L1434/1440), and the legacy JSON user_id for page-sess (L1413). Under the new upstreamRowBelongsTo rule each of these reads returns ErrInvalidBinding, so require.NoError and assert.ErrorIs(err, ErrExpired) fail. The file has the integration build tag (L4), so the default go test run does not catch it. The unit-level redis_test.go was updated correctly, which ma
Recommendation: Pass each row's real owner to the read ("user-up-1", "user2", userID, "u1", and so on), or set UserID: testOwner on rows that had none. Better, reuse testRowOwner from memory_test.go instead of declaring a second constant. Then run go test -tags integration ./pkg/authserver/storage/....
Summary
Upstream rows are addressed by token session ID (
tsid), which travels in the access token as a claim. A client can read its own out of its own token, so presenting one is not evidence of owning the credentials filed under it — and nothing checked.storage.ErrInvalidBindingdocumented the check as if it happened ("token binding validation fails (e.g., subject or client ID mismatch)"), but no backend returned it and neither read it guarded took a subject to compare with.This is the first of the two PRs for #6176: the storage reads, the contract suite, and the mechanical caller updates. The request path's generic 500 and the refresh-grant guard's refusal follow in the second.
GetUpstreamTokensandGetAllUpstreamTokenstakeexpectedUserIDand compare it with the row'sUserID. Both, because the request path uses the bulk read.ErrExpiredhands the row back so the caller can refresh it, and that row carries the refresh token; checking expiry first would give a non-owner the one credential that mints new ones.expectedUserIDisErrInvalidRequest, never permission to skip the comparison. A row recording no owner belongs to nobody. One foreign row fails a bulk read entirely rather than returning a partial view of another user's session.(nil, nil): it records no owner because it carries no credentials.Refs: #6176
Type of change
Test plan
task test)task test-e2e)task lint-fix)task testis green with a Docker daemon available, andtask genproduces no diff.New coverage,
pkg/authserver/storage/upstream_token_contract_test.go, run against both backends:ErrInvalidBindingand a nil row from both;ErrInvalidRequest;ErrNotFoundwhoever asks, neverErrInvalidBinding— reporting it as foreign would confirm it exists;ErrExpired, and the refused read leaves it unchanged;Replacing the comparison with
return nilfails 14 of those subtests.API Compatibility
v1beta1API, OR theapi-break-allowedlabel is applied and the migration guidance is described above.No operator API surface is touched. Go API surface does change, though:
storage.UpstreamTokenStorage,upstreamtoken.TokenReaderandupstreamtoken.Serviceare exported, so code outside this repository that implements them stops compiling — a storage decorator keyed by gateway and user, for example. The fix is to accept and forward the new parameter.Changes
storage/types.goexpectedUserID;upstreamRowBelongsTohelper;ErrInvalidBindingdocumented as what it now isstorage/memory.go,storage/redis.gostorage/upstream_token_contract_test.goupstreamtoken/types.go,upstreamtoken/service.goGetValidTokensandGetAllUpstreamCredentialscarry the owner throughauth/token.gosubauthserver/refresh_grant_guard.goauthserver/refresher.gohandlers/callback.go,handlers/handler.godocs/arch/11-auth-server-storage.mdEvery caller, and the owner it passes
loadUpstreamTokens(auth/token.go)sub, as issuedrefresh_grant_guard.go)requester.GetSession().GetSubject()refresher.go)upstreamtoken/service.go)ErrNotFoundhandlers/callback.go,nextMissingUpstream)There is no bypass: no "skip the check" parameter, and no second read that skips it. In synthesis mode the owner is the synthetic subject, which is a valid binding and is not special-cased.
Does this introduce a user-facing change?
Yes, though the intended failure modes land in the second PR.
Before: the storage read could return another user's upstream credential row without checking its owner.
After: the read is refused. Until the second PR lands, the request path surfaces that refusal as the 503 it already returns for a failed upstream load, rather than the generic 500 the issue asks for; the credentials are not disclosed either way. All three refresher re-reads now pass the owner from the original snapshot. A mismatch on the pre-refresh re-read stops the attempt before it calls the upstream provider. The refresh-grant guard still grants on a refused read, since it reads any read failure as "cannot tell, so grant" — that becomes a refusal in the second PR.
One further change beyond ownership:
GetAllUpstreamTokensnow validates its session ID. It had none, so an empty session ID returned an empty map; it is nowErrInvalidRequest, following "an empty session ID, provider or expected owner isfosite.ErrInvalidRequest" in the plan. A session ID that is merely unknown still returns an empty map.Special notes for reviewers
Callback cleanup on ownership mismatch. The chain walk now checks ownership in
nextMissingUpstream. If the bulk read returnsstorage.ErrInvalidBinding, the callback fails authorization and preserves the stored credentials. Previously, a first-provider mismatch detected byverifyChainIdentitytriggered chain cleanup. Applying that cleanup to every bulk-read mismatch would extend it to any provider.Is preserving credentials the intended callback behavior? If so, I'll remove the redundant first-provider comparison and retain a dedicated mismatch log on the callback path that receives
ErrInvalidBinding.🤖 Generated with Claude Code