Skip to content

Commit 62c01ba

Browse files
author
Algis Dumbris
committed
fix(security): mask secrets on MCP server payloads and stop nil/anonymous auth revealing them (smart-mcp-proxy#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 smart-mcp-proxy#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.
1 parent 607a80e commit 62c01ba

14 files changed

Lines changed: 1151 additions & 76 deletions

‎docs/api/rest-api.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,11 @@ preserved) and the [`config-to-secret`](#post-apiv1serversnameconfig-to-secret)
152152
endpoint reads the real value server-side. Flip the flag only if you
153153
need to inspect a raw value through the API for debugging.
154154

155+
On the MCP channel the flag also requires an **authenticated** caller
156+
(issue #1148): an unauthenticated `/mcp` client is admin only for backward
157+
compatibility, and gets the masked values regardless of the flag. The REST
158+
API always requires an API key, so it is unaffected.
159+
155160
The MCP `upstream_servers` tool was the original motivator for redaction
156161
(see [PR #425](https://github.com/smart-mcp-proxy/mcpproxy-go/pull/425)) —
157162
a prompt-injected agent could otherwise read another upstream's PAT via

‎docs/configuration/upstream-servers.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,22 @@ To disable redaction (for debugging only), set `reveal_secret_headers: true`
146146
in `mcp_config.json`. **It's not normally needed**: the editing flow
147147
described below works without ever exposing the plaintext to the client.
148148

149+
Since v0.64 (issue #1148) the flag additionally requires an **authenticated**
150+
caller. `/mcp` is deliberately unprotected by default
151+
(`require_mcp_auth: false`), so an unauthenticated MCP client is treated as
152+
admin for backward compatibility — but that is not an identity, and it no
153+
longer satisfies a check that hands back raw credentials. With the flag on,
154+
raw values are returned to a caller presenting the API key or an admin agent
155+
token, to a tray/socket connection (authenticated by OS-level socket
156+
permissions), and over stdio; an unauthenticated TCP `/mcp` caller gets the
157+
masked values. Nothing else changes: every other operation an unauthenticated
158+
MCP client can perform today still works.
159+
160+
Argument vectors are masked too: a credential passed as `--api-key sk-…` in
161+
`args` is masked by flag name and by value shape, and a masked argument echoed
162+
back through `args_json` is reverted to the stored value rather than persisted
163+
over it.
164+
149165
### How you edit them
150166

151167
#### Web UI / macOS tray

‎internal/auth/context.go‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,17 @@ type AuthContext struct {
2525
DisplayName string // User's display name
2626
Role string // "admin" or "user" (empty for API key / agent token auth)
2727
Provider string // OAuth provider used (e.g., "google", "github")
28+
29+
// Anonymous marks a context that was NOT authenticated and only carries
30+
// admin type for backward compatibility (issue #1148).
31+
//
32+
// /mcp is deliberately unprotected by default (require_mcp_auth=false) so
33+
// MCP clients that cannot send an API key keep working, and the middleware
34+
// therefore hands an unauthenticated request an admin context. That is
35+
// fine for the operations those clients need — and it is NOT an identity,
36+
// so it must not satisfy a check that hands back raw credentials. See
37+
// CanRevealSecrets.
38+
Anonymous bool
2839
}
2940

3041
// contextKey is an unexported type used as context key to avoid collisions.
@@ -106,6 +117,40 @@ func AdminContext() *AuthContext {
106117
}
107118
}
108119

120+
// AnonymousContext returns the back-compat admin context for an
121+
// UNAUTHENTICATED MCP request (issue #1148).
122+
//
123+
// Type stays AuthTypeAdmin on purpose: every existing IsAdmin()-based
124+
// allowance — ordinary tool calls, retrieve_tools, server add/update/patch,
125+
// quarantine approvals — behaves exactly as it did, so no MCP client that
126+
// works today stops working. The only thing the Anonymous bit changes is
127+
// CanRevealSecrets.
128+
func AnonymousContext() *AuthContext {
129+
return &AuthContext{
130+
Type: AuthTypeAdmin,
131+
Anonymous: true,
132+
}
133+
}
134+
135+
// CanRevealSecrets reports whether this caller may be handed RAW credential
136+
// values (issue #1148) — today, `upstream_servers list` under the opt-in
137+
// `reveal_secret_headers` flag.
138+
//
139+
// It is deliberately stricter than IsAdmin and deliberately nil-safe:
140+
//
141+
// - an unauthenticated /mcp caller is admin for back-compat but has proved no
142+
// identity, so it gets masked values like everyone else;
143+
// - a nil context (the stdio transport before it installs one, an in-process
144+
// caller, a test) is unprivileged rather than admin-by-absence — the
145+
// opposite of the `authCtx != nil && !authCtx.IsAdmin()` shape, which lets
146+
// the ABSENCE of a token pass a gate that a scoped token fails.
147+
//
148+
// Authenticated admins — the API key, a tray/socket connection, stdio, an
149+
// OAuth admin user in the server edition — are unaffected.
150+
func (ac *AuthContext) CanRevealSecrets() bool {
151+
return ac != nil && ac.IsAdmin() && !ac.Anonymous
152+
}
153+
109154
// UserContext returns an AuthContext for a regular OAuth-authenticated user.
110155
func UserContext(userID, email, displayName, provider string) *AuthContext {
111156
return &AuthContext{

‎internal/auth/context_test.go‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,3 +310,37 @@ func TestUserContext_NoImplicitAccess(t *testing.T) {
310310
assert.False(t, ac.CanAccessServer("github"))
311311
assert.False(t, ac.HasPermission(PermRead))
312312
}
313+
314+
// TestAnonymousContext_CanRevealSecrets pins the distinction issue #1148 turns
315+
// on: an unauthenticated /mcp caller is still treated as admin for every
316+
// operation that worked before (that back-compat is deliberate), but it is NOT
317+
// an identity, so it cannot ask for raw secrets. A nil context — the stdio
318+
// transport before it installs one, an in-process caller, a test — must fail
319+
// the same way rather than inheriting admin by absence.
320+
func TestAnonymousContext_CanRevealSecrets(t *testing.T) {
321+
anon := AnonymousContext()
322+
if !anon.IsAdmin() {
323+
t.Fatal("AnonymousContext must stay admin so existing unauthenticated MCP operations keep working")
324+
}
325+
if anon.CanRevealSecrets() {
326+
t.Error("anonymous caller must not be allowed to reveal secrets")
327+
}
328+
329+
if !AdminContext().CanRevealSecrets() {
330+
t.Error("an authenticated admin must still be allowed to reveal secrets")
331+
}
332+
333+
var nilCtx *AuthContext
334+
if nilCtx.CanRevealSecrets() {
335+
t.Error("a nil auth context must not be treated as a secret-revealing admin")
336+
}
337+
338+
agent := &AuthContext{Type: AuthTypeAgent, AgentName: "bot", AllowedServers: []string{"*"}}
339+
if agent.CanRevealSecrets() {
340+
t.Error("agent tokens must not be allowed to reveal secrets")
341+
}
342+
343+
if !AdminUserContext("u1", "a@b.c", "A", "google").CanRevealSecrets() {
344+
t.Error("an OAuth-authenticated admin user must be allowed to reveal secrets")
345+
}
346+
}

‎internal/server/mcp.go‎

Lines changed: 81 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3258,12 +3258,17 @@ func (p *MCPProxyServer) handleAddServerFromRegistry(ctx context.Context, reques
32583258

32593259
// Slim, stable projection mirroring the REST AddedServerSummary so every
32603260
// surface reports the persisted server identically.
3261+
// Issue #1148: URL and Args are the two credential-bearing fields of this
3262+
// summary (a registry entry can carry `?token=…`, and a user-supplied arg
3263+
// vector routinely carries `--api-key …`). Source them from the redacted
3264+
// view so the echo cannot republish what the caller just configured.
3265+
registryView := redactedServerView(cfg, liveRedaction)
32613266
summary := contracts.AddedServerSummary{
32623267
Name: cfg.Name,
32633268
Protocol: cfg.Protocol,
32643269
Command: cfg.Command,
3265-
Args: cfg.Args,
3266-
URL: cfg.URL,
3270+
Args: redactedArgs(cfg.Args, liveRedaction),
3271+
URL: viewString(registryView, "url", cfg.URL),
32673272
Enabled: cfg.Enabled,
32683273
Quarantined: cfg.Quarantined,
32693274
}
@@ -3415,9 +3420,14 @@ func (p *MCPProxyServer) handleUpstreamServers(ctx context.Context, request mcp.
34153420
if responseText != "" {
34163421
errMsg = responseText
34173422
}
3418-
p.emitActivityInternalToolCall("upstream_servers", targetServer, "", "", sessionID, requestID, "error", errMsg, time.Since(startTime).Milliseconds(), args, nil, nil, "")
3423+
p.emitActivityInternalToolCall("upstream_servers", targetServer, "", "", sessionID, requestID, "error", scrubUpstreamText(errMsg), time.Since(startTime).Milliseconds(), args, nil, nil, "")
34193424
} else {
3420-
p.emitActivityInternalToolCall("upstream_servers", targetServer, "", "", sessionID, requestID, "success", "", time.Since(startTime).Milliseconds(), args, responseText, nil, "")
3425+
// Issue #1148: the activity store persists in BBolt, streams over SSE
3426+
// and is exported by `mcpproxy activity list`, so the response is
3427+
// re-rendered under the AUDIT policy (a fixed marker carrying neither
3428+
// the secret's length nor its trailing bytes). One net here covers
3429+
// every current and future operation of this built-in.
3430+
p.emitActivityInternalToolCall("upstream_servers", targetServer, "", "", sessionID, requestID, "success", "", time.Since(startTime).Milliseconds(), args, redactBuiltinResponseForActivity(responseText), nil, "")
34213431
}
34223432

34233433
return result, opErr
@@ -3528,9 +3538,10 @@ func (p *MCPProxyServer) handleQuarantineSecurity(ctx context.Context, request m
35283538
if responseText != "" {
35293539
errMsg = responseText
35303540
}
3531-
p.emitActivityInternalToolCall("quarantine_security", targetServer, "", "", sessionID, requestID, "error", errMsg, time.Since(startTime).Milliseconds(), args, nil, nil, "")
3541+
p.emitActivityInternalToolCall("quarantine_security", targetServer, "", "", sessionID, requestID, "error", scrubUpstreamText(errMsg), time.Since(startTime).Milliseconds(), args, nil, nil, "")
35323542
} else {
3533-
p.emitActivityInternalToolCall("quarantine_security", targetServer, "", "", sessionID, requestID, "success", "", time.Since(startTime).Milliseconds(), args, responseText, nil, "")
3543+
// Issue #1148: see the matching net in handleUpstreamServers.
3544+
p.emitActivityInternalToolCall("quarantine_security", targetServer, "", "", sessionID, requestID, "success", "", time.Since(startTime).Milliseconds(), args, redactBuiltinResponseForActivity(responseText), nil, "")
35343545
}
35353546

35363547
return result, opErr
@@ -3748,27 +3759,43 @@ func (p *MCPProxyServer) handleListUpstreams(ctx context.Context) (*mcp.CallTool
37483759

37493760
// Enhance server list with connection status and Docker isolation info
37503761
enhancedServers := make([]map[string]interface{}, len(servers))
3751-
revealHeaders := p.config != nil && p.config.RevealSecretHeaders
3762+
// Redact sensitive header values (Authorization, X-API-Key, Cookie, etc.),
3763+
// env-var secrets, URL query credentials and argv tokens before surfacing
3764+
// them through the MCP tool. An MCP agent inside a sandbox should never be
3765+
// able to read another upstream's Bearer token, API key, or URL-embedded
3766+
// secret via `upstream_servers list`.
3767+
//
3768+
// Issue #1148: `reveal_secret_headers` is an operator opt-in for a TRUSTED
3769+
// read surface, so it now additionally requires an AUTHENTICATED admin.
3770+
// /mcp is unprotected by default, so before this an anonymous caller on
3771+
// that endpoint got the raw values the flag was meant to hand the
3772+
// operator. CanRevealSecrets is nil-safe: an in-process/stdio caller with
3773+
// no context gets masked values rather than admin-by-absence.
3774+
revealHeaders := p.config != nil && p.config.RevealSecretHeaders &&
3775+
auth.AuthContextFromContext(ctx).CanRevealSecrets()
37523776
for i, server := range servers {
3753-
// Redact sensitive header values (Authorization, X-API-Key, Cookie,
3754-
// etc.), env-var secrets, and URL query credentials before surfacing
3755-
// them through the MCP tool. An MCP agent inside a sandbox should
3756-
// never be able to read another upstream's Bearer token, API key, or
3757-
// URL-embedded secret via `upstream_servers list`. Operators who
3758-
// genuinely need the raw values can set `reveal_secret_headers: true`.
3759-
headers := server.Headers
3760-
serverURL := server.URL
3761-
serverEnv := server.Env
3777+
// The secret-bearing fields are sourced from redactedServerView — the
3778+
// shared walker over the config's own JSON — rather than from a
3779+
// per-field redactor call, so this projection cannot drift from the
3780+
// one `list_quarantined` uses. viewField falls back to the raw value
3781+
// only for keys ServerConfig omits when empty, which keeps the
3782+
// response shape byte-identical to before.
3783+
view := redactedServerView(server, liveRedaction)
3784+
headers := interface{}(server.Headers)
3785+
serverURL := interface{}(server.URL)
3786+
serverEnv := interface{}(server.Env)
3787+
serverArgs := interface{}(server.Args)
37623788
if !revealHeaders {
3763-
headers = oauth.RedactStringHeaders(server.Headers)
3764-
serverEnv = oauth.RedactEnvValues(server.Env)
3765-
serverURL = oauth.RedactURLQueryParams(server.URL)
3789+
headers = viewField(view, "headers", server.Headers)
3790+
serverEnv = viewField(view, "env", server.Env)
3791+
serverURL = viewField(view, "url", server.URL)
3792+
serverArgs = redactedArgs(server.Args, liveRedaction)
37663793
}
37673794
serverMap := map[string]interface{}{
37683795
"name": server.Name,
37693796
"protocol": server.Protocol,
37703797
"command": server.Command,
3771-
"args": server.Args,
3798+
"args": serverArgs,
37723799
"url": serverURL,
37733800
"env": serverEnv,
37743801
"headers": headers,
@@ -3803,7 +3830,7 @@ func (p *MCPProxyServer) handleListUpstreams(ctx context.Context) (*mcp.CallTool
38033830
// all) is commonly echoed into the error; scrub it before it
38043831
// reaches connection_status.last_error and health.detail.
38053832
if !revealHeaders {
3806-
lastError = oauth.RedactSensitiveData(lastError)
3833+
lastError = scrubUpstreamText(lastError)
38073834
}
38083835
}
38093836
isConnected = connInfo.State.String() == "connected"
@@ -4218,7 +4245,16 @@ func (p *MCPProxyServer) handleListQuarantinedUpstreams(ctx context.Context) (*m
42184245
}
42194246

42204247
jsonResult, err := json.Marshal(map[string]interface{}{
4221-
"servers": servers,
4248+
// Issue #1148: this used to marshal the raw []*config.ServerConfig, so
4249+
// env values, header values, oauth.client_secret, URL query
4250+
// credentials and argv tokens all left through the MCP surface in the
4251+
// clear — to any caller, /mcp being unauthenticated by default — and
4252+
// were recorded verbatim into the activity store.
4253+
//
4254+
// The full (masked) config is still the right payload here: the point
4255+
// of inspecting a quarantined server is to see HOW it is configured,
4256+
// including WHICH secrets it carries. Only the values go.
4257+
"servers": redactedServerViews(servers, liveRedaction),
42224258
"total": len(servers),
42234259
// One line per server so "nobody ever scanned this" is visible right
42244260
// here, next to the decision it should inform.
@@ -5004,7 +5040,7 @@ func (p *MCPProxyServer) handleUpdateUpstream(ctx context.Context, request mcp.C
50045040
if err := p.upstreamManager.AddServer(serverID, mergedServer); err != nil {
50055041
p.logger.Warn("Failed to connect to updated upstream", zap.String("id", serverID), zap.Error(err))
50065042
connectionStatus = statusError
5007-
connectionMessage = fmt.Sprintf("Failed to update server config: %v", err)
5043+
connectionMessage = scrubUpstreamText(fmt.Sprintf("Failed to update server config: %v", err))
50085044
} else {
50095045
// Monitor connection status for 1 minute
50105046
connectionStatus, connectionMessage = p.monitorConnectionStatus(ctx, name, 1*time.Minute)
@@ -5214,7 +5250,12 @@ func (p *MCPProxyServer) buildPatchConfigFromRequest(request mcp.CallToolRequest
52145250
if err := json.Unmarshal([]byte(argsJSON), &args); err != nil {
52155251
return nil, opts, fmt.Errorf("invalid args_json format: %v", err)
52165252
}
5217-
patch.Args = args
5253+
// #1148: the read path masks credential-shaped argv tokens; restore
5254+
// any the caller echoed back masked, so the mask is never persisted
5255+
// over the real value (parity with the env/header/url unmaskers).
5256+
// args_json REPLACES the vector, so an unedited echo of a masked list
5257+
// would otherwise wipe the credential.
5258+
patch.Args = unmaskArgv(args, existingServer.Args)
52185259
}
52195260

52205261
// Handle env JSON string - maps are deep merged with RFC 7396 null-means-remove
@@ -5566,7 +5607,13 @@ func (p *MCPProxyServer) handleTailLog(_ context.Context, request mcp.CallToolRe
55665607
"server_name": name,
55675608
"lines_requested": lines,
55685609
"lines_returned": len(logLines),
5569-
"log_lines": logLines,
5610+
// Issue #1148 (c2): the per-server log is written by mcpproxy AND by
5611+
// the child process, and both put credentials in it — the connection
5612+
// logger records the upstream URL with its `?token=…`, and an MCP
5613+
// server is free to print its own API key. Scrub every line before it
5614+
// leaves through the tool response and is recorded into the activity
5615+
// store.
5616+
"log_lines": scrubUpstreamLines(logLines),
55705617
"server_status": map[string]interface{}{
55715618
"enabled": serverConfig.Enabled,
55725619
"quarantined": serverConfig.Quarantined,
@@ -5576,6 +5623,10 @@ func (p *MCPProxyServer) handleTailLog(_ context.Context, request mcp.CallToolRe
55765623
// Add connection status if available
55775624
if client, exists := p.upstreamManager.GetClient(name); exists {
55785625
connectionStatus := client.GetConnectionStatus()
5626+
// last_error commonly echoes the upstream URL, credentials included.
5627+
if lastError, ok := connectionStatus["last_error"].(string); ok {
5628+
connectionStatus["last_error"] = scrubUpstreamText(lastError)
5629+
}
55795630
result["connection_status"] = connectionStatus
55805631
}
55815632

@@ -5854,12 +5905,15 @@ func (p *MCPProxyServer) monitorConnectionStatus(ctx context.Context, serverName
58545905
case types.StateReady:
58555906
return "ready", "Server connected and ready"
58565907
case types.StateError:
5857-
return "error", fmt.Sprintf("Server connection failed: %v", connectionInfo.LastError)
5908+
// Issue #1148 (c3): scrubbed like the `last_error` this
5909+
// same string feeds in `upstream_servers list` — it lands
5910+
// in connection_message and in the activity record.
5911+
return "error", scrubUpstreamText(fmt.Sprintf("Server connection failed: %v", connectionInfo.LastError))
58585912
case types.StatePendingAuth:
58595913
// Parked awaiting user login (#1013): waiting out the monitor
58605914
// timeout would just stall the caller — nothing will change
58615915
// until a human signs in.
5862-
return statusError, fmt.Sprintf("Server connection failed: %v", connectionInfo.LastError)
5916+
return statusError, scrubUpstreamText(fmt.Sprintf("Server connection failed: %v", connectionInfo.LastError))
58635917
case types.StateDisconnected:
58645918
// If server is explicitly disconnected and enabled is false, return disabled
58655919
for _, serverConfig := range p.config.Servers {

0 commit comments

Comments
 (0)