Repository navigation
Keep one user per upstream identity - #7277
Conversation
rdimitrov
left a comment
There was a problem hiding this comment.
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.
-
pkg/authserver/server/handlers/user.go,createUserWithIdentity, generic-error branch beforerollbackUser: the "never delete a possible owner" rule only coversErrAlreadyExists. If the Lua script commits and the reply times out (or the connection resets), the error is notErrAlreadyExists, sorollbackUserruns; the cascade inDeleteUserdeletes 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 asubthat 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 confirmedErrNotFoundor points at another user; if the read fails, leave the candidate row (asresolveLinkConflictalready does). -
pkg/authserver/server/handlers/callback.go:505(resolveFirstLegUser) anddevice_verification.go:278: the sameproviderID != h.upstreams[0].Nameguard is duplicated, with a "keep in step" comment.SingleLegis never set in this repo, so the only callers affected are embedders that buildPendingAuthorizationthemselves. For them, aSingleLegauthorization against a later upstream withoutResolvedUserIDused to resolve through an existing link and now ends inserver_error, even when a valid link already exists. Theauthorize.gopath always writesupstreams[0], so in-repo this is reachable only after an upstream reorder. Fix: either move the rule intoUserResolver(constructed with the first upstream name, returning a typed error mapped witherrors.Isat the two call sites), or refuse only the create-new-user path: look up the link first, return the existing user if found. Also useinvalid_request/access_deniedrather thanserver_error, which reads as an outage in alerts, and call the break out in the PR notes/release notes. -
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 betweenCreateUserand the script, expectingErrNotFoundand no link left behind. -
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 todocs/arch/11-auth-server-storage.mdthat 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 Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
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]>
51bdf76 to
6c1c827
Compare
|
Thanks, all four were fair. I restructured the branch and force-pushed, so the commit list changed.
|
rdimitrov
left a comment
There was a problem hiding this comment.
Re-review of 6c1c827: approve. All four earlier findings are resolved and I found no new significant ones.
- Rollback on a non-
ErrAlreadyExistslink error: resolved.resolveLinkFailurenow 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. - Duplicated first-upstream guard: resolved. The rule now lives once in
UserResolver(WithCreateOnlyFor, set fromupstreams[0]), and both the callback and device paths map the refusal toaccess_denied/403. - 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.
Closes #6980and 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
Summary
Clients compare a user's
sub_idto 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.UserResolvertakesWithCreateOnlyFor, whichNewHandlersets to the first upstream. A later upstream whose identity is already linked still resolves to its user. With no link it getsErrUpstreamCannotCreateUsersand nothing is written. One copy of the rule covers the browser callback and the device flow.docs/arch/11-auth-server-storage.mdand theSetSubjectIdentifiercomment state the rule, separate the link key fromsub_id, and list which config changes move which key.docs/redis-storage.mdadds the link script to the Redis Cluster hash-tag note.Closes #6980
Type of change
Test plan
task test)task test-e2e)task lint-fix)Ran the
pkg/authserver,pkg/authserver/storage,pkg/authserver/server/handlersandpkg/authserver/server/sessiontests with-race.Changes
pkg/authserver/storage/redis.gopkg/authserver/server/handlers/user.goWithCreateOnlyFor,ErrUpstreamCannotCreateUsers; settle a failed link write by reading the linkpkg/authserver/server/handlers/handler.gopkg/authserver/server/handlers/callback.go,device_verification.goErrUpstreamCannotCreateUserstoaccess_denied/ a 403 page, logged at WARNpkg/authserver/server/session/session.go,pkg/authserver/storage/types.goSingleLegprerequisitedocs/arch/11-auth-server-storage.md,docs/redis-storage.md*_test.goDoes this introduce a user-facing change?
Yes.
SingleLegagainst that upstream withoutResolvedUserID, or a login in flight across an upstream reorder).error=access_deniedand the device flow shows a 403 page. Nothing is written.server_error.{...}hash tag, as DCR registration already requires. Without one, first logins fail withCROSSSLOT. The operator'sDeriveKeyPrefixalways adds one, so this only affects hand-written prefixes.NewHandlerget the first-upstream rule with no switch to turn it off.NewUserResolver(stor)still compiles; the restriction is opt-in there throughWithCreateOnlyFor.Special notes for reviewers
authorization_pendinguntil it expires. This matches howErrUserNotProvisionedalready behaves, and it lets the person retry after the cause is fixed. A terminal denial for both errors would be a separate change.subject_claimvalue), not bysub_id. Renaming the first upstream, reordering upstreams, or changingsubject_claimto a claim with a different value still gives one person a second user with the samesub_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).user_test.go.