Repository navigation
Bind provider-identity rows to their issuer and claim - #7347
Conversation
rdimitrov
left a comment
There was a problem hiding this comment.
Comment: the per-row binding is the right idea and I found no bug in the resolver or the compare-and-swap scripts, but the legacy-row gap leaves the takeover this PR targets open for unused accounts.
Design: Stamping at sign-in, with the storage layer enforcing it atomically, is the right owner. ResolveUser is reached only from the callback and device flows, and remembered consent and the ID-JAG resolver are covered. The cost is a lot of machinery (new fields, a swapper interface, decorator unwrapping, three Lua scripts, an unstamped state) in about 3.5k lines. A per-upstream binding record, written set-if-absent on first boot and compared at startup, would close the legacy gap and need none of the per-row swapping.
-
pkg/authserver/server/handlers/user.go(loadAndStamp,stampUnstampedIdentity,identityAcceptable) andpkg/authserver/subjectresolver/resolver.go(Resolve): unstamped legacy rows are accepted under any issuer or claim. Scenario: the operator upgrades, then repoints the upstream before user X signs in again. X's row is still unstamped, so anyone at the new IdP with the samesubmatches it and is stamped as X. For plain OAuth2 numeric ids this is realistic. The ID-JAG resolver accepts these rows read-only, so stamping on a later sign-in does not close it forresolvecallers. Fix: stamp eagerly in a bounded startup pass, or use a per-upstream binding record. If neither, state in the docs that the upgrade and any repoint must be separate steps with a full sign-in cycle between them. -
pkg/authserver/storage/unwrap.go:24-45(ProviderIdentitySwapperFor): when it returns nil (an embedder's ownStoragewrapper, or a new in-repo decorator missing from the switch), unstamped rows are never stamped and every legacy row stays claimable. There is no startup log either. A new ToolHive decorator added later breaks this silently, because the switch duplicates the existingUnwrap()convention. Fix: log once at Warn inNewUserResolverwhen bindings are configured and the swapper is nil, and add a test that fails when a type in the package implementsUnwrap() Storagebut is not handled. -
pkg/authserver/server_impl.go(upstreamIdentityBinding) andpkg/authserver/config.go(signInUpstream,validateResolveIssuers): the binding is derived in two places and the resolver'sProvider.RowIssuer/RowSubjectClaimjust repeat the values the only caller already passes as the issuer andSubjectClaim. If the two derivations drift (for example issuer normalisation), every row is refused assubject_unknownor the wrong rows are accepted. Fix: derive the binding once and pass it through, and drop the two extra Provider fields until a caller needs them. -
pkg/authserver/server_impl.go(upstreamIdentityBinding),pkg/authserver/server/handlers/user.go(resolveUser, mismatch branch),pkg/authserver/storage/types.go(MatchesBinding): the compare is an exact string match and there is no way to say that a new issuer is the same IdP. Scenario: an operator changes the issuer fromhttps://idp.example.comtohttps://idp.example.com/, or moves to a custom domain whosesubvalues are unchanged. Every user gets a new local ID on the next sign-in and loses their upstream connections, and the old accounts are orphaned. Fix: normalise the trailing slash for OIDC as the plain-OAuth2 path already does for hosts. For real migrations, add an optional list of accepted legacy issuers that is re-stamped on use, or at least log the replaced link at Warn and document the effect indocs/arch/11-auth-server-storage.md.
Simpler alternative: store one binding record per upstream name (issuer, claim) with set-if-absent on first boot of the new binary. Compare it with the configured binding at startup and fail with a clear message ("flush the store or rename the upstream") on mismatch. That removes the per-row compare-and-swap, the swapper, the decorator unwrapping and the unstamped state, and it closes finding 1 completely. It gives up the automatic replace-on-mismatch behaviour in exchange for an operator action at repoint time, which the PR docs already ask for.
The PR is also well over the 400-line and 10-file guideline. The remembered-consent rewrite and the device error-mapping extraction are separable from the storage and binding change.
🤖 Reviewed with Claude Code
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #7347 +/- ##
==========================================
+ Coverage 82.68% 82.70% +0.01%
==========================================
Files 947 947
Lines 97351 97672 +321
==========================================
+ Hits 80499 80779 +280
- Misses 16847 16888 +41
Partials 5 5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
50b426a to
72d40d2
Compare
|
Thanks. I took most of this. The new commits are on top of a rebase onto main.
On size: the remembered-consent change fixes a check-then-use race that this PR introduced. The callback checked the row's owner and then resolved the user again through a path that could create or replace one. So I'd rather keep it here than split it out. The device error mapping moved into a helper because the handler went over the cyclomatic limit. Its behaviour is unchanged apart from the new 403 case. |
rdimitrov
left a comment
There was a problem hiding this comment.
Re-review. Points 2 and 3 are resolved. Point 4 is resolved for the default build path: NewOIDCProvider always runs go-oidc discovery, which enforces the exact issuer. Point 1 is documented accurately. go test -race ./pkg/authserver/... passes locally. A downstream embedder builds against this head, and its storage and broker tests pass. Nothing here blocks merge. Three things are worth acting on:
-
The plain OAuth 2.0 binding hashes the port.
oauth2BindingIssuer(server_impl.go) hashesstrings.ToLower(u.Host), andu.Hostincludes the port. If an operator changeshttps://api.example.com/usertohttps://api.example.com:443/user, the host is the same but the binding differs. Every user then gets a new local account and loses their upstream connections. The PR says URL edits that don't change the host are safe, so this case breaks that promise. Fix: hashu.Hostname()and drop the scheme's default port. Converting an IDN host to its punycode form would also help. -
Embedders that wrap storage silently lose stamping. The normal Go pattern is
struct{ storage.Storage }with noUnwrap, and the two downstream embedders I checked both wrap storage this way. On such a wrapper,ProviderIdentitySwapperForreturns nil. I checked this with a probe test. The consequence is that legacy rows are never stamped and a repoint refuses users. The docs cover this, but at runtime nothing tells the operator.NewHandlerbuilds the resolver once, so a single WARN at startup when bindings are configured and the swapper is nil would not be noisy. A sentence in theProviderIdentitySwapperdoc saying that wrappers should forward it would also help. -
Please file the per-upstream binding record as an issue before merge. Without it, a dormant user's row stays claimable on every future repoint, not just the first one. The resolver accepts these rows read-only, so it never closes that window. A tracked issue is enough, since this PR is already a strict improvement over main.
One more risk for the docs: an operator-managed repoint is a rolling restart, so old-config and new-config pods share Redis for a short window. They then replace each other's rows. That doesn't let one person take over another's account, but it creates orphaned users, and users who sign in during the window lose their connections. The advice to "cut over cleanly" can't be followed through the operator as written. Either recommend scaling to zero, or point to the Recreate strategy.
|
@jhrozek here is a follow-up on the mecatl side, for once this is released. It doesn't block this PR. mecatl's protected auth storage,
The fix belongs in mecatl when it pins the release that contains this PR: Mecatl's phase 2 tracking issue (stacklok/mecatl#2545) requires #7256 to be "released and pinned by Mecatl". Without this forwarding, the pin alone doesn't give mecatl the protection. |
ChrisJBurns
left a comment
There was a problem hiding this comment.
LGTM. One low-severity note inline: it's harmless with today's single-issuer configuration, but worth fixing or documenting.
Store Issuer and SubjectClaim on ProviderIdentity in memory and Redis (additive omitempty JSON members so pre-upgrade rows still decode as unstamped and older readers ignore the new fields). Add optional ProviderIdentitySwapper with atomic CompareAndSwapProviderIdentity so callers can stamp unstamped rows without clobbering timestamps and atomically replace mismatched rows while detaching the previous user's reverse index. Harden Redis DeleteUser and GetUserProviderIdentities against stale reverse-index entries, and preserve binding fields in MigrateLegacyUpstreamData. Keep UserStorage unchanged for external storage decorators. Co-authored-by: Mecatl <[email protected]>
Stamp each upstream's issuer and subject claim onto new provider-identity rows during sign-in (OIDC issuer + subject_claim, or mode-prefixed endpoint URL + extraction rule for plain OAuth 2.0) and enforce them on lookup across authorization-code callback, remembered consent, and device verification. Legacy unstamped rows match on first use and are atomically stamped via ProviderIdentitySwapper with a once-per-resolver WARN (decision A1). Mismatched rows create a new user and atomically replace the link, leaving the previous user untouched (decision B1), while respecting WithCreateOnlyFor and refusing to adopt a mismatched row in resolveLinkFailure. Keep ResolveUser's signature unchanged and skip stamping when external decorators omit ProviderIdentitySwapper. Co-authored-by: Mecatl <[email protected]>
Verify that the stored ProviderIdentity row's issuer and subject claim match the requested subject.Ref before resolving to a local user. Rows stamped under a different issuer or subject claim (or half-stamped rows) are refused with subject.ErrUnknown without writing to storage. Accept pre-upgrade unstamped rows read-only and log a once-per-resolver WARN without subject or user PII, matching decision A1 and preserving compatibility with external decorators that do not persist the new fields. Co-authored-by: Mecatl <[email protected]>
Update auth-server storage, Redis storage, and token-exchange delegation documentation for ProviderIdentity's Issuer and SubjectClaim fields, matching and unstamped-row rules, atomic compare-and-swap behavior, and operator guidance for migrating identity providers or subject claims. Co-authored-by: Mecatl <[email protected]>
Restrict swapper discovery to ToolHive's own storage decorators via storage.ProviderIdentitySwapperFor so an external decorator exposing Unwrap() is never bypassed to a backing store underneath. Reject non-string JSON binding fields in the Redis CAS Lua script instead of coercing them to empty strings, simplify rememberedIdentityRejected and NewHandler to satisfy gocyclo, add edge-case tests, and align doc wording. Co-authored-by: Mecatl <[email protected]>
The stamped issuer for plain OAuth 2.0 upstreams was the raw endpoint URL, so a path, query or same-host endpoint change gave users new accounts and the address was stored in Redis. Stamp the mode and a hash of the lower-cased endpoint host instead. Co-authored-by: Mecatl <[email protected]>
The resolver matched rows against the token's issuer and claim, but sign-in stamps the sign-in issuer and claim. Any provider entry whose token issuer differs would always return subject_unknown. Co-authored-by: Mecatl <[email protected]>
The line said the row would be stamped on the next sign-in, which is false when the storage has no compare-and-swap. Co-authored-by: Mecatl <[email protected]>
A remembered-consent callback read the identity row twice and could create or replace a user after the owner check. A lost stamp race returned the user loaded before the stamp. A binding mismatch reused the "cannot create users" error or ended as a server error. Look the expected user up without writing, re-read the row once after a lost stamp, and refuse a binding mismatch as access denied (403 on the device flow) through ErrIdentityBindingMismatch. Roll back the candidate user when the link is gone and the error proves our write did not land. Co-authored-by: Mecatl <[email protected]>
DeleteUser now keeps a provider-identity row whose JSON cannot be decoded, where it used to delete every row in the user's own index. Delete such a row again. Also document how the swapper capability is found and add tests for the reverse index after a swap and for the decorators the lookup peels. Co-authored-by: Mecatl <[email protected]>
Cover an unstamped row on both backends through the resolver and sign-in, and check that a real sign-in through the server constructor stamps the configured issuer and subject claim. Co-authored-by: Mecatl <[email protected]>
Say that unstamped rows are taken over by a new configuration until a sign-in stamps them, that existing tokens keep the old account, that renaming an upstream does not isolate it, and that the closed gate refuses resolution before the resolver runs. Co-authored-by: Mecatl <[email protected]>
Keep both handlers under the cyclomatic complexity limit, and satisfy the test helper and import-order lint rules in the new storage test. Co-authored-by: Mecatl <[email protected]>
The race-recovery paragraph still said a missing link deletes nothing, but a link write that failed with already-exists or changed now rolls back the unlinked candidate. Also make the two-sub_id case read as two separate cases. Co-authored-by: Mecatl <[email protected]>
resolveLinkFailure always rolls back the candidate before adopting a race winner; the doc said the rollback was conditional there too. ErrIdentityBindingMismatch is also returned when a re-read during race settlement finds another binding. Drop a test assertion that only checked its own table input. Co-authored-by: Mecatl <[email protected]>
Co-authored-by: Mecatl <[email protected]>
Co-authored-by: Mecatl <[email protected]>
Co-authored-by: Mecatl <[email protected]>
Co-authored-by: Mecatl <[email protected]>
Co-authored-by: Mecatl <[email protected]>
Co-authored-by: Mecatl <[email protected]>
Co-authored-by: Mecatl <[email protected]>
The replacement log was raised to WARN and lost its user ID; a test now checks it fires once at WARN with the provider and without the subject or either user ID. Co-authored-by: Mecatl <[email protected]>
The helper is not the only place the sub default is applied: the upstream provider applies it when validating ID tokens. Say instead what sharing it guarantees. Also reflow the resolver New doc. Co-authored-by: Mecatl <[email protected]>
main now declares the same generic helper in the package's tests. Co-authored-by: Mecatl <[email protected]>
The subject resolver compares a stored row with the token's issuer and the provider's subject claim, which equal the sign-in binding only while a provider has a single issuer. Fail when the resolver mapping would give one provider more than one issuer, so a second issuer cannot silently never match rows stamped with the sign-in issuer. The check runs where the server builds its resolver, which both the run-config and library paths use; subjectresolver.New is unchanged. Correct the docs and comments that said the resolver compares against the sign-in binding. Co-authored-by: Mecatl <[email protected]>
The plain OAuth 2.0 binding hashed the lower-cased URL host including the port, so writing https://api.example.com/user as https://api.example.com:443/user changed the binding and gave every user a new account. Hash the lower-cased hostname and keep the port only when it is not the scheme's default, joining with net.JoinHostPort so IPv6 literals stay correct. Docs now state exactly which edits keep the binding and which change it. Co-authored-by: Mecatl <[email protected]>
On storage without the ProviderIdentitySwapper capability, every sign-in that matched an unstamped row logged at DEBUG, so an operator whose wrapper hides the capability never saw that rows stay unstamped. Log the first occurrence per user resolver at INFO, with only the provider ID, and keep later ones at DEBUG. Co-authored-by: Mecatl <[email protected]>
State what a storage wrapper must do about ProviderIdentitySwapper: forward it when it wraps real rows, leave it out when it serves rows itself, and never fill in Issuer or SubjectClaim unless computed as the auth server does, since a differing value is a binding mismatch. Replace the "cut over cleanly" advice. Mixed old and new replicas on one Redis replace each other's rows and mint extra users, which orphans users but does not let anyone take over another account. Recommend stopping all replicas first. The operator sets no Deployment strategy and has no setting for one, so the doc recommends scaling to zero. Co-authored-by: Mecatl <[email protected]>
Bring the docs and comments in line with the binding code. Replace the old cut-over advice in the Redis guide with the stop-all-replicas steps, and add MCPRemoteProxy to the operator rollout. Describe the OAuth 2.0 issuer as a hash of host plus any non-default port, say the unstamped log lines are once per resolver, and correct the storage decorator marker comment: a wrapper outside the package carries it only by embedding one of the package's decorators. Co-authored-by: Mecatl <[email protected]>
Assert the no-swapper INFO line appears exactly once across two sign-ins, that the second sign-in logs the DEBUG line, and that neither subject values nor user IDs reach the logs. Drop the host case, port and host cases from the endpoint-selection test, since the issuer normalisation test already covers them. Co-authored-by: Mecatl <[email protected]>
72d40d2 to
a214f3b
Compare
|
Thanks for the second pass, and for building against the head. Port: fixed. The binding now hashes the hostname and keeps the port only when it isn't the scheme's default, so writing out :443 on https no longer changes it. I left punycode out. Swapper: I added the sentence on ProviderIdentitySwapper. A wrapper over real rows should forward it, and storage that serves identity rows itself should leave it nil and not fill in Issuer or SubjectClaim unless it computes them exactly as the auth server does. I didn't add a WARN. An embedder that looks identity rows up in a directory and refuses writes has a nil swapper on purpose, and a WARN would fire on every rebuild for it. The first unstamped match on a storage without a swapper is now logged once per resolver at INFO instead. The sealed-storage case on your side is real, and it makes sense to fix it when that wrapper is wired over Redis. Binding record: filed as "Record the identity binding once per upstream" (#7360). Rollout: the docs now say to stop all replicas before repointing an upstream, and that mixed replicas orphan users but don't allow takeover. The operator has no Deployment strategy setting, so Recreate isn't available there. The docs say to scale to zero. |
Codespell flags "unparseable" in the test case name added with the default-port change. Co-authored-by: Mecatl <[email protected]>
Summary
A provider-identity row is keyed by the upstream's name and the subject value, and it records nothing about which IdP or which claim produced that value. Suppose an operator keeps the store but points upstream
defaultat another IdP, or changes itssubject_claim. Every old row still matches. A person at the new IdP whose subject value equals an old one is signed in as that old user. Once ID-JAG subject resolution is enabled, they are also resolved to that user.Treating a mismatch as "not found" doesn't fix this by itself. Link creation is set-if-absent, so a second create for the same key fails, and the race recovery then adopts the user the existing row points at. A mismatched row has to be replaced atomically.
IssuerandSubjectClaimit was created under. Redis stores them as optional JSON members, so older rows still decode and older binaries ignore the new members.ProviderIdentitySwappercompare-and-swap, implemented by the memory and Redis stores.UserStorageis unchanged.subject_unknownand writes nothing.Providerto carry the sign-in binding and compare rows with that.Closes #7256
Type of change
Test plan
task test)task test-e2e)task lint-fix)task testpasses for every package this change touches. The only failures were outside it: the real-Envoy and real-Squid config tests, which need a running Docker daemon, and one run ofTestDCRRecheckTick_KeepsCurrentClientOnFailure. That test passes 20 times in a row on its own, and this change does not touchpkg/authserver/runner.The acceptance cases run on both memory and miniredis, through the shared storage contract suite and through real sign-in plus resolution:
There are also concurrent cases: two replacements of one row, and two stamps of one row.
Changes
pkg/authserver/storage/types.go,memory.go,redis.go,unwrap.goIssuerandSubjectClaimonProviderIdentity; optionalProviderIdentitySwapper(compare-and-swap) andProviderIdentitySwapperFor; Redis Lua compare-and-swap; owner-checkedDeleteUser; reverse-index reads skip stale entriespkg/authserver/server_impl.goupstreamIdentityBindingderives each upstream's binding; the subject resolver is keyed by the sign-in issuer and refuses a second issuer per provider at startuppkg/authserver/server/handlers/user.goErrIdentityBindingMismatchpkg/authserver/server/handlers/callback.go,device_verification.go,handler.gopkg/authserver/subjectresolver/resolver.godocs/arch/11-auth-server-storage.md,docs/redis-storage.md,docs/arch/17-token-exchange-delegation.mdDoes this introduce a user-facing change?
Yes.
subject_claimunder the same name.:443on https, or:80on http, changes nothing);subject_path;subject_fields, including their order.subject_mode: resolve. A row stamped under another issuer or claim is refused withsubject_unknown. The endpoint gate is still closed, so this is resolver behaviour for when it opens.access_denied, and the server-side remembered consent session is deleted. The next attempt shows the consent page.access_deniedin the browser and 403 on the device page, with a hint that the identity link was created under a different issuer or subject claim. A store without compare-and-swap also never stamps rows.ProviderIdentitySwapper, the first unstamped match per resolver is logged once at INFO, naming only the provider. Later matches stay at DEBUG. Before, every sign-in logged at DEBUG.subject_unknown.issuerandsubject_claimmembers.{...}hash tag in the key prefix, like the other multi-key scripts.DeleteUserremoves a provider row only if that user still owns it.Special notes for reviewers
ProviderIdentitySwapperFordeliberately peels only ToolHive's own storage decorators, never a decorator it doesn't know.ProviderIdentitySwapperdoc says which wrappers should forward the capability.Recreateis not an option there.CreateProviderIdentityandNewHandlernow reject a row or upstream that sets only one of issuer and claim.