mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
## Description The provider routes (`/v1/messages`, `/anthropic/v1/messages`, `/v1/chat/completions`, `/v1/responses`, Bedrock/Vertex routes and the catch-all passthrough) add operator-held credentials to what they forward: `*_extra_headers`, the Copilot token (`apply_copilot_api_auth`), and the provider env key on the litellm/anyllm backends when the request carries none. Loopback callers skip `HEADROOM_PROXY_TOKEN`, and a page open in the user's browser reaches the proxy as a loopback caller. It can send a JSON body as `Content-Type: text/plain`, which needs no CORS preflight, and the proxy parses and forwards it. CORS only stops the page from reading the answer, not the proxy from sending the request. Only the WebSocket routes checked `Origin`. The security gate now applies the WebSocket Origin rule to every HTTP request, before routing. A request is refused with 403 when it carries an `Origin` that is not: - a loopback page (`http(s)://127.0.0.1|localhost|[::1]` on any port; this is the dashboard), - an origin listed in `HEADROOM_WS_ORIGINS` / `HEADROOM_CORS_ORIGINS` (the same list `_is_allowed_websocket_origin` honours), - for a non-loopback caller only, the proxy's own address (a remote dashboard behind `HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS`). A loopback caller gets no same-origin pass, since a non-loopback `Host` with a loopback peer means a page's hostname was pointed at 127.0.0.1. A cross-site subresource load (`<img>`, `<script>`) sends no `Origin` on GET, so `Sec-Fetch-Site: cross-site` is refused too, except for a top-level navigation. Requests without `Origin` (Claude Code, Codex, Copilot's extension host, SDKs, curl) are unaffected. Because the check sits in the gate, it covers every backend, including the litellm/anyllm env-key fallback, without changing how a keyless request from a local tool is authenticated. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [x] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - `headroom/proxy/server.py`: `_is_refused_browser_request(request)` and a step 0 in `_security_gate` that answers 403 before the token check and routing. The 403 comes with the usual security headers and a hint naming `HEADROOM_WS_ORIGINS`, and an `event=proxy_browser_origin_rejected` log line records the escaped Origin. An origin listed in either `HEADROOM_WS_ORIGINS` or `HEADROOM_CORS_ORIGINS` is accepted, even when both are set. - `tests/test_proxy_browser_origin.py`: text/plain POSTs to `/v1/messages` and `/v1/chat/completions` from a loopback peer with a foreign / `null` / look-alike Origin never reach the upstream; without Origin, from a loopback page, and from a configured origin they still forward with the operator header; cross-site subresource GET refused; cross-site navigation still served; loopback peer with a re-pointed hostname refused. - `tests/test_proxy_loopback_gating.py`: two existing tests that sent a foreign `Origin` to `/stats` and `/metrics` now expect the gate's 403 (they already asserted refusal / no metadata; the gate now refuses earlier). - `docs/content/docs/security-model.mdx`: describes the rule, and lists the setups that need an explicit origin: a reverse proxy on the same host, and app-scheme desktop shells. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text # new test file on origin/main (before the fix) $ pytest tests/test_proxy_browser_origin.py FAILED ...test_foreign_page_request_is_refused_before_the_upstream[browser_headers0-/v1/chat/completions] FAILED ...test_foreign_page_request_is_refused_before_the_upstream[browser_headers0-/v1/messages] FAILED ...test_foreign_page_request_is_refused_before_the_upstream[browser_headers1-/v1/chat/completions] FAILED ...test_foreign_page_request_is_refused_before_the_upstream[browser_headers1-/v1/messages] FAILED ...test_foreign_page_request_is_refused_before_the_upstream[browser_headers2-/v1/chat/completions] FAILED ...test_foreign_page_request_is_refused_before_the_upstream[browser_headers2-/v1/messages] FAILED ...test_configured_origin_still_forwards FAILED ...test_cross_site_subresource_without_origin_is_refused ========================= 8 failed, 5 passed in 11.06s ========================= # with the fix $ pytest tests/test_proxy_browser_origin.py tests/test_proxy_loopback_gating.py tests/test_proxy_cors.py ======================= 175 passed, 5 warnings in 34.36s ======================= # wider sweep: tests/test_proxy*.py tests/test_proxy/ tests/test_header_isolation.py # tests/test_upstream_credential_scoping.py tests/test_openai_codex_routing.py # tests/test_dashboard_* tests/test_copilot* (-k "not playwright") = 12 failed, 2368 passed, 114 skipped, 30 deselected in 483.68s = # the 12 failures (tests/test_proxy_uds.py x11, one test_proxy_compress_endpoint lossy-inline case) # fail identically on origin/main in this environment $ ruff check headroom/proxy/server.py tests/test_proxy_browser_origin.py tests/test_proxy_loopback_gating.py All checks passed! $ mypy headroom/proxy/server.py --ignore-missing-imports Success: no issues found in 1 source file ``` ## Real Behavior Proof - Environment: macOS, Python 3.12. `headroom proxy --host 127.0.0.1 --no-optimize --anthropic-api-url http://127.0.0.1:<L> --anthropic-extra-headers '{"x-api-key":"OPERATOR_KEY_SENTINEL"}'`, no proxy token, with a small HTTP listener on `<L>` that logs each request's `x-api-key` and prompt. One run on origin/main, one on this branch. - Exact command / steps: three `curl -X POST http://127.0.0.1:<port>/v1/messages -H 'Content-Type: text/plain' --data '<messages JSON>'`, with `Origin: http://page.example`, with `Origin: http://127.0.0.1:<port>`, and with no Origin. - Observed result: ```text == origin/main Origin: http://page.example -> HTTP 200 Origin: http://127.0.0.1:18961 -> HTTP 200 (no Origin) -> HTTP 200 listener saw: {"path": "/v1/messages", "x-api-key": "OPERATOR_KEY_SENTINEL", "prompt": "request-1 (Origin: http://page.example)"} {"path": "/v1/messages", "x-api-key": "OPERATOR_KEY_SENTINEL", "prompt": "request-2 (Origin: http://127.0.0.1:18961)"} {"path": "/v1/messages", "x-api-key": "OPERATOR_KEY_SENTINEL", "prompt": "request-3 (X-No-Origin: 1)"} == this branch Origin: http://page.example -> HTTP 403 Origin: http://127.0.0.1:18962 -> HTTP 200 (no Origin) -> HTTP 200 listener saw: {"path": "/v1/messages", "x-api-key": "OPERATOR_KEY_SENTINEL", "prompt": "request-2 (Origin: http://127.0.0.1:18962)"} {"path": "/v1/messages", "x-api-key": "OPERATOR_KEY_SENTINEL", "prompt": "request-3 (X-No-Origin: 1)"} ``` Dashboard on the same branch: `GET /dashboard` as a cross-site navigation -> 200; same-origin `POST /settings` -> 200; same-origin `GET /stats` -> 200. - Not tested: a real Copilot upstream (the refusal happens before any handler, so it is the same for every route). ## Runtime Rollout Safety - Rollout-managed feature(s): none - Minimum rollout channel: n/a - Stable/default behavior changed: HTTP requests carrying an `Origin` that is neither loopback, configured, nor (for a remote caller) the proxy's own address now get 403. A browser app on another origin that calls the proxy directly must be listed in `HEADROOM_WS_ORIGINS` (or `HEADROOM_CORS_ORIGINS`, which also governs CORS). Electron/webview renderers that send `Origin: null` or an app scheme are refused unless listed. - Kill switch / disable path: list the origin in `HEADROOM_WS_ORIGINS`. - Unsafe override required: no - Qualification impact: none - Rollback path: revert this commit ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [x] I did **not** edit `CHANGELOG.md` — it is generated by release-please from my Conventional Commit PR title (a CI guard enforces this) ## Additional Notes A companion PR (#4846) stops a `*` entry in `HEADROOM_WS_ORIGINS` / `HEADROOM_CORS_ORIGINS` from accepting every Origin. Both PRs share `_is_allowed_websocket_origin`, so once both land `*` is ignored on HTTP too; until then, `HEADROOM_CORS_ORIGINS=*` keeps HTTP open to every Origin, as it keeps the WebSocket routes today. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
214 lines
6.8 KiB
Python
214 lines
6.8 KiB
Python
"""Requests from a browser page the proxy does not trust never reach the upstream.
|
|
|
|
The proxy adds operator-held credentials (``*_extra_headers``, the Copilot
|
|
token, provider env keys) to what it forwards, and loopback callers skip
|
|
``HEADROOM_PROXY_TOKEN``. A page open in the user's browser reaches the proxy as
|
|
a loopback caller and can send a ``text/plain`` JSON body without a CORS
|
|
preflight, so the HTTP routes apply the same Origin rule as the WebSocket
|
|
routes. Clients that send no ``Origin`` (CLI tools, SDKs, coding agents) and
|
|
loopback pages (the dashboard) are unaffected.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
import httpx
|
|
import pytest
|
|
|
|
pytest.importorskip("fastapi")
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
from headroom.proxy.server import ProxyConfig, create_app # noqa: E402
|
|
|
|
OPERATOR_SECRET = "operator-held-secret"
|
|
FOREIGN_ORIGIN = "https://page.example"
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _default_origin_policy(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.delenv("HEADROOM_WS_ORIGINS", raising=False)
|
|
monkeypatch.delenv("HEADROOM_CORS_ORIGINS", raising=False)
|
|
monkeypatch.delenv("HEADROOM_PROXY_TOKEN", raising=False)
|
|
|
|
|
|
class _Capturing(httpx.AsyncBaseTransport):
|
|
def __init__(self) -> None:
|
|
self.requests: list[httpx.Request] = []
|
|
|
|
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
|
|
async for _ in request.stream:
|
|
pass
|
|
self.requests.append(request)
|
|
if request.url.path.endswith("/chat/completions"):
|
|
body = {
|
|
"id": "chatcmpl-1",
|
|
"object": "chat.completion",
|
|
"model": "gpt-4o",
|
|
"choices": [
|
|
{
|
|
"index": 0,
|
|
"message": {"role": "assistant", "content": "ok"},
|
|
"finish_reason": "stop",
|
|
}
|
|
],
|
|
"usage": {"prompt_tokens": 5, "completion_tokens": 1, "total_tokens": 6},
|
|
}
|
|
else:
|
|
body = {
|
|
"id": "msg_1",
|
|
"type": "message",
|
|
"role": "assistant",
|
|
"model": "claude-sonnet-4-6",
|
|
"content": [{"type": "text", "text": "ok"}],
|
|
"usage": {"input_tokens": 5, "output_tokens": 1},
|
|
}
|
|
return httpx.Response(200, json=body)
|
|
|
|
|
|
def _client() -> tuple[TestClient, _Capturing]:
|
|
config = 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,
|
|
anthropic_extra_headers={"x-api-key": OPERATOR_SECRET},
|
|
openai_extra_headers={"Authorization": f"Bearer {OPERATOR_SECRET}"},
|
|
)
|
|
app = create_app(config)
|
|
transport = _Capturing()
|
|
app.state.proxy.http_client = httpx.AsyncClient(transport=transport)
|
|
# The browser and the proxy share the host, so the peer is loopback.
|
|
return TestClient(app, client=("127.0.0.1", 51000)), transport
|
|
|
|
|
|
_ROUTES = {
|
|
"/v1/messages": {
|
|
"model": "claude-sonnet-4-6",
|
|
"max_tokens": 8,
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
},
|
|
"/v1/chat/completions": {
|
|
"model": "gpt-4o",
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
},
|
|
}
|
|
|
|
|
|
def _simple_post(client: TestClient, path: str, headers: dict[str, str]) -> httpx.Response:
|
|
# A browser "simple" request: text/plain body, no custom headers, no preflight.
|
|
return client.post(
|
|
path,
|
|
content=json.dumps(_ROUTES[path]),
|
|
headers={"Content-Type": "text/plain", **headers},
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("path", sorted(_ROUTES))
|
|
@pytest.mark.parametrize(
|
|
"browser_headers",
|
|
[
|
|
{"Origin": FOREIGN_ORIGIN},
|
|
{"Origin": "null"},
|
|
{"Origin": "http://localhost.page.example"},
|
|
],
|
|
)
|
|
def test_foreign_page_request_is_refused_before_the_upstream(
|
|
path: str, browser_headers: dict[str, str]
|
|
) -> None:
|
|
client, transport = _client()
|
|
|
|
resp = _simple_post(client, path, browser_headers)
|
|
|
|
assert resp.status_code == 403
|
|
assert transport.requests == []
|
|
|
|
|
|
@pytest.mark.parametrize("path", sorted(_ROUTES))
|
|
def test_request_without_origin_still_forwards(path: str) -> None:
|
|
client, transport = _client()
|
|
|
|
resp = _simple_post(client, path, {})
|
|
|
|
assert resp.status_code == 200, resp.text
|
|
assert len(transport.requests) == 1
|
|
assert any(OPERATOR_SECRET in value for value in transport.requests[0].headers.values())
|
|
|
|
|
|
@pytest.mark.parametrize("origin", ["http://127.0.0.1:8787", "http://localhost:3000"])
|
|
def test_loopback_page_still_forwards(origin: str) -> None:
|
|
client, transport = _client()
|
|
|
|
resp = _simple_post(client, "/v1/messages", {"Origin": origin})
|
|
|
|
assert resp.status_code == 200, resp.text
|
|
assert len(transport.requests) == 1
|
|
|
|
|
|
def test_configured_origin_still_forwards(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.setenv("HEADROOM_WS_ORIGINS", "https://dash.example")
|
|
client, transport = _client()
|
|
|
|
allowed = _simple_post(client, "/v1/messages", {"Origin": "https://dash.example"})
|
|
refused = _simple_post(client, "/v1/messages", {"Origin": FOREIGN_ORIGIN})
|
|
|
|
assert allowed.status_code == 200, allowed.text
|
|
assert refused.status_code == 403
|
|
assert len(transport.requests) == 1
|
|
|
|
|
|
def test_cross_site_subresource_without_origin_is_refused() -> None:
|
|
client, transport = _client()
|
|
|
|
resp = client.get(
|
|
"/v1/models",
|
|
headers={"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Mode": "no-cors"},
|
|
)
|
|
|
|
assert resp.status_code == 403
|
|
assert transport.requests == []
|
|
|
|
|
|
def test_cross_site_navigation_to_the_dashboard_still_loads() -> None:
|
|
client, _ = _client()
|
|
|
|
resp = client.get(
|
|
"/health",
|
|
headers={"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Mode": "navigate"},
|
|
)
|
|
|
|
assert resp.status_code == 200
|
|
|
|
|
|
def test_loopback_peer_with_a_repointed_hostname_is_refused() -> None:
|
|
# Origin matches Host, but Host is not loopback while the peer is.
|
|
client, transport = _client()
|
|
|
|
resp = _simple_post(
|
|
client,
|
|
"/v1/messages",
|
|
{"Origin": "http://page.example:8787", "Host": "page.example:8787"},
|
|
)
|
|
|
|
assert resp.status_code == 403
|
|
assert transport.requests == []
|
|
|
|
|
|
def test_origin_listed_only_for_cors_still_forwards_when_both_lists_are_set(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setenv("HEADROOM_WS_ORIGINS", "https://ws.example")
|
|
monkeypatch.setenv("HEADROOM_CORS_ORIGINS", "https://dash.example")
|
|
client, transport = _client()
|
|
|
|
resp = _simple_post(client, "/v1/messages", {"Origin": "https://dash.example"})
|
|
|
|
assert resp.status_code == 200, resp.text
|
|
assert len(transport.requests) == 1
|