# Proxy protocol support

What the embedded intercepting proxy handles today, taken from
`backend/app/core/proxy/handler/`, `certs.py`, `server.py`, `transport/`
and the upstream TLS policy in `backend/app/core/tls/`. Each section ends with what adding the missing support
would take.

## Listener

- One TCP listener, `aiohttp.web.Server` (a raw handler, not the aiohttp
  router). It parses HTTP/1.0 and HTTP/1.1 only.
- No HTTP/2 on the listener itself: no h2c upgrade and no prior-knowledge
  HTTP/2. HTTP/2 is spoken inside CONNECT tunnels (see HTTP/2 below).
- The bind address and port come from `PROXY_HOST`/`PROXY_PORT` or the
  saved `proxy.listen` setting (`PUT /api/v1/proxy/settings`).

## Plain HTTP (`GET http://host/...`)

- Absolute-form requests are forwarded with an `aiohttp.ClientSession`
  (`auto_decompress=False`, `force_close=True`, so upstream connections are
  not reused). Origin-form requests fall back to the `Host` header.
- An absolute `https://` target (`GET https://host/...` without CONNECT)
  is forwarded over TLS and verified like a tunnel's upstream. Before this
  was fixed it was silently sent as plain `http://`.
- Hop-by-hop headers are removed in both directions. The response is
  streamed back in 64 KiB chunks; `Content-Length` is dropped and aiohttp
  re-frames the response for the client.
- Connect, read and total timeouts from `ProxySettings` apply.
- The request body is read before it is relayed (rules and intercept may
  change it), up to 256 MiB; a larger plain request gets a 413. Tunnelled
  HTTPS requests are streamed and have no such bound. Only the stored copy
  is cut to the capture body limit, as a flagged prefix.

## HTTPS (`CONNECT host:port`)

- The proxy first opens a TLS connection to `host:port` (any port), then
  answers `200 Connection Established` and terminates the client's TLS with
  a per-host certificate signed by the Phantom CA (TLS 1.2 minimum).
- Because the upstream side is always TLS, a CONNECT to a service that does
  not speak TLS fails.
- The upstream certificate is verified under the upstream TLS policy
  (next section). When verification fails, the client's tunnel is still
  established with Phantom's certificate so the browser can show a
  readable `502`; the first request is recorded with the failure as its
  error and the tunnel is closed. Nothing is sent upstream.
- Per-host certificates carry an IPAddress SAN when the CONNECT target is
  an IPv4 or IPv6 literal and a DNSName otherwise, plus the authority and
  subject key identifiers, `CA:FALSE`, key usage and serverAuth that strict
  verifiers (Python 3.13+, OpenSSL 3 `X509_STRICT`) require.
- Only the CONNECT connect timeout applies; reads inside the tunnel have
  no timeout.
- If the server closed the upstream connection while the tunnel was idle
  (for example while a request was held in intercept), it is reopened
  before the next request is written.
- Decrypted traffic is relayed as HTTP/1.x text, parsed by the handler:
  request line and headers, bodies framed by `Transfer-Encoding: chunked`
  or `Content-Length`, responses also by connection close. Keep-alive,
  `Expect: 100-continue` and other 1xx responses are handled. Trailers are
  relayed but not captured.

### HTTP/2

HTTP/2 is on by default (Proxy › Settings › HTTP/2, `GET`/`PUT
/api/v1/proxy/protocols` with `{"http2": true}`).

- The upstream connection of a tunnel offers `h2` and `http/1.1` by
  ALPN. Only when the server chooses `h2` is the client offered `h2` as
  well (`CertManager.get_context(host, http2=True)`); otherwise the
  tunnel is HTTP/1.1 exactly as before.
- When both sides choose `h2`, the tunnel is relayed stream by stream
  (`app/core/proxy/handler/h2_tunnel.py`, codec from the `h2` package).
  Each client stream becomes one captured exchange with `HTTP/2` as its
  version and one stream on the server connection, relayed by its own
  task, so a held or slow request does not hold up the others.
- The request is read whole before it is sent, so intercept and match
  and replace work as for HTTP/1.1. The response is streamed to the
  client frame by frame as it arrives, unless responses are held; then
  it is read whole, shown, and sent as released.
- Pseudo-headers become the method, URL and status of the exchange; the
  other headers are recorded as they arrived. Headers sent on are
  lower-cased, connection-specific ones are dropped, and
  `content-length` follows an edited body.
- Informational responses (`100`, `103`) and trailers (gRPC's
  `grpc-status`) are passed on; trailers are not captured. Server push
  is refused (`ENABLE_PUSH = 0`). A stream reset by either side is reset
  on the other with the same code.
- Flow control is end to end: data from the server is acknowledged only
  once it was passed to the client, so a slow client slows the server
  instead of filling memory.
- A client that keeps to HTTP/1.1 although the server chose `h2` gets
  the upstream connection reopened for HTTP/1.1.
- With HTTP/2 off, every tunnel offers `http/1.1` only on both sides.
  The setting applies to new tunnels; open ones keep their version.
- Replay, Repeater, Intruder and scans send over HTTP/1.1, also when
  they resend a request captured over HTTP/2.
- Not supported: request bodies streamed while the server already
  answers (client-streaming and bidirectional gRPC wait for the whole
  request), extended CONNECT (RFC 8441, WebSocket over HTTP/2: browsers
  open a separate HTTP/1.1 connection for WebSockets), and HTTP/2
  without TLS (h2c).

### Verified behaviour

Tested in `test_proxy_protocols.py` and `test_proxy_http2.py` against
local servers:

- Without HTTP/2 on, a client offering `h2` and `http/1.1` negotiates
  `http/1.1` with the intercepting certificate, and the upstream
  contexts ask a server that prefers HTTP/2 for `http/1.1`.
- With an HTTP/2 server, requests and responses travel over HTTP/2 and
  are stored as `HTTP/2` exchanges with their bodies; a response sent in
  slow frames with trailers arrives whole; a held request and response
  are edited; an HTTP/1.1-only client still reaches the HTTP/2 server.
- A client keeps one keep-alive connection to the proxy for several
  requests in a row. Upstream connections are opened per request
  (`force_close`), as described under Plain HTTP.
- A chunked response that arrives in slow parts is relayed whole and
  stored exactly as sent.

## Upstream TLS verification

One policy (`app/core/tls/`) decides how upstream certificates are checked
by the proxy (CONNECT, absolute-form `https://`, `wss://`), the replay tool
and the scan HTTP client.

- **Default: verify.** Certificates are checked against the system CA store
  with hostname checking. If the system store is empty (some minimal
  containers), the `certifi` bundle is used.
- **`ca_bundle`:** a PEM file on the backend host whose CAs are trusted in
  addition to the system store. This keeps verification on for a lab or
  internal CA. A bundle that cannot be loaded is rejected when saved; a
  saved bundle that later disappears is ignored with a warning (the system
  store still applies).
- **`insecure_hosts`:** hosts that skip verification. An entry is an exact
  host name, an IP address, or `*.suffix`. `*.example.com` covers
  `a.example.com` and `a.b.example.com` but not `example.com` itself (list
  it separately) and never `evilexample.com`. Matching ignores case, IPv6
  brackets and a trailing dot. Other wildcards, schemes, ports and paths
  are rejected with 422. At most 500 entries.
- **`allow_insecure`:** skip verification for every host. Off by default;
  the backend logs a warning when it is on.

REST (persisted under the `proxy.tls` setting):

```
GET /api/v1/proxy/tls
-> {"allow_insecure": false, "insecure_hosts": [], "ca_bundle": null, "verify_default": true}

PUT /api/v1/proxy/tls
   {"allow_insecure": false, "insecure_hosts": ["lab.local", "*.lab.local"], "ca_bundle": "/path/ca.pem"}
-> same shape as GET, patterns canonical (lower case, de-duplicated)
```

`PUT` replaces the whole policy; omitted fields take their defaults, so it
never widens an exception by accident. `verify_default` is false only while
`allow_insecure` is on. Invalid patterns and unusable bundles return 422
with the standard error body. A change applies to new upstream connections
of the running proxy at once (tunnels already open keep theirs), and to
the next replay and the next scan. The standalone relay (`make proxy`)
verifies every host.

A verification failure is reported with one message everywhere (proxy
`502` body, flow `error`, replay flow `error`, scan log and
`result_summary.tls_failures`); it is a single line, wrapped here:

```
Upstream TLS verification failed: self-signed certificate. The request was not sent to lab.local.
If you are authorized to test lab.local without certificate checks, add "lab.local" to the upstream
TLS exceptions (Proxy settings > Upstream TLS, PUT /api/v1/proxy/tls "insecure_hosts"), or trust its
CA with "ca_bundle".
```

The reason is OpenSSL's verify message, for example `self-signed
certificate`, `unable to get local issuer certificate`, `certificate has
expired` or `Hostname mismatch, certificate is not valid for 'x'`. The
scan HTTP client also returns `tls_error: true` with such a response.

## WebSocket

Sessions are captured in both relay paths; [WebSocket sessions](websocket.md)
has the model, limits, API, MCP tools and HAR mapping.

- `wss://` inside a CONNECT tunnel: the upgrade request and its `101`
  response are recorded as a flow of kind `websocket`. After that the
  bytes are piped untouched, and a copy is parsed frame by frame (RFC
  6455: masking, fragmentation, control frames between fragments,
  permessage-deflate inflated per direction) into messages with their
  direction, opcode, sizes and close code.
- `ws://` (and absolute `wss://`) on the plain path: the upstream
  handshake is made first, so a refused upgrade answers 502 and is
  recorded; a completed one is recorded as a `websocket` flow and the
  messages (text, binary, ping, pong, close codes) are relayed and
  recorded one by one. Automatic ping and close answers are off, so
  pings and close codes reach the other side.
- Messages are bounded per message (body limit), per session (frame and
  byte caps) and by the capture memory budget, written in batches, and
  announced with throttled `proxy.ws.frames` and one `proxy.ws.closed`
  event. The capture filter applies to the handshake: a skipped session
  records no frames.
- Not supported: holding or editing messages in intercept, replaying a
  session, WebSocket over HTTP/2 (RFC 8441; extended CONNECT is not
  offered, so browsers use HTTP/1.1 for WebSockets).

## HTTP/3 and QUIC

- Not supported. The listener is TCP only and nothing handles UDP, so
  QUIC cannot pass through the proxy. `Alt-Svc` response headers are
  relayed unchanged.
- Needed: a QUIC and HTTP/3 stack (such as `aioquic`), a UDP listener, a
  way for clients to send QUIC to a proxy (CONNECT-UDP / MASQUE, RFC 9298),
  and the same per-host certificate interception on QUIC's TLS 1.3
  handshake. A cheaper step is stripping `Alt-Svc` so clients keep using
  TCP.

## gRPC

| Variant | Transport | Through the proxy |
|---|---|---|
| gRPC (native) | HTTP/2 only, trailers carry `grpc-status` | Works for unary and server-streaming calls with HTTP/2 on: captured as HTTP/2 exchanges, intercepted, trailers passed on. Client-streaming and bidirectional calls wait for the whole request. Bodies are length-prefixed protobuf frames shown as binary. |
| gRPC-Web | HTTP/1.1 `POST` with `application/grpc-web` or `application/grpc-web-text`; trailers framed in the body | Works as ordinary HTTP: captured, intercepted, replayed and sent from Repeater. Bodies are length-prefixed protobuf frames, shown as binary (or base64 text for `-text`); there is no protobuf decoder. |
| gRPC transcoded to JSON (gateway) | HTTP/1.1 JSON | Works as ordinary HTTP. |

A useful view of native gRPC needs the service's `.proto` descriptors (or
server reflection) to decode messages, and resending it needs HTTP/2 in
Repeater and Intruder, which send HTTP/1.1 today.

## Capture and storage

- Request and response bodies are stored as seen on the wire after
  transfer framing is removed: content codings (gzip, br, ...) are kept,
  up to `PROXY_BODY_LIMIT` bytes per body (the full size is recorded).
- Replayed requests are stored the same way (`httpx` `aiter_raw()`), with
  the original response headers.
- Content codings are removed only for display, by bounded decoders capped
  at `DECODE_LIMIT` (8 MiB): gzip, x-gzip, deflate (zlib or raw), br and
  zstd, including stacked codings such as `gzip, br`.

## Intercept

Interception is a switch separate from starting and stopping the proxy
(`GET`/`PUT /api/v1/proxy/intercept`). The proxy runs with it off by
default, and the switch is never persisted: it is off after a restart.
The options are persisted under the `proxy.intercept` setting:

- `requests` (default on): hold a request before it is sent upstream;
- `responses` (default off): hold a response before it reaches the client;
- `in_scope_only` (default on): hold only hosts in the capture vault's
  scope. The scope is read for every exchange while the switch is on.
- `block_out_of_scope` (default off), **Block out of scope** in the
  Intercept toolbar: strict scope. While it is on, every request to a
  host outside the capture vault's scope is refused with `403` and an
  `X-Phantom-Blocked: scope` header, whether the intercept switch is on
  or not: plain requests, WebSocket upgrades and CONNECT tunnels alike.
  Nothing is sent upstream and nothing is recorded. This is how the
  research browser (or any client) is kept to the permitted origins. To
  review requests with external effects before they leave, add an
  intercept rule that holds them (for example every `POST`, `PUT` or
  `DELETE`).

What is held:

- Plain HTTP requests (`GET http://...`) and every request inside a
  CONNECT tunnel, and their final responses. 1xx and `101 Switching
  Protocols` responses are never held; the plain `ws://` path and frames
  after a `101` are not intercepted.
- A held exchange suspends only the task relaying its connection; other
  connections keep flowing. Each held message waits on its own future in
  the `InterceptQueue` (`app/core/proxy/intercept.py`).
- A tunnelled request with `Expect: 100-continue` is answered with
  `100 Continue` by the proxy so its body can be held; the `Expect`
  header is then not sent upstream.

Bodies:

- A body is read ahead before the message is held, up to
  `PROXY_BODY_LIMIT` (512 KiB by default). Such a body can be edited.
- A larger body is held with its first part only. It is shown truncated,
  cannot be edited (an edit with `body` is rejected with 422), and is
  relayed in its original framing after the decision, so the start line
  and headers can still be changed.
- Bodies are held and edited as raw bytes: content codings (gzip, br, ...)
  are kept. `raw_body` in the item detail is exactly what will be sent;
  `body` is the display form with codings removed.

Edits (`POST /api/v1/proxy/intercept/items/{id}/forward`):

- Requests: `method`, `url`, `headers`, `body`; responses: `status_code`,
  `reason`, `headers`, `body`. `headers` replaces the whole list (order and
  duplicates kept). `body_encoding` is `utf-8` or `base64`.
- Content-Length and Transfer-Encoding are always recomputed: a replaced
  body is sent with a new Content-Length and without chunked encoding; a
  body that could not be buffered keeps its original framing headers.
- Inside an HTTPS tunnel the upstream connection is already open, so the
  URL may only change its path and query. On the plain path the URL may
  point anywhere; the edited host is recorded in history.
- An edit identical to the held message counts as unchanged.

Decisions and releases:

- `forward` (edited or not), `drop`, and `POST .../intercept/release`
  (forward everything unchanged). Turning the switch off, or turning off
  the option that held a message, forwards it unchanged.
- A dropped request never reaches the server; a dropped response never
  reaches the client. The client receives `502` (inside a tunnel the
  connection is closed after it) and the flow is recorded with
  `error = "Dropped in intercept"`.
- A message nobody decides on is forwarded unchanged after
  `PROXY_INTERCEPT_TIMEOUT` seconds (300 by default); the
  `intercept.released` event then has `reason = "timeout"`. Clients may
  give up earlier on their own timeouts.
- Stopping or moving the listener and shutting the application down
  forward held messages unchanged first (`reason = "stopped"`). A message
  whose client disconnects while it is held (the connection is watched
  twice a second) leaves the queue at once with `reason = "cancelled"`,
  and nothing is relayed.
- Deciding on a released message returns 409; unknown ids return 404; of
  two decisions arriving together exactly one applies.
- Every held message keeps the vault it was captured for. An agent sees
  and decides only messages of vaults its token reaches, so moving
  capture to another vault never hands an agent the previous vault's
  traffic.
- On the plain path, the upstream total timeout (300 s) still runs while a
  response is held, so a response body larger than the body limit may be
  cut if it is held for longer.

History: the stored flow is what was actually sent. `intercepted` marks a
flow with a held side, `edited` a flow whose held side was changed.

Realtime (global events; the capture vault is in the payload):
`intercept.held` (item summary), `intercept.released` (`id`, `direction`,
`decision`, `reason`, `edited`), `intercept.updated` (switch, options and
rules). `proxy.status` also carries `intercepting` and `held`.

### Filter rules

Rules decide what is held, on top of the switch, the direction options and
the in-scope option. An item is held only if it matches no enabled **Skip**
(exclude) rule and, when any enabled **Hold** (include) rule targets its
direction, at least one of them.

- Fields: `host`, `method`, `path`, `url`, `query` (from the request line;
  for a response, from the request that produced it), `header` (named),
  `body`, and for responses only `status` and `mime` (Content-Type without
  parameters).
- Operators: `equals`, `contains`, `starts_with`, `ends_with`, `wildcard`
  (fnmatch, whole value, case-insensitive), `regex` (search; anchor with
  `^`/`$`); `negate` inverts the result (a negated header rule matches when
  the header is absent).
- Case: host, method, header names and type ignore case; path, URL, query,
  header values, body and status are case-sensitive.
- Body rules see the held body only (at most `PROXY_BODY_LIMIT`), decoded as
  UTF-8 with replacement; compressed bodies are not decoded for matching.
- Regex is bounded: patterns are compiled when saved, values are capped at
  512 characters, regex and wildcard see the first 64 KiB of a value, and
  each regex search stops after 50 ms (counted as no match). Plain operators
  see the whole value.
- At most 200 rules, saved as one ordered list (`PUT
  /api/v1/proxy/intercept/rules` with `{"rules": [...]}`); invalid rules are
  rejected with the rule index and field. Changing rules releases held
  items the new rules no longer select.
- `POST /api/v1/proxy/intercept/rules/test` evaluates a sample message
  against given or saved rules without saving anything.

Not yet: match-and-replace rules.
