fix(proxy): check x-headroom-base-url off the event loop in chat and responses (#4856)

## Description

`handle_openai_chat` and `handle_openai_responses` validated
`x-headroom-base-url` with the synchronous `is_safe_upstream_url`, which
waits for the DNS lookup (up to `HEADROOM_UPSTREAM_RESOLVE_TIMEOUT_S`, 3
s by default) on the event-loop thread. Chat did this three times per
request and responses twice, so one slow-resolving host held up every
other in-flight request for several seconds. The other routes in
`headroom/providers/proxy_routes.py` already use
`is_safe_upstream_url_async`.

Both handlers now resolve the header once, through a new
`_resolve_openai_upstream_base_async` that uses the async guard (lookup
on a worker thread, pin scope opened on the request's task), and reuse
that result for the destination and the extra-header decision.

## Type of Change

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

## Changes Made

- `headroom/proxy/handlers/openai.py`: header parsing split into
`_openai_base_url_candidate`; sync `_resolve_openai_upstream_base` (kept
for `_resolve_openai_upstream`) and new
`_resolve_openai_upstream_base_async` share it;
`_openai_upstream_from(request, custom)` picks the upstream from an
already-resolved override; chat and responses call the async resolver
once.
- `tests/test_proxy/test_openai_upstream_guard_off_loop.py`: asserts the
guard runs once and not on the event-loop thread, for chat and
responses.
- `tests/test_proxy_openai_cache_key_integration.py`: its stub now
patches the async resolver the handler calls.

**Sibling PRs that touch the same code** (merge order note):
`fix/upstream-idna-pin-once` adds the identical `_openai_upstream_from`
and resolve-once hunks (this PR is a superset of that part);
`fix/openai-base-url-reject` changes the rejection branch of
`_resolve_openai_upstream_base`, which after this PR must be mirrored in
`_resolve_openai_upstream_base_async`. Suggested order: idna-pin-once,
then this PR, then reject (rebasing reject means raising the 400 from
the shared rejection path in both resolvers).

## 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 on origin/main (c21b0813)
E   AssertionError: the guard ran on the event-loop thread
E   assert [True, True, True] == [False]      (chat)
E   assert [True, True] == [False]            (responses)
============================== 2 failed in 0.72s ===============================

# This branch: new test + cache-key integration
============================== 7 passed in 7.30s ===============================

# Area suites: test_upstream_guard, test_grok_shared_proxy_call_sites, test_proxy/test_openai_upstream_header,
# test_proxy_openai_cache_key_integration, test_upstream_credential_scoping, test_header_isolation,
# test_proxy_hardening, test_openai_codex_routing, test_proxy/test_openai_upstream_guard_off_loop
======================= 282 passed, 5 warnings in 56.32s =======================

$ ruff check / ruff format --check (0.17.3) on changed files
All checks passed!
3 files already formatted
$ 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, full app from `create_app` driven
through `httpx.ASGITransport` on one event loop; `socket.getaddrinfo`
replaced so `slow.example` takes 2 s to answer (everything else real).
- Exact command / steps: start a `/v1/chat/completions` request with
`x-headroom-base-url: https://slow.example/v1`, then 0.2 s later send
`GET /livez` and time it.
- Observed result:
  ```text
  == origin/main
/livez sent 0.2s after a chat request naming a 2s-to-resolve host: HTTP
200 after 6.03s (0.20s if the loop is free)
  == this branch
/livez sent 0.2s after a chat request naming a 2s-to-resolve host: HTTP
200 after 0.20s (0.20s if the loop is free)
  ```
- Not tested: under real slow DNS.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: no change in which upstream is
chosen; the lookup moves to a worker thread and happens once per
request.
- Kill switch / disable path: none needed
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert

## 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

Fix adapted from a proposal by HetCreep.

Follow-up, not in this PR: `select_passthrough_base_url`
(`headroom/providers/proxy_targets.py`, Azure `api-key` branch) and
`headroom/providers/registry.py` still call the sync guard; the
passthrough route already checks the same header with the async guard
first, so the sync call there is a second lookup on the loop.

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

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

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4856"
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>
This commit is contained in:
Tejas Chopra
2026-11-15 01:52:37 +05:30
committed by GitHub
co-authored by Claude Opus 5.5 JerrettDavis
parent c8b3d67715
commit 2f58877732
4 changed files with 90 additions and 7 deletions
+29 -3
View File
@@ -503,7 +503,8 @@ def _resolve_openai_handler_path(
return parsed.path
def _resolve_openai_upstream_base(request_headers: dict[str, str]) -> str | None:
def _openai_base_url_candidate(request_headers: dict[str, str]) -> tuple[str, str] | None:
"""Return ``(raw, normalized)`` for an ``x-headroom-base-url`` override, before the guard."""
raw_base_url = _header_get(request_headers, _OPENAI_BASE_URL_HEADER)
if raw_base_url is None:
return None
@@ -521,6 +522,14 @@ def _resolve_openai_upstream_base(request_headers: dict[str, str]) -> str | None
if urlparse(normalized).scheme not in {"http", "https"}:
return None
return raw_base_url, normalized
def _resolve_openai_upstream_base(request_headers: dict[str, str]) -> str | None:
candidate = _openai_base_url_candidate(request_headers)
if candidate is None:
return None
raw_base_url, normalized = candidate
if not is_safe_upstream_url(normalized):
# Client-supplied upstream resolves to a private/loopback/link-local or
# cloud-metadata address (SSRF). Ignore the override and fall back to the
@@ -531,6 +540,23 @@ def _resolve_openai_upstream_base(request_headers: dict[str, str]) -> str | None
return normalized
async def _resolve_openai_upstream_base_async(request_headers: dict[str, str]) -> str | None:
""":func:`_resolve_openai_upstream_base` for the async request handlers.
The guard resolves the client-chosen host with a blocking wait; the async
form runs that lookup on a worker thread so a slow-resolving host does not
hold up every other request on the event loop.
"""
candidate = _openai_base_url_candidate(request_headers)
if candidate is None:
return None
raw_base_url, normalized = candidate
if not await is_safe_upstream_url_async(normalized):
logger.warning("ignoring unsafe x-headroom-base-url override: %r", raw_base_url)
return None
return normalized
def _upstream_pin_lapsed(url: str) -> bool:
"""True when this request pinned ``url``'s host and that pin has expired."""
pin = guarded_pin(urlparse(url).hostname or "")
@@ -3641,7 +3667,7 @@ class OpenAIHandlerMixin:
)
model = body.get("model", "unknown")
messages = body.get("messages", [])
custom_upstream_base_url = _resolve_openai_upstream_base(request.headers)
custom_upstream_base_url = await _resolve_openai_upstream_base_async(request.headers)
upstream_base_url = self._openai_upstream_from(request, custom_upstream_base_url)
# Ghost text and next edits: CAPI does not serve these models. A
# caller-chosen x-headroom-base-url is left alone, as in
@@ -6420,7 +6446,7 @@ class OpenAIHandlerMixin:
# cannot ride a Grok request to api.x.ai. Mixed ChatGPT-auth plus
# Grok signals still withhold extras, even though the ChatGPT branch
# below sends the request to chatgpt.com.
custom_upstream_base_url = _resolve_openai_upstream_base(request.headers)
custom_upstream_base_url = await _resolve_openai_upstream_base_async(request.headers)
upstream_base_url = custom_upstream_base_url
openai_upstream_base_url = self._openai_upstream_from(request, custom_upstream_base_url)
headers = merge_extra_headers(
@@ -0,0 +1,50 @@
"""The OpenAI chat and responses handlers check ``x-headroom-base-url`` off the event loop.
``is_safe_upstream_url`` waits on a DNS lookup. Called from an ``async def``
handler it holds the event-loop thread for that wait, so one slow-resolving
host delays every other in-flight request.
"""
from __future__ import annotations
import asyncio
import pytest
from tests.test_grok_shared_proxy_call_sites import _run_chat, _run_responses
from tests.test_openai_codex_routing import _DummyTokenizer
_HEADERS = {
"Authorization": "Bearer sk-test",
"User-Agent": "codex-tui/0.146.0",
"x-headroom-base-url": "https://gateway.example/v1",
}
@pytest.fixture
def guard_calls(monkeypatch: pytest.MonkeyPatch) -> list[bool]:
"""Record, for each guard call, whether it ran on the event-loop thread."""
monkeypatch.delenv("HEADROOM_ALLOWED_BASE_URLS", raising=False)
calls: list[bool] = []
def _recording_guard(url: str, *, scope: object = None) -> bool:
try:
asyncio.get_running_loop()
except RuntimeError:
calls.append(False)
else:
calls.append(True)
return True
monkeypatch.setattr("headroom.proxy.upstream_guard.is_safe_upstream_url", _recording_guard)
monkeypatch.setattr("headroom.proxy.handlers.openai.is_safe_upstream_url", _recording_guard)
monkeypatch.setattr("headroom.tokenizers.get_tokenizer", lambda model: _DummyTokenizer())
return calls
@pytest.mark.parametrize("run", [_run_chat, _run_responses], ids=("chat", "responses"))
def test_the_override_is_checked_off_the_event_loop(run, guard_calls: list[bool]) -> None: # noqa: ANN001
outbound = run(_HEADERS, model="gpt-4o")
assert outbound.url.startswith("https://gateway.example/v1")
assert guard_calls == [False], "the guard ran on the event-loop thread"
@@ -120,9 +120,11 @@ def test_openai_different_custom_upstream_not_served_from_cache(monkeypatch) ->
"""Two OpenAI-compatible gateways must not share a response entry (#3346)."""
calls: list[str] = []
async def _custom_base(headers): # noqa: ANN001
return headers.get("x-headroom-base-url")
monkeypatch.setattr(
"headroom.proxy.handlers.openai._resolve_openai_upstream_base",
lambda headers: headers.get("x-headroom-base-url"),
"headroom.proxy.handlers.openai._resolve_openai_upstream_base_async", _custom_base
)
with _make_cached_proxy_client() as client:
+7 -2
View File
@@ -1115,13 +1115,18 @@ def test_openai_chat_custom_base_reports_zai_as_outcome_provider(
assert captured.get("outcome_provider") == "zai"
async def _always_safe(url: str) -> bool:
"""Stand-in for the async upstream guard the chat handler awaits."""
return True
def test_openai_chat_outcome_provider_uses_the_fixed_taxonomy(
monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path
) -> None:
"""Buffered chat labels each custom base from the fixed set, never the host."""
# Keep the SSRF guard out of the way: these hosts are deliberately
# unresolvable, and a DNS miss makes the handler ignore the override.
monkeypatch.setattr("headroom.proxy.handlers.openai.is_safe_upstream_url", lambda url: True)
monkeypatch.setattr("headroom.proxy.handlers.openai.is_safe_upstream_url_async", _always_safe)
# Keep the lifetime savings store out of the user's real on-disk state.
monkeypatch.setenv("HEADROOM_SAVINGS_PATH", str(tmp_path / "savings.json"))
with _make_proxy_client() as client:
@@ -1196,7 +1201,7 @@ def test_openai_chat_custom_base_flood_cannot_grow_the_provider_set(
limited_auth = "Bearer rate-limited"
# The flood hosts are unresolvable on purpose; without this stub the SSRF
# guard would drop the override and relabel the flood as "openai".
monkeypatch.setattr("headroom.proxy.handlers.openai.is_safe_upstream_url", lambda url: True)
monkeypatch.setattr("headroom.proxy.handlers.openai.is_safe_upstream_url_async", _always_safe)
# Bucket by the raw credential so the stub limiter below can refuse just
# ``limited_auth``; the identity rule itself is covered by its own tests.
monkeypatch.setattr(