Skip to content

gateway: harden the audit surface, rename /healthz, share task ownership - #3

Merged
blakebauman merged 1 commit into
mainfrom
harden/gateway-audit
Aug 7, 2026
Merged

blakebauman merged 1 commit into
mainfrom
harden/gateway-audit

Conversation

@blakebauman

Copy link
Copy Markdown
Member

An audit of the gateway's security-relevant surfaces, the fixes it turned up, and the two follow-ups it earned.

⚠️ Contains a breaking wire change

/healthz is renamed to /health with no alias — it 404s. The README freezes /healthz by name as v1 wire surface, and the deprecation policy is that anything removed is deprecated in a minor first and dropped no sooner than the next major, so by fold's own contract this belongs in a v2. Deployed pods, load balancers, and uptime checks still probing /healthz break on upgrade. Called out here so the release framing is a decision, not an accident.

Hardening

/health was an unauthenticated load amplifier Every call fanned a real MCP ping to every upstream. The console state API is rate limited for exactly this reason; the health endpoint can't be — it's what orchestrators probe — so the Helm chart had already worked around it with a TCP liveness probe. The fan-out is now single-flighted and reused for 1s, keyed on the routing snapshot so a reload or discovery sync invalidates immediately.
Orphaned subscriptions leaked forever resources/unsubscribe was the only path that decremented the ref count, and a client is under no obligation to send one before disconnecting. Every subscribe-then-vanish left the gateway holding an upstream subscription permanently and grew the ref-count table without bound. The minute sweeper now reaps entries whose session is gone and releases the upstream subscription with the last live subscriber.
Rebinding guard trusted a malformed authority net.SplitHostPort splits at the last colon without checking what follows, so Host: localhost:8080.evil.com read as the allowed host localhost. Ports are now validated numeric and Origin parses as a URL instead of being string-split.
Token-endpoint body was unbounded The last unbounded read fold made of a remote party (JWKS and discovery docs were already capped). Now 1 MiB.
Token fetches weren't single-flighted A burst of first-time callers for one principal became a burst of grant requests, each carrying the client secret and that caller's own bearer token — the amplification the JWKS cache already refuses to create. Now serialized per cache key, with the exchanged-token cache bounded and expired entries pruned.
Two credentialed clients still followed redirects v1.0.1 fixed the token endpoint but not the discovery poller (bearer credential + authority to register upstreams) or the audit webhook (configured headers + a batch naming principals and tools). Go only strips Authorization when a redirect leaves the domain, so a sibling host or a plain-http same-host target kept it. Both refuse redirects now.
Unbounded in-memory maps resourceOwner and principalLimits are keyed by identifiers the gateway doesn't choose and never evicted. Both now use internal/bounded — a generational map that promotes on read. Eviction is safe at each call site: every one falls back to a path that already handles an unknown key.

Fleet-wide task ownership

The audit found that security-model.md stated the minting-principal binding flatly while it only ever held per instance: alice mints on A, bob asks B, B has no record, falls through to the probe, and gets handed her task.

Task ownership is an authorization record, not a routing hint, so it moves out of process memory into a new state.Store primitive (Get/GetMany/Set/SetMany/Delete, per-entry TTL) on state.Provider. resourceOwner deliberately stays in-process — a miss there just re-probes.

  • Redis is authoritative on reads, so an instance never serves a record another has since replaced. Every write is mirrored locally and reads fall back to the mirror on error, matching the redisOnce precedent: an outage degrades to per-instance enforcement, not to no records. redis.Nil is authoritative absence and does not consult the mirror.
  • Nothing client-supplied enters shared state verbatim — the key is a digest of the task id (callers name one freely on lookup), the owner is a digest of issuer\x00subject, the same rule principalLimiter already follows.
  • tasks/list batches — one GetMany for the page, one SetMany for genuinely-changed records (zero writes in steady state). Two round trips regardless of page size, so list latency doesn't scale with the federation's task set.
  • 24h TTL, not configurable — shortening only weakens the binding, lengthening only costs storage. Expiry degrades to the probe path, which is already the documented behavior for a task fold never saw minted.

Remaining limits are documented, not hidden: a gateway without Redis is still per-instance. deploy.md now says Redis is "the difference between a guarantee and a coincidence" for multi-replica deployments with task-using upstreams.

Tests

  • gateway/tasks_fleet_test.go — three tests driving two real gateways over one miniredis: ownership holds across instances (all four task methods plus tasks/list both sides), survives destroying the minting instance, survives Redis dying mid-flight.
  • gateway/hardening_test.go — health fan-out sharing, snapshot invalidation, subscription reaping through a real client disconnect, malformed-authority rejection, discovery redirect refusal.
  • auth/upstream_hardening_test.go — token single-flight under 8 concurrent callers, oversized response, cache pruning.
  • audit/audit_test.go — webhook redirect refusal.
  • internal/state, internal/bounded — Store contract on both providers (sharing, scoping, batch, expiry, outage-mirror); expiry, promotion, and eviction.

Gate

make check clean (0 lint issues, -race) · conformance 40/40 · added p50 199 µs vs the 5 ms gate · helm-check clean. No config-schema change, so no schema lockstep needed.

🤖 Generated with Claude Code

Findings from an audit of the gateway, plus the two follow-ups it earned.

Hardening. /health single-flighted its upstream fan-out and reuses the
result for a second: unauthenticated and unbudgeted, one poll became a
ping against every upstream as fast as it could be driven. The console
state API is rate limited for exactly this reason; the health endpoint
cannot be — it is what orchestrators probe — so the Helm chart had
already worked around it with a TCP liveness probe.

The sweeper now releases subscriptions whose downstream client
disconnected without unsubscribing. resources/unsubscribe was the only
path that decremented the ref count, and a client is under no obligation
to send one before going away, so the gateway held upstream
subscriptions forever and the ref-count table grew without bound.

Host and Origin authorities now validate the port, and Origin parses as
a URL. net.SplitHostPort splits at the last colon without checking what
follows, so "localhost:8080.evil.com" read as the allowed host
"localhost" — a rebinding bypass for any caller that chooses its own
header.

The token-endpoint response body is bounded (1 MiB, the last unbounded
read fold made of a remote party), fetches are single-flighted per cache
key, and the exchanged-token cache is bounded. A burst of first-time
callers for one principal became a burst of grant requests, each
carrying the client secret and that caller's own bearer token — the
amplification the JWKS cache already refuses to create.

The discovery poller and the audit webhook refuse redirects. v1.0.1
fixed this for the token endpoint; these two carry a bearer credential
and the sink's configured headers, and Go only strips Authorization when
a redirect leaves the domain, so a sibling host or a plain-http same-host
target would still have received them.

Per-instance stores keyed by identifiers the gateway does not choose —
resource-URI ownership, the per-principal limiter memo — are bounded by
internal/bounded, a generational map that promotes on read. Eviction is
safe at every call site: each falls back to a path that already handles
an unknown key.

/healthz is now /health, everywhere: gateway, fold-discovery, Helm
probes, compose, the conformance script, docs. Note this removes an
endpoint the README freezes as v1 wire surface, so by fold's own
deprecation policy it belongs in a major.

Task ownership is fleet-wide. It is an authorization record rather than
a routing hint, so it moves out of process memory into a new state.Store
primitive: with Redis every instance reads the same ownership and the
binding survives a rolling restart, closing the hole where a caller
reached another principal's task simply by landing on an instance that
never served the mint. Redis is authoritative on reads so an instance
never serves a superseded record, every write is mirrored locally, and
an outage falls back to that mirror rather than to no records at all.
Entries key on a digest of the task id and hold a digest of the owning
principal — nothing client-supplied enters shared state verbatim.
tasks/list resolves a whole page in one GetMany and writes back only
changed records in one SetMany, so list latency does not scale with the
federation's task set. Records expire after 24 hours and a gateway
without Redis is still per-instance; both degrade to the locate-by-probe
fallback, and deploy.md now says so plainly.

make check clean (0 lint issues, -race), conformance 40/40, added p50
199us against the 5ms gate, helm-check clean.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@blakebauman
blakebauman merged commit d8c08b7 into main Aug 7, 2026
6 checks passed
@blakebauman
blakebauman deleted the harden/gateway-audit branch August 7, 2026 14:04
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.

1 participant