Skip to content

fix(security): stop leaking upstream credentials on MCP read surfaces - #1157

Merged
4 commits merged into
mainfrom
fix/1148-quarantine-secrets
Sep 1, 2026
Merged

4 commits merged into
mainfrom
fix/1148-quarantine-secrets

Conversation

@Dumbris

@Dumbris Dumbris commented Sep 1, 2026

Copy link
Copy Markdown
Member

Fixes #1148.

The vulnerability

quarantine_security operation=list_quarantined serialised raw config.ServerConfig values, returning every quarantined server's credentials in plaintext over /mcp — which is unauthenticated by default. Verified on a live instance with no API key on the request:

"url":"https://host/mcp?token=urlsecret999",
"args":["mcp-foo","--api-key","sk-argv-secret-777"],
"env":{"QA_SECRET_TOKEN":"sk-super-secret-value-12345"},
"headers":{"X-AuthToken":"hdr-secret-98765"},
"oauth":{"client_secret":"oauth-secret-4242"}

Quarantine exists to hold untrusted servers pending review — so precisely those servers' credentials were the ones being dumped, to anything that could reach the listener, including a prompt-injected agent already connected.

The response was also persisted verbatim into the activity store.

Correction to the original report: it is not a nil auth context slipping through the gate. mcpAuthMiddleware deliberately installs auth.AdminContext() for unauthenticated /mcp requests for back-compat — an anonymous→admin promotion. So the fix distinguishes anonymous-admin from authenticated-admin rather than merely being nil-safe.

What this changes

  • One redacted view (redactedServerView) for MCP-facing server payloads, built by walking the generic JSON form rather than a hand-written field list — so the next field added to ServerConfig is masked by construction. Reuses fix(server): record redacted mutation payloads and target server in the activity log #1149's redaction machinery; no second scheme.
  • AnonymousContext() keeps Type: admin (so nothing an unauthenticated client does today breaks) but adds CanRevealSecrets(), nil-safe, gating reveal_secret_headers. The stdio transport now declares an explicit admin context instead of relying on nil.
  • Sibling leak paths closed: inspect_quarantined rendered the raw GetConnectionStatus() map (including last_error) — the original report wrongly said it emits only tool analysis; connection errors returned unscrubbed at three sites; tail_log's raw log lines, whose credentials mcpproxy itself wrote there (connection.go logged the raw URL including ?token=).
  • URL credential redaction fixed at the seam, not per-site: transport errors are redacted as they enter mcpproxy, so ~176 downstream zap.Error sites inherit it. Individually hardened only the sites upstream of that choke point.
  • oauth.RedactURL had no user:pass@ rule at all — found by the sweep. It is the fallback RedactURLQueryParams takes when url.Parse fails, i.e. exactly the malformed URL a connection error is being logged about, so every logSafeURL call site leaked basic-auth passwords down that path.
  • url.URL.Redacted() is not enough: it masks only the userinfo password and leaves ?token= intact. Replaced with the project's redactor.

The part I'd most want reviewed: argv unmasking is gone

The first two attempts added an unmask so a masked value echoed back on write wouldn't overwrite the real secret. Review found this created a worse bug than the disclosure it fixed: unmaskArgv reverted by value (then by index), with no binding to what it was masked from — so a caller could relocate a stored credential into an arbitrary command line and have mcpproxy substitute the real secret. Round 2 bound it to the index; round 3 showed index alone is not a binding, since the attacker supplies the whole vector.

Argv unmasking is now deleted. An argv slot has no key, and the caller supplies both the vector and command, so no "surrounding context" rule is airtight — mcp-foo --api-key X and curl --api-key X are indistinguishable to any such rule. A masked echo is refused with an error naming the index and telling the caller to resend the real value. Env, headers, URL and oauth.client_secret keep their unmask contracts: they have a key to bind to.

Behaviour change for the changelog: upstream_servers update now rejects an args_json still containing a redaction placeholder. Previously such a write was silently reverted.

Verification

Four fix→re-review rounds, three adversarial lenses plus targeted re-checks; every leak reproduced with a zap observer or a live probe before being fixed, and re-probed after. Final verdict: clean.

Gates: go build ./..., -tags server, go test ./internal/... -race, -tags server ./internal/serveredition/..., golangci-lint v2 → 0 issues.

Deliberately not fixed here

Registry-source URLs (list_registries and friends) are left raw: config.RegistryEntry has no credential field, requires_key marks keys configured elsewhere, and the URL is the catalog's identity — masking it would destroy the surface's only content.

Algis Dumbris and others added 4 commits September 1, 2026 06:46
…mous auth revealing them (#1148)

`quarantine_security list_quarantined` json.Marshal'd the raw
[]*config.ServerConfig from storage, so every credential the struct
carries left through the MCP surface in the clear — and /mcp is
unprotected by default, so any caller could read them. The leak was
wider than reported: env values, header values, oauth.client_secret,
URL query credentials AND argv tokens. The response was then recorded
verbatim into the activity store (BBolt, SSE, `activity list`).

Redacted view (a):
  New internal/server/mcp_server_view.go builds MCP-facing server
  payloads by walking the config's OWN JSON through the shared
  redaction walker from #1149, not from a hand-written key list — so
  the next field added to ServerConfig is masked by default rather
  than leaked by default. The walker is now policy-driven: live
  surfaces render with oauth.MaskValue, persisted ones with
  oauth.AuditMaskValue.

  Env, header and URL leaves deliberately reproduce internal/oauth's
  own rendering byte for byte on live surfaces, because
  UnmaskEnvValues/UnmaskHeaders/UnmaskURL recognise an echoed mask by
  that exact string; rendering them any other way would make a
  read-modify-write client persist the mask over the real secret.
  Every other leaf — argv tokens and any future field — is
  detector-masked unconditionally. argv had no unmask contract, so
  one is added (unmaskArgv) alongside masking it.

Auth gate (b):
  The gate read `authCtx != nil && !authCtx.IsAdmin()`, so absence of
  a token passed where a scoped agent token failed. The real path is
  narrower than "nil is admin": mcpAuthMiddleware deliberately
  installs an admin context for unauthenticated /mcp back-compat.
  That upgrade stays — it is why unauthenticated MCP clients work —
  but the context is now marked Anonymous, and the new nil-safe
  CanRevealSecrets() distinguishes it from an authenticated admin.
  Its single consumer is `reveal_secret_headers`. stdio now installs
  an explicit admin context instead of relying on nil.

  Behaviour change, exhaustively: list_quarantined is masked for
  everyone; reveal_secret_headers:true returns raw values only to an
  API-key/agent admin, a tray socket connection, or stdio; tail_log
  lines and connection_message strings are scrubbed; activity rows
  for both management built-ins record the audit-masked response.
  NOT changed: ordinary tool calls, retrieve_tools, add/update/patch/
  enable/disable/restart and every quarantine approval still work for
  an unauthenticated /mcp session. The REST API is untouched.

Sibling paths (c):
  - upstream_servers list: reveal gate above; argv now masked; the
    projection is sourced from the view so it cannot drift.
  - tail_log: lines and connection_status.last_error scrubbed. Fixed
    at the source too — Connect() logged the raw upstream URL into
    server-<name>.log on every attempt (logSafeURL).
  - connection errors: the three unscrubbed sites in
    monitorConnectionStatus / handleUpdateUpstream now use the same
    scrubUpstreamText as the list path's last_error.
  - add_from_registry summary: url and args from the view.
  - inspect_quarantined: verified safe — it emits tool analysis only,
    never the server config. Unchanged.
#1148 review found

Round-2 review of #1148. All nine findings were reproduced against the
real code before anything was changed; eight are fixed, one was a
request to enumerate rather than a defect.

1 (MAJOR, introduced by #1148). unmaskArgv reverted a masked argv token
by VALUE with no binding, so a caller could relocate a stored credential
anywhere in the vector. The sharper half is not execution — anyone who
can patch a server can already exfiltrate env secrets by pointing
`command` at a shell — it is RE-DISCLOSURE: a value masked because of
the FLAG in front of it (`--api-key <secret>`) has no credential shape of
its own, so moving it into a bare positional slot made the very next
`upstream_servers list` hand it back in the clear. Masked read →
relocate write → clear read-back undid all of #1148 over an endpoint
that is unauthenticated by default. The revert is now bound to the INDEX
it was masked at plus the flag that bound it, which is the same shape as
the safeguards the sibling contracts already carry (UnmaskEnvValues /
UnmaskHeaders bind to the map key; UnmaskURL refuses a new scheme/host).
A reordered or resized vector no longer round-trips its masks — the
caller resends the real values, which is the safe direction. The old
"ambiguous mask" refusal is gone: positional binding resolves a
collision correctly instead of giving up on it.

2 (MAJOR). inspect_quarantined — the sibling of the list_quarantined
path #1148 fixed, one screen away — still rendered the raw
GetConnectionStatus() map (last_error included) and raw ListTools errors
into its response. The claim that it "emits tool analysis only" was
wrong. Two response builders extracted and scrubbed.

3 (MAJOR). scrubUpstreamText applied the 512-byte ACTIVITY-STORE cap to
LIVE reads, silently truncating every tail_log line and connection
error. tail_log is the primary debugging surface and a long line is what
an operator opens it for. The cap moved to scrubUpstreamTextForAudit;
the live scrubber no longer truncates.

4 (MAJOR). Neither tokenPattern, secretPattern nor the `<param>=` sweep
has a `user:pass@` shape, so basic-auth passwords survived every
free-form scrubber. Fixed at the source in oauth.RedactSensitiveData, so
the REST last_error / health.detail / Diagnostic.Cause scrubbers inherit
it too.

5 (MAJOR). redactArgvWith ran the value-shaped detector ALONE on
unpaired tokens — it knows database connection strings, not
`https://user:pass@host` or `?token=…`. So `--endpoint <url>` and a bare
positional URL leaked on BOTH policies while `--endpoint=<url>` was
masked: the same inline-vs-space asymmetry #1146 round 3 fixed once.
Unpaired tokens now go through redactStringWith, the same function the
inline branch delegates to, so the spellings agree by construction.

6 (MAJOR). #1148 started masking oauth.client_secret on the MCP read
surface without giving the write path anything to recognise the mask by,
so an unedited echo through oauth_json — which REPLACES the block —
persisted `••••42 (17 chars)` as the client secret. unmaskLiveOAuth
reverts it, bound to the field. The contract is now stated in the docs:
the argv mask is an MCP rendering, reverted only by the MCP write path;
REST returns and accepts `args` unredacted and stays self-consistent,
and contracts.OAuthConfig carries no client_secret at all.

7 (MINOR). With the detector off for contracted leaves, the LIVE surface
returned `ghp_…` in the clear whenever it sat under a benign env/header
name, while the audit policy masked it — and live is the surface an
unauthenticated caller reads. The detector now also runs on live, but
only over a leaf the name rule left BYTE-IDENTICAL, which is exactly the
gap and deliberately spares #872's component-wise connection-string
rendering (`postgres://u:••••(N chars)@host/db` stays readable and
editable). Because that rendering is no longer oauth's, unmaskLiveEnv /
Headers / URL reproduce it and run first on the write path, so closing
the disclosure does not open the read-modify-write corruption.

8 (MINOR). internal/transport/http.go logged the raw cfg.URL on 14 sites
— at Error level on the streamable-HTTP path, so it fired regardless of
log level — plus the OAuth client_secret at Debug. #1148's "fixed at the
source" claim covered only internal/upstream/core. logSafeURL mirrors
the helper that package already has; the client_secret field is now a
boolean.

9 (MINOR). Not a defect: enumerated on stdioAuthContext instead. Three
paths change for stdio and all three make it behave as the API-key admin
it is — principalFromContext ("" → "admin"), sessionPreflightScope (nil
→ a scope over the full server universe, which an admin is wholly inside)
and CanRevealSecrets, which is the point of the change. Three more
change shape with an identical outcome (code_execution's AuthInfo,
direct-dispatch gates, the preflight record's empty UserID). The rest
gate on agent/user identity and are untouched. The two substantive ones
are pinned by a test.

No REST or MCP schema changed, so no swagger regeneration.
…d redact URL credentials in connection errors

Round 3 of the #1148 review.

1. argv masks are never reverted again — they are REFUSED (MAJOR).

   unmaskArgv still relocated a stored credential into a caller-chosen command
   line whenever the mask was not flag-bound. argvFlagBoundMasks marks index i
   only when stored[i-1] is a sensitive flag, so a token masked by the
   value-shaped detector — or any mask at index 0 — was bound to nothing but its
   index. Reproduced against the real code:

     stored   = ["mcp-foo", "run", "ghp_16Cabcdef…"]
     incoming = ["--silent", "--data", "ghp_…****"]
     -> the live token was substituted into the attacker's argv.

   Option (b) from the review, and (a) is not salvageable: an argv slot has no
   key, and the caller supplies the whole vector AND `command` in the same
   patch, so every candidate binding — index, preceding flag, even a
   byte-identical vector — is caller-controlled. A "same surrounding context"
   rule still lets the secret move from `mcp-foo --api-key X` to
   `curl --api-key X`, because the meaning of argv lives in `command`.

   unmaskArgv/argvFlagBoundMasks are gone. checkArgvMaskEcho refuses the write
   when args_json carries a mask (an exact echo of a stored token's live
   rendering, or any token bearing a mask marker) and tells the caller to resend
   the real value. That is safe in both directions: the secret never moves, and
   the mask is never persisted over the credential either — the read-modify-write
   corruption the revert existed to prevent. Refusing beats silently ignoring
   args_json, which REPLACES the vector.

   Tests: a mask at every position, in argv vectors of every shape (including
   neighbours copied verbatim from the stored vector), for a flag-bound mask, a
   detector-shaped mask and a mask at index 0, is always refused and never
   reverted; the marker list is pinned to the functions that render masks; and
   the write path itself (buildPatchConfigFromRequest) rejects the relocation
   attempt with the stored vector untouched.

2. Raw upstream URLs in logs — the remaining siblings (MINOR, pre-existing;
   identical on origin/main).

   internal/upstream/manager.go logged client.GetConfig().URL at Info on every
   connect attempt; internal/upstream/cli/client.go and connection_oauth.go's
   deprecated-endpoint error did the same. All three now go through
   oauth.RedactURLQueryParams / the existing logSafeURL helper.

   The observer test written for the manager site showed the field masks were
   only half of it: a net/http error quotes the request URL inside its own
   message (`Post "https://host/mcp?token=…": dial tcp …`), so the credential
   still reached main.log at Error level through zap.Error, and was stored as
   the client's last error. Redacted once at the seam where the transport error
   enters mcpproxy (core Connect), plus the log sites that fire before it (both
   auth-strategy loops, the SSE connection-lost handlers, the transport's
   request-failure log). The wrapper keeps the original reachable through
   Unwrap, so errors.Is/As and the substring classification the connect paths do
   are unaffected.
…sweep found

Round 4 of the issue #1148 review, plus the exhaustive raw-URL sweep across
internal/upstream, internal/transport and internal/server it asked for.

- managed/client.go onStateChange logged the raw configured URL as
  `current_url` at ERROR level on the deprecated-endpoint (410 Gone) branch —
  the exact twin of the connection_oauth.go site round 3 fixed. Routed through
  a new Client.logSafeURL, matching core.Client and HTTPTransportConfig.

- transport/retry_after.go rendered the request URL with the stdlib's
  url.URL.Redacted() on every 429/503-with-a-hint, at Info. That masks ONLY the
  userinfo password and leaves `?token=…` verbatim. Uses the project's own
  redactor now.

- oauth.RedactURL had no `user:pass@` rule at all. It is the fallback
  RedactURLQueryParams takes when url.Parse FAILS — i.e. exactly the URL a
  connection error is being logged about — so every logSafeURL() call site in
  three packages leaked the basic-auth password down that path. The userinfo
  masking is factored out of RedactSensitiveData and shared, so the two
  scrubbers cannot drift.

- The two OAuth client-creation failures and the SSE stream-read failure in
  internal/transport logged their error bare; mcp-go builds the first two from
  url.Parse and *url.Error quotes the raw URL it was handed. They use
  logSafeErrorField now.

- upstream/manager.go GetStats put the raw cfg.URL and last_error into the
  per-server status map. Round 3 deferred this as out of scope; deciding it
  now: the map is served verbatim as `upstream_stats` on /api/v1/status, on the
  /api/v1/servers response and on every SSE `status` event, alongside a server
  list that httpapi.redactServerSecrets and Runtime.redactServerSecrets already
  mask — so one half of a single payload was masked and the other was not. Both
  fields are masked here, honouring the same reveal_secret_headers opt-out.

Explicitly out of scope, with evidence: the registry-source URLs in
internal/server (list_registries, add/edit/remove_registry_source). A
config.RegistryEntry carries no credential — `requires_key` marks a registry
whose key is configured elsewhere — and the URL is the identity of the catalog.

Docs: docs/configuration/upstream-servers.md still described the argv revert
that round 3 deleted, so an operator would expect a masked args_json echo to
round-trip safely when it now returns a hard error. The binding table and the
prose state the new contract: argv masks are REFUSED, resend the real value or
omit args_json. No other page repeats the old claim.
@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying mcpproxy-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit: c2beb53
Status: ✅  Deploy successful!
Preview URL: https://f71fec33.mcpproxy-docs.pages.dev
Branch Preview URL: https://fix-1148-quarantine-secrets.mcpproxy-docs.pages.dev

View logs

@github-actions

github-actions Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: fix/1148-quarantine-secrets

Available Artifacts

  • archive-darwin-amd64 (29 MB)
  • archive-darwin-arm64 (26 MB)
  • archive-linux-amd64 (17 MB)
  • archive-linux-arm64 (15 MB)
  • archive-windows-amd64 (29 MB)
  • archive-windows-arm64 (26 MB)
  • frontend-dist-pr (0 MB)
  • installer-dmg-darwin-amd64 (23 MB)
  • installer-dmg-darwin-arm64 (21 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 33477208963 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

@codecov-commenter

codecov-commenter commented Sep 1, 2026 •

Copy link
Copy Markdown

@Dumbris Dumbris closed this pull request by merging all changes into main in 3e6c420 Sep 1, 2026
@Dumbris
Dumbris deleted the fix/1148-quarantine-secrets branch September 1, 2026 12:16
Dumbris added a commit that referenced this pull request Sep 2, 2026
…errors (#1181)

* fix(security): stop credentials reaching logs, stdout and structured errors (#1158)

A default `mcpproxy serve` at DEBUG published an argv secret 12 times and a
URL-query secret 8 times in a 20-second startup, with no trace mode enabled.
Verified on a live instance: 24 cleartext occurrences across main.log,
server-<name>.log and the terminal, now 0.

Four classes, four rules, all routed through seams the #1148/#1157 sweep
already built rather than a new matcher.

1. Spawn argv. Every spawn log site used shellwrap.RedactDockerArgs alone -
   a STRUCTURAL rule that masks the value half of `-e KEY=VALUE` and is blind
   to `--api-key sk-live-...`. New oauth.Redaction.SpawnArgv /
   SpawnCommandString compose it with the SEMANTIC flag-name + value-shape
   rule (Redaction.Argv) and reach inside the single `-c "<whole command
   line>"` element the login-shell wrap produces - the form that actually
   leaked, since every non-docker stdio server on macOS spawns that way.
   Redaction.Argv itself is untouched: it backs the read doors and
   CheckArgvMaskEcho on the write doors, so the spawn rule has to be additive
   and log-only. There is deliberately no "already masked, skip" guard
   between the two stages - the bullet marker carries no character in
   secretPattern's value class, so stage 2 is provably a no-op on a stage-1
   rendering, and a whole-token guard would silence stage 2 for an entire
   command string as soon as one benign `-e` put a marker in it.

2. The OAuth authorization URL - the largest leak, and one the site list
   missed. autoDetectResource returns the configured server URL verbatim on
   every fallback branch, that becomes extraParams["resource"], and all THREE
   authorize-URL emission paths splice it into the query and then log it at
   INFO and print it with fmt.Printf. Both sinks on all three paths now go
   through logSafeAuthURL, and the per-value extra-param Debug lines through
   Redaction.ExtraParamValue. The credential arrives percent-encoded one
   level down, where neither the sensitive-parameter name rule nor
   secretPattern can see it, so URLValueDeep decodes one nesting level.
   maskExtraParams no longer treats `resource` as a public endpoint.

3. URL log fields inside internal/oauth (~75 sites across discovery.go,
   config.go, transport_wrapper.go, persistent_token_store.go), plus the
   configured-URL field in runtime.go and the registry-source URLs in
   internal/server. They use the AUDIT rendering, not the name-rule-only
   RedactURLQueryParams the issue names, because a credential under an
   unrecognised parameter name still reached the log otherwise.
   url.URL.Redacted() is not used anywhere - it masks the userinfo password
   and leaves `?token=` intact.

4. The structured OAuth error is scrubbed where it is BUILT
   (createMetadataError and the seven contracts.OAuthErrorDetails literals),
   not where it is serialized: the encoder sees an opaque struct and cannot
   know which leaves are URLs, and every future consumer inherits the fix.

Also: the trace transport's stdout Printf copies and zap fields (URL,
headers, request/response bodies, SSE frames) - both sinks or neither;
logSafeErrorField upgraded to ScrubUpstreamText; the launcher's startup
banner takes an injected Spec.RedactArgs whose nil default OMITS argv, so a
future caller that forgets it loses a diagnostic rather than a secret.

Diagnostics are preserved throughout: flag names, env KEY names, and each
URL's scheme/host/path survive; only values are replaced.

Two AST guard tests derive the rule from the source across BOTH
internal/oauth and internal/upstream/core, so the next URL log field or a
re-raw'd authorize-URL Printf fails CI rather than shipping.

Behaviour change to note: log lines, `mcpproxy upstream logs`, the
`upstream_servers tail_log` MCP tool, `mcpproxy auth status/login` output and
the 400 body of POST /api/v1/servers/{id}/login now render masked values
where they previously showed cleartext. No config, storage, contract or
frontend change.

* fix(security): close the OAuth code, error-text and quoting gaps the first pass left

Round-2 cross-review of #1158. Seven blocking/major findings, three confirmed
minors, three judged-then-fixed, and one design comment that was simply wrong.

The sharpest was pre-existing on main rather than introduced here: the OAuth
CALLBACK handler logged the authorization CODE at Info, plus the whole raw
callback query, on every single login. The code is a single-use credential
redeemable at the token endpoint, and it sat in ~/.mcpproxy/logs/main.log for
the window before mcpproxy spent it — forever, for a flow that never completed.
`state` (the CSRF nonce that pairs with it) was on five more lines and inside
two operator-visible error messages; it is now a truncated SHA-256, which is
all the log lines ever used it for.

The rest is one theme: masking a FIELD does not mask the STATEMENT.

  - A *url.Error renders the request URL inside its own text, so fourteen
    `zap.Error(err)` calls in discovery.go published, on the identical line, the
    credential their masked `metadata_url` sibling was written to hide. New
    logSafeErrorField/LogSafeErrorText in internal/oauth; internal/transport's
    twin, which had drifted back to the name-rule-only scrubber, rejoins it.
  - `url_tried` survived raw four lines below a line this branch fixed, along
    with every `auth_server*` field in discovery.go — because the AST guard's
    regex was written from the sites already fixed. It now matches `_tried$`
    and the four auth-server names, and a second guard fails any log statement
    that carries a URL field and a raw zap.Error together.
  - contracts.OAuthFlowError was scrubbed field-by-field at seven construction
    sites, and one got it half right: emptyClientIDFlowError masked
    Details.ServerURL and set Details.DCRStatus.Error raw on the same struct,
    which is JSON-encoded straight to the REST caller. One scrubbedFlowError at
    construction now walks the whole struct, and a third guard requires every
    literal to go through it.
  - Client.logSafeURL, managed.Client.logSafeURL, the transport config, the CLI
    client and the four registry routes rendered with RedactURLQueryParams —
    the NAME rule only — while this branch's own new renderer deliberately does
    not, and says why. One exported oauth.LogSafeURL now backs all of them.

Two spawn-rule corrections pull in opposite directions and both matter:

  - The command-string tokenizer split on whitespace only, while the string it
    is fed comes from Shellescape — so a credential containing a space arrived
    single-quoted, was split into four tokens, and had exactly its first
    fragment masked. On the `-c "<whole command line>"` form the original
    commit calls "the form that actually leaked". The split is now shell-aware
    (including the `'"'"'` idiom), falling back to whitespace-only when quotes
    do not balance, because swallowing the rest of a line into one token would
    be a new leak rather than a safe degradation.
  - The other direction: IsSensitiveKeyName matches SUBSTRINGS, so applying it
    to a spawn argv blanked `--max-tokens 4096` and `--public-key-path /etc/x`.
    The property that makes this redaction acceptable to an operator is that
    flag names, hosts and ordinary values survive, so the log-only rule now
    subtracts a short list of qualifier segments (max/min/num/public/…). It
    keeps the substring match rather than switching to segment EQUALITY, which
    would have silently un-masked `--apikey` and `--clientsecret`.

Three findings were investigated rather than reflexively fixed; all three were
genuine and all three are closed. The PRM's own authorization_servers list left
createMetadataError unscrubbed beside siblings that were scrubbed. The token
endpoint's non-200 BODY was embedded verbatim in the refresh error — provider
free text that echoes request parameters, unbounded, logged and returned over
REST. And the launched child's stdout/stderr went into the per-server log raw,
which matters more than it looks: GET /api/v1/servers/{id}/logs serves that
file, so an upstream echoing its own startup banner puts a credential mcpproxy
handed it onto an HTTP surface.

Finally, the design comment claiming the two-stage spawn composition is
provably idempotent was false, and the pinning test used the one fixture that
hid it: RedactSensitiveData's sensitiveParams sweep matches `[^&\s]+`, which
DOES match the bullet marker, so `SLACK_TOKEN=••••` becomes
`SLACK_TOKEN=***REDACTED***` while `API_KEY=••••` does not. The composition is
disclosure-safe, not byte-idempotent; the comment now says so and both
spellings are pinned.

Diagnostics preserved throughout: flag names, env KEY names, hosts, paths, OAuth
error codes, DCR status codes and `code_present` all survive.

* fix(security): close the two leaks the live check found, at the seams that feed every sink

The round-2 live run — a stdio server carrying an argv secret and printing a
token on startup, plus an http server with `?token=` and `?opaque=ghp_…` in its
URL — still put two credentials in the log after every fix above had landed.
Both were the same shape as finding B3 one level further out.

`sk-live-…` appeared 8 times because the stdio stderr PUMP
(core/monitoring.go) is a different code path from the launcher's loggerWriter.
It feeds THREE sinks from one string: main.log, the per-server log that
GET /api/v1/servers/{id}/logs serves, and the recent-stderr ring buffer that
connectStdio splices into the "did not respond to MCP initialize" error — which
is itself logged and returned to REST callers. Scrubbing the line once at the
top of the loop covers all three.

`ghp_…` appeared 15 times because redactURLCredentialsInError — the ONE seam
where a transport error enters mcpproxy, and whose own doc comment says
"redacting once, where the transport error enters mcpproxy, is what keeps a
future log site from re-leaking it" — ran the NAME rule only. `opaque` is not a
recognised parameter name, so the token walked through it and then through
managed.Client, upstream.Manager, the supervisor and the runtime, each of which
zap.Errors the string it is handed and none of which can be fixed from its own
file. ScrubUpstreamText there fixes all four.

Also registers the three new exported renderings with the fail-closed net's
discovery gate: LogSafeURL and LogSafeCallbackQuery are bound and probed;
StateFingerprint is recorded as not-a-rendering, with the reason — it keeps no
byte of its input, no read door publishes it and no write door consumes it, so
putting a per-value hash into MaskMarkers would be meaningless.

Live re-run across seven sinks (three log files, stdout, GET /api/v1/servers
and both GET /api/v1/servers/{id}/logs payloads): 0 occurrences of all five
planted secrets, while `--api-key`, `--max-tokens 4096`, `--public-key-path
/etc/ssl/pub.pem`, the SLACK_TOKEN key name, the upstream host and "connection
refused" all survive.

* test(security): make the spawn-redaction tests host-independent

Both failures were POSIX assumptions in tests added by the #1158 round-2 work,
and both are Windows-only.

internal/oauth: the -c command-line fixtures were built with
shellwrap.Shellescape, which switches on runtime.GOOS and emits cmd.exe
double-quoting on Windows - so the sanity assertions looked for a POSIX quote
and the ' idiom that were never going to be there. The tokenizer under test
handles the POSIX form WrapWithUserShell produces, and a Windows core still
reads per-server logs and configs a POSIX host wrote, so the fixture must be
POSIX-quoted on every host. Added posixShellescape plus
TestPosixShellescape_MatchesProduction, which pins it against the real
Shellescape on POSIX - keeping the drift protection that building the fixture
from production code was there to provide.

internal/upstream/launcher: the banner tests spawned /bin/echo, which does not
exist on Windows. Argv redaction in the banner is platform-independent, so
rather than skipping the way this package's POSIX signal-semantics tests do,
the interpreter is chosen per host and the expected command path travels with
it.

Verified: both packages pass on darwin, and GOOS=windows go vet is clean.
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.

quarantine_security list_quarantined returns env/headers/oauth secrets in plaintext, unauthenticated

2 participants