Commit Graph
3 Commits
Author SHA1 Message Date
491afe98b1 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>
2026-11-15 01:52:42 +05:30
904e56a357 fix(proxy): pin non-ASCII upstream hosts by A-label and resolve x-headroom-base-url once (#4855)
## Description

Two related fixes for client-chosen upstreams (`x-headroom-base-url`).

1. **Non-ASCII hosts.** The upstream guard resolved and pinned a host
under the spelling the client sent (e.g. `évil.test`), but httpx
IDNA-encodes the host and httpcore asks
`PinnedAddressBackend.connect_tcp` for the A-label (`xn--vil-9la.test`).
The pin lookup missed, the destination looked "never checked", and the
name was resolved a second time at connect. `socket.getaddrinfo` also
encodes Unicode names with IDNA 2003, which spells some names
differently from httpx's IDNA 2008 (`straße` → `strasse` vs
`xn--strae-oqa`), so the check could look up a different name from the
one dialled. The guard now converts the host to the A-label httpx will
use, resolves that name and pins under it; `guarded_pin` normalises the
same way, so either spelling finds the pin.
2. **One resolution per request.** `handle_openai_chat` resolved
`x-headroom-base-url` three times and `handle_openai_responses` twice.
Each resolution is a separate DNS lookup, so the destination and the
extra-header trust check could be decided from different answers, and
operator extra headers could be merged for a destination different from
the one validated. Both handlers now resolve once and pass that result
to a new `_openai_upstream_from(request, custom)`;
`_resolve_openai_upstream` keeps its behaviour by delegating to it.

## Type of Change

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

## Changes Made

- `headroom/proxy/upstream_guard.py`: `_connect_name()` (lower-case IDNA
A-label via `httpx.URL`, ASCII hosts unchanged); `is_safe_upstream_url`
resolves and pins that name and rejects a host that cannot be encoded;
`guarded_pin` looks up by the same key.
- `headroom/proxy/handlers/openai.py`: `_openai_upstream_from`; chat and
responses reuse the single `custom_upstream_base_url`; the second lookup
later in chat is removed.
- Tests:
`tests/test_upstream_guard.py::test_a_non_ascii_host_is_resolved_and_pinned_under_its_connect_name`,
`tests/test_grok_shared_proxy_call_sites.py::test_the_base_url_override_is_resolved_once_per_request[chat|responses]`.

**Sibling PRs that touch the same code** (merge order note): the
off-loop guard PR (`fix/upstream-guard-off-loop`) contains the identical
`_openai_upstream_from` / resolve-once hunks plus the async resolver, so
it should rebase cleanly on top of this one; the 400-on-rejection PR
(`fix/openai-base-url-reject`) edits `_resolve_openai_upstream_base`.
Suggested order: this PR, then off-loop, then reject.

## 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 (c21b0813)
E   AssertionError: assert ['straße.example'] == ['xn--strae-oqa.example']
E   AssertionError: the override was resolved 3 times     (chat)
E   AssertionError: the override was resolved 2 times     (responses)
============================== 3 failed in 7.66s ===============================

# Same tests on this branch
tests/test_upstream_guard.py .                                           [ 33%]
tests/test_grok_shared_proxy_call_sites.py ..                            [100%]
============================== 3 passed in 6.94s ===============================

# 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
================= 283 passed, 5 warnings in 122.32s (0:02:02) ==================

$ ruff check / ruff format --check (0.17.3) on changed files
All checks passed!
4 files already formatted
$ mypy headroom/proxy/upstream_guard.py headroom/proxy/handlers/openai.py --ignore-missing-imports
Success: no issues found in 2 source files
```

## Real Behavior Proof

- Environment: macOS, Python 3.12, `create_app` + `TestClient` with the
real guard, real `PinnedAddressBackend` and a real local HTTP server on
127.0.0.1; only `socket.getaddrinfo` is replaced, answering `8.8.8.8`
for the Unicode name and `127.0.0.1` for its A-label (a resolver that
answers differently per spelling).
- Exact command / steps: POST to a passthrough route with
`x-headroom-base-url: http://évil.test:<port>` (raw byte on the wire),
on origin/main and on this branch.
- Observed result:
  ```text
  == origin/main
  RESULT (200, '{"secret":"internal-only"}')
DNS ['évil.test', 'xn--vil-9la.test'] # checked one name, connected by
resolving another
  HITS ['/internal/admin/canary?mode=mutate']
  == this branch
  RESULT (400, '{"detail":"Rejected unsafe upstream base URL"}')
DNS ['xn--vil-9la.test'] # one lookup, of the name that would be dialled
  HITS []
  ```
- Not tested: live public IDN domains.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: ASCII hosts unchanged. Non-ASCII
hosts are now resolved by their A-label (the name that is actually
dialled). A host httpx cannot IDNA-encode is rejected by the guard
(httpx could not connect to it anyway).
- 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. The resolver now also looks up
the A-label itself (not just pins under it), which closes the IDNA
2003/2008 spelling difference.

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

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

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4855"
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 -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-11-14 10:46:16 +05:30
PeterandJerrett Davis ef1c528e92 fix(grok): route CLI traffic to api.x.ai on shared proxies (#2693)
## Description

`headroom wrap grok` points the Grok CLI at the local proxy via
`GROK_MODELS_BASE_URL` and, when it starts the proxy, sets
`openai_api_url=https://api.x.ai`. When Claude/Codex already own port
8787, wrap reuses that process without restart (other wrappers
attached), so process-wide `OPENAI_API_URL` stays
`https://api.openai.com`.

Grok CLI cannot stamp `x-headroom-base-url` (no custom attribution
headers). Inference then goes to OpenAI with xAI session tokens and
returns 401. Observed on the wire:

- `x-xai-token-auth: xai-grok-cli`
- `user-agent: grok-pager/... grok-shell/...`
- outbound `POST https://api.openai.com/v1/chat/completions` status 401

This PR adds per-request Grok CLI detection and routes chat / models /
responses to `https://api.x.ai` when those signals are present and the
OpenAI target is still its default, without restarting the shared proxy
or changing Claude/Codex paths. An operator-configured gateway is never
bypassed.

Not covered by #2626 (attribution / UA map only when custom base is
already `api.x.ai`).

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

- Add `is_grok_cli_request()` in `providers/grok/runtime.py` using
narrow wire signals: exact `x-xai-token-auth: xai-grok-cli` and the
`grok-pager/` / `grok-shell/` UA product tokens, compared per
whitespace-split token so wrappers like `litellm-grok/1.0` cannot match
- Resolve OpenAI chat and responses final upstream as:
`x-headroom-base-url` then Grok CLI then process `OPENAI_API_URL`
- Route `GET /v1/models` and OpenAI-classified passthrough through the
same Grok to xAI base
- Add unit tests for detector, resolver priority, and passthrough/models
base selection
- Add `tests/test_grok_shared_proxy_call_sites.py`, which drives
`handle_openai_chat` and `handle_openai_responses` against a stubbed
transport and asserts the outbound URL — reverting either call site to
the old `custom_only or OPENAI_API_URL` formula turns these red
- Gate Grok to xAI routing on the OpenAI target still being its default,
via one shared `route_grok_to_xai()` predicate used by both the
chat/responses resolver and the models/passthrough path, so an
operator-configured gateway is never bypassed

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check` / `ruff format`)
- [x] New tests added for new functionality when applicable
- [x] Manual testing performed

### Test Output

```text
# Grok routing: call sites, detector, resolver priority, passthrough/models
uv run pytest tests/test_grok_shared_proxy_call_sites.py \
  tests/test_provider_grok.py tests/test_provider_proxy_targets.py \
  tests/test_proxy/test_openai_upstream_header.py \
  tests/test_openai_codex_routing.py -q
============================== 48 passed in 0.46s ==============================

uv run ruff check .
All checks passed!

uv run ruff format --check .
1331 files already formatted

uv run mypy headroom --ignore-missing-imports
Success: no issues found in 506 source files

# Full suite (uv, Python 3.14, tests + scripts/tests) — honesty note
==== 15 failed, 9480 passed, 592 skipped in 553.64s ====
# Replaying those 15 as a set gives an identical 11 failed / 4 passed at the
# merge base, at HEAD~1 and at HEAD, so this branch introduces no failure.
# Causes are local-env: missing cargo, missing litellm extra, Windows-only
# asyncio path, AF_UNIX path length. The 4 test_proxy_health.py kompress tests
# pass in isolation at every ref and fail only under the full suite
# (pre-existing ordering pollution; the new test file is not the cause --
# it runs clean immediately before test_proxy_health.py).
# tests/test_memory_eval.py excluded: it imports litellm at collection time.
# Fork CI pytest not yet run (action_required until maintainer approves).
```

## Real Behavior Proof

- Environment: macOS arm64; Grok CLI 0.2.117; PR branch
`fix/grok-shared-proxy-xai-routing` (0.33.1-dev) running as the only
proxy on 8787 with `openai_api_url=null` and `--backend anthropic` (same
shared-proxy shape as Claude/Codex-started 8787). Stock Headroom 0.33.0
was first used to capture the before failure.
- Exact command / steps: 1) Before: with stock 0.33.0 on 8787, run
`headroom wrap grok` (or attach via `GROK_MODELS_BASE_URL`) and inspect
`~/.headroom/logs/proxy.log`. 2) After: replace the process with this
branch (`uv run python -m headroom.cli proxy --host 127.0.0.1 --port
8787 --backend anthropic`, no OpenAI target override). 3)
`GROK_MODELS_BASE_URL=http://127.0.0.1:8787/v1 grok -p "Reply with
exactly one word: pong" --always-approve`. 4) Confirm health still shows
`openai_api_url: null` and inspect proxy log outbound lines.
- Observed result: Before (stock): Grok chat with `x-xai-token-auth:
xai-grok-cli` forwarded to `https://api.openai.com/v1/chat/completions`
→ 401. After (this branch): same Grok CLI on the same port; `/v1/models`
for `user-agent: grok-shell/0.2.117` returned 200; chat outbound was
`POST path=https://api.x.ai/v1/chat/completions` with status 200; CLI
printed `pong` and exited 0. Codex models list against the same proxy
still returned 200.
- Not tested: multi-day soak with Claude + Codex + Grok all attached for
hours; production PyPI release build; full-suite green under fork CI
(local full run had 7 env-only failures unrelated to this change);
savings attribution still labels provider as openai without custom base
(orthogonal, #2626).

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

## Screenshots (if applicable)

N/A — evidence is CLI output and proxy logs (redacted auth).

## Additional Notes

- Explicitly out of scope: savings attribution as `provider=xai` without
custom base (see #2626), multi-provider matrix for Kimi/Mistral,
hard-coded per-agent ports.
- ChatGPT Codex auth still wins on `/v1/responses` before this chain
runs.
- Priority: `x-headroom-base-url` > Grok CLI signals (only while
`OPENAI_API_URL` is still the default) > process OpenAI default. The
gate matters because an operator who points the proxy at a gateway
(LiteLLM, Azure, self-hosted vLLM) chose it for every OpenAI-compatible
client: a client User-Agent must not silently bypass it, nor carry that
gateway's `OPENAI_TARGET_API_HEADERS` to a different vendor. The
shared-proxy case this PR fixes runs with `openai_api_url: null`, so it
is unaffected.
- Fork PR workflows may show `action_required` until a maintainer
approves first-time external CI runs.
## Runtime Rollout Safety

- Rollout-managed feature(s): none; routing is selected per request from
narrow Grok CLI wire signals.
- Minimum rollout channel: normal stable release after focused routing
and credential-isolation coverage passes.
- Stable/default behavior changed: only Grok-fingerprinted requests on a
proxy whose OpenAI target remains the default route to api.x.ai;
explicit client base URLs and operator-configured gateways retain
priority.
- Kill switch / disable path: use an explicit non-default OpenAI
gateway/target, or human-revert this routing change.
- Unsafe override required: none.
- Qualification impact: Grok chat, Responses, models, passthrough, and
cross-vendor header-isolation regressions must remain green.
- Rollback path: human-revert the PR; no persisted state or migration is
involved.

---------

Co-authored-by: Jerrett Davis <mxjerrett@gmail.com>
2026-10-01 00:11:46 -05:00