mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-12-03 18:39:57 +08:00
feat/https-compose-caddy
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 (
|
||
|
|
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 (
|
||
|
|
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> |