Files
headroom/tests/test_proxy/test_openai_upstream_header.py
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

169 lines
6.2 KiB
Python

"""Tests for ``OpenAIHandlerMixin._resolve_openai_upstream``.
The dedicated OpenAI handlers (``/v1/chat/completions``,
``/v1/responses``) must honor the ``x-headroom-base-url`` request header
so OpenAI-compatible gateways (LiteLLM, CPA, self-hosted vLLM, Azure
OpenAI) route correctly — consistent with the generic passthrough route
that already honors it (see ``providers/proxy_routes.py``).
These tests pin the resolution contract:
- header present → its value wins
- header absent → configured ``OPENAI_API_URL`` fallback
- header empty or whitespace-only → fallback (no blanking)
- Grok CLI wire signals → ``api.x.ai``, but only while the OpenAI target is
still the default (a configured gateway is never bypassed)
The chat/responses call sites are covered end to end in
``tests/test_grok_shared_proxy_call_sites.py``.
"""
from __future__ import annotations
import pytest
fastapi = pytest.importorskip("fastapi")
httpx = pytest.importorskip("httpx")
from starlette.datastructures import Headers # noqa: E402
from headroom.proxy.handlers.openai import OpenAIHandlerMixin # noqa: E402
@pytest.fixture(autouse=True)
def _allow_reserved_test_upstream(monkeypatch: pytest.MonkeyPatch) -> None:
"""Permit the reserved, intentionally unresolvable test origin."""
monkeypatch.setenv("HEADROOM_ALLOWED_BASE_URLS", "gateway.example")
class _FakeRequest:
"""Minimal stand-in exposing ``headers`` like a real Starlette request.
Uses ``starlette.datastructures.Headers`` so header lookup is
case-insensitive, matching the production ``request.headers`` — a
plain ``dict`` would let case-folding regressions pass silently.
"""
def __init__(self, headers: dict[str, str]) -> None:
self.headers = Headers(headers=headers)
def _stub_proxy(fallback_url: str) -> OpenAIHandlerMixin:
"""A bare mixin instance with only ``OPENAI_API_URL`` configured."""
return type( # type: ignore[return-value]
"_S",
(OpenAIHandlerMixin,),
{"OPENAI_API_URL": fallback_url},
)()
def test_header_overrides_configured_url() -> None:
proxy = _stub_proxy("https://api.openai.test")
# The transport sends the upstream origin (no /v1 path).
request = _FakeRequest({"x-headroom-base-url": "https://gateway.example"})
assert proxy._resolve_openai_upstream(request) == "https://gateway.example"
def test_missing_header_falls_back_to_configured_url() -> None:
proxy = _stub_proxy("https://api.openai.test")
request = _FakeRequest({})
assert proxy._resolve_openai_upstream(request) == "https://api.openai.test"
def test_empty_header_falls_back_to_configured_url() -> None:
"""An explicitly empty or whitespace-only header must not blank the upstream."""
proxy = _stub_proxy("https://api.openai.test")
empty = _FakeRequest({"x-headroom-base-url": ""})
assert proxy._resolve_openai_upstream(empty) == "https://api.openai.test"
whitespace = _FakeRequest({"x-headroom-base-url": " "})
assert proxy._resolve_openai_upstream(whitespace) == "https://api.openai.test"
def test_header_lookup_is_case_insensitive() -> None:
"""Transports may send mixed-case header names; lookup must still resolve."""
proxy = _stub_proxy("https://api.openai.test")
# Real transports routinely send Title-Case header names.
request = _FakeRequest({"X-Headroom-Base-Url": "https://gateway.example"})
assert proxy._resolve_openai_upstream(request) == "https://gateway.example"
def test_header_with_subpath_preserves_path() -> None:
"""A custom upstream served from a sub-path (e.g. /api/v1) must keep the path,
not be collapsed to the bare origin (#2047)."""
proxy = _stub_proxy("https://api.openai.test")
request = _FakeRequest({"x-headroom-base-url": "https://gateway.example/api/v1"})
assert proxy._resolve_openai_upstream(request) == "https://gateway.example/api/v1"
# Trailing slash is normalized away, not doubled.
trailing = _FakeRequest({"x-headroom-base-url": "https://gateway.example/api/v1/"})
assert proxy._resolve_openai_upstream(trailing) == "https://gateway.example/api/v1"
def test_grok_cli_routes_to_xai_when_process_default_is_openai() -> None:
"""Shared proxy started by Claude/Codex keeps OPENAI_API_URL=api.openai.com.
Grok CLI cannot stamp x-headroom-base-url; wire signals must still route
chat completions to api.x.ai so xAI session tokens are not sent to OpenAI.
"""
proxy = _stub_proxy("https://api.openai.com")
request = _FakeRequest(
{
"authorization": "Bearer redacted",
"x-xai-token-auth": "xai-grok-cli",
"user-agent": "grok-pager/0.2.117 grok-shell/0.2.117 (macos; aarch64)",
}
)
assert proxy._resolve_openai_upstream(request) == "https://api.x.ai"
def test_grok_cli_ua_alone_routes_to_xai() -> None:
proxy = _stub_proxy("https://api.openai.com")
request = _FakeRequest({"user-agent": "grok-shell/0.2.112 (macos; aarch64)"})
assert proxy._resolve_openai_upstream(request) == "https://api.x.ai"
def test_custom_base_url_still_wins_over_grok_signals() -> None:
"""Explicit x-headroom-base-url remains highest priority (gateway override)."""
proxy = _stub_proxy("https://api.openai.com")
request = _FakeRequest(
{
"x-headroom-base-url": "https://gateway.example",
"x-xai-token-auth": "xai-grok-cli",
"user-agent": "grok-shell/0.2.112",
}
)
assert proxy._resolve_openai_upstream(request) == "https://gateway.example"
def test_non_grok_clients_keep_process_openai_default() -> None:
proxy = _stub_proxy("https://api.openai.com")
request = _FakeRequest(
{
"authorization": "Bearer sk-test",
"user-agent": "codex-tui/0.146.0",
}
)
assert proxy._resolve_openai_upstream(request) == "https://api.openai.com"
def test_grok_signals_do_not_override_a_configured_gateway() -> None:
"""Grok routing is a fallback for the default target, not an override."""
proxy = _stub_proxy("https://gateway.internal")
request = _FakeRequest(
{
"x-xai-token-auth": "xai-grok-cli",
"user-agent": "grok-shell/0.2.117",
}
)
assert proxy._resolve_openai_upstream(request) == "https://gateway.internal"