Commit Graph
4 Commits
Author SHA1 Message Date
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
Tejas Chopra 1f96dabc19 fix(security): address u9up assessment findings (WEB-01–07) (#2207)
Hardens client-selected upstreams, memory identity resolution, downloaded binary integrity, telemetry import, Docker defaults, Neo4j credentials, and archive extraction. Refreshes the branch against current main and preserves newer same-origin and loopback protections.
2026-08-20 09:02:44 -05:00
Tejas Chopra 2976d49f18 fix(proxy): preserve sub-path in X-Headroom-Base-Url custom upstream (#2037) (#2127)
## Description

`_resolve_openai_upstream_base` ran the `X-Headroom-Base-Url` value
through `_normalize_origin`, which strips the path. A custom
OpenAI-compatible upstream served from a sub-path, such as
`https://host/api/v1`, was routed to the bare origin and returned
`proxy_error` (#2037). This re-attaches the path after origin
normalization.

This is a clean extraction of the path fix from #2047, which bundled it
with an unrelated `supports_websockets = true` to `false` default change
across init/wrap/codex. #2047 can be closed in favor of this narrower
fix.

Closes #2037

## 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`: re-attach the request header path
component in `_resolve_openai_upstream_base` after origin normalization.
- `tests/test_proxy/test_openai_upstream_header.py`: assert sub-paths
are preserved and trailing slashes are normalized.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ pytest tests/test_proxy/test_openai_upstream_header.py
5 passed

$ ruff check headroom/proxy/handlers/openai.py tests/test_proxy/test_openai_upstream_header.py
All checks passed!
```

## Real Behavior Proof

- Environment: local proxy header resolution path, custom
OpenAI-compatible upstream configured via `X-Headroom-Base-Url`.
- Exact command / steps: resolve `X-Headroom-Base-Url:
https://gateway.example/api/v1` through `_resolve_openai_upstream_base`
/ `_resolve_openai_upstream`.
- Observed result: before the fix, the upstream resolved to
`https://gateway.example` and lost `/api/v1`, causing the proxy to route
to the wrong endpoint. After the fix, it resolves to
`https://gateway.example/api/v1`; a trailing slash is normalized away.
- Not tested: end-to-end request against a live third-party
OpenAI-compatible gateway. The regression is covered at the proxy
routing helper layer where the path was dropped.

## 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
- [ ] I have updated the CHANGELOG.md if applicable

## Screenshots (if applicable)

N/A.

## Additional Notes

- Documentation is not updated because this fixes the existing header
behavior rather than changing a documented user-facing contract.
- Changelog is not updated in this PR; the change is scoped to the
regression and test.
- `mypy headroom` was not run in the author's workflow.
2026-07-13 19:53:45 -04:00
6c48ac81f2 fix(proxy): honor x-headroom-base-url in dedicated OpenAI handlers (#1502)
## Description

The dedicated OpenAI handlers (`/v1/chat/completions`, `/v1/responses`)
ignore the `x-headroom-base-url` request header that the opencode/CLI
transports already send on every routed request
(`plugins/opencode/src/transport.ts`) and that the generic passthrough
route already honors (`providers/proxy_routes.py:953`).

As a result, OpenAI-compatible gateways (LiteLLM, CPA, self-hosted vLLM,
Azure OpenAI) route correctly for passthrough traffic, but the dedicated
chat/responses handlers fall back to the default `OPENAI_API_URL` and
send the request — and the user's provider key — to the wrong upstream.
This forces OpenCode users behind a custom gateway to run a hand-rolled
plugin that re-spawns the proxy with `OPENAI_TARGET_API_URL` instead of
the supported `HeadroomPlugin`.

Refs #1503 (feature-request issue with full spec — API surface, failure
modes, security considerations).

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

Non-breaking: when the header is absent (the common case), behavior is
identical to before — `_resolve_openai_upstream` falls back to
`self.OPENAI_API_URL`.

## Changes Made

- Added `OpenAIHandlerMixin._resolve_openai_upstream(request)` — returns
`request.headers.get("x-headroom-base-url") or self.OPENAI_API_URL`.
Prefers the header, falls back to the configured URL.
- Used it at the two direct-path HTTP upstream sites:
- `handle_openai_chat` →
`build_copilot_upstream_url(self._resolve_openai_upstream(request),
"/v1/chat/completions")`
- `handle_openai_responses` →
`build_copilot_upstream_url(self._resolve_openai_upstream(request),
"/v1/responses")`
- This makes the dedicated handlers behave identically to the catch-all
passthrough and the Azure path (`_select_passthrough_base_url`,
`providers/proxy_routes.py:66,:953`), which already read the same
header.
- The header is already stripped before forwarding by
`helpers._strip_internal_headers`, so no upstream leakage /
fingerprinting is introduced.
- CHANGELOG entry under `### Bug Fixes`.

## Testing

<!-- Check what you actually ran, then paste the real command output
below. -->

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`) — not run locally (maturin
native build not available in my env; covered by CI)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

New `tests/test_proxy/test_openai_upstream_header.py` pins the
resolution contract (3 cases):

```text
$ pytest tests/test_proxy/test_openai_upstream_header.py -q
...
collected 3 items
tests/test_proxy/test_openai_upstream_header.py ...                      [100%]
========================= 3 passed, 1 warning in 0.25s =========================
```

Fail-before confirmed (unpatched handler raises `AttributeError:
_resolve_openai_upstream`):

```text
FAILED tests/test_proxy/test_openai_upstream_header.py::test_header_overrides_configured_url
FAILED tests/test_proxy/test_openai_upstream_header.py::test_missing_header_falls_back_to_configured_url
FAILED tests/test_proxy/test_openai_upstream_header.py::test_empty_header_falls_back_to_configured_url
========================= 3 failed, 1 warning in 0.29s =========================
```

Lint/format:

```text
$ ruff check headroom/proxy/handlers/openai.py tests/test_proxy/test_openai_upstream_header.py
Ruff: No issues found
$ ruff format --check headroom/proxy/handlers/openai.py tests/test_proxy/test_openai_upstream_header.py
2 files already formatted
```

## Real Behavior Proof

- Environment: macOS (darwin), Python 3.12 (pipx install of
`headroom-ai`), Headroom proxy `headroom proxy --port 8787` with
`OPENAI_TARGET_API_URL=https://cpa.funxyz.fun` (an OpenAI-compatible
gateway — "CLI Proxy API"). OpenCode with a custom `cpa` provider
(`@ai-sdk/openai-compatible`, `baseURL: https://cpa.funxyz.fun/v1`)
using the official `HeadroomPlugin`.
- Exact command / steps: traced the bug in the installed package source
— confirmed `handle_openai_chat` builds its upstream URL from
`self.OPENAI_API_URL` only (`proxy/handlers/openai.py:2487`), never
reading `x-headroom-base-url`, while `providers/proxy_routes.py:953`
reads it for passthrough. Then applied this patch and re-imported the
handler from the repo source via `PYTHONPATH`.
- Observed result: before the patch, `/v1/chat/completions` requests
ignored the `x-headroom-base-url: https://cpa.funxyz.fun` header (set by
the opencode transport) and routed to the default upstream, failing
against a non-OpenAI gateway — requiring a custom respawn-plugin
workaround. After the patch, `_resolve_openai_upstream` returns the
header value and the request forwards to the configured gateway; the
official `HeadroomPlugin` works without the env-var workaround. Unit
tests pass (3/3) and fail on the unpatched handler (3/3).
- Not tested: full `uv sync` CI matrix (native `headroom._core` maturin
build unavailable locally, so `headroom.proxy.server` import chain that
pulls `transforms/content_router` can't be exercised here — the edited
handler module imports fine and the focused unit tests exercise the new
method directly). WebSocket/Codex paths (`handle_openai_responses_ws`,
`_ws_http_fallback`) — intentionally out of scope (see Additional
Notes). `mypy headroom` — deferred to CI.

## 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 — no public
API/docs surface; the header is already documented as an internal
control flag in `helpers.py:1489-1495`
- [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 have updated the CHANGELOG.md if applicable

## Additional Notes

**Scope boundary — WebSocket paths intentionally unchanged.** The two WS
sites (`handle_openai_responses_ws`, `_ws_http_fallback`) are
Codex-specific and left as-is:

1. They short-circuit to `chatgpt.com` under ChatGPT-session auth (not
arbitrary gateways).
2. The WS path strips `x-headroom-base-url` from `upstream_headers`
(`_strip_internal`, ~line 3756) before the upstream URL is built, and
`_ws_http_fallback` receives already-stripped headers as a parameter.
Honoring the header there would require threading it through the WS
internals and changing a signature, for a path a custom
OpenAI-compatible WebSocket gateway is unlikely to use. The HTTP paths
cover the realistic gateway case. Happy to do it as a follow-up if
maintainers want it.

**Issue-first.** This is a behaviour change, so per CONTRIBUTING a
feature-request issue (#1503) is open for triage with the full spec (API
surface, user stories, failure modes, security). This PR implements it;
holding for maintainer 👍 before treating as ready to merge.

---------

Co-authored-by: ShutovKS <shutovks@example.local>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-07-01 22:24:39 -05:00