From d9ae7ad7219d19f32eec10d3dfd1ea2eb6331ff3 Mon Sep 17 00:00:00 2001 From: Tejas Chopra Date: Tue, 17 Nov 2026 09:48:30 +0530 Subject: [PATCH] fix(proxy): stop a "*" origin setting from waiving the WebSocket Origin check (#4846) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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:/v1/responses` with the `websockets` client, once with `Origin: https://page.example` and once with `Origin: http://127.0.0.1:`. - 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 Reported by @JoaoMarcos44. Thank you for your contribution! 🩵 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: JerrettDavis --- headroom/proxy/handlers/openai.py | 10 +++++--- tests/test_openai_codex_routing.py | 40 ++++++++++++++++++++++++++++++ tests/test_proxy_cors.py | 20 ++++++++++++--- 3 files changed, 62 insertions(+), 8 deletions(-) diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.py index 831bddb4a..38a0c5fdf 100644 --- a/headroom/proxy/handlers/openai.py +++ b/headroom/proxy/handlers/openai.py @@ -640,7 +640,11 @@ def _allowed_ws_origins_from_env() -> list[str] | None: raw = os.environ.get(_CORS_ALLOWED_ORIGINS_ENV) if raw is None or not raw.strip(): return None - return [origin.strip() for origin in raw.split(",") if origin.strip()] + # "*" is a CORS answer (which pages may read a response). It never waives + # the Origin check, which decides whether the proxy acts on the request at + # all, so it is dropped here; a list left empty means the loopback default. + origins = [origin.strip() for origin in raw.split(",") if origin.strip()] + return [origin for origin in origins if origin != "*"] or None def _is_loopback_ws_origin(origin: str) -> bool: @@ -657,7 +661,7 @@ def _is_allowed_websocket_origin(headers: dict[str, str]) -> bool: Native clients commonly omit Origin, so absence is allowed. When Origin is present, default to loopback-only and allow explicit configured origins via - HEADROOM_WS_ORIGINS or HEADROOM_CORS_ORIGINS. + HEADROOM_WS_ORIGINS or HEADROOM_CORS_ORIGINS. A ``*`` entry matches nothing. """ origin = _header_get(headers, "origin") if not origin: @@ -666,8 +670,6 @@ def _is_allowed_websocket_origin(headers: dict[str, str]) -> bool: allowed_origins = _allowed_ws_origins_from_env() if allowed_origins is None: return _is_loopback_ws_origin(origin) - if "*" in allowed_origins: - return True normalized_origin = _normalize_origin(origin) if normalized_origin is None: diff --git a/tests/test_openai_codex_routing.py b/tests/test_openai_codex_routing.py index bd919d252..c36d0bccf 100644 --- a/tests/test_openai_codex_routing.py +++ b/tests/test_openai_codex_routing.py @@ -953,6 +953,46 @@ def test_websocket_origin_policy_can_be_pinned_with_env(monkeypatch): assert _is_allowed_websocket_origin({"origin": "http://localhost:3000"}) is False +@pytest.mark.parametrize( + ("ws_origins", "cors_origins"), + [(None, "*"), ("*", None), (None, "*, https://dash.example.com")], +) +def test_websocket_origin_policy_ignores_wildcard(monkeypatch, ws_origins, cors_origins): + for name, value in ( + ("HEADROOM_WS_ORIGINS", ws_origins), + ("HEADROOM_CORS_ORIGINS", cors_origins), + ): + if value is None: + monkeypatch.delenv(name, raising=False) + else: + monkeypatch.setenv(name, value) + + assert _is_allowed_websocket_origin({"origin": "https://remote.example"}) is False + # A bare "*" leaves the loopback default in place. + if "dash.example.com" not in (cors_origins or ""): + assert _is_allowed_websocket_origin({"origin": "http://127.0.0.1:8787"}) is True + else: + assert _is_allowed_websocket_origin({"origin": "https://dash.example.com"}) is True + + +def test_handle_openai_responses_ws_closes_foreign_origin_under_wildcard_cors(monkeypatch): + monkeypatch.delenv("HEADROOM_WS_ORIGINS", raising=False) + monkeypatch.setenv("HEADROOM_CORS_ORIGINS", "*") + handler = _DummyOpenAIHandler() + websocket = _DummyWebSocket({"origin": "https://remote.example"}) + + with patch.dict(sys.modules, {"websockets": MagicMock()}): + with patch( + "headroom.proxy.handlers.openai._resolve_codex_routing_headers", + side_effect=AssertionError("routing should not run"), + ): + anyio.run(handler.handle_openai_responses_ws, websocket) + + assert websocket.closed is True + assert websocket.close_code == 1008 + assert websocket.close_reason == "origin not allowed" + + def test_handle_openai_responses_ws_resolves_codex_routing_headers(): class SentinelError(RuntimeError): pass diff --git a/tests/test_proxy_cors.py b/tests/test_proxy_cors.py index 384fc7876..8fa0cb80c 100644 --- a/tests/test_proxy_cors.py +++ b/tests/test_proxy_cors.py @@ -94,8 +94,20 @@ def test_explicit_allowlist_override(monkeypatch: pytest.MonkeyPatch) -> None: def test_wildcard_optback(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("HEADROOM_CORS_ORIGINS", "*") - resp = _preflight(_make_client(), "http://evil.com") - assert resp.status_code == 200 - assert resp.headers.get("access-control-allow-origin") == "*" + 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 resp.headers.get("access-control-allow-credentials") != "true" + assert local.headers.get("access-control-allow-credentials") != "true"