Skip to content

fix: bind OAuth state to the server incarnation so stale writes cannot re-create credentials (Spec 116 PR2b; #1607) - #1621

Merged
Dumbris merged 12 commits into
mainfrom
fix/1607-oauth-incarnation-binding
Oct 14, 2026
Merged

Dumbris merged 12 commits into
mainfrom
fix/1607-oauth-incarnation-binding

Conversation

@Dumbris

@Dumbris Dumbris commented Oct 13, 2026

Copy link
Copy Markdown
Member

Scope

Spec 116 PR2b only (#1607; specs/116-config-commit-consistency tasks T048, T048a-e, T048g, T048i, T055b, T055d, T055e and the OAuth halves of T055c/T055f). It binds OAuth state to the server incarnation, building on PR4's gated OAuth transport (oauth.Env) and Retire(). An OAuth write from an old instance that was already in flight (a token refresh or a login completion) can no longer land after the removal purge and re-create credentials under the name. A same-name re-add never sees the old server's tokens.

Design

  • Credential binding. commitview.ServerGen gains OAuthEpoch. It is the generation of the commit that created the name, or of the last commit that cleared its OAuth state because its OAuth config changed. CredentialBinding{Incarnation, OAuthEpoch} comes from ServerGen.Binding(). Prepare computes the epoch from the commit's OAuth-clear set (PrepareInput.OAuthCleared), so the snapshot, the row (UpstreamRecord.OAuthEpoch, written in the transaction that deletes the credentials) and the commit result all carry the same view.

  • Instances are bound at construction. GenerationChange.Binding reaches the manager's desired view at step 7. newWiredClientLocked binds each instance to the binding of the generation it was built for, never read from the row (R6.1). The transient manual-login clients get the registered instance's binding, as they already share its gate. A binding move always unregisters (and retires) the instance, even when the connection settings are otherwise equal.

  • Bound storage operations (internal/storage/oauth_binding.go). Each is one bbolt transaction that reads the upstreams row and acts only while the row carries the binding:

    • UpdateOAuthTokenIfBound: token saves, including a login's paired token and client.
    • SaveOAuthClientIfBound: DCR saves.
    • SaveOAuthCompletionEventIfBound.
    • DeleteOAuthTokenIfBound: the 5xx clear.
    • ClearOAuthClientIfBound: the config-build hygiene clears and the refresh invalid_client clear. It keeps the tokens (R9.4).
    • ClearOAuthClientIfBoundAndClientID: the login's stale-DCR clears.

    Records carry the epoch they were written under, and bound reads ignore records of any other epoch. Every write to oauth_tokens takes Revision = bucket.NextSequence(). Bound clears act only on the revision their caller read (R7.3).

  • Refresh coordinator state (flight, latch, cooldown, re-registration, lastSavedAt) is keyed by (server key, binding) (R7.1). Forget/ForgetServer drop it for purged and OAuth-cleared servers (commit step 6) and on logout. RefreshManager ignores a terminal outcome whose binding is not the registered instance's binding (Runtime.CurrentCredentialBinding).

  • Construction-time check. storage.Manager.CheckCommittedView runs in the manager before addServerConfigAt/ReplaceInstanceAt build an instance. It uses the committed view the manager holds. A stale worker therefore builds no instance and no OAuth config.

  • Standalone logout uses BoltDB.ClearOAuthTokenForStandaloneLogout (exact key, current state) (R8.3). scripts/check-upstream-write-sites.sh forbids the unconditional OAuth mutators in non-test internal/upstream/** and internal/oauth/**, and allows the standalone clear only in internal/upstream/cli/client.go. Self-test cases are added.

  • Superseded failures. When storage refused a login's result, or the instance was retired, the failure is logged and not recorded on the server status by name. The live check showed it flipping the re-added server into an error state.

Deviations from the spec text (documented in tasks.md, "PR2b implementation note")

  • The zero binding means "unbound", i.e. the current state. Once a commit exists, a write needs the row to exist and takes the row's epoch, and a read sees every record. Daemon instances are always bound. Refusing every unbound write would break mcpproxy auth login without a daemon.
  • Records store only the epoch, not the incarnation. An epoch value is unique to one commit and name. Bound writers check both incarnation and epoch on the row.
  • Upgrade safety. A server with no stored stamp (a database from before Spec 116) gets an incarnation but keeps epoch 0, so records written before PR2b stay readable and an upgrade signs nobody out.
  • Where CheckCommittedView runs. It lives in the manager's constructors, not in each worker. If storage cannot be read, construction goes ahead (the bound writes still guard the credentials). A missing or moved row refuses construction.
  • Unconditional BoltDB mutators stay exported for fixtures and tests; the write-site grep enforces the ban instead of unexporting them.
  • The login-path stale-DCR clears keep their client-id predicate inside the bound transaction. That flow holds the client id it sent, not a record revision.

Lock order

Lock order is unchanged. The binding checks and CheckCommittedView are single bbolt transactions (L2 leaves) taken with no runtime lock held. The coordinator's mutex stays a leaf, and Forget runs under L0 after the approval locks are released (L0 → leaf).

Compatibility

  • Rows and records without the new fields read as epoch 0 / revision 0, and legacy rows keep epoch 0, so no migration is needed and existing sign-ins survive the upgrade.
  • REST payloads are unchanged except that oauth_epoch appears (omitempty) where a ServerGen is serialised.
  • Login, refresh, logout, DCR, stale-client recovery and concurrent-login pairing behave as before on a live server.
  • A refresh result parked across a removal was already discarded on main by the Spec 113 FR-006a generation CAS. The new protection matters for login completions, DCR saves, clears and completion events.

Verification

  • Failing-first tests (separate commit). They fail to build on the parent. Mutating the binding check or the revision check out makes them fail.
    • Storage: T2.18, T2.20, T048e.
    • oauth: T2.9, T2.13, T2.15 a/b with the same-binding variants, T2.16.
    • core: T2.9 through a real code exchange against tests/oauthserver.
    • manager: T2.14.
    • runtime: T2.14 with the commit parked at afterStorage, and T2.17.
  • go test -race -tags server -timeout 30m -skip "E2E|Binary|MCPProtocol|TestInfoEndpoint|TestGracefulShutdownNoPanic|TestSocketInfoEndpoint" ./internal/...: 84 packages ok.
  • New tests at -race -count=20 (core/runtime at -count=10), with GOMAXPROCS=1 and 4: ok.
  • ./scripts/test-api-e2e.sh on a scratch port: 70/70.
  • The write-site self-test: 167/167.
  • golangci-lint v2, bare and --build-tags server: no finding in a changed file.
  • Windows, Linux, server and qa_hooks builds pass; make build passes.
  • Live, on fresh scratch daemons with a local OAuth fixture. Baseline is main plus only the park point.
    • A login's token save is parked after the token response, then the server is removed (and re-added). On main a token record is re-created for the removed name, and the re-added server connects with the old server's token. On this branch there are 0 records, and the re-added server stays at "Sign-in required".
    • A signed-in server that is removed and re-added starts unauthenticated, with its own DCR client.
    • Normal DCR login, refresh (paired) and logout work.
    • Two concurrent logins keep the stored token and client paired.
    • Evidence: docs/qa/0.70.0-ux-2026-10-10/remediation/evidence/1607/EVIDENCE.md (local QA tree).

Fixes #1607

🤖 Generated with Claude Code

…PR2b; #1607)

T2.9, T2.13, T2.14, T2.15 (a/b, with the same-binding R7.3 variants),
T2.16, the OAuth half of T2.17, T2.18, T2.20 and T048e, plus the commit's
epoch rule and the manager's binding threading. They fail to build on the
parent: the credential binding API does not exist there yet.
…t re-create credentials (Spec 116 PR2b; #1607)

Every committed server view now carries an OAuth epoch next to its
incarnation: the generation of the commit that created the name or last
cleared its OAuth state because its OAuth configuration changed.
{Incarnation, OAuthEpoch} is the server's credential binding. The commit
computes it in Prepare (from the commit's OAuth-clear set), stamps it on
the upstreams row in the transaction that deletes the credentials, and
records it in the manager's desired view; the manager binds every instance
(and the transient clients of a manual login) to the binding of the
generation it was built for.

Every OAuth write, read and clear an instance makes goes through a storage
method that checks the binding against the row in the same bbolt
transaction: token saves (code exchange with its paired client, refresh),
DCR client saves, completion events, the 5xx token clear, the config-build
DCR hygiene clears and the clears after a rejected refresh or login. A
write that was already past its network round-trip when the server was
removed, replaced or reconfigured is discarded, so nothing is re-created
under the name and a same-name re-add starts signed out. Records carry
the epoch they were written under (reads ignore other epochs) and a bucket
sequence Revision; bound clears act only on the revision their caller read.

Refresh coordinator state (flights, latch, cooldown, re-registration,
lastSavedAt) is keyed by (server key, binding) and dropped for purged and
OAuth-cleared servers; the RefreshManager ignores a terminal outcome of a
superseded binding. Before building an instance the manager checks that the
stored row still carries the committed view it holds. A failure of a
superseded login is not recorded on the replacement's status. The
standalone CLI logout uses ClearOAuthTokenForStandaloneLogout, and the
write-site script forbids the unconditional OAuth mutators in
internal/upstream and internal/oauth.
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: fix/1607-oauth-incarnation-binding

Available Artifacts

  • archive-darwin-amd64 (31 MB)
  • archive-darwin-arm64 (28 MB)
  • archive-linux-amd64 (19 MB)
  • archive-linux-arm64 (17 MB)
  • archive-windows-amd64 (31 MB)
  • archive-windows-arm64 (28 MB)
  • frontend-dist-pr (0 MB)
  • installer-dmg-darwin-amd64 (27 MB)
  • installer-dmg-darwin-arm64 (25 MB)
  • smart-mcp-proxymcpproxy-go0PIRSP.dockerbuild (0 MB)

How to Download

Option 1: GitHub Web UI (easiest)

  1. Go to the workflow run page linked above
  2. Scroll to the bottom "Artifacts" section
  3. Click on the artifact you want to download

Option 2: GitHub CLI

gh run download 38459144233 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

@codecov-commenter

codecov-commenter commented Oct 13, 2026 •

Copy link
Copy Markdown

…resh outcomes to the schedule's binding, scan commit files for OAuth clears (Spec 116 PR2b review r1; #1607)
…h, including one that keeps the access token (Spec 116 PR2b review r2; #1607)
…g's schedule against a late save, document startup schedules (Spec 116 PR2b review r3; #1607)
…describe bound OAuth reads as epoch-filtered (Spec 116 PR2b review r4; #1607)
…resh read, and treat a rewrite since as superseding (Spec 116 PR2b review r5; #1607)
… revision check as superseding: no latch, no terminal outcome (Spec 116 PR2b review r6; #1607)
…ht's own clear as superseding: no latch, no terminal outcome (Spec 116 PR2b review r7; #1607)
…tance's binding and record it only after the bound DB event landed (Spec 116 PR2b review r8; #1607)

A login completion of an instance a removal/re-add or an OAuth-config commit
superseded was refused by the binding-checked DB write but still set the
name-only recent-completion flag, so a same-name replacement skipped its
automatic OAuth deferral and could open browser authorization unasked.
The completion record now carries the binding; MarkOAuthCompletedWithDBBound
records only when the bound write landed; core instances mark and read it
through MarkOAuthCompletedBound / HasRecentOAuthCompletionBound.
… bind the in-process OAuth completion callback to the completing instance (Spec 116 PR2b review r9; #1607)

A same-binding registration rewrite that superseded an invalid_client
rejection skipped the latch but still returned the terminal error, so a
proactive attempt failed its schedule and reported re-authentication
required; the rejection is now re-classified as non-terminal and retried.

MarkOAuthCompletedBound still invoked the name-only completion callback,
whose RetryConnection disconnected and reconnected a same-name replacement
for a superseded instance's login; the completion is now dropped when the
manager's current binding differs, and the manager's bound callback
re-checks the binding before retrying.
…e registry critical section and retry only that instance (Spec 116 PR2b review r10; #1607)
@Dumbris
Dumbris merged commit d89d0d2 into main Oct 14, 2026
50 checks passed
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.

Spec 116 PR2b: bind OAuth token reads/writes to the server incarnation

2 participants