Skip to content

Compare the owner on upstream token reads - #7219

Open
hellouz818 wants to merge 1 commit into
stacklok:mainfrom
hellouz818:fix/6176-owner-checked-upstream-reads
Open

hellouz818 wants to merge 1 commit into
stacklok:mainfrom
hellouz818:fix/6176-owner-checked-upstream-reads

Conversation

@hellouz818

@hellouz818 hellouz818 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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.ErrInvalidBinding documented 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.

  • GetUpstreamTokens and GetAllUpstreamTokens take expectedUserID and compare it with the row's UserID. Both, because the request path uses the bulk read.
  • The comparison runs before the expiry check. ErrExpired hands 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.
  • An empty expectedUserID is ErrInvalidRequest, 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.
  • A null-marker row still reads as (nil, nil): it records no owner because it carries no credentials.
  • A new shared contract suite runs these rules against memory and miniredis, so a deployment moving from one to the other cannot quietly lose them.

Refs: #6176

Type of change

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

Test plan

  • Unit tests (task test)
  • E2E tests (task test-e2e)
  • Linting (task lint-fix)
  • Manual testing (describe below)

task test is green with a Docker daemon available, and task gen produces no diff.

New coverage, pkg/authserver/storage/upstream_token_contract_test.go, run against both backends:

  • the owner gets the row, from both reads;
  • another user gets ErrInvalidBinding and a nil row from both;
  • one foreign row among a session's rows fails the bulk read rather than returning the rest;
  • a row with no stored user is refused;
  • an empty expected owner is ErrInvalidRequest;
  • on the single-row read, an absent row is ErrNotFound whoever asks, never ErrInvalidBinding — reporting it as foreign would confirm it exists;
  • an expired row is refused by owner before ErrExpired, and the refused read leaves it unchanged;
  • the owner still gets an expired row and its refresh token;
  • a null-marker row reads as no row;
  • the session-keyed and user-keyed reads agree on who owns what;
  • sibling sessions of different users stay apart.

Replacing the comparison with return nil fails 14 of those subtests.

API Compatibility

  • This PR does not break the v1beta1 API, OR the api-break-allowed label is applied and the migration guidance is described above.

No operator API surface is touched. Go API surface does change, though: storage.UpstreamTokenStorage, upstreamtoken.TokenReader and upstreamtoken.Service are 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

File Change
storage/types.go Both reads take expectedUserID; upstreamRowBelongsTo helper; ErrInvalidBinding documented as what it now is
storage/memory.go, storage/redis.go The comparison, before expiry, in both backends
storage/upstream_token_contract_test.go New shared contract suite
upstreamtoken/types.go, upstreamtoken/service.go GetValidTokens and GetAllUpstreamCredentials carry the owner through
auth/token.go Request path passes the token's sub
authserver/refresh_grant_guard.go Guard passes the session's subject
authserver/refresher.go Three re-reads pass the snapshotted row's owner
handlers/callback.go, handlers/handler.go Chain walk passes the user being authenticated
docs/arch/11-auth-server-storage.md New "Upstream Row Ownership" section
mocks Regenerated

Every caller, and the owner it passes

Caller Owner
Request path, loadUpstreamTokens (auth/token.go) the validated token's sub, as issued
Refresh-grant guard, bulk read and recheck (refresh_grant_guard.go) requester.GetSession().GetSubject()
Refresher, three re-reads (refresher.go) the owner of the row the refresh started from
Service existence check after a failed refresh (upstreamtoken/service.go) the same owner as the call; a mismatch counts as gone, like ErrNotFound
Interactive chain walk (handlers/callback.go, nextMissingUpstream) the user being authenticated in that flow

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: GetAllUpstreamTokens now validates its session ID. It had none, so an empty session ID returned an empty map; it is now ErrInvalidRequest, following "an empty session ID, provider or expected owner is fosite.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 returns storage.ErrInvalidBinding, the callback fails authorization and preserves the stored credentials. Previously, a first-provider mismatch detected by verifyChainIdentity triggered 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

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

codecov Bot commented Nov 23, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.14085% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.60%. Comparing base (7da77cd) to head (df219b5).

Files with missing lines Patch % Lines
pkg/authserver/storage/redis.go 87.50% 4 Missing ⚠️
pkg/auth/token.go 60.00% 2 Missing ⚠️
pkg/authserver/storage/memory.go 91.66% 1 Missing ⚠️
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.
📢 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.

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

See the inline comments.

}

nextProvider, err := h.nextMissingUpstream(ctx, sessionID, chain)
nextProvider, err := h.nextMissingUpstream(ctx, sessionID, subject, chain)

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.

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)

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 · 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/....

This branch has not been deployed

No deployments
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