Skip to content

Bind provider-identity rows to their issuer and claim - #7347

Merged
jhrozek merged 32 commits into
stacklok:mainfrom
jhrozek:identity-link-binding
Nov 28, 2026
Merged

jhrozek merged 32 commits into
stacklok:mainfrom
jhrozek:identity-link-binding

Conversation

@jhrozek

@jhrozek jhrozek commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

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 default at another IdP, or changes its subject_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.

  • Rows record their binding. Each row now stores the Issuer and SubjectClaim it was created under. Redis stores them as optional JSON members, so older rows still decode and older binaries ignore the new members.
  • Lookups check the binding. Sign-in, remembered consent, device verification and ID-JAG resolution accept a row only when its issuer and claim equal the upstream's current values.
    • Sign-in creates a new local user and replaces the row through a new optional ProviderIdentitySwapper compare-and-swap, implemented by the memory and Redis stores. UserStorage is unchanged.
    • Resolution answers subject_unknown and writes nothing.
  • Rows created before this change are bound on first use. Such a row has neither value. It is accepted and stamped with the current values the first time its user signs in interactively.
  • Plain OAuth 2.0 binding. These upstreams have no issuer, so they are bound to their mode plus a SHA-256 hash of the identity endpoint's host (and its port when not the default), and to their subject extraction rule. The port counts only when it is not the scheme's default. Path, query, trailing-slash, host-case or written-out default-port edits don't re-key users, and no endpoint address is stored.
  • Remembered consent only looks up. It reads the row once and accepts it only for the user who gave the consent. It no longer goes through user creation.
  • A lost stamp race is re-checked. If another request stamps or replaces a row between the read and the stamp, sign-in reads the row once more and decides again. It never returns the user it loaded before.
  • The resolver compares with the token's issuer. The ID-JAG subject resolver compares a row with the issuer the token arrived under and the provider's subject claim. Both equal the sign-in binding while a provider has one issuer, which is the only setup today. A startup check refuses a second issuer for one provider. A cross-issuer mapping is planned in "Delegated access: tokens and actors from third-party issuers" (Delegated access: tokens and actors from third-party issuers #7159); it will need Provider to carry the sign-in binding and compare rows with that.

Closes #7256

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 passes 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 of TestDCRRecheckTick_KeepsCurrentClientOnFailure. That test passes 20 times in a row on its own, and this change does not touch pkg/authserver/runner.

The acceptance cases run on both memory and miniredis, through the shared storage contract suite and through real sign-in plus resolution:

  • after an issuer change, and separately after a claim change, an old row matches neither sign-in nor resolution;
  • a row created under the current values keeps working;
  • an unstamped row is accepted and stamped.

There are also concurrent cases: two replacements of one row, and two stamps of one row.

Changes

File Change
pkg/authserver/storage/types.go, memory.go, redis.go, unwrap.go Issuer and SubjectClaim on ProviderIdentity; optional ProviderIdentitySwapper (compare-and-swap) and ProviderIdentitySwapperFor; Redis Lua compare-and-swap; owner-checked DeleteUser; reverse-index reads skip stale entries
pkg/authserver/server_impl.go upstreamIdentityBinding derives each upstream's binding; the subject resolver is keyed by the sign-in issuer and refuses a second issuer per provider at startup
pkg/authserver/server/handlers/user.go Binding checks, stamping, atomic replacement, the lookup-only path for remembered consent, ErrIdentityBindingMismatch
pkg/authserver/server/handlers/callback.go, device_verification.go, handler.go Wiring and error mapping
pkg/authserver/subjectresolver/resolver.go Refuses rows stamped under another issuer or claim than the token's
docs/arch/11-auth-server-storage.md, docs/redis-storage.md, docs/arch/17-token-exchange-delegation.md The row fields, the matching rule, and how to migrate an IdP

Does this introduce a user-facing change?

Yes.

  • Changing an upstream's issuer or subject_claim under the same name.
    • Before: the next sign-in returned the old local user, even for a different person whose subject value matched.
    • After: for a row stamped under the old values, sign-in creates a new local user and replaces the link. The old user record is kept. Upstream connections stored under the old user don't carry over, so users must reconnect them.
  • Rows that existed before this change.
    • Before: rows had no binding.
    • After: they are stamped with the current issuer and claim at the user's next interactive sign-in, logged once per resolver at WARN. Until then they match whatever configuration sees them first. So a row unused between the upgrade and a repoint is taken over by the new configuration.
  • Plain OAuth 2.0 upstreams. These edits now give users new local accounts:
    • changing the identity endpoint's host, or its port when it is not the scheme's default (writing out :443 on https, or :80 on http, changes nothing);
    • changing the mode;
    • changing subject_path;
    • changing subject_fields, including their order.
  • ID-JAG subject_mode: resolve. A row stamped under another issuer or claim is refused with subject_unknown. The endpoint gate is still closed, so this is resolver behaviour for when it opens.
  • Remembered consent after a repoint.
    • Before: the remembered consent was reused, for the old user.
    • After: one access_denied, and the server-side remembered consent session is deleted. The next attempt shows the consent page.
  • A later upstream, or a store without compare-and-swap, meeting a mismatched row.
    • Before: resolved to the linked user. On a store without compare-and-swap that would have been the old account.
    • After: access_denied in 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.
  • Storage without a swapper. For storage that has no 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.
  • A second issuer for one provider. No setting produces this today. If a later change adds one, startup refuses it with an error naming the provider and its issuers. Before, the resolver accepted it and every user who had signed in got subject_unknown.
  • Redis.
    • Provider-identity JSON gains optional issuer and subject_claim members.
    • On Redis Cluster, replacing a row needs the {...} hash tag in the key prefix, like the other multi-key scripts.
    • DeleteUser removes a provider row only if that user still owns it.
  • Existing tokens. They are unchanged by a repoint: issued access and refresh tokens keep the old account. Operators should revoke sessions before repointing. "Refresh tokens are sent to a repointed upstream's new IdP" (Refresh tokens are sent to a repointed upstream's new IdP #7333) tracks binding the upstream token rows too.

Special notes for reviewers

  • A store without the compare-and-swap capability refuses a mismatched row instead of adopting it. Today's behaviour there would be to adopt the old row's user, which is exactly the takeover this change removes.
    • ProviderIdentitySwapperFor deliberately peels only ToolHive's own storage decorators, never a decorator it doesn't know.
    • On such a store, unstamped rows match without a write and are never stamped.
  • A nil swapper is a legitimate state, so there is no WARN for it. Storage that serves identity rows itself, for example by looking each one up in a directory and refusing writes, leaves the capability unimplemented and its rows stay unstamped. A WARN would fire on every rebuild of such an embedder. The first unstamped match is logged once at INFO instead, and the ProviderIdentitySwapper doc says which wrappers should forward the capability.
  • The startup check for a second issuer cannot fire today. The resolver map has one entry per provider. It guards the cross-issuer mapping planned in "Delegated access: tokens and actors from third-party issuers" (Delegated access: tokens and actors from third-party issuers #7159), which removes it.
  • Accepted trade-off: the window for dormant users stays open. A user who stays away from sign-in through a repoint keeps an unstamped row that the new configuration can claim. The docs name the window and ask for separate rollouts. A per-upstream binding record would close it. It is tracked in "Record the identity binding once per upstream" (Record the identity binding once per upstream #7360).
  • Rows are stamped lazily. There is no startup scan, and stamping never finishes by itself. The docs say so and recommend a fresh store when old accounts must not carry over. The docs also explain why renaming the upstream is not enough: the legacy-data migration copies unstamped rows to the current upstream name at startup.
  • Mixed-configuration replicas against one store replace each other's rows and create extra users. That orphans users and drops their upstream connections, and it does not let one person take over another's account. The docs say to stop all replicas before repointing (scale to zero). The operator has no Deployment strategy setting, so Recreate is not an option there.
  • Validation of half-stamped rows. CreateProviderIdentity and NewHandler now reject a row or upstream that sets only one of issuer and claim.

@jhrozek
jhrozek requested a review from ChrisJBurns as a code owner November 26, 2026 19:08

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

  1. pkg/authserver/server/handlers/user.go (loadAndStamp, stampUnstampedIdentity, identityAcceptable) and pkg/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 same sub matches 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 for resolve callers. 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.

  2. pkg/authserver/storage/unwrap.go:24-45 (ProviderIdentitySwapperFor): when it returns nil (an embedder's own Storage wrapper, 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 existing Unwrap() convention. Fix: log once at Warn in NewUserResolver when bindings are configured and the swapper is nil, and add a test that fails when a type in the package implements Unwrap() Storage but is not handled.

  3. pkg/authserver/server_impl.go (upstreamIdentityBinding) and pkg/authserver/config.go (signInUpstream, validateResolveIssuers): the binding is derived in two places and the resolver's Provider.RowIssuer/RowSubjectClaim just repeat the values the only caller already passes as the issuer and SubjectClaim. If the two derivations drift (for example issuer normalisation), every row is refused as subject_unknown or 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.

  4. 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 from https://idp.example.com to https://idp.example.com/, or moves to a custom domain whose sub values 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 in docs/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

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.63291% with 37 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.70%. Comparing base (2cb4005) to head (86902fd).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pkg/authserver/server/handlers/user.go 91.66% 12 Missing ⚠️
pkg/authserver/storage/unwrap.go 53.84% 6 Missing ⚠️
pkg/authserver/server_impl.go 90.56% 5 Missing ⚠️
pkg/authserver/server/handlers/callback.go 89.65% 3 Missing ⚠️
.../authserver/server/handlers/device_verification.go 72.72% 3 Missing ⚠️
pkg/authserver/storage/types.go 89.65% 3 Missing ⚠️
pkg/authserver/server/handlers/handler.go 90.00% 2 Missing ⚠️
pkg/authserver/storage/redis.go 95.55% 2 Missing ⚠️
pkg/authserver/storage/memory.go 96.96% 1 Missing ⚠️
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.
📢 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
jhrozek force-pushed the identity-link-binding branch from 50b426a to 72d40d2 Compare November 26, 2026 20:09
@jhrozek

jhrozek commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. I took most of this. The new commits are on top of a rebase onto main.

  1. Dormant rows: you're right that an unstamped row from before the upgrade can be taken over if the upstream is repointed before that user signs in again. I looked at stamping everything in a startup pass, and at a per-upstream binding record. Neither covers the case where the upgrade and the repoint ship in the same rollout. For the case they do cover, it takes an in-place repoint of an existing upstream name, a user who stays away for the whole window, and a matching subject value at the new IdP, all at once. For comparison, Keycloak's federated identity links, Kratos and Dex all key links on the provider alias and don't record an issuer at all. So I kept this to docs. The migration sections now say plainly that unstamped rows are taken over through both sign-in and ID-JAG resolution, that the upgrade and any repoint need to be separate rollouts with time between them, and that a fresh store is the only hard isolation. If you think it's worth closing in code anyway, the per-upstream record is the smaller fix, and I'm happy to do it as a follow-up.

  2. Swapper discovery: agreed, the switch duplicated Unwrap(). The lookup now follows Unwrap() only through types that implement an unexported storageDecorator() marker. All five decorators in the package carry it, and a wrapper from outside the package can't, so it still never reaches under an embedder's own storage. There's also a test that builds the server through the real constructor with the decorators turned on and checks that sign-in still stamps a row through them. Removing any one marker fails it. I didn't add the WARN. A nil swapper is a legitimate state for an embedder whose wrapper serves identity rows itself, and it would log on every resolver build there.

  3. Done. RowIssuer and RowSubjectClaim are gone. The resolver compares the row with the issuer it's keyed by and its SubjectClaim. Stamping, signInUpstream and validateResolveIssuers now share one helper for the OIDC binding, including the "sub" default.

  4. I didn't add slash normalisation. go-oidc's discovery requires the configured issuer to equal the IdP's iss exactly, and we never skip that check. So a slash-only config change fails at startup instead of re-keying anyone, and the stamped string is always the IdP's own form. A move to a custom domain is a real issuer change, and re-keying is the documented result. I didn't want to add a legacy-issuers option before someone asks for it. The replaced-link log is now WARN, with provider, issuer and claim only, and there's a test that it carries no subject or user ID.

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

  1. The plain OAuth 2.0 binding hashes the port. oauth2BindingIssuer (server_impl.go) hashes strings.ToLower(u.Host), and u.Host includes the port. If an operator changes https://api.example.com/user to https://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: hash u.Hostname() and drop the scheme's default port. Converting an IDN host to its punycode form would also help.

  2. Embedders that wrap storage silently lose stamping. The normal Go pattern is struct{ storage.Storage } with no Unwrap, and the two downstream embedders I checked both wrap storage this way. On such a wrapper, ProviderIdentitySwapperFor returns 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. NewHandler builds 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 the ProviderIdentitySwapper doc saying that wrappers should forward it would also help.

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

@rdimitrov

Copy link
Copy Markdown
Member

@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, internal/adapter/mcpbroker/sealedauthstorage.Storage, embeds storage.Storage. It deliberately has no Unwrap, and it can't carry the unexported storageDecorator marker. So ProviderIdentitySwapperFor returns nil for it. I confirmed that with a probe test against this head. On mecatl's Redis path this has two effects:

  • Rows from before the upgrade are never stamped. The takeover protection therefore never applies to existing mecatl users.
  • A repoint refuses every stamped user with access_denied instead of re-keying them.

The fix belongs in mecatl when it pins the release that contains this PR: sealedauthstorage.Storage should implement ProviderIdentitySwapper by forwarding to the inner store. Provider-identity rows aren't sealed, so plain forwarding is enough. It also needs a test showing that sign-in stamps and replaces rows through the decorator. as1server's cappedStorage embeds *storage.MemoryStorage, so it gets the method by promotion; a test asserting that would be worth adding.

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
ChrisJBurns previously approved these changes Nov 27, 2026

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

LGTM. One low-severity note inline: it's harmless with today's single-issuer configuration, but worth fixing or documenting.

jhrozek and others added 22 commits November 27, 2026 18:51
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]>
jhrozek and others added 3 commits November 27, 2026 18:51
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]>
jhrozek and others added 6 commits November 27, 2026 19:27
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]>
@jhrozek

jhrozek commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

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

Bind provider-identity rows to the issuer and subject claim that created them

3 participants