Skip to content

Keep one user per upstream identity - #7277

Merged
jhrozek merged 5 commits into
stacklok:mainfrom
jhrozek:one-identity-one-user
Nov 25, 2026
Merged

jhrozek merged 5 commits into
stacklok:mainfrom
jhrozek:one-identity-one-user

Conversation

@jhrozek

@jhrozek jhrozek commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Clients compare a user's sub_id to decide who owns a session, and the agent check compares it with a grant's user. Both assume one upstream identity never maps to two authorization-server users. The code mostly guaranteed this, but nothing tested it, and three gaps could still break it: a Redis link write that was not atomic with its reverse index, a failed link write that could roll back the user that owns the link, and user creation through a later upstream. This PR closes them and pins the rule with tests.

  • Atomic Redis link write. The user check, the set-if-absent link write and the reverse-index entry run as one Lua script, so a failed set write cannot leave a link behind for a user that is then rolled back.
  • Failed link writes read the link before deleting anything. If the link points at our own user (the write committed and the reply was lost), the user is kept. If it points at another user, a concurrent first login won: our user is rolled back and the winner's is returned, so both logins get the same user. If there is no link, or it cannot be read, nothing is deleted and the error is returned, because a write that timed out can still commit after the read. An unlinked user row is harmless.
  • Only the first upstream creates users. UserResolver takes WithCreateOnlyFor, which NewHandler sets to the first upstream. A later upstream whose identity is already linked still resolves to its user. With no link it gets ErrUpstreamCannotCreateUsers and nothing is written. One copy of the rule covers the browser callback and the device flow.
  • Tests. A storage contract for one link per identity on memory and Redis (including a link to a user that was deleted first), concurrent and repeat first logins on both backends, every link-failure outcome, and the first-upstream rule on the browser, device and ID-JAG subject resolver paths.
  • Docs. docs/arch/11-auth-server-storage.md and the SetSubjectIdentifier comment state the rule, separate the link key from sub_id, and list which config changes move which key. docs/redis-storage.md adds the link script to the Redis Cluster hash-tag note.

Closes #6980

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)

Ran the pkg/authserver, pkg/authserver/storage, pkg/authserver/server/handlers and pkg/authserver/server/session tests with -race.

Changes

File Change
pkg/authserver/storage/redis.go Link write as one Lua script: user check, set-if-absent link, reverse-index entry
pkg/authserver/server/handlers/user.go WithCreateOnlyFor, ErrUpstreamCannotCreateUsers; settle a failed link write by reading the link
pkg/authserver/server/handlers/handler.go Build the resolver with the first upstream as the only one that creates users
pkg/authserver/server/handlers/callback.go, device_verification.go Map ErrUpstreamCannotCreateUsers to access_denied / a 403 page, logged at WARN
pkg/authserver/server/session/session.go, pkg/authserver/storage/types.go Describe the rule, the two keys and the SingleLeg prerequisite
docs/arch/11-auth-server-storage.md, docs/redis-storage.md The one-user-per-identity rule; Redis Cluster hash-tag requirement for the link script
*_test.go Contract, concurrency, link-failure and first-upstream tests

Does this introduce a user-facing change?

Yes.

  • Login that reaches user resolution through a later upstream with no carried user (for example SingleLeg against that upstream without ResolvedUserID, or a login in flight across an upstream reorder).
    • Before: created a second user and link for the same person.
    • After: if that upstream's identity is already linked, the login resolves to the linked user as before. If not, the browser callback redirects with error=access_denied and the device flow shows a 403 page. Nothing is written.
  • Two first logins for one identity at the same time.
    • Before: the login that lost the link race got server_error.
    • After: both succeed with the same user.
  • Redis Cluster. A user's first login now runs a Lua script over three keys, so on Redis Cluster the key prefix must contain a {...} hash tag, as DCR registration already requires. Without one, first logins fail with CROSSSLOT. The operator's DeriveKeyPrefix always adds one, so this only affects hand-written prefixes.
  • Embedders of NewHandler get the first-upstream rule with no switch to turn it off. NewUserResolver(stor) still compiles; the restriction is opt-in there through WithCreateOnlyFor.

Special notes for reviewers

  • Deviation from Test that one upstream identity never maps to two authorization-server users #6980. The issue asks for a startup check that rejects two providers configured with the same issuer, and for the losing login to fail and succeed on retry. This PR does neither. Only the first upstream creates users, so a second provider for the same issuer cannot create a second user, and returning the winner's user is better than failing. A startup check would also reject setups that are safe under the first-upstream rule.
  • Device poller after a refusal. The browser gets a 403 page, but the device request stays pending, so the polling client keeps getting authorization_pending until it expires. This matches how ErrUserNotProvisioned already behaves, and it lets the person retry after the cause is fixed. A terminal denial for both errors would be a separate change.
  • Two keys. Users are found by the link key (upstream name plus subject_claim value), not by sub_id. Renaming the first upstream, reordering upstreams, or changing subject_claim to a claim with a different value still gives one person a second user with the same sub_id. The reverse case (same name, different issuer) is tracked as "Bind provider-identity rows to the issuer and subject claim that created them" (Bind provider-identity rows to the issuer and subject claim that created them #7256).
  • Concurrency test. The first-login test releases 16 callers together for 50 rounds on both backends. It does not force every round through the "another user won" path; that path is pinned deterministically by the mocked link-failure table in user_test.go.

@jhrozek
jhrozek requested a review from ChrisJBurns as a code owner November 24, 2026 16:44

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

Comment: the atomic link write and conflict handling are the right fix at the right owner, but one rollback path can still delete a live user, and the first-upstream guard breaks embedders and sits in the wrong place.

Design: CreateProviderIdentity owns "one link per (provider, subject)", and making the Redis write a single Lua script with one hash tag is correct and cluster-safe. resolveLinkConflict (read the link, adopt the winner, only then roll back) is the right shape. The "only the first upstream creates users" rule is a resolver concern, but it is enforced as two copies in the callback and device handlers.

  1. pkg/authserver/server/handlers/user.go, createUserWithIdentity, generic-error branch before rollbackUser: the "never delete a possible owner" rule only covers ErrAlreadyExists. If the Lua script commits and the reply times out (or the connection resets), the error is not ErrAlreadyExists, so rollbackUser runs; the cascade in DeleteUser deletes the committed link and the user. Meanwhile a concurrent login B for the same identity has read the link and adopted user U, so it holds a sub that no longer exists and the next login mints a new user. This is the same lost-reply case the PR fixes, through a different error. Fix: for every non-nil error, read the link first; roll back only when the link is confirmed ErrNotFound or points at another user; if the read fails, leave the candidate row (as resolveLinkConflict already does).

  2. pkg/authserver/server/handlers/callback.go:505 (resolveFirstLegUser) and device_verification.go:278: the same providerID != h.upstreams[0].Name guard is duplicated, with a "keep in step" comment. SingleLeg is never set in this repo, so the only callers affected are embedders that build PendingAuthorization themselves. For them, a SingleLeg authorization against a later upstream without ResolvedUserID used to resolve through an existing link and now ends in server_error, even when a valid link already exists. The authorize.go path always writes upstreams[0], so in-repo this is reachable only after an upstream reorder. Fix: either move the rule into UserResolver (constructed with the first upstream name, returning a typed error mapped with errors.Is at the two call sites), or refuse only the create-new-user path: look up the link first, return the existing user if found. Also use invalid_request/access_denied rather than server_error, which reads as an outage in alerts, and call the break out in the PR notes/release notes.

  3. pkg/authserver/storage/redis.go (the script): the -1 (user missing) return is untested; the contract tests only cover a missing user sequentially. Add a test that deletes the user between CreateUser and the script, expecting ErrNotFound and no link left behind.

  4. Closes #6980: the issue asked for startup rejection of same-issuer upstreams and for the race loser to fail cleanly. The PR deliberately does neither, and the reasoning holds (returning the winner's user is better). Please update the issue so the closure doesn't hide the changed acceptance list. Also add one line to docs/arch/11-auth-server-storage.md that in-flight logins fail after an upstream reorder.

Simpler alternative: keep the Lua script, resolveLinkConflict, rollbackUser and the contract/concurrency tests; replace the two handler guards and the resolveFirstLegUser helper with one check in UserResolver.

🤖 Reviewed with Claude Code

@codecov

codecov Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.03922% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 81.86%. Comparing base (8d64314) to head (6c1c827).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
.../authserver/server/handlers/device_verification.go 80.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7277      +/-   ##
==========================================
- Coverage   81.86%   81.86%   -0.01%     
==========================================
  Files         915      915              
  Lines       92868    92896      +28     
==========================================
+ Hits        76029    76046      +17     
- Misses      16834    16845      +11     
  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.

jhrozek and others added 5 commits November 24, 2026 22:42
Clients compare sub_id to decide who owns a session, and that assumes
one upstream identity never maps to two users. The set-if-absent link
write is what keeps that true, but nothing tested it. Run one contract
against the memory and Redis stores: a second link for the same
(provider, subject) is refused and leaves the first untouched, a link to
a missing user writes nothing, and concurrent creates leave exactly one
link.

Co-authored-by: Mecatl <[email protected]>
The link and its entry in the user's reverse-lookup set were written by
separate commands, so a failed set write could leave a link pointing at
a user the caller then rolled back. Do the user check, the set-if-absent
link write, and the set add in one Lua script, and delete the link
inside the script if the set add fails. All three keys share the
namespace hash tag, so the script is valid in cluster mode.

Co-authored-by: Mecatl <[email protected]>
Two first logins for one identity could race, and a link write can fail
without saying whether it committed (a lost Redis reply, a timeout).
Rolling back first could delete the user that owns the link, and the
delete cascades to the link.

Read the link before deleting anything. If it points at our own user,
keep that user. If it points at another user, a concurrent login won:
roll back ours and return the winner's, so both logins get the same
user. If there is no link, or it cannot be read, delete nothing and
return the error: a write that timed out can still commit after the
read, and an unlinked user row is harmless while deleting the owner is
not.

Co-authored-by: Mecatl <[email protected]>
Every login chain starts at the first upstream, and later upstreams
carry the user it resolved. A pending authorization that reaches user
resolution through a later upstream with no carried user (for example a
SingleLeg one) would link that upstream's subject to a second user for
one person.

UserResolver takes WithCreateOnlyFor, which NewHandler sets to the first
upstream. A later upstream whose identity is already linked still
resolves to its user, so embedders whose storage resolves identities
itself are unaffected. With no link it gets ErrUpstreamCannotCreateUsers,
mapped to access_denied (403 on the device page), and nothing is
written. NewUserResolver stays source compatible. One copy of the rule
covers the browser callback and the device flow, including a device
login that outlives a change of first upstream.

Co-authored-by: Mecatl <[email protected]>
Say how one upstream identity maps to one user, and where it can still
drift. Users are found by the link key (upstream name plus subject_claim
value), while sub_id is the raw iss and sub and is not used for lookup.
List which changes move which key: a renamed or reordered first
upstream or a changed subject_claim gives a second user with the same
sub_id, and an upstream renamed to another issuer gives one user two
sub_id values. Readers of sub_id need this to know whether it can repeat
across users.

Co-authored-by: Mecatl <[email protected]>
@jhrozek

jhrozek commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, all four were fair. I restructured the branch and force-pushed, so the commit list changed.

  1. Rollback on a non-ErrAlreadyExists error: every failed link write now reads the link first. Ours, keep it. Someone else's, roll back and adopt theirs. I went a step further than you suggested on the "no link" case: it doesn't roll back either. A timed-out script can still run after our read, so a miss doesn't prove the write failed. An unlinked user row is harmless, and deleting the owner isn't. The rollback also no longer uses WithoutCancel, by the same reasoning.

  2. Took the simpler alternative. The rule is in UserResolver now (WithCreateOnlyFor, set by NewHandler to the first upstream). It looks the link up first, so a later upstream with an existing link still resolves. With no link it returns ErrUpstreamCannotCreateUsers, which the callback maps to access_denied and the device page to a 403. The two handler guards are gone, and the break is in the PR's user-facing section.

  3. Added a contract case on both backends that creates the user, deletes it, then links it, and expects ErrNotFound with no link left. The script is atomic, so nothing can delete the user between its EXISTS and its SET. Deleting just before the call is the only interleaving there is.

  4. Commented on the issue with what changed in the acceptance list and why. The docs now cover logins in flight across an upstream change, with a rename and a reorder described separately since they fail differently.

@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 6c1c827: approve. All four earlier findings are resolved and I found no new significant ones.

  1. Rollback on a non-ErrAlreadyExists link error: resolved. resolveLinkFailure now reads the link for every failure before deleting anything. Link points at our user: keep it. Link points at another user: roll back ours and adopt the winner. No link or unreadable: delete nothing and return the error. This is stricter than what we asked for, and right.
  2. Duplicated first-upstream guard: resolved. The rule now lives once in UserResolver (WithCreateOnlyFor, set from upstreams[0]), and both the callback and device paths map the refusal to access_denied/403.
  3. Untested user-missing script path: resolved. The contract test covers the deleted-before-link case on both memory and Redis. Your argument that the script is atomic holds.
  4. Closes #6980 and the reorder upgrade note: resolved. The architecture doc now covers in-flight logins across an upstream reorder.

Design: unchanged in shape. The Redis link, user check and set entry are one Lua script, the race loser adopts the winner, and the identity link stays the single source of truth for who owns an upstream identity. The new one-user-per-identity rule sits in the resolver, which owns user creation, and the only two callers handle its error. The Redis script uses the same keys as before, so a rolling upgrade is compatible; the only operator-visible change is the CROSSSLOT requirement for hand-written prefixes without a hash tag, and that is documented.

Before merge, please confirm the failing E2E Test Lifecycle (kindest/node:v1.35.1) check is a flake and that lint is clean. I couldn't read its log, and it looks unrelated to this change.

🤖 Reviewed with Claude Code

@jhrozek
jhrozek merged commit 65462c9 into stacklok:main Nov 25, 2026
45 of 47 checks passed
@github-actions github-actions Bot mentioned this pull request Nov 25, 2026
2 tasks
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.

Test that one upstream identity never maps to two authorization-server users

2 participants