fix(proxy): reject a private x-headroom-base-url on chat and responses with 400 (#4857)

## Description

When the upstream guard rejected an `x-headroom-base-url` override (an
address on a private, loopback, link-local or otherwise non-public
network, or a host outside `HEADROOM_ALLOWED_BASE_URLS` in allowlist
mode), `_resolve_openai_upstream_base` logged a warning and returned
`None`. `/v1/chat/completions` and `/v1/responses` then sent the request
— the prompt and the client's `Authorization`, meant for the gateway the
client named — to the configured `OPENAI_API_URL` instead. Every other
route that reads the header (`headroom/providers/proxy_routes.py`:
Anthropic messages, Gemini, models, embeddings, audio, passthrough)
refuses with `400 Rejected unsafe upstream base URL`.

The OpenAI chat and responses handlers now refuse the same way.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [x] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update

## Changes Made

- `headroom/proxy/handlers/openai.py`: `_resolve_openai_upstream_base`
raises `HTTPException(400, "Rejected unsafe upstream base URL")` instead
of returning `None` when the guard rejects the override (malformed /
non-http(s) values are unchanged: still ignored).
- `docs/content/docs/security-model.mdx`: one behaviour for all routes
(the page previously documented the two different outcomes).
-
`tests/test_upstream_guard.py::test_openai_routes_refuse_a_private_override_instead_of_using_the_default[chat|responses]`:
real app, configured OpenAI target is a local recording server; asserts
400 and that the configured target is never contacted.

**Sibling PRs that touch the same code** (merge order note):
`fix/upstream-guard-off-loop` adds `_resolve_openai_upstream_base_async`
next to this function; whichever merges second must make the async
resolver raise the same 400 (that PR's rejection branch is the one place
to change). `fix/upstream-idna-pin-once` touches the call sites only.
Suggested order: idna-pin-once, off-loop, then this PR rebased.

## 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: {"secret":"internal-only"}
E   assert 200 == 400                (chat: answered by the configured target)
E   assert 200 == 400                (responses: answered by the configured target)
======================= 2 failed, 61 deselected in 5.64s =======================

# This branch
======================= 2 passed, 61 deselected in 5.81s =======================

# 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_loopback_gating
================= 429 passed, 10 warnings in 87.64s (0:01:27) ==================

$ ruff check / ruff format --check (0.17.3) on changed files
All checks passed!
2 files already formatted
```

## Real Behavior Proof

- Environment: macOS, Python 3.12, `python -m headroom.cli proxy
--no-optimize` from this branch and from origin/main,
`OPENAI_TARGET_API_URL` pointing at a local server that records every
request it receives.
- Exact command / steps:
`curl http://127.0.0.1:$PORT/v1/chat/completions -H 'authorization:
Bearer client-gateway-key' -H 'x-headroom-base-url:
http://192.168.1.50:8000/v1' -d '{"model":"gpt-4o","messages":[...]}'`,
and the same for `/v1/responses`.
- Observed result:
  ```text
  == origin/main
  POST /v1/chat/completions -> HTTP 200 {"...":"from-configured-target"}
  POST /v1/responses        -> HTTP 200 {"...":"from-configured-target"}
  configured target received:
    /v1/chat/completions auth= Bearer client-gateway-key
    /v1/responses        auth= Bearer client-gateway-key
  == this branch
POST /v1/chat/completions -> HTTP 400 {"detail":"Rejected unsafe
upstream base URL"}
POST /v1/responses -> HTTP 400 {"detail":"Rejected unsafe upstream base
URL"}
  configured target received: (nothing)
  ```
- Not tested: Codex WebSocket responses path (it does not read this
header).

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: **yes.** A client that sends
`x-headroom-base-url` pointing at a private/LAN/loopback address (or, in
allowlist mode, an unlisted host) to `/v1/chat/completions` or
`/v1/responses` now gets a 400 instead of having its request answered by
the configured OpenAI target. Such a request never reached the host the
client named, so the only working setups affected are ones that relied
on the silent fallback. A DNS lookup that fails or times out for a
public gateway is also a rejection, so it now surfaces as a 400 instead
of quietly sending the request to the default target.
- Kill switch / disable path: operators who route to an internal gateway
add it to `HEADROOM_ALLOWED_BASE_URLS` (existing setting); clients can
drop the header to use the configured target.
- 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: the OpenCode plugin
(`plugins/opencode/src/transport.ts`, `isRoutableUpstream`) only keeps
loopback upstreams out of the proxy, so an OpenCode provider on a LAN
address is still routed through Headroom, which now answers 400 for it
(previously the request went to the default OpenAI target). Sending
private-network upstreams direct needs a source change plus regenerating
the committed bundles (`headroom/providers/opencode/_dist/index.js`,
`hook-shim/handler.js`), and hostnames that resolve to LAN addresses
cannot be recognised without DNS, so it is left for a separate PR.

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

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

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4857"
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:42 +05:30
committed by GitHub
co-authored by Claude Opus 5.5 JerrettDavis
parent 2f58877732
commit 491afe98b1
4 changed files with 53 additions and 17 deletions
+7 -8
View File
@@ -53,15 +53,14 @@ and two separate guards bound it.
on a private, loopback, link-local, or otherwise non-public address: the confused-deputy
case where the proxy is used to reach cloud metadata (`169.254.169.254`) or RFC1918
hosts the caller cannot reach directly. NAT64-embedded IPv4 is unwrapped before the
check, so it cannot be smuggled through an IPv6 literal. What happens to a rejected
override depends on the route. The OpenAI Chat Completions and Responses handlers
(`/v1/chat/completions`, `/v1/responses` and their unprefixed and Codex/ChatGPT-backend
aliases) **ignore** it: the request proceeds to the configured upstream and a warning
is logged. The other routes that read the header **reject** the request with HTTP 400
(`Rejected unsafe upstream base URL`) before contacting any upstream: Anthropic
check, so it cannot be smuggled through an IPv6 literal. Every route that reads the
header **rejects** such a request with HTTP 400 (`Rejected unsafe upstream base URL`)
and logs a warning, before contacting any upstream: the OpenAI Chat Completions and
Responses handlers (with their unprefixed and Codex/ChatGPT-backend aliases), Anthropic
Messages and token counting, the native Gemini routes, model listing, embeddings,
moderations, audio, and the generic passthrough. A client that sends an unsafe override
should be ready for either outcome. `HEADROOM_ALLOWED_BASE_URLS` (comma-separated hosts or URLs)
moderations, audio, and the generic passthrough. The request is never sent to the
configured upstream instead, since it carries a prompt and an `Authorization` meant for
the gateway the client named. `HEADROOM_ALLOWED_BASE_URLS` (comma-separated hosts or URLs)
re-permits specific internal endpoints as an explicit operator choice: a bare host
permits every safe scheme and port on that host, a full URL permits only its exact
normalized origin. DNS resolution is bounded by `HEADROOM_UPSTREAM_RESOLVE_TIMEOUT_S`
+8 -5
View File
@@ -532,11 +532,14 @@ def _resolve_openai_upstream_base(request_headers: dict[str, str]) -> str | 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
# configured upstream; set HEADROOM_ALLOWED_BASE_URLS to permit specific
# internal endpoints.
logger.warning("ignoring unsafe x-headroom-base-url override: %r", raw_base_url)
return None
# cloud-metadata address. Refuse, as the other routes do: falling back to
# the configured upstream would send the prompt and the Authorization
# meant for the named gateway to a host the client did not choose. Set
# HEADROOM_ALLOWED_BASE_URLS to permit specific internal endpoints.
from fastapi import HTTPException
logger.warning("rejecting unsafe x-headroom-base-url: %r", raw_base_url)
raise HTTPException(status_code=400, detail="Rejected unsafe upstream base URL")
return normalized
+7 -4
View File
@@ -343,12 +343,15 @@ def test_the_base_url_override_is_resolved_once_per_request(
{**_OPENAI_CLIENT_HEADERS, "x-headroom-base-url": "https://changing.example/v1"},
path="/v1/chat/completions" if handle == "handle_openai_chat" else "/v1/responses",
)
anyio.run(getattr(handler, handle), request)
from fastapi import HTTPException
# The single lookup answers with a private address, so the override is refused.
with pytest.raises(HTTPException) as refused:
anyio.run(getattr(handler, handle), request)
assert refused.value.status_code == 400
assert calls == ["changing.example"], f"the override was resolved {len(calls)} times"
if handler.captured_request is not None:
outbound = _outbound(handler.captured_request)
assert "changing.example" not in outbound.url, outbound.url
assert handler.captured_request is None, "the request was sent somewhere"
def _run_image_chat(monkeypatch: pytest.MonkeyPatch, *, expire_pins: bool) -> dict[str, list[Any]]:
+31
View File
@@ -1050,6 +1050,37 @@ async def test_a_proxied_client_still_pins_its_direct_transport(
await client.aclose()
@pytest.mark.parametrize("path", ["/v1/chat/completions", "/v1/responses"])
def test_openai_routes_refuse_a_private_override_instead_of_using_the_default(
path: str, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A rejected ``x-headroom-base-url`` is a 400, like on the other routes.
Dropping the header and continuing sent the prompt and the client's
Authorization, meant for its own gateway, to the configured OpenAI target.
"""
monkeypatch.delenv("HEADROOM_ALLOWED_BASE_URLS", raising=False)
with (
_InternalService() as configured,
TestClient(_app(openai_api_url=configured.url)) as client,
):
response = client.post(
path,
headers={
"Authorization": "Bearer client-gateway-key",
"x-headroom-base-url": "http://192.168.1.50:8000/v1",
},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": "hi"}],
"input": "hi",
},
)
assert response.status_code == 400, response.text
assert configured.hits == [], "the request went to the configured upstream instead"
# ---------------------------------------------------------------------------
# A non-ASCII host is checked and pinned under the name httpcore connects with
# ---------------------------------------------------------------------------