mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(proxy): refuse HTTP requests from untrusted browser origins (#4853)
## 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>
This commit is contained in:
co-authored by
Claude Opus 5.5
JerrettDavis
parent
70ba72138d
commit
ab1d0292df
@@ -259,6 +259,22 @@ still names the attacker's page, and that is what this gate rejects. Requests wi
|
||||
`Origin` at all (CLI tools, curl) pass, which is the intended behaviour for a
|
||||
locally-driven surface.
|
||||
|
||||
The provider routes (`/v1/messages`, `/v1/chat/completions`, `/v1/responses`, the
|
||||
passthrough) add operator credentials to what they forward, so every HTTP request goes
|
||||
through the same browser check in the security gate before routing: a request whose
|
||||
`Origin` is not a loopback page, an origin listed in `HEADROOM_WS_ORIGINS` /
|
||||
`HEADROOM_CORS_ORIGINS`, or (for a non-loopback caller) the proxy's own address is
|
||||
refused with **403**. A cross-site subresource load, which carries no `Origin`, is
|
||||
refused by `Sec-Fetch-Site: cross-site` unless it is a top-level navigation. Requests
|
||||
with no `Origin` (SDKs, coding agents, curl) are unaffected.
|
||||
|
||||
A reverse proxy on the same host that forwards a public hostname to `127.0.0.1` needs the
|
||||
page's origin (`https://name`) listed in `HEADROOM_WS_ORIGINS`: the proxy sees a loopback
|
||||
peer with a non-loopback `Host`, which is indistinguishable from a re-pointed hostname.
|
||||
Only `http`, `https`, `ws` and `wss` origins can be listed. Pages that send an app scheme (such as
|
||||
`tauri://localhost`) or `Origin: null` (sandboxed iframes, `file://` pages) are always
|
||||
refused; a desktop app should call the proxy from its native side, which sends no `Origin`.
|
||||
|
||||
### The two CIDR allowlists
|
||||
|
||||
Two environment variables can extend this beyond loopback. Both default to empty, so the
|
||||
|
||||
@@ -863,6 +863,64 @@ from headroom.proxy.handlers import ( # noqa: E402
|
||||
OpenAIHandlerMixin,
|
||||
StreamingMixin,
|
||||
)
|
||||
from headroom.proxy.handlers.openai import ( # noqa: E402
|
||||
_is_allowed_websocket_origin,
|
||||
_is_loopback_ws_origin,
|
||||
_normalize_origin,
|
||||
)
|
||||
|
||||
|
||||
def _is_cors_listed_origin(origin: str) -> bool:
|
||||
"""True when ``origin`` is listed in HEADROOM_CORS_ORIGINS (``*`` lists nothing)."""
|
||||
normalized = _normalize_origin(origin)
|
||||
if normalized is None:
|
||||
return False
|
||||
listed = (
|
||||
_normalize_origin(entry.strip())
|
||||
for entry in os.environ.get("HEADROOM_CORS_ORIGINS", "").split(",")
|
||||
if entry.strip() and entry.strip() != "*"
|
||||
)
|
||||
return normalized in listed
|
||||
|
||||
|
||||
def _is_refused_browser_request(request: Request) -> bool:
|
||||
"""Return True for a browser request from a page the proxy does not trust.
|
||||
|
||||
The proxy adds operator credentials (extra headers, the Copilot token,
|
||||
provider env keys) to what it forwards, and loopback callers skip the
|
||||
proxy token, so a page open in the user's browser must not be able to
|
||||
drive it with a "simple" request (``text/plain`` body, no preflight).
|
||||
|
||||
Requests without ``Origin`` (CLI tools, SDKs, coding agents) pass. With
|
||||
``Origin``, these pass: loopback pages (the dashboard), the origins the
|
||||
WebSocket routes accept (``HEADROOM_WS_ORIGINS`` / ``HEADROOM_CORS_ORIGINS``),
|
||||
and, for a non-loopback peer, a page served from this proxy's own address
|
||||
(a remote dashboard). A loopback peer gets no same-origin pass: there a
|
||||
non-loopback Host means a page's hostname was pointed at 127.0.0.1.
|
||||
A cross-site subresource load (``<img>``, ``<script>``) carries no
|
||||
``Origin`` on GET, so ``Sec-Fetch-Site: cross-site`` is refused too, except
|
||||
for a top-level navigation.
|
||||
"""
|
||||
headers = request.headers
|
||||
origin = headers.get("origin")
|
||||
if origin:
|
||||
if (
|
||||
_is_loopback_ws_origin(origin)
|
||||
or _is_allowed_websocket_origin(dict(headers))
|
||||
or _is_cors_listed_origin(origin)
|
||||
):
|
||||
return False
|
||||
client = getattr(request, "client", None)
|
||||
peer = getattr(client, "host", None) if client is not None else None
|
||||
host_header = headers.get("host")
|
||||
return (
|
||||
is_loopback_host(peer)
|
||||
or not host_header
|
||||
or not _request_has_same_origin_or_no_provenance(request, host_header)
|
||||
)
|
||||
fetch_site = (headers.get("sec-fetch-site") or "").lower()
|
||||
fetch_mode = (headers.get("sec-fetch-mode") or "").lower()
|
||||
return fetch_site == "cross-site" and fetch_mode != "navigate"
|
||||
|
||||
|
||||
def _apply_stateless_persistence(config: ProxyConfig) -> None:
|
||||
@@ -4528,6 +4586,26 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
|
||||
|
||||
@app.middleware("http")
|
||||
async def _security_gate(request, call_next):
|
||||
# 0) Browser provenance. Runs before the token check because loopback
|
||||
# callers skip that check, and a page in the user's browser reaches
|
||||
# the proxy as a loopback caller.
|
||||
if _is_refused_browser_request(request):
|
||||
logger.warning(
|
||||
"event=proxy_browser_origin_rejected method=%s path=%s origin=%s",
|
||||
request.method,
|
||||
_auth_rejection_path(request.url.path),
|
||||
_auth_rejection_path(request.headers.get("origin") or "-"),
|
||||
)
|
||||
rejection = JSONResponse(
|
||||
status_code=403,
|
||||
content={
|
||||
"error": "cross-origin request rejected",
|
||||
"hint": "add this page's origin to HEADROOM_WS_ORIGINS to allow it",
|
||||
},
|
||||
)
|
||||
_apply_security_headers(rejection)
|
||||
return rejection
|
||||
|
||||
# 1) Optional inbound auth. When a token is configured, require it on
|
||||
# non-loopback requests; loopback callers and health probes are
|
||||
# exempt. Loopback is the same trust boundary the admin/debug
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
"""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
|
||||
@@ -698,10 +698,28 @@ def test_dashboard_client_cidr_grants_stats_metadata_to_same_origin_browser(
|
||||
assert "config" in payload
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cached", [False, True])
|
||||
def test_dashboard_client_cidr_refuses_cross_origin_browser_stats(
|
||||
monkeypatch: pytest.MonkeyPatch, cached: bool
|
||||
) -> None:
|
||||
monkeypatch.setenv("HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS", "100.90.0.5/32")
|
||||
client = TestClient(
|
||||
_make_app(),
|
||||
base_url="http://100.82.0.2:8787",
|
||||
client=("100.90.0.5", 12345),
|
||||
)
|
||||
|
||||
response = client.get(
|
||||
"/stats", params={"cached": int(cached)}, headers={"origin": "http://attacker.example"}
|
||||
)
|
||||
|
||||
# The security gate refuses a foreign browser Origin before the route runs.
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"headers",
|
||||
[
|
||||
{"origin": "http://attacker.example"},
|
||||
{"referer": "http://attacker.example/dashboard"},
|
||||
],
|
||||
)
|
||||
@@ -1106,7 +1124,8 @@ def test_metrics_trusted_cidr_cross_origin_browser_rejected(
|
||||
client=("10.9.0.7", 40000),
|
||||
)
|
||||
resp = client.get("/metrics", headers={"Origin": "http://attacker.example"})
|
||||
assert resp.status_code == 404
|
||||
# Refused by the security gate (403) before the route's own guard (404).
|
||||
assert resp.status_code == 403
|
||||
|
||||
|
||||
def test_metrics_token_authenticated_network_caller_allowed(
|
||||
|
||||
Reference in New Issue
Block a user