Metadata-Version: 2.4
Name: onewolf-mcp-guard-http
Version: 0.15.0
Summary: OneWolf AI Security - MCP HTTP/SSE reverse proxy (enforced security for remote MCP servers)
Author: OneWolf Team
License: MIT
Project-URL: Homepage, https://github.com/onewolf-ai/onewolf-guard
Project-URL: Repository, https://github.com/onewolf-ai/onewolf-guard
Project-URL: Issues, https://github.com/onewolf-ai/onewolf-guard/issues
Keywords: ai-security,mcp,model-context-protocol,http,sse,reverse-proxy
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: httpx>=0.25.0
Requires-Dist: starlette>=0.40.0
Requires-Dist: uvicorn>=0.30.0
Requires-Dist: onewolf-mcp-guard>=0.15.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: httpx>=0.25.0; extra == "dev"
Requires-Dist: respx>=0.21; extra == "dev"
Requires-Dist: cryptography>=42; extra == "dev"

# OneWolf MCP Guard HTTP

HTTP/SSE reverse proxy for **remote MCP servers**. Sits between an MCP client (Cursor remote, Continue, etc.) and a real MCP server that speaks Streamable HTTP, intercepting `tools/call` traffic and running OneWolf security checks automatically.

This is the HTTP sibling of [`onewolf-mcp-guard`](https://pypi.org/project/onewolf-mcp-guard/) (which proxies stdio). The intercept logic is reused: same `SecurityInterceptor`, same circuit breaker, same allowlist semantics.

## Scope

| Sub-PR | Status | Scope |
|---|---|---|
| **B1.1** | merged | POST `/messages` with JSON responses + auth bearer + intercept tools/call |
| **B1.2** | merged | SSE upstream streaming (multi-event) — filter the final response, preserve notifications, re-emit SSE to client |
| **B1.3** | **this PR** | Rate limit per tenant (token bucket), structured audit log with file sink, optional mTLS |

The proxy now accepts both response shapes from the upstream MCP server: `application/json` (single envelope) and `text/event-stream` (one or many SSE events). For SSE responses the proxy parses every event and first validates the SHAPE of the whole stream (card #5426): exactly one `result`/`error` answering the request `id`; a duplicate response, a response for another `id` or without `id`, or an event that is not an inspectable JSON-RPC message (non-JSON, array, `result` + `error`) refuses the whole stream with JSON-RPC `-32099` in both modes. An empty-data priming event is accepted. The body is read with a byte cap and an event cap. Then it filters the response, gives server notifications in the stream one aggregated verdict (label `mcp:sse_events`), and re-emits the stream.

## What it does

```
MCP client → POST /messages → onewolf-mcp-guard-http → upstream MCP server
                                       ↕
                              OneWolf API (analyze + filter-output)
```

For every `tools/call`:
1. **Before forwarding:** sends tool name + arguments to OneWolf `/api/v1/analyze`. If prompt injection / exfiltration is detected, returns a JSON-RPC `-32600` error to the client.
2. **After response:** sends the response text to OneWolf `/api/v1/extension/filter-output`. If PII / credentials / secrets are detected, the response is sanitized before reaching the client.

For every `tools/list` response (anti tool-poisoning):
- Each advertised tool (name + description + inputSchema) is analyzed via OneWolf `/api/v1/analyze`. In **enforce** mode a tool with a poisoned description is **removed from the listing** before it reaches the client — on BOTH the JSON and the SSE (`text/event-stream`) transports; in **monitor** mode the full listing passes through and the tool is only logged (`tools_list_would_remove`). Verdicts are cached per listing (SHA-256).

Everything else (initialize, notifications) is forwarded; its SSE response goes through the same stream-shape validation, the sampling/elicitation gate and the notification filter.

## Installation

```bash
pip install onewolf-mcp-guard-http
```

Or, from a checkout of this repository, for development:

```bash
pip install -e ".[dev]"
```

Python 3.10+ required.

## Configuration

| Variable | Required | Default | Description |
|---|---|---|---|
| `ONEWOLF_API_KEY` | yes | — | OneWolf API key (for analyze + filter-output) |
| `ONEWOLF_URL` | no | `http://localhost:8001` | OneWolf backend URL |
| `ONEWOLF_GUARD_HTTP_UPSTREAM_URL` | yes | — | The real MCP server URL (the one we're protecting). `https://` for any remote host; `http://` only for `localhost`, `127.0.0.1` or `[::1]` (card #6191). `user:pass@` in the URL is refused |
| `ONEWOLF_GUARD_HTTP_UPSTREAM_PIN` | no | — | Up to 2 SHA-256 pins of the upstream certificate public key (SPKI), comma separated (current + next). 64 hex (with or without `:`) or `sha256//<base64>`. Requires `https://`. A pin set in the Console (Registro MCP) wins over this one. See "Upstream certificate pin" |
| `ONEWOLF_GUARD_HTTP_API_KEY` | yes | — | Bearer token clients must present to reach this proxy |
| `ONEWOLF_GUARD_HTTP_UPSTREAM_API_KEY` | no | — | Optional bearer token to send to the upstream MCP server |
| `ONEWOLF_GUARD_HTTP_HOST` | no | `127.0.0.1` | Bind host |
| `ONEWOLF_GUARD_HTTP_PORT` | no | `8765` | Bind port |
| `ONEWOLF_GUARD_HTTP_UPSTREAM_TIMEOUT` | no | `60` | Upstream timeout PER httpx operation (connect / each read / write), in seconds. A server that drips bytes slower than this never trips it; see `UPSTREAM_DEADLINE` |
| `ONEWOLF_GUARD_HTTP_UPSTREAM_DEADLINE` | no | `300` | TOTAL wall-clock deadline of one upstream exchange (open + headers + whole body), in seconds. Above it the connection is closed, whatever was read is discarded (nothing partial reaches the client) and the call is refused with `-32099` (`mcp_sse_limit_exceeded`, `limit=upstream_deadline_exceeded`), in both modes. When smaller than `UPSTREAM_TIMEOUT`, the deadline wins. Every exchange logs one `upstream_response` line (`method`, `status`, `elapsed_ms`, `error`, never the body) to calibrate it. Invalid, `<= 0`, `nan` or `inf` falls back to the default with a warning (same rule as `UPSTREAM_TIMEOUT`) |
| `ONEWOLF_GUARD_HTTP_UPSTREAM_MAX_BYTES` | no | `MAX_BLOB_BYTES * 4 // 3 + 4 + 1 MiB` (~67.7 MiB) | Hard cap on the upstream body (JSON or SSE), read in streaming; above it the read stops and the call is refused with `-32099` (`mcp_sse_limit_exceeded`). Derived from the Document Shield blob limit so a document the Shield accepts is not refused. Invalid or `<= 0` falls back to the default with a warning |
| `ONEWOLF_GUARD_HTTP_SSE_MAX_EVENTS` | no | `1000` | Max events in one upstream SSE response; above it `-32099` (`mcp_sse_limit_exceeded`). Invalid or `<= 0` falls back to the default with a warning |
| `ONEWOLF_GUARD_MODE` | no | `enforce` | `enforce` (block on threat) or `monitor` (log only) |
| `ONEWOLF_MCP_SERVER_NAME` | no | — | Registry identity of the wrapped server. When set (or `ONEWOLF_MCP_SERVER_ID`), every `tools/call` consults `POST /api/v1/mcp/check` before analysis and a server the org marked untrusted is denied. Both unset = no registry traffic. |
| `ONEWOLF_MCP_SERVER_ID` | no | — | Same as above, by id. |

The org **tool policy** (`POST /api/v1/tool-policies/check`) is consulted on every
`tools/call`, with no opt-out and no caching — a policy edited in the panel takes
effect on the next call. It is **fail-closed**: a check that produces no verdict
(timeout, 5xx, 401/403, body without `allowed`) denies in `enforce` mode and only
logs in `monitor`.

**B1.3 — rate limit / audit / mTLS:**

| Variable | Default | Description |
|---|---|---|
| `ONEWOLF_GUARD_HTTP_RATE_LIMIT_RPM` | `60` | Sustained requests per minute per tenant (token bucket refill rate) |
| `ONEWOLF_GUARD_HTTP_RATE_LIMIT_BURST` | `10` | Burst size — max tokens in bucket before throttling kicks in |
| `ONEWOLF_GUARD_HTTP_AUDIT_FILE` | — | Optional JSONL path; every decision is appended here AND to stderr |
| `ONEWOLF_GUARD_HTTP_SSL_CERT` | — | Path to TLS certificate (PEM). Pair with `SSL_KEY` to enable HTTPS |
| `ONEWOLF_GUARD_HTTP_SSL_KEY` | — | Path to TLS private key (PEM) |
| `ONEWOLF_GUARD_HTTP_SSL_CA` | — | CA bundle for mTLS — when set, clients must present a cert signed by it |
| `ONEWOLF_GUARD_HTTP_TRUST_FORWARDED_FOR` | `false` | Honor `X-Forwarded-For` for audit client-IP. **Set only when behind a trusted reverse proxy that strips incoming XFF.** Default uses the kernel socket peer (unforgeable). |

All A2 hardening env vars from `onewolf-mcp-guard` (breaker threshold, granular timeouts, etc.) apply here too because the underlying `SecurityInterceptor` is the same.

## Rate limit (B1.3)

Token-bucket per tenant. A **tenant** is identified by `sha256(bearer_token)[:16]` — never the raw secret. Buckets are per-process (in-memory dict); multi-instance deployments would need a Redis-backed limiter (not in B1.3 scope).

When the bucket is empty, the proxy returns **HTTP 429** with a `Retry-After` header (rounded up to the next whole second) and emits a `rate_limit_exceeded` audit event with the tenant id. Health checks bypass the limit.

## Audit log (B1.3)

Every request decision is emitted as a structured JSON event to **stderr** (always) and optionally to a **file** via `ONEWOLF_GUARD_HTTP_AUDIT_FILE`. Events carry tenant id, client IP, user agent (capped at 200 chars), tool name, decision and timing.

**Client IP — anti-spoofing**: by default the audit `ip` field is the kernel-attested TCP socket peer (unforgeable). `X-Forwarded-For` is **ignored** unless you set `ONEWOLF_GUARD_HTTP_TRUST_FORWARDED_FOR=true`, which you should only do when the proxy sits behind a trusted reverse proxy (nginx/Envoy/CloudFront) that strips incoming `X-Forwarded-For` from clients before adding the real peer IP. Otherwise any caller can put whatever IP they want in the audit log, breaking forensic correlation.

Enrichment is applied to **both** middleware-level events (`rate_limit_exceeded`) and request-handler events (`request_allowed`, `request_blocked`, `request_would_block`, `response_modified`, `response_blocked`, `response_allowed`, `upstream_error`, `body_parse_error`, `request_invalid_params`, `response_filter_error_forwarded`, `registry_feature_disabled`,
`tool_policy_would_block`, `request_would_redact`, `request_redacted`,
`response_redact_no_text`). An input mask that cannot be applied (no `masked_text`, invalid JSON, or JSON that is not an object) is refused and audited as `request_blocked` with `reason=redact_unmaskable` and `detail` = `no_text` | `parse_error` | `not_a_dict` | `no_params`; the original arguments are never forwarded. A `tools/call` whose `params.arguments` is present but is not a JSON object (string, list, number or bool) is refused in `enforce` with JSON-RPC `-32602` and the generic message `Invalid params: arguments must be an object` (notification: 204), before the registry, tool policy or `/analyze`, and audited as `request_invalid_params` with `reason=arguments_not_object` and `arguments_type` (the Python type name, never the value); in `monitor` it is forwarded as before and audited as `request_would_block` with the same fields. Absent or `null` `arguments` count as `{}` and are not refused (card #4348). Only the pre-auth events (`auth_missing`, `auth_invalid`) lack `tenant_id` — by design, there is no authenticated tenant yet at that point.

Sensitive bytes — the raw bearer token, the OneWolf API key, and request/response PII — **never** appear in audit. Use `tenant_id` (hash) and `ip` for forensic pivots.

## TLS / mTLS (B1.3)

Set `SSL_CERT` + `SSL_KEY` to boot the proxy on HTTPS via uvicorn's built-in TLS. Set `SSL_CA` additionally to require client certificates signed by that CA (mutual TLS).

```bash
export ONEWOLF_GUARD_HTTP_SSL_CERT=/etc/tls/proxy.crt
export ONEWOLF_GUARD_HTTP_SSL_KEY=/etc/tls/proxy.key
export ONEWOLF_GUARD_HTTP_SSL_CA=/etc/tls/clients-ca.crt   # mTLS
onewolf-mcp-guard-http
```

When TLS is on, the startup log line reads `listening on https://...` with `+mTLS` when client cert verification is enabled.

## Upstream certificate pin (card #6191)

The guard checks, in the TLS handshake of EVERY outgoing connection, the
SHA-256 of the upstream leaf certificate public key (`subjectPublicKeyInfo`).
A key outside the list closes the connection before any request byte is sent
and the client gets JSON-RPC `-32099` with
`data.reason = "MCP_UPSTREAM_CERT_MISMATCH"`, in both `enforce` and `monitor`.
CA and hostname verification stay on: the pin adds to them, never replaces them.

Get the pin:

```bash
openssl s_client -connect HOST:443 -servername HOST </dev/null   | openssl x509 -pubkey -noout | openssl pkey -pubin -outform der   | openssl dgst -sha256
```

- Source: the pin set in the Console (Registro MCP > Editar servidor), delivered by
  `/mcp/check` when `ONEWOLF_MCP_SERVER_NAME`/`ID` is set, wins; without it,
  `ONEWOLF_GUARD_HTTP_UPSTREAM_PIN`. Register the NEXT key before rotating it.
- Backend pin configured, backend down at boot and no env pin: `enforce` does not
  talk to the upstream until the backend answers (`MCP_UPSTREAM_PIN_UNAVAILABLE`);
  `monitor` goes on with CA only and logs `upstream_pin_unverified`.
- `ONEWOLF_URL` over plain `http://` to a remote host: the backend pin is ignored
  (`backend_pins_ignored_plaintext`); only the env pin applies.
- CA: `SSL_CERT_FILE` / `SSL_CERT_DIR` when set (corporate CA, TLS inspection),
  otherwise the `certifi` bundle, as httpx does by default.
- `HTTPS_PROXY` (CONNECT) works: the pin is checked against the server inside the
  tunnel, never against the proxy. A proxy that terminates TLS is a mismatch.
- Every refusal is recorded in Guard Logs (`POST /api/v1/mcp/local-block`).
- Boot logs `guard_http_started` with `upstream_host` and `upstream_tls` = `pinned_backend` | `pinned_env` | `pending_backend` | `ca_only` | `plaintext_local`; `ca_only` also logs `upstream_tls_unpinned`.

## Upgrade

0.14.0 (card #6191) can refuse to boot a config that worked before: remote
`http://` upstream, or credentials in the upstream URL. See
[`sdk/MIGRATION.md`](../../MIGRATION.md).

## Run

```bash
export ONEWOLF_API_KEY=cd_xxx
export ONEWOLF_GUARD_HTTP_UPSTREAM_URL=https://real-mcp-server.example.com
export ONEWOLF_GUARD_HTTP_UPSTREAM_PIN=<sha256 of the server public key>
export ONEWOLF_GUARD_HTTP_API_KEY=$(openssl rand -hex 32)
onewolf-mcp-guard-http
# [guard-http] listening on http://127.0.0.1:8765 → upstream https://real-mcp-server.example.com (mode=enforce)
```

The proxy logs structured JSON events to stderr — same vocabulary as the stdio guard (`request_allowed`, `request_blocked`, `response_modified`, `tool_policy_would_block`, `registry_feature_disabled`, `request_redacted`, `response_redact_no_text`, etc.) plus HTTP-specific events (`auth_missing`, `auth_invalid`, `upstream_error`, `guard_http_started`).

## Client config (Cursor remote MCP example)

Point your MCP client at the proxy URL and include the proxy API key:

```json
{
  "mcpServers": {
    "production-mcp-guarded": {
      "url": "http://localhost:8765/messages",
      "headers": {
        "Authorization": "Bearer <ONEWOLF_GUARD_HTTP_API_KEY>"
      }
    }
  }
}
```

## Health check

```bash
curl http://localhost:8765/health
# {"status":"ok","service":"onewolf-mcp-guard-http"}
```

Unauthenticated by design so deploys / load balancers can probe it.

## Modes

**enforce** (default):
- Blocks malicious requests with JSON-RPC `-32600`
- Fail-closed when OneWolf API is unreachable
- Fail-closed when upstream MCP server is unreachable (JSON-RPC `-32099`)

**monitor**: logs every decision but never blocks. The OneWolf analyze step still runs, but block decisions only generate `request_would_block` events — the request is forwarded anyway. Exceptions: a secret in a response blocks in both modes (#1371), and upstream stream/format violations (-32099: duplicate/foreign/unparseable SSE result, stream without response, byte/event cap, SSE resume) are refused in both modes. A `tools/call` response that cannot be masked leaf by leaf (`leaf_rewrite_unsafe`, #5424) is also refused in both modes (JSON-RPC `-32600`).

## Limits (inherited from stdio guard)

- Payloads (after JSON serialization of arguments, or response text) > 100,000 chars are refused to prevent silent truncation bypass.
- Request body limit is also bounded by Starlette's default body cap.

## Testing

```bash
pytest tests/
```

**99 unit tests** covering: config validation (incl. B1.3 SSL/mTLS + rate-limit env vars), upstream client (JSON, SSE single + multi-event parsing, id-match finder, serialize roundtrip, parser edge cases, auth, errors), server (auth, intercept block/allow/redact paths, invalid params, monitor mode, multi-block + structuredContent PII bypass coverage, SSE response path: multi-event filter + re-emit + filter-error fail-closed + no-text passthrough), **B1.3 — rate limit token bucket + tenant isolation + tenant_id derivation + audit log (file sink + stderr) + CORS expose-headers regression + handler-event tenant enrichment**.

### Manual E2E (validated)

Tested against the official [MCP Inspector](https://github.com/modelcontextprotocol/inspector) in Direct mode (browser → proxy → FastMCP upstream):

- `echo("ping inspector b13")` → upstream response returned unchanged.
- `get_pii_dump()` → CPF/RG/credit-card redacted by `/api/v1/extension/filter-output` and `structuredContent` masked leaf by leaf (bypass-proof).
- Audit log captured both calls with `tenant_id` (16-hex sha256), `ip`, `user_agent`, `tool_name`, `threat_score`, `time_ms`. The raw bearer token was never logged.
- Curl-driven load (30 parallel) → 19 allowed, 11 returned 429 with `Retry-After`, each `rate_limit_exceeded` event carrying the tenant id.

## Known limitations (B1.2)

1. ~~Filter runs only on the final response event.~~ Revoked by card #5426: server notifications in the stream get one aggregated verdict per stream (`mcp:sse_events`). A block refuses in both modes; a redact in `enforce` drops the analyzed notifications (`mcp_sse_event_dropped`) or, if one is a server request (has `id`), refuses the response (`redact_not_representable`); `monitor` only audits (`mcp_sse_event_would_drop`).
2. **SSE resume is refused** (card #5426): a POST carrying `Last-Event-ID` gets `-32099` (`mcp_sse_resume_refused`) and the upstream is not called; a notification/response with it gets 204; GET `/messages` is 405. The header is never forwarded upstream nor exposed back. A stream that ends before the response gets `-32099` (`mcp_sse_no_response`). Client must restart the request on disconnect.
3. **No rate limit** — any authenticated client can flood the proxy. B1.3 adds rate limiting.

## Security note — `structuredContent` redaction

MCP 2025-03-26 added an optional `structuredContent` field on tools/call results — arbitrary JSON that can carry the same data as `content[]` (often in raw form). Both this HTTP guard and the stdio guard now:

1. Concatenate the JSON serialization of `structuredContent` into the text analyzed by `/api/v1/extension/filter-output`, so PII in the structured payload reaches the detector.
2. On redaction, **rewrite leaf by leaf** (card #5424, shared `guard_core.rewrite_leaves`): each `content[i].text` and each string inside `structuredContent` receives its own mask. Clean leaves stay byte-identical and non-string values keep their type. JSON and SSE responses carry the same rewrite. Card #5481: when the backend returns UTF-16 `spans` with the redaction, the guard maps each span to its leaf from the single analysis call (shared `guard_core.redact_tool_result`, no leaf cap); a span outside one leaf (dict key, number, separator) is refused. Without usable spans it falls back to the per-leaf rewrite above (capped at 64 leaves).
3. If any leaf cannot be masked safely, the response is **refused with a JSON-RPC error**. Partial or original content is never delivered.

**Embedded resources and off-contract shapes (card #5476).** A `content[]` block of type `resource` contributes `resource.text` to the analysis and, on redaction, is masked in place (`uri`/`mimeType` untouched). The rest of the block (`uri`, `mimeType`, `_meta`, `annotations`, extra keys; everything except `type` and `resource.text`/`resource.blob`) is analyzed too: `block` blocks, and text to mask there refuses the response (not a maskable leaf). `resource.blob` is not analyzed: a `redact` verdict on a response carrying a blob is refused with a JSON-RPC error. Off-contract shapes (`content` not a list, raw items in `content[]`, non-string `text`, non-object `resource`) are analyzed as their JSON serialization: `allow` forwards them unchanged, `block` blocks, `redact` is refused (no leaf to mask). A `resource_link` block is analyzed whole (minus `type`): `name`/`title`/`description` are masked in place, while text to mask in `uri` or an extra key refuses the response. A non-object `result` is analyzed too, on `tools/call` and on the guarded methods (`resources/read`, `prompts/get`, ...): `redact` is refused; a non-object `tools/list` result is refused in `enforce` and forwarded in `monitor` (`null` is forwarded as before). Applies in `enforce` and `monitor`.

This closes a bypass equivalent in severity to the multi-text-block bypass fixed in PR #252.

## License

MIT
