Repository navigation
fix(security): gate the REST and SSE doors on caller identity and token scope - #1182
Merged
Merged
Conversation
…e REST enumeration (#1166, #1167) Two defects with one root cause: every REST/SSE/doctor read door re-derived "what may this caller see?" for itself, so the MCP surface and the REST surface drifted apart. #1167 — reveal_secret_headers was ANDed with caller identity only on the MCP door. Five other doors checked the flag alone, with the *http.Request in scope and its AuthContext never consulted. Reproduced live: a read-only agent token scoped to one server received all four credential classes in plaintext (Authorization header, URL query token, argv secret, env secret) on GET /api/v1/servers, GET /api/v1/config and the /events stream. #1166 — allowed_servers scoped tool discovery and execution but not enumeration, so the same token listed every configured server. One shared predicate, read by every door: auth.RevealSecretsAllowed(ctx, flag) — flag AND authenticated admin auth.CanEnumerateServer(ctx, name) — admin/absent = unrestricted auth.IsScopedCaller(ctx) Request-scoped doors thread the caller in (httpapi.revealSecrets / visibleServers / canSeeServer / filterUpstreamStatsServers). Context-free producers — the /events fan-out and both upstream_stats implementations — lose the opt-out entirely and mask unconditionally: a payload produced once for a mixed-privilege audience has no caller to gate against, so it is masked for the least-privileged member of that audience. SSE is rendered PER SUBSCRIBER into a fresh map and a fresh slice, never edited in place: publishEvent fans one payload pointer out to every subscriber, so an in-place filter would empty the admin Web UI's list (its merge treats each payload as authoritative) and be an unsynchronised map write concurrent with another connection's json.Marshal. A subscriber who may see raw values gets the notify-only shape instead and re-fetches through the gated REST door, so the two doors stay in parity. Also fixed, beyond the issue's site list: - GET /api/v1/config leaked every credential AND the global admin api_key to an agent token. It is an admin document, not a server list, so it is now 403 for agent tokens rather than filtered leaf by leaf. - management.Doctor applied its redaction to only two of the fields it builds from healthDetail; the health.ActionConfigure branch emitted the SAME string RAW into contracts.OAuthIssue.Error, serialized verbatim by both /api/v1/doctor and the MCP handleDoctor — and that leaked with the flag OFF. Both strings are now scrubbed once at the top of the per-server loop so no future branch can reintroduce a raw copy. - GET /api/v1/tools would have returned a strictly larger inventory than the /servers fix just denied. Also scoped: /api/v1/index/search, /diagnostics, /doctor, /profiles, /annotations/coverage, /security/scans, /status. - GET /api/v1/servers/{id}/diagnostics returns the same 404 for an unentitled server as for an absent one. Behaviour is unchanged for every admin path: API key, tray unix socket, CLI, and the middleware's no-AuthContext passthrough all short-circuit both predicates, pinned by TestGetServers_AdminContextsUnfiltered. Two existing tests asserted the behaviour deliberately removed from the context-free producers and are inverted with a comment naming #1167.
#1166) The servers.changed embed was one event type of twenty-odd. Live, with an admin and a token scoped to `alpha` subscribed to the same stream, disabling `beta` delivered this to the SCOPED subscriber: data: {"payload":{"action":"server_disabled","affected_entity":"beta", "changed_fields":["enabled"],"new_values":{"enabled":false}, "previous_values":{"enabled":true},"source":"api"},...} Same disclosure #1166 is about — the name, the state and the mutation history of a server outside the caller's scope — through a different event type than renderEventPayloadForCaller was written to handle. The class, enumerated from every publishEvent call site in internal/runtime: server_name activity.tool_call.{started,completed,rejected}, activity.policy_decision, activity.quarantine_change, activity.tool_quarantine_change, activity.prompt_get.completed, oauth.token_refreshed, oauth.refresh_failed, security.scan_settled, security.integrity_alert server the servers.changed coalescer extras (enable_toggle, quarantine_toggle, restart, server_disconnected, …) target_server activity.internal_tool_call.completed affected_entity activity.config_change Scoped on payload KEY rather than on a per-type table, so a new producer using the shape every existing producer uses is covered on the day it lands. DROP, not redact, for everything except servers.changed. A frame with the name blanked still carries the mutation, its shape and its timing, and is still an exact count oracle for how many servers are being hidden. Nothing first-party depends on receiving every frame: the Web UI's authoritative mergeServers keys off servers.changed and authenticates as admin, and the tray reads the stream over the unix socket, which is admin by OS-level auth. servers.changed is the one type never dropped. It is COALESCED last-write-wins, so a window in which both alpha and beta changed publishes one event whose marker may name beta; dropping on that name would strand the scoped subscriber's view of alpha until an unrelated change fired. It is rendered instead — and the coalescer extra that names an out-of-scope server is now removed, which the embed-only filter missed. On the notify-only path (ListServers failed upstream) that extra WAS the entire payload, and the old "nothing to scope" early return handed it over verbatim. Also dropped for a scoped caller: config.reloaded, config.saved and secrets.changed. They carry no server identity but announce mutations of the admin config document — the document this change already made a 403 for agent tokens. A live notification stream about it must not be the way back in. The shared-payload invariant is unchanged and now tested harder: the decision is made per subscriber before rendering, and the render still builds a fresh map. TestSSE_ServersChangedRenderedPerSubscriber is extended rather than duplicated — two concurrent subscribers, one Event value fanned out by pointer, and the admin's frames plus the bus's own map asserted intact after the burst. Verified live on a scratch instance: pre-fix binary reproduces the frame above on the scoped subscriber; with the fix the scoped stream contains zero occurrences of "beta" while the admin still receives the config_change and a servers.changed carrying both servers and "server":"beta".
…und 9) Seven cross-review findings on the #1166/#1167 branch. All of them are the same shape as the original defect: a read door that never asked who was calling. G1 — the whole /api/v1/servers/{id} read subtree except /diagnostics had no scope gate. A token scoped to `alpha` could name `beta` directly and read its tool list, its scan report, its scanned file tree, its per-server tool-call history and its raw stdout/stderr. The logs one is the sharpest: upstream stderr routinely echoes the argv and env the process was launched with, so it is a credential disclosure that walks straight around the #1158 log-redaction work — nothing redacts a log tail. The gate is now a chi middleware on the subtree (scopedServerSubtree), beside decodeServerIDParam and for the same reason: this subtree keeps growing sub-resources and every one of them answered for itself. New ones inherit it. The previous round deferred this because these handlers answer 200 for a server that does not exist, so status parity with an absent server was not reachable. That is a reason to fix the existence check, not to leave the hole: the gate supplies it, and for a scoped caller "not yours" and "not there" are now one 404 with one body. Admins are untouched, 200-on-absent quirk included. G2 — the activity / tool-call / session doors had no gate at all, and they hand over tool-call ARGUMENTS and RESPONSES, not just server names. The entitlement is pushed into the query rather than applied to its result: - storage.ActivityFilter.AllowedServers rides in the one Matches() pass that ListActivities and StreamActivities both run, so /activity, /activity/summary and /activity/export narrow with a coherent `total`. - storage.ToolCallScope threads into runtime.GetToolCalls (before pagination) and storage.GetToolCallsBySession (inside the counting pass). A post-filter would shrink the page while `total` kept counting the removed records — a broken pager, and its own count oracle. /activity/{id} and /tool-calls/{id} take the absent record's 404; so does /tool-calls/{id}/replay, which dispatches a real call and had no gate either. A caller-supplied ?server= narrows within the entitlement and cannot escape it: the authorization term is evaluated first, in the same predicate. /activity/usage filters its per-tool rows and drops the two aggregates that cannot be re-derived per server (the tokens-saved headline, the global timeline). Its response cache is keyed by the caller's scope — without that the first caller of a query seeds the entry every other tenant reads for the TTL. /sessions and /sessions/{id} are DENIED (403) instead: an MCPSession describes a client and the user's workspace and carries no server attribution to project. G3 — GET /api/v1/stats/tokens is denied to non-admins for the same reason: PerServerToolListSizes is keyed by every configured server (a complete inventory enumeration) and the scalars beside it are fleet-wide, so a projected map would leave a cross-tenant oracle in numbers that merely looked filtered. This is the position recomputeServerStats already takes on the same struct — it DROPS TokenMetrics from GET /api/v1/servers rather than report it wrongly. G4 — `quarantined_servers` was always 0 for a scoped caller: both consumers recompute it from a per-entry `quarantined` key that NEITHER upstream_stats producer emitted, so a security surface read clean while one of the caller's own servers sat quarantined. Both producers now emit it, which also closes the same latent hole in contracts.ConvertUpstreamStatsToServerStats. The StateView producer's entry-building is split into upstreamStatsFromSnapshot so the shape is testable without standing up a supervisor. G5 — the three notions of "scope" are now written down in one place (scope_subtree.go) and the handleAgentTokenAuth comment that read as if the preflight intersection were the enumeration boundary is corrected. Token scope alone is the boundary; profile is an ergonomic filter and is caller-selectable, so folding it in would let a caller change what it is authorized to see. G6 — requireAdminRead keyed on Type == AuthTypeAgent while IsScopedCaller and revealSecrets key on !IsAdmin(). Identical today, but a server-edition AuthTypeUser context would have passed it and read GET /api/v1/config. One mux, one definition of "not admin". G7 — status.message carried "Connected to 1/2 servers, retrying..." verbatim on the exact route where total_servers was recomputed to stop being a count oracle. Blanked for a scoped caller; `phase` survives. Two reviewer findings were verified as false positives and deliberately not acted on: total_tools on the Manager fallback (the fallback enriches tool_count before the map reaches the filter) and revealSecrets returning false without an AuthContext (the documented fail-closed design; no admin path regresses).
…#1166 round 10) GET /api/v1/info was registered ungated and built web_ui_url with cfg.APIKey appended verbatim, so a read-only agent token scoped to one server received "web_ui_url":"http://127.0.0.1:18733/ui/?apikey=devkey-abc123" and could re-authenticate as an admin. Reproduced live on a scratch instance: the scoped token got 403 on /api/v1/config, then 200 on the same route using the key it had just read out of /info. That made every scope control on this branch decorative. The defect predates the branch; it does not survive it. The route stays readable and the field stays present — /info is version, endpoint, pid and update-policy metadata that agents and the CLI poll, and the base URL discloses nothing listen_addr does not. Only the credential is withheld, gated on auth.CanRevealSecrets: the same predicate the other raw-credential doors use, which fails closed on an absent AuthContext and refuses the unauthenticated /mcp back-compat admin context. The tray (socket), the Web UI and the CLI all carry an explicit admin context and are unaffected. Also in this round: - SSE: an identity-bearing frame that names NO server reached a scoped subscriber, because the filter dropped only on a non-empty name. EmitActivityInternalToolCall omits target_server for every built-in call not routed to one upstream (retrieve_tools, describe_tool, upstream_servers) and those frames carry arguments and response. Visibility is now decided by event TYPE and fails closed when the identity is missing. - /security/scanners and /security/scanners/{id}/status serialized ConfiguredEnv, i.e. the operator's vendor API keys, in the clear while the field's own comment claimed they were redacted. Redacted at the type via ScannerPlugin.RedactedForAPI; ${keyring:} references are preserved because they are pointers, not secrets, and the save path now skips the sentinel so a round-trip cannot overwrite a real key. - Four more ungated fleet-wide doors now 403 for a non-admin caller: /security/queue, /security/overview, /telemetry/payload and /onboarding/state (plus the mark POST, which echoes the same document). Each is an inventory enumeration or a scalar computed over the whole fleet with no per-server projection — the /config and /stats/tokens answer. - /security/scans/{jobId}/report is SCOPED rather than denied: it is a per-server document reached by job id, so it walked around the /servers/{id} subtree gate. An unentitled server now gets the same 404 as an unknown job. - /secrets/refs and /secrets/config 403 for a non-admin caller: values are masked, but they enumerate the secrets of servers the caller cannot see, and are a narrower view of the document /config denies. - The /activity/usage cache key was not injective (bare comma and pipe separators, and config validation rejects only a colon in a server name), so a server named `a,b` collided with the scope ["a","b"] and one tenant's cached response could be served to another. Now length-prefixed. - /activity/usage contradicted itself for a scoped caller: the early return skipped the loop that also accumulates total_calls/total_errors, so the headline read 0 beside rows summing to more. It is now summed over the rows the same response carries. - scopedServerSubtree answered 404 on ANY inventory-read error, telling an entitled caller its own server had been deleted. "Could not determine" is now 503; entitlement is still decided first, so the 503 can never become an existence oracle. - Restored the doc comment an insertion had orphaned above ActivityFilter.serverAllowed. Every fix carries a test proven to fail against a permissively neutered guard.
…ite doors (#1166 round 11) Three findings from the final cross-model review of the #1166/#1167 branch. M1 — GET /api/v1/status served telemetry.ActivationState to any agent token: mcp_clients_seen_ever is the operator's entire MCP-client inventory and retrieve_tools_calls_24h is an exact deployment-wide counter — the same operator plane this branch already 403s /sessions and /onboarding/state for, and the same count-oracle shape it removed from total_servers on this very route. The block is now OMITTED for a scoped caller rather than the route denied: /status is a liveness surface agents legitimately poll, and the key is already absent whenever telemetry is unwired, so every consumer tolerates it. M2 — PUT /api/v1/profiles/active had no admin check. A read-only agent token could change the server-level active profile and thereby change what the Web UI and the tray display. Gated by the same config_write policy as the other config-level writes. M3 — the scanner-env redaction had no write guard. The read doors mask every literal env value to "***", so a client that read GET /security/scanners and posted the document back stored the sentinel over a real vendor key. The frontend was taught to skip it, but the server must not depend on a cooperating client. Sentinel-valued entries are dropped server-side; ConfigureScanner merges, so an omitted key keeps its stored value. Docs: agent-tokens.md now lists the denials this branch added (/security/overview, /security/queue, /telemetry/payload, /onboarding/state, /onboarding/mark, /secrets/refs, /secrets/config) plus the two above. Every fix is pinned by a test proven to fail without it, driving the production chi route table with a real mcp_agt_ token and paired with an admin control on the same router.
Deploying mcpproxy-docs with
|
| Latest commit: |
79e05d5
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://a2251280.mcpproxy-docs.pages.dev |
| Branch Preview URL: | https://claude-sec-1166-1167-rest-ss.mcpproxy-docs.pages.dev |
…scan exemption The #1148 round-8 doorscan guard fired on this branch: #1166 extracted the StateView upstream_stats body out of (m).GetUpstreamStats into the package-level upstreamStatsFromSnapshot so the entry shape is testable without a Supervisor. The oauth.RedactUpstreamStats call moved with the body, so the door is still redacted at its single return - only the exemption key was stale, which the guard correctly reported as both a new unexempted door and an exemption for code that no longer exists.
Contributor
📦 Build ArtifactsWorkflow Run: View Run Available Artifacts
How to DownloadOption 1: GitHub Web UI (easiest)
Option 2: GitHub CLI gh run download 33619001532 --repo smart-mcp-proxy/mcpproxy-go
|
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
This was referenced Sep 2, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1166, #1167, #1180.
Three defects on the REST and SSE doors, all reproduced on a live instance before and after.
#1180 — privilege escalation (found while verifying the other two)
GET /api/v1/inforeturned the global admin API key to any authenticated caller, including a read-only agent token scoped to one server:That token could then authenticate as admin.
allowed_serverswas therefore not a security boundary in any shipped version — a scoped caller never had to defeat the scope checks, it just read the key. Pre-existing on main.The key is now withheld from any caller failing
CanRevealSecrets. The route and the field stay:/infois version/endpoint/pid metadata that agents and the CLI legitimately poll, and the base URL discloses nothinglisten_addrdoes not.#1167 —
reveal_secret_headerswas not ANDed with caller identityThe MCP door required
flag && CanRevealSecrets(). The REST, SSE, doctor and diagnostics doors checked the flag alone, so a read-only scoped token received all four secret classes —Authorizationheader, URL query token, argv secret, env secret — on/servers,/configand the/eventsstream./configwas not in the issue's site list and also leaked, along with the globalapi_key.Context-free producers (the SSE fan-out, both
upstream_statsproducers) now mask unconditionally, since a payload with no caller cannot be gated. ScannerConfiguredEnvis redacted at the type, making its own "secrets redacted in API" comment true for the first time.#1166 — REST enumeration ignored
allowed_serversThe MCP door filtered on
CanAccessServer; REST did not. Closing it properly took three passes, because hand-enumerating a route table does not converge — the final pass found the whole/servers/{id}/*read subtree (including stdout/stderr logs, which routinely echo launch argv and env) and the entire activity/tool-call family, which serves tool-call arguments and responses. Those leaked strictly more than the enumeration the issue described.The subtree is now gated by a chi middleware so new sub-resources inherit it, with a combined scope-and-existence check making unentitled and absent one identical 404. Entitlement is pushed into the storage queries (
ActivityFilter.AllowedServers,storage.ToolCallScope) so a page and its total always describe the same set — a post-filter that shrinks the page while the total counts hidden records is its own oracle. Documents with no per-server projection are denied outright.A follow-up for the durable fix is filed as #1178: a route-table guard test, so a new
GETcannot ship unscoped.Verified live on this commit
Across 16 routes, a read-only token scoped to
alphasees zero references tobetaand the admin key appears nowhere; an admin sees everything unchanged;/servers/{id}/*returns 200 foralphaand an identical 404 for bothbetaand a nonexistent name.Review
Two
opencode(gpt-5.6-sol) rounds, both returning BLOCKING; 19 genuine findings closed, 4 false positives re-derived and rejected with evidence. 33 tests, with non-biting regression guards labelled as such rather than presented as proof.