headroom/tests/test_proxy_loopback_gating.py
Kenneth Wong 560319cef4
fix(dashboard): serve per-request metadata to trusted-gateway peers (#1766)
## Description

The dashboard's per-request metadata — the `recent_requests` /
`request_logs` tail and the `config` block (which echoes upstream API
URLs + backend settings) — is gated to loopback callers via
`_request_is_loopback`. It requires **both** a loopback peer IP
(`request.client.host == 127.0.0.1`) and a loopback `Host` header.

When Headroom runs in a **bridge-network container** (Docker/podman, or
Apple Containerization / `mocker`), a browser on the host reaches the
proxy through the container gateway, so `request.client.host` is the
**gateway IP** (e.g. `172.18.0.1`, or `192.168.64.1` on macOS vmnet),
not `127.0.0.1`. `include_sensitive` is therefore `False`, and the
"Recent Requests" table renders empty even though the operator is
browsing locally at `http://127.0.0.1:8787/dashboard`.

`curl` from **inside** the container (real `127.0.0.1` peer) confirmed
the data is present and populated — only the host-browser path was being
stripped.

The fix treats a peer inside an operator-configured trusted-gateway CIDR
(`HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS` — the same allow-list already
used by `forwarded_headers.py` to sanitize `X-Forwarded-*`) as
loopback-equivalent, while **retaining the loopback `Host`-header gate
as the DNS-rebinding defence**. It is opt-in and empty by default, so
there is **no behavior change** unless the operator explicitly
allow-lists their container gateway.

Closes #

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- `headroom/proxy/server.py` — `_request_is_loopback` now: (1) always
enforces the loopback `Host`-header gate first; (2) returns `True` for a
genuine loopback peer; (3) additionally returns `True` for a peer inside
`HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS` via the existing
`peer_is_trusted_gateway` / `load_trusted_gateway_cidrs` helpers.
- `tests/test_proxy_loopback_gating.py` — added
`test_stats_metadata_served_to_trusted_gateway_peer`: gateway peer
stripped without the allow-list, served with it, and DNS-rebinding
(non-loopback `Host`) still rejected even for a trusted gateway peer.
- `CHANGELOG.md` — Unreleased → Fixed entry.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ pytest tests/test_proxy_loopback_gating.py -q
14 passed, 1 warning in 3.56s

$ ruff check headroom/proxy/server.py tests/test_proxy_loopback_gating.py
All checks passed!
```

## Real Behavior Proof

- Environment: Headroom 0.29.0 in a `mocker compose` (Apple
Containerization) bridge container on macOS; host browser at
`http://127.0.0.1:8787/dashboard`.
- Exact command / steps: before the fix, `mocker compose exec
headroom-proxy sh -c 'curl -s http://127.0.0.1:8787/stats'` (peer = real
`127.0.0.1`) returned a populated `recent_requests` array, while the
host browser saw an empty table. After adding
`HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS` covering the container gateway
and recreating, the host browser's dashboard shows the Recent Requests
table again.
- Observed result: dashboard per-request table restored for the host
browser; aggregate-only view unchanged for untrusted network callers.
- Not tested: IPv6 gateway CIDRs (the underlying
`peer_is_trusted_gateway` supports them; not exercised in this
environment).

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Additional Notes

Pure opt-in: `HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS` is empty by default,
so `_request_is_loopback` behavior is byte-identical to today unless an
operator allow-lists a gateway CIDR. Reuses the existing trusted-gateway
machinery rather than introducing a new config surface. Docs/compose
examples intentionally omitted — deployment-specific.

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-07-12 16:29:36 -05:00

187 lines
7.1 KiB
Python

"""Loopback-gating tests for state-mutating / content-leaking endpoints.
``/transformations/feed`` can return full prompt + completion bodies (when
``log_full_messages`` is on) and ``/cache/clear`` mutates server state. With the
default ``--host 0.0.0.0`` Docker bind, neither should be reachable by an
arbitrary network client — they are gated to the loopback interface via
``require_loopback`` (the same guard already used for ``/admin/*`` and
``/debug/*``). See #863.
"""
from __future__ import annotations
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from headroom.cache.backends import InMemoryBackend
from headroom.cache.compression_store import get_compression_store, reset_compression_store
from headroom.proxy.server import ProxyConfig, create_app
GATED = [
("get", "/transformations/feed"),
("post", "/cache/clear"),
]
def _make_app() -> FastAPI:
return create_app(
ProxyConfig(
optimize=False,
cache_enabled=False,
rate_limit_enabled=False,
cost_tracking_enabled=False,
log_requests=False,
ccr_inject_tool=False,
ccr_handle_responses=False,
ccr_context_tracking=False,
image_optimize=False,
)
)
def _loopback_client() -> TestClient:
# A real loopback peer + a loopback Host header — passes both guard gates
# (client-IP check and the DNS-rebinding Host-header check).
return TestClient(_make_app(), base_url="http://127.0.0.1", client=("127.0.0.1", 12345))
def _seed_ccr_entry() -> str:
reset_compression_store()
store = get_compression_store(backend=InMemoryBackend())
return store.store(
"seeded-ccr-content",
"<<ccr:seeded>>",
original_tokens=3,
compressed_tokens=1,
tool_name="seeded-test",
)
@pytest.mark.parametrize("method,path", GATED)
def test_non_loopback_caller_gets_404(method: str, path: str) -> None:
# A vanilla TestClient presents client.host="testclient", which is not a
# loopback IP, so the guard returns 404 (invisible, not 403).
client = TestClient(_make_app())
resp = client.request(method, path)
assert resp.status_code == 404, resp.text
@pytest.mark.parametrize("method,path", GATED)
def test_loopback_caller_allowed(method: str, path: str) -> None:
client = _loopback_client()
resp = client.request(method, path)
assert resp.status_code == 200, resp.text
# CCR data endpoints — cached session content, gated to 404 off-loopback (#1227).
CCR_GATED = [
("post", "/v1/retrieve"),
("get", "/v1/retrieve/stats"),
("get", "/v1/retrieve/somehash"),
("post", "/v1/retrieve/tool_call"),
("post", "/v1/compress"),
]
@pytest.mark.parametrize("method,path", CCR_GATED)
def test_ccr_non_loopback_gets_404(method: str, path: str) -> None:
resp = TestClient(_make_app()).request(method, path, json={})
assert resp.status_code == 404, resp.text
def test_ccr_retrieve_hash_route_blocks_valid_hash_for_non_loopback() -> None:
ccr_hash = _seed_ccr_entry()
try:
loopback = _loopback_client()
loopback_resp = loopback.get(f"/v1/retrieve/{ccr_hash}")
assert loopback_resp.status_code == 200, loopback_resp.text
assert loopback_resp.json()["original_content"] == "seeded-ccr-content"
network_resp = TestClient(_make_app()).get(f"/v1/retrieve/{ccr_hash}")
assert network_resp.status_code == 404, network_resp.text
finally:
reset_compression_store()
def test_dns_rebinding_host_header_rejected() -> None:
# Loopback peer IP but an attacker-controlled Host header (the DNS-rebinding
# shape) must still be rejected by the second gate.
client = TestClient(_make_app(), base_url="http://127.0.0.1", client=("127.0.0.1", 12345))
resp = client.get("/transformations/feed", headers={"host": "attacker.example"})
assert resp.status_code == 404, resp.text
def _client(*, loopback: bool) -> TestClient:
app = _make_app()
if loopback:
return TestClient(app, base_url="http://127.0.0.1", client=("127.0.0.1", 12345))
# Default TestClient presents client.host="testclient" — not loopback.
return TestClient(app)
def test_health_config_block_is_loopback_only(monkeypatch: pytest.MonkeyPatch) -> None:
"""/health stays reachable for monitors but hides the `config` block (which
echoes upstream API URLs + backend settings) from non-loopback callers."""
monkeypatch.setenv("HEADROOM_SKIP_UPSTREAM_CHECK", "1")
network = _client(loopback=False).get("/health")
assert network.status_code == 200
assert "config" not in network.json()
# Basic health is still visible to monitors.
assert network.json()["status"] in {"healthy", "unhealthy"}
local = _client(loopback=True).get("/health")
assert local.status_code == 200
assert "config" in local.json()
def test_stats_per_request_metadata_is_loopback_only() -> None:
"""/stats keeps aggregate counters public but restricts per-request metadata
(recent_requests / request_logs) and `config` to loopback callers."""
network = _client(loopback=False).get("/stats")
assert network.status_code == 200
payload = network.json()
assert "tokens" in payload # aggregate counters still served
assert "recent_requests" not in payload
assert "request_logs" not in payload
assert "config" not in payload
local = _client(loopback=True).get("/stats").json()
assert "recent_requests" in local
assert "config" in local
def test_stats_metadata_served_to_trusted_gateway_peer(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Containerized dashboards: a browser on the host reaches a bridge-network
container via the gateway IP, so the peer isn't 127.0.0.1 and per-request
metadata gets stripped. When the operator allow-lists the gateway CIDR via
HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS, the peer is treated as
loopback-equivalent and the metadata is served again."""
gateway_ip = "172.18.0.1" # typical docker/mocker bridge gateway
app = _make_app()
def _gateway_client() -> TestClient:
# Loopback Host header (the operator browses http://127.0.0.1:8787) but
# the peer IP is the container gateway, not loopback.
return TestClient(app, base_url="http://127.0.0.1", client=(gateway_ip, 54321))
# Without the allow-list, the gateway peer is untrusted → metadata stripped.
monkeypatch.delenv("HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS", raising=False)
stripped = _gateway_client().get("/stats").json()
assert "recent_requests" not in stripped
assert "config" not in stripped
# Allow-list the gateway CIDR → peer trusted → metadata served.
monkeypatch.setenv("HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS", "172.18.0.0/16")
served = _gateway_client().get("/stats").json()
assert "recent_requests" in served
assert "config" in served
# DNS-rebinding defence still applies even for a trusted gateway peer: a
# non-loopback Host header must be rejected.
rebind = TestClient(app, base_url="http://attacker.example", client=(gateway_ip, 54321))
payload = rebind.get("/stats").json()
assert "recent_requests" not in payload