Files
headroom/tests/test_proxy_cors.py
d9ae7ad721 fix(proxy): stop a "*" origin setting from waiving the WebSocket Origin check (#4846)
## Description

The WebSocket routes (`/v1/responses`, `/v1/live`) check the browser
`Origin` against `HEADROOM_WS_ORIGINS`, falling back to
`HEADROOM_CORS_ORIGINS`. A `*` entry in either made every Origin
acceptable. `HEADROOM_CORS_ORIGINS=*` is a documented value for CORS
(which pages may *read* a response), so loosening CORS for a remote
dashboard also let any page open in the user's browser open these
sockets, and the proxy then adds its own credentials upstream.

`*` now matches nothing in the Origin check. A list that holds only `*`
keeps the loopback default; explicit origins in either variable keep
working. CORS itself is unchanged.

## 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)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/proxy/handlers/openai.py`: `_allowed_ws_origins_from_env`
drops `*` entries (empty result means the loopback default);
`_is_allowed_websocket_origin` no longer short-circuits to `True` on
`*`. `providers/codex/live.py` uses the same helper, so `/v1/live` is
covered too.
- `tests/test_openai_codex_routing.py`: policy test for `*` via either
variable and mixed with an explicit origin, plus a handler test that a
foreign Origin is closed with 1008 under `HEADROOM_CORS_ORIGINS=*`.

## 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 tests on origin/main (before the fix)
$ pytest tests/test_openai_codex_routing.py -k wildcard
FAILED tests/test_openai_codex_routing.py::test_websocket_origin_policy_ignores_wildcard[None-*]
FAILED tests/test_openai_codex_routing.py::test_websocket_origin_policy_ignores_wildcard[*-None]
FAILED tests/test_openai_codex_routing.py::test_websocket_origin_policy_ignores_wildcard[None-*, https://dash.example.com]
FAILED tests/test_openai_codex_routing.py::test_handle_openai_responses_ws_closes_foreign_origin_under_wildcard_cors
======================= 4 failed, 43 deselected in 1.33s =======================

# with the fix
$ pytest tests/test_openai_codex_routing.py tests/test_codex_live.py
======================= 57 passed, 7 warnings in 16.31s ========================

$ ruff check headroom/proxy/handlers/openai.py tests/test_openai_codex_routing.py
All checks passed!
$ mypy headroom/proxy/handlers/openai.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` started with `HEADROOM_CORS_ORIGINS='*'`, one run on
origin/main and one on this branch.
- Exact command / steps: open `ws://127.0.0.1:<port>/v1/responses` with
the `websockets` client, once with `Origin: https://page.example` and
once with `Origin: http://127.0.0.1:<port>`.
- Observed result:
  ```text
  == origin/main (HEADROOM_CORS_ORIGINS=*)
  Origin=https://page.example -> handshake accepted, socket open
  Origin=http://127.0.0.1:18941 -> handshake accepted, socket open
  == this branch (HEADROOM_CORS_ORIGINS=*)
  Origin=https://page.example -> handshake refused HTTP 403
  Origin=http://127.0.0.1:18942 -> handshake accepted, socket open
  ```
- Not tested: `/v1/live` end to end (same helper, covered by the unit
tests' shared code path).

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: only for operators who set `*` in
`HEADROOM_WS_ORIGINS` or `HEADROOM_CORS_ORIGINS`. Native clients (Codex,
SDKs) send no Origin and are unaffected; loopback pages still connect.
- Kill switch / disable path: list the browser origins that need the
WebSocket routes explicitly 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
- [ ] 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

`HEADROOM_WS_ORIGINS` is not documented anywhere, so there was no doc to
update. A companion PR applies the same Origin rule to the HTTP routes;
once both land, `*` is ignored there too because they share
`_is_allowed_websocket_origin`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4846"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

Reported by @JoaoMarcos44. Thank you for your contribution! 🩵

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-11-17 09:48:30 +05:30

114 lines
4.4 KiB
Python

"""CORS scoping tests.
The proxy binds on localhost and serves content endpoints (e.g. ``/v1/retrieve``
returns raw, uncompressed tool outputs). A wildcard CORS origin combined with
``allow_credentials=True`` let any web page the user had open read those
responses via a cross-origin fetch to ``127.0.0.1`` (CWE-346). The default
policy must allow only loopback origins — on *any* port, since the bound port
lives in the CLI/uvicorn layer, not in ``ProxyConfig`` — while still offering an
explicit override for Docker / remote-dashboard deployments. See #863 / #864.
"""
from __future__ import annotations
import httpx
import pytest
from fastapi.testclient import TestClient
from headroom.proxy.server import ProxyConfig, create_app
def _make_client() -> TestClient:
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,
)
return TestClient(create_app(config))
def _preflight(client: TestClient, origin: str) -> httpx.Response:
"""Send a CORS preflight; CORSMiddleware answers it directly."""
return client.options(
"/v1/messages",
headers={"Origin": origin, "Access-Control-Request-Method": "POST"},
)
@pytest.mark.parametrize(
"origin",
[
"http://localhost:8787",
"http://127.0.0.1:8787",
"http://localhost:9000", # non-default port — must still be allowed
"http://127.0.0.1:54321",
"https://localhost:8787",
"http://[::1]:8787", # IPv6 loopback
"http://localhost", # no explicit port
],
)
def test_loopback_origins_allowed_on_any_port(monkeypatch: pytest.MonkeyPatch, origin: str) -> None:
monkeypatch.delenv("HEADROOM_CORS_ORIGINS", raising=False)
resp = _preflight(_make_client(), origin)
assert resp.status_code == 200, resp.text
assert resp.headers.get("access-control-allow-origin") == origin
# The original vulnerability was wildcard + credentials; credentials stay off.
assert resp.headers.get("access-control-allow-credentials") != "true"
@pytest.mark.parametrize(
"origin",
[
"http://evil.com",
"https://attacker.example",
"http://localhost.evil.com", # suffix smuggling
"http://127.0.0.1.evil.com",
"http://notlocalhost", # prefix smuggling
],
)
def test_cross_origin_pages_rejected(monkeypatch: pytest.MonkeyPatch, origin: str) -> None:
monkeypatch.delenv("HEADROOM_CORS_ORIGINS", raising=False)
resp = _preflight(_make_client(), origin)
# A disallowed origin is never echoed back, so the browser blocks the read.
assert resp.headers.get("access-control-allow-origin") != origin
def test_explicit_allowlist_override(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("HEADROOM_CORS_ORIGINS", "https://dash.example.com, http://10.0.0.5:3000")
client = _make_client()
allowed = _preflight(client, "https://dash.example.com")
assert allowed.status_code == 200
assert allowed.headers.get("access-control-allow-origin") == "https://dash.example.com"
# Once an explicit list is set, loopback is no longer implicitly trusted.
blocked = _preflight(client, "http://localhost:8787")
assert blocked.headers.get("access-control-allow-origin") != "http://localhost:8787"
def test_wildcard_optback(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("HEADROOM_CORS_ORIGINS", "*")
monkeypatch.delenv("HEADROOM_WS_ORIGINS", raising=False)
client = _make_client()
# "*" widens which pages may read a response; it does not let a foreign
# page drive the proxy, so the security gate refuses it before CORS runs.
foreign = _preflight(client, "http://evil.com")
assert foreign.status_code == 403
assert foreign.headers.get("access-control-allow-origin") is None
refused_post = client.post("/v1/messages", content="{}", headers={"Origin": "http://evil.com"})
assert refused_post.status_code == 403
# A page the proxy trusts still gets the wildcard answer.
local = _preflight(client, "http://127.0.0.1:8787")
assert local.status_code == 200
assert local.headers.get("access-control-allow-origin") == "*"
# Wildcard opt-back must not silently re-enable credentialed reads.
assert local.headers.get("access-control-allow-credentials") != "true"