Skip to content

security(headers): redact sensitive header values in upstream_servers list and /api/v1/servers - #425

Merged
Dumbris merged 1 commit into
smart-mcp-proxy:mainfrom
HaloCollar:upstream-pr/redact-secret-headers
Apr 26, 2026
Merged

Dumbris merged 1 commit into
smart-mcp-proxy:mainfrom
HaloCollar:upstream-pr/redact-secret-headers

Conversation

@electrolobzik

@electrolobzik electrolobzik commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Pull Request

Description

Both the upstream_servers MCP tool's list operation and the REST GET /api/v1/servers endpoint were returning the per-server Headers map verbatim — so any caller of those endpoints (an MCP
agent inside a sandbox, a local tool with the API key, the Web UI, the macOS tray) could read Authorization: Bearer , X-API-Key, session cookies, and other secrets out of another
upstream's config.

Concretely observed: a sandboxed MCP agent calling mcpproxy:upstream_servers operation=list got back a registered GitHub server's Authorization: Bearer ghp_… PAT in plaintext.

What changes

  • internal/oauth/logging.go — new RedactStringHeaders(map[string]string) map[string]string that mirrors the existing RedactHeaders(http.Header) helper but takes the form actually used in
    cfg.Headers. Same sensitiveHeaders allowlist, same REDACTED marker, returns a copy (input not mutated).
  • internal/server/mcp.go (handleListUpstreams) — redacts the headers field on every server entry before serialising the tool result.
  • internal/httpapi/server.go (handleGetServers) — new private redactServerHeaders helper applied in both the management-service code path and the legacy fallback before writeSuccess.
  • internal/config/config.go — new RevealSecretHeaders bool field (reveal_secret_headers JSON / reveal-secret-headers mapstructure key, default false). Setting it to true opts out of redaction
    for users who genuinely need raw values surfaced (e.g. a custom UI that round-trips full PUT replaces).

Sensitive header names redacted (case-insensitive, list lives in oauth.sensitiveHeaders): Authorization, X-API-Key, Cookie, Set-Cookie, X-Access-Token, X-Refresh-Token, X-Auth-Token,
Proxy-Authorization.

What does NOT change

PATCH / merge semantics. The underlying stored cfg.Headers is untouched — only the read-side response is redacted. So upstream_servers operation=patch continues to deep-merge by name; only
the value displayed in subsequent reads is masked. Existing callers that omit unchanged fields keep working exactly as before.

Migration

None. Existing config files keep working; reveal_secret_headers defaults to false. To opt out: {"reveal_secret_headers": true} in mcp_config.json.

Testing

Unit tests added in internal/oauth/logging_test.go (TestRedactStringHeaders, 8 sub-tests): redacts Bearer Authorization, redacts X-Api-Key, redacts Cookie/Set-Cookie, preserves non-sensitive
headers (Content-Type), case-insensitive header name matching, nil input returns nil, empty input returns empty map, input map is not mutated.

E2E tests updated in internal/server/e2e_test.go:

  • TestE2E_PatchDeepMergesEnvAndHeaders — now asserts Authorization == "REDACTED" (key preserved by merge, value masked in API output) while X-Custom and X-New-Header retain their actual
    values, validating both that merge semantics still work and that redaction is scoped to the sensitive-name list.
  • TestE2E_MultipleEnableDisablePreservesConfig — same pattern: Authorization key survives 5 enable/disable toggles, with the value redacted in read-back.

Local test runs (clean):
ok github.com/smart-mcp-proxy/mcpproxy-go/internal/oauth
ok github.com/smart-mcp-proxy/mcpproxy-go/internal/server (incl. the two E2E tests above)
ok github.com/smart-mcp-proxy/mcpproxy-go/internal/httpapi
ok github.com/smart-mcp-proxy/mcpproxy-go/internal/config
ok github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts
go build ./... clean.

Manual verification: end-to-end call against the running proxy now returns REDACTED for the GitHub server's Authorization header (previously returned the live PAT).

  • I have tested these changes locally
  • I have added/updated tests that prove my fix is effective or my feature works
  • All existing tests pass

… list and /api/v1/servers

Both the `upstream_servers` MCP tool's `list` operation and the REST
`GET /api/v1/servers` endpoint were returning the per-server `headers`
map verbatim — including `Authorization: Bearer <PAT>`, `X-API-Key`,
session cookies, and other secrets that any caller (an MCP agent in a
sandbox, a local tool with the API key) could read out of *another*
upstream's config.

Wires the existing `oauth.RedactHeaders()` helper logic over to the
`map[string]string` form used in `cfg.Headers` and applies it at both
surfaces. Sensitive header names (Authorization, X-API-Key, Cookie,
Set-Cookie, X-Access-Token, X-Refresh-Token, X-Auth-Token,
Proxy-Authorization) are replaced with `***REDACTED***`; everything
else passes through unchanged. PATCH semantics (deep-merge) are
unaffected — the underlying stored config is untouched, only the
response is redacted.

Adds an opt-out config flag `reveal_secret_headers` (default false)
for users who specifically need the raw values surfaced (e.g. a custom
UI that round-trips full PUT replaces). Default-on redaction means
existing deployments are protected without action.

- internal/oauth/logging.go: new RedactStringHeaders helper for map[string]string
- internal/oauth/logging_test.go: 8 new test cases covering sensitive-name matching, case insensitivity, nil/empty input, non-mutation
- internal/config/config.go: new RevealSecretHeaders bool config field (default false)
- internal/server/mcp.go: redact in handleListUpstreams (MCP `upstream_servers` tool)
- internal/httpapi/server.go: new redactServerHeaders helper, applied in both code paths of handleGetServers
- internal/server/e2e_test.go: update TestE2E_PatchDeepMergesEnvAndHeaders and TestE2E_MultipleEnableDisablePreservesConfig to assert the new redacted output

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

Thank you for the contribution! Clean security fix — sensible default, opt-out provided, well-tested. 🙏

@Dumbris

Dumbris commented Apr 26, 2026

Copy link
Copy Markdown
Member

Thanks for the security fix and the thorough writeup — approved! 🙏

CI is red on Verify OpenAPI Artifacts: the new RevealSecretHeaders field on Config gets picked up by swag, so oas/swagger.yaml (+10 lines) and oas/docs.go (+1 line) need to be regenerated and committed. The check ran the regen and found uncommitted diffs.

Two ways to unblock:

Option A — quickest: enable Allow edits and access to secrets by maintainers in the PR sidebar, and we'll push the regen.

Option B — push it yourself:

make swagger
git add oas/swagger.yaml oas/docs.go
git commit -m "chore(oas): regenerate OpenAPI artifacts for reveal_secret_headers"
git push

Either way, once that lands and CI is green we'll merge. Thanks again!

@Dumbris

Dumbris commented Apr 26, 2026

Copy link
Copy Markdown
Member

Merging now via admin override — bypassing the OAS check, will push the make swagger regen as a follow-up commit on main. Thanks again for the fix! 🙏

@Dumbris
Dumbris merged commit 2566e24 into smart-mcp-proxy:main Apr 26, 2026
15 of 17 checks passed
Dumbris pushed a commit that referenced this pull request Apr 26, 2026
Picks up the new reveal_secret_headers field on Config introduced in #425.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Dumbris pushed a commit that referenced this pull request May 14, 2026
User feedback on the previous commit: dropping REST/SSE redaction
unblocked the UI but narrowed the threat model from PR #425 (a local
process that holds the API key but not filesystem access could read
other upstreams' Bearer tokens off the wire). The better trade-off is
to keep both halves of PR #425 intact AND let the UI edit without
round-tripping the redacted sentinel.

Solution: deep-merge PATCH semantics so the client sends only the keys
that changed. Redacted-but-untouched values stay out of the patch
entirely, the backend keeps the real string on disk.

Backend:

- internal/httpapi/server.go::handlePatchServer — when the request
  body contains `headers` or `env`, MERGE into the existing stored map
  instead of replacing. New `headers_remove` / `env_remove` fields
  carry explicit deletes. Sending both is allowed (deletes apply after
  upserts).
- internal/httpapi/server.go::AddServerRequest — adds the two
  `*_remove` fields with a comment documenting the new semantics. The
  add path ignores them.
- internal/httpapi/server.go::handleGetServers — re-enable
  `redactServerHeaders` on both code paths.
- internal/runtime/event_bus.go::emitServersChanged — re-enable
  redaction on SSE `servers.changed` payloads. SSE rides the same
  trust boundary as the REST GET.
- internal/config/config.go::RevealSecretHeaders — restore the
  original PR #425 doc (REST + MCP both gated) with a new paragraph
  pointing at the deep-merge mechanism that makes the UI work anyway.

Tests:

- internal/httpapi/patch_server_test.go — 4 new tests pinning the
  merge semantics:
  - TestHandlePatchServer_HeadersDeepMerge — `headers: {X-New: v}`
    against existing `{Authorization, X-Trace}` preserves both
    original keys and adds X-New.
  - TestHandlePatchServer_HeadersRemove — `headers_remove: [...]`
    deletes the listed keys.
  - TestHandlePatchServer_HeadersSetAndRemove — both fields in one
    PATCH; deletes apply after upserts.
  - TestHandlePatchServer_EnvDeepMerge — same pattern for env.
- internal/runtime/event_bus_payload_test.go — restored the original
  PR #425 assertion (`...RedactsSensitiveHeaders`).

Frontend (Web UI):

- ServerDetail.vue — `patchServerDiff(patch, action)` replaces the old
  `patchKVMap`. Each per-row UI action now sends a minimal targeted
  patch:
    - Edit one row: `{headers: {key: newValue}}`
    - Delete one row: `{headers_remove: [key]}`
    - Add one row: `{headers: {newKey: newValue}}`
    - Convert to secret: `{headers: {key: "${keyring:NAME}"}}`
  The redacted sentinel for unchanged keys never round-trips, by
  construction.
- KVValueCell.vue — restore the `isBackendRedacted` branch. When the
  cell renders `***REDACTED***`, the reveal / Convert-to-secret
  buttons disappear (we don't hold the real value) and the cell shows
  the sentinel verbatim with a tooltip explaining that editing still
  works through the inline edit button.

macOS Swift:

- ServerDetailView.swift::saveEdits — switch from "send the full
  parsed map" to "diff against `server.headers` / `server.env` and
  send the diff". New private helper `diffKVMap(original:next:)`
  returns a `(set, remove)` tuple suitable for the deep-merge PATCH
  body. The same invariant holds: leaving a redacted line untouched
  in the textarea produces `next[k] == "***REDACTED***" ==
  original[k]`, so the key stays out of both sides of the diff and
  the backend preserves the real value.
- ServerDetailView.swift::kvRow — restore the
  `value != "***REDACTED***"` gate on the Convert-to-secret button
  (the sentinel isn't useful as a keyring payload).
- ServerDetailView.swift::editHeaders doc — explain the new flow.

End-to-end verification against the live local instance:

  $ curl -s -H "X-API-Key: ..." /api/v1/servers | jq '...synapbus.headers'
  → {"Authorization": "***REDACTED***"}                   # redacted ✓

  $ jq '...synapbus.headers' ~/.mcpproxy/mcp_config.json
  → {"Authorization": "Bearer 1d386..."}                  # real on disk

  $ curl -X PATCH .../servers/synapbus -d '{"headers":{"X-Trace-Test":"merge-works"}}'
  $ jq '...synapbus.headers' ~/.mcpproxy/mcp_config.json
  → {"Authorization": "Bearer 1d386...", "X-Trace-Test": "merge-works"}
                                                          # real token preserved ✓

  $ curl -X PATCH .../servers/synapbus -d '{"headers_remove":["X-Trace-Test"]}'
  $ jq '...synapbus.headers' ~/.mcpproxy/mcp_config.json
  → {"Authorization": "Bearer 1d386..."}                  # X-Trace-Test deleted ✓

PR #425's E2E tests still pass (TestE2E_PatchDeepMergesEnvAndHeaders,
TestE2E_MultipleEnableDisablePreservesConfig — both exercise the MCP
tool which still redacts). PR #425's intent is fully preserved.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Dumbris pushed a commit that referenced this pull request May 14, 2026
…cted values

User feedback: the Headers card looked split-brained. A non-sensitive
header showed `••••XX (NN chars)` with a Convert-to-secret button. The
Authorization header showed `***REDACTED***` with no button — exactly
the most-likely candidate for "move me to keyring" was the one the UI
refused to convert, because the client side couldn't hand the real value
to the existing two-step (POST /secrets, then PATCH server) flow.

This change unifies both display and conversion:

1. **Single mask format on the wire** — internal/oauth/logging.go
   replaces the `***REDACTED***` sentinel in RedactStringHeaders with
   MaskValue(v), producing `••••<last2> (<N> chars)` for literal
   secrets. The same format the Web UI / macOS tray have been computing
   client-side. Bare ${keyring:NAME} / ${env:VAR} references pass
   through unchanged (they're labels, not secrets; the UI needs to
   recognise them to render the keyring chip).

2. **Server-side atomic convert** — new endpoint:
       POST /api/v1/servers/{name}/config-to-secret
       body: {"scope": "header"|"env", "key": "<k>", "secret_name": "<n>"}
   The backend reads the real value from the loaded config, stores it
   in the OS keyring under secret_name, and rewrites the config field
   with ${keyring:<n>}. The client never has to possess the plaintext,
   so Convert-to-secret now works on the redacted-on-read path too.

3. **Reveal button removed from KVValueCell.vue** — with all literals
   displayed identically and Convert-to-secret available everywhere,
   the reveal toggle was a security-shaped speed bump with no real use
   case. The two paths to peek at a value (open the config file, or
   edit-cancel) remain. revealedKeys reactive state and the
   reveal/hide events disappear from the parent too.

4. **Symmetric macOS Swift cleanup** — ServerDetailView.swift::kvRow
   drops the `value != "***REDACTED***"` gate on the Convert-to-secret
   button. maskedHeaderValue() drops the sentinel special case.
   performConvertToSecret() calls the new atomic endpoint via the new
   APIClient.convertConfigToSecret helper instead of two-stepping
   through storeSecret + PATCH.

Backend tests updated for the new format:

- internal/oauth/logging_test.go::TestRedactStringHeaders — asserts the
  ••••et (40 chars) mask shape with length + last-2 suffix. New
  sub-tests pin the keyring/env-ref pass-through, short-value (<=4
  chars -> bare ••••), and empty-value ((empty)) edge cases.
- internal/runtime/event_bus_payload_test.go — SSE redaction test
  asserts the new format on the wire.
- internal/server/e2e_test.go — both PR #425 round-trip tests now
  assert mask shape instead of literal sentinel.

New backend test coverage:

- internal/httpapi/patch_server_test.go — 9 new sub-tests for the
  /config-to-secret endpoint validation paths: missing scope / key /
  secret_name, invalid scope, key not on server, value already a
  reference (keyring + env separately), empty value, server not found.
  Happy-path lives in the live verification because secret.Resolver is
  a concrete struct without a mock.

End-to-end verification on live local mcpproxy:

  GET /api/v1/servers
  -> synapbus.headers.Authorization = ••••59 (71 chars)            # new format
  -> kaggle.headers.Authorization   = ••••N} (30 chars)            # Bearer\${k...} also masked

  POST /api/v1/servers/synapbus/config-to-secret
       {"scope":"header","key":"Authorization","secret_name":"synapbus-authorization"}
  -> 200 {"reference":"\${keyring:synapbus-authorization}"}
  -> on disk: {"Authorization": "\${keyring:synapbus-authorization}"}
  -> GET response: passes the bare reference through unchanged

  Web UI: Headers row transformed from
          `Authorization ••••59 (71 chars) [lock] Convert to secret`
          to
          `Authorization [key-chip] stored in keyring: synapbus-authorization`
          via the Convert-to-secret modal — no intermediate steps for
          the user, no plaintext on the client.

  CLI: `upstream patch synapbus --header X-Cli-Verify=hello` /
       `upstream patch synapbus --header-remove X-Cli-Verify` still
       work; the keyring reference on Authorization survives both.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Dumbris pushed a commit that referenced this pull request May 14, 2026
User feedback on the previous commit: dropping REST/SSE redaction
unblocked the UI but narrowed the threat model from PR #425 (a local
process that holds the API key but not filesystem access could read
other upstreams' Bearer tokens off the wire). The better trade-off is
to keep both halves of PR #425 intact AND let the UI edit without
round-tripping the redacted sentinel.

Solution: deep-merge PATCH semantics so the client sends only the keys
that changed. Redacted-but-untouched values stay out of the patch
entirely, the backend keeps the real string on disk.

Backend:

- internal/httpapi/server.go::handlePatchServer — when the request
  body contains `headers` or `env`, MERGE into the existing stored map
  instead of replacing. New `headers_remove` / `env_remove` fields
  carry explicit deletes. Sending both is allowed (deletes apply after
  upserts).
- internal/httpapi/server.go::AddServerRequest — adds the two
  `*_remove` fields with a comment documenting the new semantics. The
  add path ignores them.
- internal/httpapi/server.go::handleGetServers — re-enable
  `redactServerHeaders` on both code paths.
- internal/runtime/event_bus.go::emitServersChanged — re-enable
  redaction on SSE `servers.changed` payloads. SSE rides the same
  trust boundary as the REST GET.
- internal/config/config.go::RevealSecretHeaders — restore the
  original PR #425 doc (REST + MCP both gated) with a new paragraph
  pointing at the deep-merge mechanism that makes the UI work anyway.

Tests:

- internal/httpapi/patch_server_test.go — 4 new tests pinning the
  merge semantics:
  - TestHandlePatchServer_HeadersDeepMerge — `headers: {X-New: v}`
    against existing `{Authorization, X-Trace}` preserves both
    original keys and adds X-New.
  - TestHandlePatchServer_HeadersRemove — `headers_remove: [...]`
    deletes the listed keys.
  - TestHandlePatchServer_HeadersSetAndRemove — both fields in one
    PATCH; deletes apply after upserts.
  - TestHandlePatchServer_EnvDeepMerge — same pattern for env.
- internal/runtime/event_bus_payload_test.go — restored the original
  PR #425 assertion (`...RedactsSensitiveHeaders`).

Frontend (Web UI):

- ServerDetail.vue — `patchServerDiff(patch, action)` replaces the old
  `patchKVMap`. Each per-row UI action now sends a minimal targeted
  patch:
    - Edit one row: `{headers: {key: newValue}}`
    - Delete one row: `{headers_remove: [key]}`
    - Add one row: `{headers: {newKey: newValue}}`
    - Convert to secret: `{headers: {key: "${keyring:NAME}"}}`
  The redacted sentinel for unchanged keys never round-trips, by
  construction.
- KVValueCell.vue — restore the `isBackendRedacted` branch. When the
  cell renders `***REDACTED***`, the reveal / Convert-to-secret
  buttons disappear (we don't hold the real value) and the cell shows
  the sentinel verbatim with a tooltip explaining that editing still
  works through the inline edit button.

macOS Swift:

- ServerDetailView.swift::saveEdits — switch from "send the full
  parsed map" to "diff against `server.headers` / `server.env` and
  send the diff". New private helper `diffKVMap(original:next:)`
  returns a `(set, remove)` tuple suitable for the deep-merge PATCH
  body. The same invariant holds: leaving a redacted line untouched
  in the textarea produces `next[k] == "***REDACTED***" ==
  original[k]`, so the key stays out of both sides of the diff and
  the backend preserves the real value.
- ServerDetailView.swift::kvRow — restore the
  `value != "***REDACTED***"` gate on the Convert-to-secret button
  (the sentinel isn't useful as a keyring payload).
- ServerDetailView.swift::editHeaders doc — explain the new flow.

End-to-end verification against the live local instance:

  $ curl -s -H "X-API-Key: ..." /api/v1/servers | jq '...synapbus.headers'
  → {"Authorization": "***REDACTED***"}                   # redacted ✓

  $ jq '...synapbus.headers' ~/.mcpproxy/mcp_config.json
  → {"Authorization": "Bearer 1d386..."}                  # real on disk

  $ curl -X PATCH .../servers/synapbus -d '{"headers":{"X-Trace-Test":"merge-works"}}'
  $ jq '...synapbus.headers' ~/.mcpproxy/mcp_config.json
  → {"Authorization": "Bearer 1d386...", "X-Trace-Test": "merge-works"}
                                                          # real token preserved ✓

  $ curl -X PATCH .../servers/synapbus -d '{"headers_remove":["X-Trace-Test"]}'
  $ jq '...synapbus.headers' ~/.mcpproxy/mcp_config.json
  → {"Authorization": "Bearer 1d386..."}                  # X-Trace-Test deleted ✓

PR #425's E2E tests still pass (TestE2E_PatchDeepMergesEnvAndHeaders,
TestE2E_MultipleEnableDisablePreservesConfig — both exercise the MCP
tool which still redacts). PR #425's intent is fully preserved.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Dumbris pushed a commit that referenced this pull request May 14, 2026
…cted values

User feedback: the Headers card looked split-brained. A non-sensitive
header showed `••••XX (NN chars)` with a Convert-to-secret button. The
Authorization header showed `***REDACTED***` with no button — exactly
the most-likely candidate for "move me to keyring" was the one the UI
refused to convert, because the client side couldn't hand the real value
to the existing two-step (POST /secrets, then PATCH server) flow.

This change unifies both display and conversion:

1. **Single mask format on the wire** — internal/oauth/logging.go
   replaces the `***REDACTED***` sentinel in RedactStringHeaders with
   MaskValue(v), producing `••••<last2> (<N> chars)` for literal
   secrets. The same format the Web UI / macOS tray have been computing
   client-side. Bare ${keyring:NAME} / ${env:VAR} references pass
   through unchanged (they're labels, not secrets; the UI needs to
   recognise them to render the keyring chip).

2. **Server-side atomic convert** — new endpoint:
       POST /api/v1/servers/{name}/config-to-secret
       body: {"scope": "header"|"env", "key": "<k>", "secret_name": "<n>"}
   The backend reads the real value from the loaded config, stores it
   in the OS keyring under secret_name, and rewrites the config field
   with ${keyring:<n>}. The client never has to possess the plaintext,
   so Convert-to-secret now works on the redacted-on-read path too.

3. **Reveal button removed from KVValueCell.vue** — with all literals
   displayed identically and Convert-to-secret available everywhere,
   the reveal toggle was a security-shaped speed bump with no real use
   case. The two paths to peek at a value (open the config file, or
   edit-cancel) remain. revealedKeys reactive state and the
   reveal/hide events disappear from the parent too.

4. **Symmetric macOS Swift cleanup** — ServerDetailView.swift::kvRow
   drops the `value != "***REDACTED***"` gate on the Convert-to-secret
   button. maskedHeaderValue() drops the sentinel special case.
   performConvertToSecret() calls the new atomic endpoint via the new
   APIClient.convertConfigToSecret helper instead of two-stepping
   through storeSecret + PATCH.

Backend tests updated for the new format:

- internal/oauth/logging_test.go::TestRedactStringHeaders — asserts the
  ••••et (40 chars) mask shape with length + last-2 suffix. New
  sub-tests pin the keyring/env-ref pass-through, short-value (<=4
  chars -> bare ••••), and empty-value ((empty)) edge cases.
- internal/runtime/event_bus_payload_test.go — SSE redaction test
  asserts the new format on the wire.
- internal/server/e2e_test.go — both PR #425 round-trip tests now
  assert mask shape instead of literal sentinel.

New backend test coverage:

- internal/httpapi/patch_server_test.go — 9 new sub-tests for the
  /config-to-secret endpoint validation paths: missing scope / key /
  secret_name, invalid scope, key not on server, value already a
  reference (keyring + env separately), empty value, server not found.
  Happy-path lives in the live verification because secret.Resolver is
  a concrete struct without a mock.

End-to-end verification on live local mcpproxy:

  GET /api/v1/servers
  -> synapbus.headers.Authorization = ••••59 (71 chars)            # new format
  -> kaggle.headers.Authorization   = ••••N} (30 chars)            # Bearer\${k...} also masked

  POST /api/v1/servers/synapbus/config-to-secret
       {"scope":"header","key":"Authorization","secret_name":"synapbus-authorization"}
  -> 200 {"reference":"\${keyring:synapbus-authorization}"}
  -> on disk: {"Authorization": "\${keyring:synapbus-authorization}"}
  -> GET response: passes the bare reference through unchanged

  Web UI: Headers row transformed from
          `Authorization ••••59 (71 chars) [lock] Convert to secret`
          to
          `Authorization [key-chip] stored in keyring: synapbus-authorization`
          via the Convert-to-secret modal — no intermediate steps for
          the user, no plaintext on the client.

  CLI: `upstream patch synapbus --header X-Cli-Verify=hello` /
       `upstream patch synapbus --header-remove X-Cli-Verify` still
       work; the keyring reference on Authorization survives both.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Dumbris added a commit that referenced this pull request May 14, 2026
…t-to-secret (#466)

* feat(server-detail): expose and edit headers + env in Web UI

Headers and env were dropped at the runtime -> management -> contract
boundary, so neither the Web UI nor the macOS tray could render or
round-trip them. A server configured with a static Authorization header
(e.g. synapbus with a Bearer token) appeared with no headers section at
all on the Web UI Config tab.

Backend wiring (this commit, all surfaces):
- internal/runtime/runtime.go: GetAllServers emits headers and env from
  serverStatus.Config in serverMap.
- internal/management/service.go: ListServers extracts headers and env
  in both typed (map[string]string) and generic (map[string]interface{})
  shapes. Existing redaction at the HTTP layer continues to apply.

Web UI (Config tab):
- New Headers card with redact-by-default + click-to-reveal, per-row
  inline edit/delete, an Add row, and a "Convert to secret" button that
  stores the literal value in the OS keyring and rewrites the field as
  `${keyring:<name>}`.
- Same affordances applied to the Environment Variables card.
- New reusable KVValueCell component encapsulates the per-row UX so
  Headers and Env share the same display/edit/reveal/convert logic.
- api.ts: new patchServer() and storeSecret() helpers wrapping
  PATCH /api/v1/servers/{id} and POST /api/v1/secrets respectively.
- types/api.ts: add `headers` to Server interface (the contracts.ts
  twin already had it; api.ts had drifted).

Note on reveal: backend redaction replaces sensitive header values with
`***REDACTED***` unless `reveal_secret_headers: true` is set in config.
The KVValueCell detects that sentinel and disables both reveal and the
"Convert to secret" button (since neither has the real value in hand),
surfacing a tooltip that points the user at the config flag.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(server-detail): render \${keyring:...} preview literally in convert modal

Vue templates do NOT interpret \${...} as JS template-literal syntax —
the dollar-and-braces inside the modal body were rendering verbatim as
'${'{'}'... text. Replace the awkward \${'{'} escape with a plain string
interpolation through {{ '...' }} mustache so the user sees the
actual reference syntax they're about to substitute into config.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(macos): display + edit headers and env on server detail

Adds full round-trip support for headers and env on the macOS tray's
server detail screen, matching the new Web UI experience.

API model:
- ServerStatus gains `headers` and `env` (both [String: String]?).
  CodingKeys updated to map the JSON `headers` and `env` fields the Go
  backend now emits (companion to the runtime + management wiring in
  the parent commit).

View:
- Headers section under Connection for HTTP / streamable-http servers,
  visible in both view mode (sorted key list with masked values) and
  edit mode (KEY=VALUE textarea, parallel to the existing env textarea).
- editEnvVars now pre-populates from `server.env` instead of starting
  empty — fixes the long-standing stub at L939 that explicitly noted
  the missing config API.
- editHeaders works the same way for headers.
- saveEdits() sends both maps unconditionally so deletes round-trip;
  refuses to save if any header value is still `***REDACTED***` (the
  backend sentinel emitted when `reveal_secret_headers: false`) so we
  don't silently overwrite a real secret with the placeholder.
- New helpers: parseKVTextarea (shared between env and headers) and
  maskedHeaderValue (recognises `${keyring:...}` and `${env:...}`
  references and renders them as-is, masks literal values, surfaces the
  redaction sentinel verbatim so users know to flip
  reveal_secret_headers in their config).

Convert-to-secret in Swift: deferred. The Web UI surfaces this per row
through KVValueCell; the equivalent SwiftUI experience would need a new
modal + state machine that doesn't fit the existing textarea-based
edit form. Tracked as a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(macos): Convert-to-secret + sidebar cap + redacted-save guard hardening

User feedback on the previous macOS commit triggered three follow-up fixes
that all land naturally together:

Sidebar cap (MainWindow.swift):
- NavigationSplitView only set `min: 180, ideal: 220` for the sidebar
  column. SwiftUI was free to expand it unbounded after some layout
  transitions, squeezing the detail pane to a sliver on the right.
- Add `max: 280` so the sidebar stays at a sensible width while the
  detail pane gets the rest. Verified visually on the server detail
  Config tab.

Redacted-save guard (ServerDetailView.swift::saveEdits):
- Previous version only refused to save when the textarea still
  contained `***REDACTED***` literally. A user could still delete the
  redacted line, add a new header, and silently wipe out the real
  Authorization behind the redaction.
- Now we diff the new headers map against the original `server.headers`
  and refuse the save when either (a) a `***REDACTED***` literal is
  still present OR (b) any key whose original value was redacted is
  missing entirely from the new map. The error message lists the
  offending keys and points the user at `reveal_secret_headers: true`.

Convert-to-secret on macOS (the previously-deferred work):
- New SwiftUI sheet binding through `@State convertSheet:
  ConvertToSecretContext?`. The sheet body mirrors the Web UI flow —
  pre-suggests a secret name (`<server-name>-<key>`, lowercased and
  hyphen-sanitised), shows a live `${keyring:NAME}` preview, has
  Cancel + Convert with proper keyboard shortcuts.
- Headers view-mode rendering switched from the static
  `configRow(label:value:)` to a new `kvRow(scope:key:value:)` that
  renders `${keyring:…}` / `${env:…}` references as a capsule chip
  with no actions, surfaces the `***REDACTED***` sentinel verbatim
  (still no convert button — we don't have the real value), and shows
  a 🔒 button for genuine literal values that opens the convert sheet.
- Environment Variables now also renders in view mode (previously it
  was edit-only) with the same kvRow affordances. Visible whenever the
  server has any env vars, regardless of protocol — stdio servers can
  finally inspect their pre-populated env without entering edit mode.
- APIClient gains `storeSecret(name:value:)` wrapping POST
  /api/v1/secrets which returns the `${keyring:<name>}` reference
  string to substitute back into the server config via the existing
  `updateServer` PATCH.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(headers): stop redacting REST + SSE responses; scope reveal_secret_headers to MCP tool only

User feedback on the previous round: the Server Detail edit form refused
to save when any header value still contained the `***REDACTED***`
sentinel, and pushed users at the `reveal_secret_headers: true` config
flag to unblock themselves. That trade-off was wrong — it punished the
human UI to protect an agent code path.

The actual threat model:

- REST API (`/api/v1/servers`, SSE `/events`): gated by the local
  per-install API key. Same trust boundary as access to
  `~/.mcpproxy/mcp_config.json` on disk where these values are already
  stored in plaintext. Redacting in the response bought no real
  security, only broke the Web UI + macOS tray edit-and-save round-trip.

- MCP `upstream_servers` tool: invoked by AI agents, output gets
  read back to the LLM context. THIS is the agent-context exposure
  `reveal_secret_headers` was created to protect — and that redaction
  was already implemented separately in `internal/server/mcp.go:~2545`,
  unaffected by this change.

Backend changes:
- internal/httpapi/server.go: drop `redactServerHeaders` calls in
  `handleGetServers` (both code paths) and remove the now-unused method.
- internal/runtime/event_bus.go: drop the `redactServerHeaders` call on
  SSE `servers.changed` payloads and remove the now-unused method.
- internal/runtime/event_bus_payload_test.go: rewrite the redaction test
  to assert the new policy — SSE must now carry plaintext, the test name
  changes from `…_RedactsSensitiveHeaders` to `…_SendsPlaintextHeaders`.
- internal/config/config.go: update the `RevealSecretHeaders` doc to
  explicitly scope the flag to the MCP tool. REST + SSE always send
  plaintext from now on.

UI cleanup (the redaction sentinel is no longer expected on the wire):
- macOS Swift `saveEdits()`: drop the elaborate redacted-save guard
  (refused save when ***REDACTED*** literal still in textarea OR a
  redacted key was deleted). Both cases became impossible once the REST
  API serves plaintext.
- macOS Swift `kvRow()`: drop the `value != "***REDACTED***"` check
  that disabled the Convert-to-secret button.
- macOS Swift `performConvertToSecret()`: drop the matching guard.
- Vue `KVValueCell.vue`: drop the `isBackendRedacted` computed flag
  and the "Backend redacted this value, set reveal_secret_headers"
  tooltip. Reveal and Convert are always available on literal values.
- Vue `ServerDetail.vue::commitConvert()`: drop the same guard.

Verified end-to-end on macOS and Web UI:
- REST: `curl /api/v1/servers` → `Authorization: Bearer 1d386f...`
  (the real 71-char token).
- MCP tool: `upstream_servers list` → `"Authorization":"***REDACTED***"`
  (still hidden from agents).
- macOS Server Detail → synapbus → Edit → Headers textarea pre-populated
  with the real Bearer token; Save no longer blocked.
- Web UI synapbus Config → Headers row shows `••••59 (71 chars)` with
  reveal eye, Convert-to-secret 🔒, edit, delete — all functional.

OAS spec regenerated.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(headers): restore REST/SSE redaction and add deep-merge PATCH

User feedback on the previous commit: dropping REST/SSE redaction
unblocked the UI but narrowed the threat model from PR #425 (a local
process that holds the API key but not filesystem access could read
other upstreams' Bearer tokens off the wire). The better trade-off is
to keep both halves of PR #425 intact AND let the UI edit without
round-tripping the redacted sentinel.

Solution: deep-merge PATCH semantics so the client sends only the keys
that changed. Redacted-but-untouched values stay out of the patch
entirely, the backend keeps the real string on disk.

Backend:

- internal/httpapi/server.go::handlePatchServer — when the request
  body contains `headers` or `env`, MERGE into the existing stored map
  instead of replacing. New `headers_remove` / `env_remove` fields
  carry explicit deletes. Sending both is allowed (deletes apply after
  upserts).
- internal/httpapi/server.go::AddServerRequest — adds the two
  `*_remove` fields with a comment documenting the new semantics. The
  add path ignores them.
- internal/httpapi/server.go::handleGetServers — re-enable
  `redactServerHeaders` on both code paths.
- internal/runtime/event_bus.go::emitServersChanged — re-enable
  redaction on SSE `servers.changed` payloads. SSE rides the same
  trust boundary as the REST GET.
- internal/config/config.go::RevealSecretHeaders — restore the
  original PR #425 doc (REST + MCP both gated) with a new paragraph
  pointing at the deep-merge mechanism that makes the UI work anyway.

Tests:

- internal/httpapi/patch_server_test.go — 4 new tests pinning the
  merge semantics:
  - TestHandlePatchServer_HeadersDeepMerge — `headers: {X-New: v}`
    against existing `{Authorization, X-Trace}` preserves both
    original keys and adds X-New.
  - TestHandlePatchServer_HeadersRemove — `headers_remove: [...]`
    deletes the listed keys.
  - TestHandlePatchServer_HeadersSetAndRemove — both fields in one
    PATCH; deletes apply after upserts.
  - TestHandlePatchServer_EnvDeepMerge — same pattern for env.
- internal/runtime/event_bus_payload_test.go — restored the original
  PR #425 assertion (`...RedactsSensitiveHeaders`).

Frontend (Web UI):

- ServerDetail.vue — `patchServerDiff(patch, action)` replaces the old
  `patchKVMap`. Each per-row UI action now sends a minimal targeted
  patch:
    - Edit one row: `{headers: {key: newValue}}`
    - Delete one row: `{headers_remove: [key]}`
    - Add one row: `{headers: {newKey: newValue}}`
    - Convert to secret: `{headers: {key: "${keyring:NAME}"}}`
  The redacted sentinel for unchanged keys never round-trips, by
  construction.
- KVValueCell.vue — restore the `isBackendRedacted` branch. When the
  cell renders `***REDACTED***`, the reveal / Convert-to-secret
  buttons disappear (we don't hold the real value) and the cell shows
  the sentinel verbatim with a tooltip explaining that editing still
  works through the inline edit button.

macOS Swift:

- ServerDetailView.swift::saveEdits — switch from "send the full
  parsed map" to "diff against `server.headers` / `server.env` and
  send the diff". New private helper `diffKVMap(original:next:)`
  returns a `(set, remove)` tuple suitable for the deep-merge PATCH
  body. The same invariant holds: leaving a redacted line untouched
  in the textarea produces `next[k] == "***REDACTED***" ==
  original[k]`, so the key stays out of both sides of the diff and
  the backend preserves the real value.
- ServerDetailView.swift::kvRow — restore the
  `value != "***REDACTED***"` gate on the Convert-to-secret button
  (the sentinel isn't useful as a keyring payload).
- ServerDetailView.swift::editHeaders doc — explain the new flow.

End-to-end verification against the live local instance:

  $ curl -s -H "X-API-Key: ..." /api/v1/servers | jq '...synapbus.headers'
  → {"Authorization": "***REDACTED***"}                   # redacted ✓

  $ jq '...synapbus.headers' ~/.mcpproxy/mcp_config.json
  → {"Authorization": "Bearer 1d386..."}                  # real on disk

  $ curl -X PATCH .../servers/synapbus -d '{"headers":{"X-Trace-Test":"merge-works"}}'
  $ jq '...synapbus.headers' ~/.mcpproxy/mcp_config.json
  → {"Authorization": "Bearer 1d386...", "X-Trace-Test": "merge-works"}
                                                          # real token preserved ✓

  $ curl -X PATCH .../servers/synapbus -d '{"headers_remove":["X-Trace-Test"]}'
  $ jq '...synapbus.headers' ~/.mcpproxy/mcp_config.json
  → {"Authorization": "Bearer 1d386..."}                  # X-Trace-Test deleted ✓

PR #425's E2E tests still pass (TestE2E_PatchDeepMergesEnvAndHeaders,
TestE2E_MultipleEnableDisablePreservesConfig — both exercise the MCP
tool which still redacts). PR #425's intent is fully preserved.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(headers): unify delete syntax to JSON Merge Patch + add CLI patch

User feedback on the previous round: REST PATCH had two ways to delete
a key (`headers_remove: ["X"]` array vs MCP tool's `{"X": null}`). The
MCP tool's syntax is cleaner and is a documented standard (RFC 7396).
Unify on it and add a CLI command so all three interfaces — MCP, REST,
CLI — behave the same way.

Backend (internal/httpapi/server.go):
- AddServerRequest.Headers and .Env switch from `map[string]string` to
  `map[string]*string`. Go's encoding/json then maps a missing key to
  "no entry", a present non-null value to a non-nil `*string`, and a
  present `null` to a nil pointer. The merge loop reads each entry: nil
  pointer = delete, non-nil = upsert.
- Drop the `headers_remove` / `env_remove` array fields. A single `null`
  in the same map carries the same intent and aligns with the MCP tool.
- POST (add) ignores nil entries via the new flattenNullableMap helper;
  `null` on create has no meaning.
- redactServerHeaders / SSE redaction unchanged.

Tests (internal/httpapi/patch_server_test.go):
- Rewrite the previous `*_remove`-style tests to use literal JSON null
  payloads via `json.RawMessage`. The raw-byte approach is independent
  of any Go marshaling quirks that could collapse `null` values.
- New TestHandlePatchServer_HeadersEmptyStringSetsNotDeletes pins the
  distinction between `""` (set to empty) and `null` (delete) — JSON
  Merge Patch is explicit about it and a future refactor that
  "helpfully" collapses one to the other would silently break.
- Total: 7 tests, all green.

Web UI (frontend/src/views/ServerDetail.vue):
- deleteKv now sends `{headers: {key: null}}` instead of the array
  form. JSON.stringify emits `null` literally, no special handling.
- Drop the `scopeRemoveKey` helper (no longer needed).

macOS Swift (native/macos/MCPProxy/MCPProxy/Views/ServerDetailView.swift):
- diffKVMap returns a single `[String: Any]` patch dict where deleted
  keys map to `NSNull()` instead of returning the previous
  `(set, remove)` tuple.
- saveEdits writes the patch as `updates["headers"] = patch` directly;
  no `headers_remove` companion field anymore.
- performConvertToSecret sends a single-key patch
  `{field: {key: ref}}` instead of building the full map — minimal
  wire payload, never round-trips the redacted Authorization.
- The trap was real and surprising: Swift's default `JSONEncoder` on
  `[String: String?]` SILENTLY DROPS nil entries from the JSON output.
  Using `[String: Any]` with `NSNull()` + `JSONSerialization` (the
  encoder our APIClient already uses) renders `null` correctly.

Swift unit test (native/macos/MCPProxy/MCPProxyTests/MergePatchEncodingTests.swift):
- 4 tests pinning the encoding contract:
  1. NSNull encodes as literal `null` via JSONSerialization.
  2. A delete-only patch round-trips through JSON and the value
     parses back as NSNull (not "", not absent).
  3. The wrong path — `[String: String?]` + default `JSONEncoder` —
     does silently drop nils. Documented as a poison-pill test so a
     future refactor that "simplifies" to it has to explicitly delete
     this test and read the comment first.
  4. Empty string still encodes as `""` and explicit null as `null`
     — the JSON Merge Patch set-vs-delete distinction is preserved.

CLI (cmd/mcpproxy/upstream_cmd.go + internal/cliclient/client.go):
- New `mcpproxy upstream patch <name>` subcommand with flags:
    --header K=V         upsert (repeatable)
    --header-remove K    delete (repeatable)
    --env K=V            upsert (repeatable)
    --env-remove K       delete (repeatable)
- New cliclient.PatchServer(name, body) sends raw JSON to PATCH
  /api/v1/servers/{name}. Body shape is the same JSON Merge Patch the
  Web UI and macOS tray send.
- Closes the CLI gap I called out in the boundaries-matrix summary —
  REST, MCP, and CLI now all support both write and delete on headers
  / env with the same semantics.

Live end-to-end verification:

  $ mcpproxy upstream patch synapbus --header "X-Cli-Test: hello-from-cli"
  ✅ Patched synapbus: 1 header(s) set
  → on disk: { Authorization (real Bearer), X-Cli-Test }  (Auth preserved)

  $ mcpproxy upstream patch synapbus --header-remove X-Cli-Test
  ✅ Patched synapbus: 1 header(s) removed
  → on disk: { Authorization (real Bearer) }              (Auth preserved)

  $ mcpproxy upstream patch synapbus --header "X-Foo: v" --header-remove X-Foo
  Error: --header and --header-remove for "X-Foo" conflict; pick one

  Web UI: "+ Add header" → X-WebUI-Test=from-browser → Save
  → on disk: { Authorization (real Bearer), X-WebUI-Test }

  macOS tray: Edit → textarea pre-populated with
  "Authorization=***REDACTED***" → user appends "X-Mac-Test=hello-from-mac"
  → Save
  → on disk: { Authorization (REAL Bearer, preserved!), X-Mac-Test }

PR #463 subagent review confirmed the unrelated "disable tool" pattern
is a different domain (reversible state in BBolt vs destructive
mutation in mcp_config.json) and should not be unified with this work.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(headers): unify display + server-side convert-to-secret for redacted values

User feedback: the Headers card looked split-brained. A non-sensitive
header showed `••••XX (NN chars)` with a Convert-to-secret button. The
Authorization header showed `***REDACTED***` with no button — exactly
the most-likely candidate for "move me to keyring" was the one the UI
refused to convert, because the client side couldn't hand the real value
to the existing two-step (POST /secrets, then PATCH server) flow.

This change unifies both display and conversion:

1. **Single mask format on the wire** — internal/oauth/logging.go
   replaces the `***REDACTED***` sentinel in RedactStringHeaders with
   MaskValue(v), producing `••••<last2> (<N> chars)` for literal
   secrets. The same format the Web UI / macOS tray have been computing
   client-side. Bare ${keyring:NAME} / ${env:VAR} references pass
   through unchanged (they're labels, not secrets; the UI needs to
   recognise them to render the keyring chip).

2. **Server-side atomic convert** — new endpoint:
       POST /api/v1/servers/{name}/config-to-secret
       body: {"scope": "header"|"env", "key": "<k>", "secret_name": "<n>"}
   The backend reads the real value from the loaded config, stores it
   in the OS keyring under secret_name, and rewrites the config field
   with ${keyring:<n>}. The client never has to possess the plaintext,
   so Convert-to-secret now works on the redacted-on-read path too.

3. **Reveal button removed from KVValueCell.vue** — with all literals
   displayed identically and Convert-to-secret available everywhere,
   the reveal toggle was a security-shaped speed bump with no real use
   case. The two paths to peek at a value (open the config file, or
   edit-cancel) remain. revealedKeys reactive state and the
   reveal/hide events disappear from the parent too.

4. **Symmetric macOS Swift cleanup** — ServerDetailView.swift::kvRow
   drops the `value != "***REDACTED***"` gate on the Convert-to-secret
   button. maskedHeaderValue() drops the sentinel special case.
   performConvertToSecret() calls the new atomic endpoint via the new
   APIClient.convertConfigToSecret helper instead of two-stepping
   through storeSecret + PATCH.

Backend tests updated for the new format:

- internal/oauth/logging_test.go::TestRedactStringHeaders — asserts the
  ••••et (40 chars) mask shape with length + last-2 suffix. New
  sub-tests pin the keyring/env-ref pass-through, short-value (<=4
  chars -> bare ••••), and empty-value ((empty)) edge cases.
- internal/runtime/event_bus_payload_test.go — SSE redaction test
  asserts the new format on the wire.
- internal/server/e2e_test.go — both PR #425 round-trip tests now
  assert mask shape instead of literal sentinel.

New backend test coverage:

- internal/httpapi/patch_server_test.go — 9 new sub-tests for the
  /config-to-secret endpoint validation paths: missing scope / key /
  secret_name, invalid scope, key not on server, value already a
  reference (keyring + env separately), empty value, server not found.
  Happy-path lives in the live verification because secret.Resolver is
  a concrete struct without a mock.

End-to-end verification on live local mcpproxy:

  GET /api/v1/servers
  -> synapbus.headers.Authorization = ••••59 (71 chars)            # new format
  -> kaggle.headers.Authorization   = ••••N} (30 chars)            # Bearer\${k...} also masked

  POST /api/v1/servers/synapbus/config-to-secret
       {"scope":"header","key":"Authorization","secret_name":"synapbus-authorization"}
  -> 200 {"reference":"\${keyring:synapbus-authorization}"}
  -> on disk: {"Authorization": "\${keyring:synapbus-authorization}"}
  -> GET response: passes the bare reference through unchanged

  Web UI: Headers row transformed from
          `Authorization ••••59 (71 chars) [lock] Convert to secret`
          to
          `Authorization [key-chip] stored in keyring: synapbus-authorization`
          via the Convert-to-secret modal — no intermediate steps for
          the user, no plaintext on the client.

  CLI: `upstream patch synapbus --header X-Cli-Verify=hello` /
       `upstream patch synapbus --header-remove X-Cli-Verify` still
       work; the keyring reference on Authorization survives both.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs: cover PR #466 headers/env editing + Convert-to-secret + new endpoints

REST API (docs/api/rest-api.md):
- New section on Header redaction and the ••••<last2> (<N> chars) mask
  format, when reveal_secret_headers applies, and why operators rarely
  need to flip it.
- New PATCH /api/v1/servers/{name} endpoint documented with full JSON
  Merge Patch (RFC 7396) semantics: non-null upserts, JSON null deletes,
  absent keys preserved. Includes worked curl examples and the
  empty-string-is-not-delete gotcha.
- New POST /api/v1/servers/{name}/config-to-secret endpoint —
  atomically moves a header/env value out of mcp_config.json into the
  OS keyring without the client ever holding the plaintext.

CLI (docs/cli/management-commands.md):
- New `upstream patch` subcommand with --header / --header-remove /
  --env / --env-remove flags and the deep-merge guarantee that no
  un-named key gets disturbed.

Configuration guide (docs/configuration/upstream-servers.md):
- New "Headers, Environment Variables, and Secrets" section explaining
  the wire mask, the three editing surfaces (Web UI / macOS tray /
  CLI / REST), and the ${keyring:NAME} / ${env:VAR} reference shapes.
- Cross-links to the REST PATCH reference, the CLI subcommand, and the
  keyring integration page.

Web UI (docs/web-ui/server-detail.md, new):
- Dedicated page for the Server Detail Configuration tab focused on
  the Headers and Environment Variables cards. Documents the value
  formats (masked literal, keyring chip, env chip, plain), the
  per-row actions (add / edit / delete / convert), and the
  convert-to-secret flow including the atomic backend swap.
- Two embedded screenshots showing the Headers card and the
  Convert-to-secret modal.

Screenshots (docs/screenshots/server-detail/):
- web-headers-card.png — the Headers card with masked Authorization
  + Convert to secret button. Captured against the live local
  instance with synapbus configured with a real Bearer token.
- web-convert-modal.png — the modal preview with auto-suggested
  secret name and the ${keyring:NAME} live preview.

Cross-references between the four pages so a reader can land anywhere
and find the relevant detail in two clicks.

* lint: drop trailing period from upstream patch daemon-required error

staticcheck ST1005 — error strings must not end with punctuation. Flatten
the multi-line message into a single sentence so the no-trailing-period
rule is easy to keep over time.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Code <[email protected]>
Dumbris added a commit that referenced this pull request Jul 21, 2026
…ings (#875)

* fix(security): redact env secrets and URL query params in server listings (#872)

Server listings masked header values but returned env values and URL query
secrets in clear text at all three parity seams (upstream_servers MCP list,
GET /api/v1/servers, and the SSE servers.changed payload), and echoed the raw
upstream URL (query secrets and all) into connection_status.last_error /
health.detail on connect failure.

Add two helpers next to the #425 header redactors in internal/oauth/logging.go:
RedactEnvValues (masks values under sensitive-looking keys via MaskValue,
references pass through, non-sensitive keys stay readable) and
RedactURLQueryParams (net/url parse, masks sensitive query values while leaving
the path, non-sensitive params, and ${env:}/${keyring:} references verbatim).

Apply both at all three seams gated by the existing reveal_secret_headers flag,
and scrub URL secrets out of last_error / health.detail with RedactSensitiveData.
Rename the httpapi/runtime redactServerHeaders methods to redactServerSecrets to
reflect the wider scope; REST↔SSE parity is preserved so the Web UI merge does
not flicker. Write paths (PATCH deep-merge) are untouched.

* fix(security): scrub URL secrets from diagnostic.cause in server listings (#872)

The #872 redaction masked env/URL/header secrets and scrubbed last_error /
health.detail, but the Spec 044 structured diagnostic.cause echoes the same
raw connect error verbatim, leaking the full upstream URL (query secrets and
all) through GET /api/v1/servers and the SSE servers.changed payload.

Scrub Diagnostic.Cause with RedactSensitiveData at both parity seams
(httpapi redactServerSecretFields + runtime redactServerSecrets), in parity
with the existing last_error / health.detail scrub.

Also update two stale E2E assertions that expected plaintext env values under
sensitive-looking keys (TEST_KEY, API_KEY); #872 now masks those, so assert
the masked-display format instead — matching the headers assertion the fix
already updated.

* fix(security): close remaining #872 secret leaks on diagnostics/doctor/tray

Follow-up to the #872 redaction work; the initial fix masked the servers
list/SSE/MCP seams but left three sibling surfaces leaking the same
URL/env secrets:

- macOS tray saveEdits() sent the full env map unconditionally before
  the diff, so an unchanged secret round-tripped the read-path mask
  (`••••23 (14 chars)`) and PATCH deep-merge upserted the mask over the
  real on-disk plaintext. Drop the unconditional send; rely on diffKVMap
  (upsert + NSNull delete), mirroring headers.
- GET /api/v1/servers/{id}/diagnostics returned health.detail and
  diagnostic.cause raw from GetAllServers, bypassing redaction. Scrub
  both, gated on reveal_secret_headers.
- management.Doctor() (and the httpapi legacy diagnostics fallback)
  copied unscrubbed health.detail/last_error into UpstreamErrors; scrub
  them in parity with the list route.

Also close two acknowledged gaps on the same seams: add sig/signature to
the free-form RedactSensitiveData param list (Azure-SAS URL secrets), and
mask basic-auth userinfo passwords in RedactURLQueryParams.

* chore(oas): regenerate OpenAPI artifacts

* fix(security): mask-aware URL write path + broader redaction heuristics (#872)

Address cross-model review findings on the secret-redaction work:

- Mask-aware write path (URL/env/headers): the read path masks secrets
  in the server URL query string and userinfo, but `url` is a single
  string field with no client-side diff. A client editing a non-secret
  part and echoing the masked value back would persist the mask over the
  real credential. RedactURLQueryParams/RedactEnvValues/RedactStringHeaders
  now have UnmaskURL/UnmaskEnvValues/UnmaskHeaders counterparts applied in
  both write paths (REST PATCH and MCP upstream_servers update/patch), so
  an echoed mask is reverted to the stored real value while genuine edits
  persist. Protects all clients, not just the tray.

- Connection-string env vars: values that parse as a URL with userinfo
  (DATABASE_URL, REDIS_URL, ...) now mask only the password, keeping
  scheme/host/db readable. DSN / CONNECTION_STRING / CONN_STR keys are
  added to the whole-value sensitive markers.

- URL query redaction now matches on a normalized param name (lowercase,
  '-'/'_' stripped) against a normalized sensitive set extended with
  X-Amz-Credential/Signature/Security-Token, authToken and access-token
  variants; "credential" added to the regex scrubber set for free-form
  error/health.detail strings.

- isConfigReference requires a syntactically complete ${keyring:...} /
  ${env:...} reference (anchored regex) so a composite like
  ${env:NAME}garbage is masked instead of passing through unmasked.

* fix(security): authority-safe, component-wise URL unmask on write path (#872)

Round-2 review hardening of the mask-aware write path:

- UnmaskURL now refuses to move a stored secret onto a different
  scheme/host: a restore happens only when incoming keeps the stored
  scheme and host:port (and, for the userinfo password, the same
  username). Redirecting the URL to another host leaves the mask literal
  so the write fails validation instead of leaking the real credential.

- Duplicate sensitive query keys are restored positionally (i-th masked
  occurrence <- i-th stored occurrence) and only when the incoming and
  stored occurrence counts for that key match; a mismatch leaves the
  masks literal rather than guessing.

- UnmaskEnvValues unmasks URL-shaped values under non-sensitive keys
  component-wise via UnmaskURL, so editing a non-secret part of a
  connection string (db name, an option) restores just the password
  component — with the same authority safeguard — instead of persisting
  the password mask as the real password. Whole-value masks (sensitive
  keys, RedactSensitiveData fallback) keep the exact-match revert.

* fix(security): whole-value revert before component unmask for malformed URL env values (#872)

Round-3 review edge case: a URL-shaped value under a non-sensitive env
key that is a MALFORMED URL is masked by RedactURLQueryParams via its
RedactURL regex fallback (url.Parse fails). The component-wise UnmaskURL
branch also fails to parse it and returns the mask unchanged, so an
unedited echo would persist the mask over the stored secret.

Reorder UnmaskEnvValues to try the whole-value revert (incoming ==
maskedEnvValue(key, stored) -> stored) BEFORE the component-wise
UnmaskURL branch, so a malformed masked value round-trips back to the
real secret. Well-formed URL-shaped values with a genuine edit still
fall through to component-wise UnmaskURL (with the authority safeguard).
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.

2 participants