Skip to content

fix: retirement barrier so retired upstream instances cannot dial or send credentialed requests (Spec 116 PR4; #1564) - #1612

Merged
Dumbris merged 12 commits into
mainfrom
fix/116-pr4-retirement-barrier
Oct 13, 2026
Merged

Dumbris merged 12 commits into
mainfrom
fix/116-pr4-retirement-barrier

Conversation

@Dumbris

@Dumbris Dumbris commented Oct 13, 2026

Copy link
Copy Markdown
Member

Scope

Spec 116 PR4 (specs/116-config-commit-consistency, plan §PR4, tasks T080–T099): a per-instance retirement barrier. Once the upstream manager unregisters an instance (removal, endpoint/connection change, quarantine, same-name replacement, restart, ForceReconnectAll, Docker recovery) it is retired before the removing call returns, and from then on it cannot dial, launch a stdio/Docker/launcher process, write to its connections, run its OAuth client, preflight or discovery helpers, retry through net/http, or open the OAuth browser flow. Teardown (MCP close, process-group kill, docker stop) still runs.

Builds on PR3's unregisterLocked and Spec 117's managed.Client.Retire() (one Retire for both, per research.md). Not in this PR: binding OAuth tokens and refresh flights to the incarnation (#1607); oauth.Env and the coordinator's retired-refusal path are the hooks for it.

Design

  • internal/upstream/dialgate (new): Gate with Admit (read lock around one leaf operation), DialContext (dial and connection registration in one admitted section, retirement-aware track), gated net.Conn writes, TrackProcess, Transport(base) / HTTPTransport() (per-instance gated *http.Transport), and Retire: latch under connsMu → cancel gate context → close tracked conns → kill tracked process groups → write-lock barrier → second sweep. WrapTransport is lock-free and capability-preserving: gatedStdio / gatedStreamableHTTP / gatedSSE forward exactly their kind's optional interfaces (BidirectionalInterface, HTTPConnection, SetConnectionLostHandler, RequiresLegacyProtocol, OAuth handler accessors) plus Unwrap(); a retired wrapper answers server-to-client requests with a JSON-RPC error.
  • core: each core.Client owns a gate. stdio start (incl. Docker run) and launcher spawn run in an admitted section together with process-group registration (the child now runs under the gate context instead of context.Background()); the launcher's reachability probe and the OAuth browser launch are gated; every CreateHTTPClient/CreateSSEClient branch builds on the gated transport (HTTPTransportConfig.Gate) and returns a client over WrapTransport; capability assertions go through one helper core.innerTransport (OAuth handler lookup, Streamable HTTP session snapshot).
  • oauth: oauth.Env{Ctx, Transport} threaded through CreateOAuthConfigWithEnv, ValidateOAuthMetadataWithEnv, the PRM/AS preflights, resource auto-detection, metadata discovery and the discovery cache fetch; the OAuth HTTPClient mcp-go uses for registration, code exchange and refresh runs on the instance transport. A discovery flight refused by a retired gate is not cached (a waiter that joined it runs its own fetch); a refresh refused by a retired gate has no side effects (no latch, cooldown or client clear).
  • managed / manager: unregisterLocked → Retire() closes the gate; calls, tools/list and health probes on a retired instance return ErrInstanceRetired ("server unavailable"), are not classified and are not charged to the replacement; RefreshOAuthToken and manual OAuth refuse retired instances, and the transient manual-OAuth clients share the registered instance's gate.
  • CI: scripts/check-upstream-write-sites.sh gains the FR-024a scan (no http.Get/Head/Post/PostForm(, http.DefaultClient, http.DefaultTransport, transport-less http.Client{} in internal/oauth, internal/upstream/core, internal/transport; no GetTransport() in internal/upstream outside core/gate.go), allowlist scripts/ungated-http-allowlist.txt (process-default fallbacks only), 13 new self-test cases.
  • qa_hooks: MCPPROXY_QA_PARK_DIAL, MCPPROXY_QA_PARK_OAUTH (comma-separated targets).

Deviations from the spec (also in tasks.md "PR4 implementation note")

  • Retire SIGKILLs tracked process groups (Windows: closes the Job) before and after its barrier but does not poll up to 1 s for exit; reaping stays with the transport's Close. Polling would hold the manager's locks for up to 1 s per stdio removal.
  • Windows CREATE_SUSPENDED → Job → resume (T093b) and the Windows Job test (T085b/T4.12) are deferred; Windows keeps the existing Job assignment right after Start, now inside the admitted section.
  • Docker CLI calls other than the launch (ps/rm before a launch, logs, inspect, stop) are not gated: they go to the local Docker daemon, never to the upstream, and are ownership checks or teardown.
  • stdio sends are latch-checked in the wrapper (mcp-go owns the stdin pipe); a send that passed the latch before Retire can reach stdin, and Retire kills the group before returning.
  • The capability helper lives in core/gate.go (not transport_unwrap.go). A streamable-HTTP session DELETE on the teardown of a retired instance is refused (nothing reaches the retired endpoint).

Lock order

Gate.mu is L5 and Gate.connsMu L5' (plan §Lock order): Retire runs inside unregisterLocked under captureMu W + Manager.mu W (L3 → L4 → L5). The read lock is held only around one leaf operation (a dial + registration, one write, a process start + registration), never nested; the wrapper takes no lock; the gate never calls back into the manager or runtime. The barrier therefore waits only for leaf operations whose connections it has already closed (bounded; warning above 1 s).

Compatibility

No new dependencies, no wire or config change. Behavioural changes: removed/replaced/quarantined instances stop immediately (in-flight calls on them fail as unavailable); exported oauth helpers keep their signatures (…WithEnv variants added). The CLI client and other non-daemon users of core.Client get an open gate that is never retired.

Verification

  • New tests (T4.1–T4.11, T4.13–T4.17) in internal/upstream/dialgate, internal/upstream (retire_*_test.go, driving the manager's real unregisterLocked), internal/upstream/core/retire_test.go, internal/oauth/retire_preflight_test.go; -race -count=20 at GOMAXPROCS=1 and 4. Disabling the gate retirement (PR3's flag-only retire) fails 8 of the upstream tests; controls pass either way.
  • Benchmark: gated loopback 1 KiB write +2.9% (budget 5%).
  • go test -race -tags server -timeout 30m -skip "E2E|Binary|MCPProtocol|TestInfoEndpoint|TestGracefulShutdownNoPanic|TestSocketInfoEndpoint" ./internal/... green; ./scripts/test-api-e2e.sh (scratch port) 69/0; golangci-lint v2 bare and --build-tags server: no findings in changed files; Windows/Linux cross-builds, -tags server, -tags qa_hooks, make build ok.
  • Live L4 on scratch daemons (qa070 big profile + custom OAuth config), baseline = origin/main + the park points only:
    • stdio dial parked, server removed, released: baseline spawns the removed server's command; PR spawns nothing (connect refused: … retired); re-add starts a fresh instance.
    • SSE dial parked, server removed: baseline sends the stream GET with Authorization to the removed endpoint; PR sends nothing. HTTP remove/replace: 0 requests to the old endpoint in both (PR3's context cancel already covered that window); replacement connects.
    • OAuth refresh parked, server removed: baseline sends refresh_token + client secret to /token; PR sends 0 requests; no browser flow.
    • Quarantine: old instance refused; quarantined on-demand capture and unquarantine work.
    • Removal latency (SC-004): baseline median 0.484 s, PR 0.479 s.

Fixes #1564

🤖 Generated with Claude Code

…aunches and writes (Spec 116 PR4)

A Gate admits one leaf operation at a time under a read lock (a dial plus the
registration of its connection, one connection write, a process start plus
its registration). Retire latches under the connection mutex, cancels the
gate context, closes tracked connections, kills tracked process groups,
waits on a write-lock barrier for sections admitted before the latch, and
sweeps again. Transport(base) clones an http.Transport with a gated dialer;
WrapTransport wraps an mcp-go transport, preserving exactly the optional
capabilities of its kind (stdio, streamable HTTP, SSE) with Unwrap.

Tests: ordering, bounded Retire with a hung peer, late registration (both
sweeps), no nesting, net/http retry refused, capability parity and pinned
mcp-go method sets, and the write benchmark (T4.3, T4.7, T4.10, T4.16, T4.17).
…edentialed requests (Spec 116 PR4; #1564)

Every instance that leaves the upstream manager's registry is retired before
the call that removed it returns (unregisterLocked -> managed.Client.Retire
-> the core client's dial gate): a commit retires removed, replaced and
quarantined instances before it publishes, and a restart, ForceReconnectAll
or Docker recovery retires the old instance before installing the new one.

The gate covers everything an instance sends:
- stdio, Docker run and launcher starts run in an admitted section together
  with the process-group registration; Retire SIGKILLs tracked groups;
- every HTTP/SSE branch builds on the instance's gated http.Transport, and
  the mcp-go client is rebuilt over dialgate.WrapTransport;
- OAuth preflight, resource auto-detection, metadata discovery, cache fetch,
  registration, code exchange and refresh run on the instance transport
  (oauth.Env, CreateOAuthConfigWithEnv, ValidateOAuthMetadataWithEnv);
  retired discovery flights are not cached and refused refreshes have no
  side effects;
- the OAuth browser launch and the launcher's reachability probe are gated;
  manual OAuth shares the registered instance's gate; RefreshOAuthToken and
  manual OAuth refuse a retired instance;
- a call, tools/list or health probe on a retired instance fails as server
  unavailable and is not charged to the replacement.

The FR-024a scan in check-upstream-write-sites.sh rejects ungated HTTP in
internal/oauth, internal/upstream/core and internal/transport, and
GetTransport() outside core.innerTransport. qa_hooks gains
MCPPROXY_QA_PARK_DIAL and MCPPROXY_QA_PARK_OAUTH (comma-separated targets)
for the live check.

OAuth token binding to the incarnation stays #1607.
@cloudflare-workers-and-pages

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

Copy link
Copy Markdown

…1564)

- tools/list on an instance retired mid-flight (leader and coalesced
  waiters) answers ErrInstanceRetired, as a tool call does, and moves no
  state machine.
- A gated connection's Read reports ErrRetired when retirement closed it
  under the read, so a cut-off discovery fetch is not cached and a cut-off
  refresh charges no grant.
- The refresh coordinator retries a joined retired flight until it gets a
  non-retirement answer or leads its own flight.
- Launcher children stay tracked until Stop reaps them; the retirement
  kill is launcher.Handle.Kill (process group / the launcher's own Job).
- stdio: a child already dead at registration still gets its process
  group killed (Setpgid: pgid = pid), so descendants do not survive.
- FR-024a scan checks every http.Client literal within its own braces.
- Tests: in-flight tools/list T4.5, descendant-aware stdio fixture,
  launcher Stop/Kill, mid-read discovery, coordinator retry, refresh race
  tests over the gated wrapped transports; docs and spec notes.
…1564)

- launcher: Handle.Kill signals the process group recorded at spawn also
  after the leader exited, so a descendant backgrounded with redirected
  streams dies on retirement; a group whose number a live process holds as
  its PID (reused) is left alone.
- dialgate: a process registration's kill is serialized with Untrack; no
  kill runs after Untrack returns. Disconnect and the post-OAuth reconnect
  untrack the stdio child before the close that reaps it.
- Windows: assignProcessTree fails when the Job Object cannot be created or
  assigned; the stdio launch section kills the child and fails the start
  (FR-025a).
- managed: a probe in flight at retirement produces no Error transition and
  no failure or retry accounting (FR-026).
- oauth: RefreshCoordinator.Do normalizes a nil context before its retry
  loop.
- FR-024a scan tracks brace depth per http.Client literal.
- Tests: Docker and launcher launch admission (T4.1) with a launch observer
  seam; server-to-client ping and SSE connection loss through the production
  wrappers (T4.17).
…1564)

- launcher: a child whose tree cannot be contained (Windows Job Object
  create/assign failure) is killed and Spawn fails inside the admitted
  launch section (FR-025a covers the launcher path).
- launcher: the reused-group guard keys on a reaped flag set under reapMu
  right after cmd.Wait, not on Done; Kill runs under the same lock.
- dialgate: a Write cut off by retirement reports ErrRetired, so a refresh
  POST cut mid-write sets no cooldown for the replacement's grant.
- manager: StartManualOAuthQuick/WithInfo map a login on an instance
  retired meanwhile to "server not found" (FR-027) instead of a 500 with
  the internal retirement text; browser launches reach the launch observer.
- FR-024a scan: http.Client with whitespace or a comment before its brace,
  and spaced selectors, are detected.
- Tests: launcher containment and reap-window guard, write cut by
  retirement (gate and coordinator), manual login retired mid-flight (both
  entry points), T4.4 code exchange parked through the gated client and
  RefreshOAuthToken on an instance retired after lookup; zombie-tolerant
  descendant check. qa_hooks MCPPROXY_QA_PARK_LOGIN for the live check.
…1564)

- launcher: reap the leader under reapMu after a non-reaping exit wait
  (waitid WNOWAIT on Linux, kqueue NOTE_EXIT on Darwin/BSD), so a retirement
  Kill can never signal a process-group ID released by an unlocked
  cmd.Wait and reused by an unrelated group; test seams made atomic.
- stdio: clear processGroupID before the transport's Close reaps a child
  the retired gate refused to track, so Connect's failure cleanup cannot
  signal a released group ID.
- FR-024a scanner: join selectors split after the dot (http. / Get(u),
  http. / Client{}) across blank and comment lines, reset per file.
- SC-004: opt-in in-process measurement (MCPPROXY_SC004_MEASURE=1) with
  a retire observer seam; commit p99 20 ms, retire p99 42 us, but the
  320-tool purge takes ~5.5 s (pre-existing per-document bleve deletes,
  #1617), so T098 is reopened.
…1564)

- launcher: when the non-reaping exit wait is unavailable (kqueue refused,
  waitid denied), reap with a non-blocking wait4 polled under reapMu
  instead of an unlocked cmd.Wait, so Kill never signals a released and
  reused process-group ID; Kill is never held up by a live child.
- FR-024a scanner: track slice/array/map literals of clients so gated
  []http.Client{{Transport: x}} passes and elided transport-less elements
  ([]*http.Client{{...}}, map values) are reported.
…d (Spec 116 PR4 Sol round 6; #1564)

The post-reap reuse guard (kill(pgid,0)==ESRCH) could not tell our group
from an unrelated group that reused the number and whose leader was reaped
too. The reaper now keeps an exited leader a zombie while another member of
its group runs (kern.proc.pgrp on macOS, /proc on Linux), so Kill and Stop
signal a pinned group ID under reapMu; after the reap the group is never
signalled. Where members cannot be listed, the rest of the group is killed
just before the reap.
@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: fix/116-pr4-retirement-barrier

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-goCNWZ07.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 38409588483 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

@Dumbris
Dumbris merged commit 9894081 into main Oct 13, 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.

security: no retirement barrier for upstream dials - removed/replaced/quarantined servers can still launch or receive credentialed requests

2 participants