Files
headroom/tests/test_issue_1779_https_proxy_route.py
brcebnandJD Davis 9624d40d5e docs(claude): keep Remote Control behind Headroom via an HTTPS_PROXY route (#1779) (#4575)
## Description

Claude Code v2.1.196+ disables Remote Control (`/remote-control`, `/rc`:
a local session mirrored to claude.ai/code and the Claude mobile apps)
whenever `ANTHROPIC_BASE_URL` names a host other than
`api.anthropic.com`. The check is client-side and compares the host
only, so every standard Headroom setup
(`ANTHROPIC_BASE_URL=http://127.0.0.1:8787`) loses Remote Control, and
the only documented fix so far is "run Claude without Headroom for those
sessions".

The troubleshooting page already named the route that remains: leave
`ANTHROPIC_BASE_URL` unset and reach Headroom through an `HTTPS_PROXY`
front end with a local CA trusted through `NODE_EXTRA_CA_CERTS` (the
enterprise proxy path Claude Code supports). It was left as an open item
on #1779. This PR ships that route, tested end to end with a real Claude
Code session steered from the Claude iOS app while every request went
through Headroom.

How it works:

```text
Claude Code --HTTPS_PROXY--> mitmdump 127.0.0.1:8790
    api.anthropic.com  /v1/messages*  -> Headroom 127.0.0.1:8787 -> api.anthropic.com
    api.anthropic.com  other paths    -> api.anthropic.com (unchanged)
    any other host (claude.ai, OAuth) -> raw CONNECT tunnel, never decrypted
```

- `ANTHROPIC_BASE_URL` is unset, so the gate passes and subscription
auth is untouched.
- mitmproxy decrypts `api.anthropic.com` only (`--allow-hosts`). The
Remote Control bridge (`claude.ai`) is never decrypted.
- Only the Messages API goes to Headroom. Feature flags, telemetry and
the rest of the API keep going straight to Anthropic.

One trap found while setting it up, and handled here: the Headroom proxy
is often started by the `headroom init hook ensure` hook, so it inherits
Claude Code's environment (the running proxy had `CLAUDECODE=1`). Its
httpx client honours `HTTPS_PROXY`, so its upstream calls would come
back through mitmproxy and loop. The docs tell users to prefix the hook
with `env -u HTTPS_PROXY -u HTTP_PROXY -u NODE_EXTRA_CA_CERTS`. As a
second guard, the addon marks the requests it redirects
(`x-rc-proxy-hop`) and sends a marked request straight to Anthropic. The
marker deliberately avoids the `x-headroom-` prefix: Headroom strips
those headers before forwarding upstream (`_strip_internal_headers`),
which would erase the marker. My first local version used
`x-headroom-rc` and the new test catches exactly that.

Refs #1779

## Type of Change

- [ ] Bug fix (non-breaking change which fixes an issue)
- [x] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `examples/claude_code_remote_control/route_to_headroom.py`: the
mitmproxy addon (redirect `/v1/messages*` to Headroom, loop guard, SSE
streaming, `HEADROOM_RC_UPSTREAM` override). mitmproxy is imported only
for type checking, so it is not a Headroom dependency.
- `examples/claude_code_remote_control/README.md`: setup (macOS /
Linux), Claude Code settings, starting Headroom without the proxy
variables, verification, caveats, rollback.
- `docs/content/docs/troubleshooting.mdx`: the Remote Control section
offers this route next to "launch Claude without Headroom", and the
"What remains" paragraph now points to it.
- `examples/README.md`: index entry.
- `tests/test_issue_1779_https_proxy_route.py`: routing rules pinned
with stand-in flow objects.

No Headroom runtime code changes, no new dependency.

## Testing

- [x] Unit tests pass (`pytest`) — the new file plus the existing #1779
gate tests
- [x] Linting passes (`ruff check .`) — on the changed Python files,
ruff 0.17.0 (the pinned version)
- [ ] Type checking passes (`mypy headroom`) — N/A, no change under
`headroom/`
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ python -m pytest -q tests/test_issue_1779_https_proxy_route.py tests/test_issue_1779_remote_control_gate.py
64 passed in 0.77s

# Loop-guard test with the marker renamed to x-headroom-rc (proves it catches the trap):
FAILED tests/test_issue_1779_https_proxy_route.py::test_hop_marker_survives_headroom_header_stripping
1 failed, 9 passed

$ ruff check <changed files> && ruff format --check <changed files>
All checks passed!
```

Smoke test of the addon in a real `mitmdump` (12.3.1) with Headroom
running on 8787:

```text
POST https://api.anthropic.com/v1/messages  -> "server connect 127.0.0.1:8787", "Streaming response from 127.0.0.1"
GET  https://api.anthropic.com/v1/models    -> "server connect api.anthropic.com:443" (not redirected)
GET  https://claude.ai/ (no custom CA given) -> TLS handshake succeeds, i.e. tunnelled, not intercepted
```

## Real Behavior Proof

- Environment: macOS (Darwin 27), Claude Code 2.1.312 (native install,
claude.ai Max subscription), Headroom 0.37.0 (`headroom proxy --mode
token --backend anthropic`, started by the `headroom init hook ensure`
hooks), mitmproxy 12.3.1 run as a LaunchAgent.
- Exact command / steps: `~/.claude/settings.json` `env` =
`HTTPS_PROXY=http://127.0.0.1:8790`, `NO_PROXY=localhost,127.0.0.1,::1`,
`NODE_EXTRA_CA_CERTS=~/.mitmproxy/mitmproxy-ca-cert.pem`,
`ANTHROPIC_BASE_URL` removed, `remoteControlAtStartup: true`, both
headroom hook commands prefixed with `env -u HTTPS_PROXY -u HTTP_PROXY
-u NODE_EXTRA_CA_CERTS`. Started a new `claude` session.
- Observed result: `/status` shows the proxy; answers stream normally;
the mitmdump log shows one `127.0.0.1:8787` request per turn and no
repeats; the session shows up in the Claude iOS app (Code tab) and
answers messages sent from the phone; Headroom's savings keep counting
those requests.
- Not tested: Linux and Windows (the README gives the Linux equivalent
but it was not run), the VS Code extension and Claude Desktop sessions,
`headroom wrap claude` (which sets `ANTHROPIC_BASE_URL` itself, so it is
not compatible with this route).

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: N/A
- Stable/default behavior changed: no, opt-in recipe; nothing changes
for existing users
- Kill switch / disable path: restore `ANTHROPIC_BASE_URL`, remove the
three variables, stop mitmdump
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert the commit (docs, example and test only)

## Review Readiness

- [x] I performed a self-review
- [ ] PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`

## Additional Notes

- Possible follow-up, not in this PR: `remote_control_gate_message` /
`remote_control_gate_short_message` still only suggest running Claude
without Headroom. They could link to this section. I left them untouched
to keep this PR docs-only and avoid changing strings the #1779 / #3426
tests pin.
- Security trade-off, stated in the README: the user trusts a locally
generated CA for `api.anthropic.com` only; the CA key stays on the
machine (`~/.mitmproxy`). Everything else is tunnelled.


### Maintainer current-main requalification

Exact head `b9d7a8a9e72a87ebdc69e1cbcb9e00df3265a22a`, upstream main
`e4a60ed72f6ef5b28569f8bfbe2163cfda32c948`.

Mechanically updated from current upstream main. The addon, host/path
selection, hop-loop guard, header handling and streaming behavior are
unchanged. The maintainer documentation fix addresses the new Devin
note: remove ANTHROPIC_BASE_URL from all active settings scopes,
explicitly including project .claude/settings.json and
.claude/settings.local.json, while retaining other entries/hooks. Source
inspection confirms project-scoped headroom init claude writes the
variable to settings.local.json, so removing only the user/shell setting
is insufficient. The setup and caveat now cover that case.

Both issue-1779 suites pass (64 tests), plus ten shared Gemini fixture
cases after the test-only repair for independently verified main
failures. Changed Python Ruff/format and whitespace checks pass. No new
runtime dependency or contributor routing logic was introduced. The
author's existing macOS/native Claude/Remote Control/mitmproxy
end-to-end evidence and exclusions were read; these independent Windows
checks cover routing contracts and documentation accuracy, not a live
macOS/Linux/Windows Remote Control session or a fresh native build.
Author readiness attestations remain unchanged; nothing merged.


Exact-head hosted checks are being handled by maintainers. No new
finding in the reviewed scope; formal approval awaits exact-head hosted
qualification; nothing merged.


### Maintainer current-main requalification

Exact head `c5e1ea2afcbd7e4c91a75869706c6f68f08f7e3a`, upstream main
`c01cf07d943d816cfd9d97e6838ed4e38f1ff9a4`.

Final main synchronization with upstream
c01cf07d94 after all six Dependabot
merges. The example addon and routing/gate test inputs are unchanged
from the previously approved branch; reviewed the additive
troubleshooting documentation overlap. Actual isolated Click8.5.0 and
the fresh combined native DLL:20 HTTPS-proxy-route/Gemini tests plus57
Remote Control gate tests pass; Ruff and whitespace pass. Initial gate
setup errors were caused by C: temp-drive exhaustion; isolated workspace
temp on G: passes with no source workaround or weakened assertion.
Existing scoped macOS/native Claude Remote Control proof remains
applicable to the unchanged addon; no fresh Windows
live-Remote-Control/provider claim. No contributor settings policy
rewritten or readiness attestations changed. No new source finding;
final approval awaits exact-head hosted qualification. Nothing merged.


Exact-head hosted checks are being handled by maintainers. No new
finding in the reviewed scope; formal approval awaits exact-head hosted
qualification; nothing merged.


### Maintainer current-main requalification

Exact head `5400c2c4fd86922f8e2f76d2752c9a5e1bdbe6f3`, upstream main
`2b0315b2d4b0d54947050bbdad2de9e89df06378`.

Requalified against upstream main
2b0315b2d4. All 71 integration patches
match the main delta after diff-location normalization. The HTTPS-proxy
addon and Remote Control route/gate inputs are byte-identical to the
preceding reviewed head. The docs explicitly cover user, project and
project-local settings, preserving other environment entries and hooks;
this addresses the prior Devin project-scope finding.

All 208 HTTPS-route, Remote Control gate, Gemini and doctor tests pass
using isolated temporary storage on G:. Ruff lint/format passes for all
33 changed Python files; offline lock and whitespace checks pass. The
existing native DLL matches its recorded build inputs and checksum; no
fresh build is claimed. Earlier scoped macOS/native Claude Remote
Control evidence remains applicable to the unchanged addon. No fresh
Windows live Remote Control, cloud/provider or mobile-client
qualification is claimed. Current author and Devin discussion
considered; no new blocker found. Exact-head hosted qualification is
pending before approval. Maintainers handle CI; nothing merged.


Exact-head hosted checks are being handled by maintainers. No new
finding in the reviewed scope; formal approval awaits exact-head hosted
qualification; nothing merged.

---------

Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-11-11 09:54:43 -06:00

113 lines
3.9 KiB
Python

"""Issue #1779: the HTTPS_PROXY route that keeps Remote Control with Headroom.
``examples/claude_code_remote_control/route_to_headroom.py`` is a mitmproxy addon:
Claude Code keeps ``ANTHROPIC_BASE_URL`` unset (so its Remote Control gate passes)
and reaches Headroom through ``HTTPS_PROXY``. These tests pin the routing rules
with stand-in flow objects, so mitmproxy is not a test dependency.
"""
from __future__ import annotations
import importlib.util
from pathlib import Path
from types import ModuleType, SimpleNamespace
import pytest
from headroom.proxy.helpers import _strip_internal_headers
ADDON = (
Path(__file__).resolve().parents[1]
/ "examples"
/ "claude_code_remote_control"
/ "route_to_headroom.py"
)
@pytest.fixture()
def addon(monkeypatch: pytest.MonkeyPatch) -> ModuleType:
monkeypatch.delenv("HEADROOM_RC_UPSTREAM", raising=False)
spec = importlib.util.spec_from_file_location("route_to_headroom", ADDON)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _flow(host: str, path: str, headers: dict[str, str] | None = None) -> SimpleNamespace:
request = SimpleNamespace(
pretty_host=host,
host=host,
port=443,
scheme="https",
path=path,
headers=dict(headers or {}),
)
return SimpleNamespace(request=request, response=SimpleNamespace(stream=False))
def test_messages_call_goes_to_headroom(addon: ModuleType) -> None:
flow = _flow("api.anthropic.com", "/v1/messages?beta=true")
addon.request(flow)
assert (flow.request.scheme, flow.request.host, flow.request.port) == (
"http",
"127.0.0.1",
8787,
)
assert flow.request.path == "/v1/messages?beta=true"
assert flow.request.headers[addon.HOP_HEADER] == "1"
def test_count_tokens_goes_to_headroom(addon: ModuleType) -> None:
flow = _flow("api.anthropic.com", "/v1/messages/count_tokens")
addon.request(flow)
assert flow.request.host == "127.0.0.1"
@pytest.mark.parametrize(
("host", "path"),
[
("api.anthropic.com", "/api/oauth/profile"),
("api.anthropic.com", "/v1/models"),
("claude.ai", "/v1/messages"),
("api.anthropic.com.evil.example", "/v1/messages"),
],
)
def test_everything_else_is_untouched(addon: ModuleType, host: str, path: str) -> None:
flow = _flow(host, path)
addon.request(flow)
assert (flow.request.scheme, flow.request.host, flow.request.port) == ("https", host, 443)
assert addon.HOP_HEADER not in flow.request.headers
def test_second_pass_from_headroom_goes_to_anthropic(addon: ModuleType) -> None:
"""A Headroom that inherited HTTPS_PROXY must not loop back into itself."""
flow = _flow("api.anthropic.com", "/v1/messages", {addon.HOP_HEADER: "1"})
addon.request(flow)
assert (flow.request.scheme, flow.request.host, flow.request.port) == (
"https",
"api.anthropic.com",
443,
)
assert addon.HOP_HEADER not in flow.request.headers
def test_hop_marker_survives_headroom_header_stripping(addon: ModuleType) -> None:
"""Headroom strips ``x-headroom-*`` upstream; a marker named so would loop."""
assert not addon.HOP_HEADER.startswith("x-headroom-")
forwarded = _strip_internal_headers({addon.HOP_HEADER: "1", "x-headroom-mode": "token"})
assert forwarded == {addon.HOP_HEADER: "1"}
def test_upstream_is_configurable(addon: ModuleType, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("HEADROOM_RC_UPSTREAM", "10.0.0.5:9999")
flow = _flow("api.anthropic.com", "/v1/messages")
addon.request(flow)
assert (flow.request.host, flow.request.port) == ("10.0.0.5", 9999)
def test_responses_are_streamed(addon: ModuleType) -> None:
flow = _flow("api.anthropic.com", "/v1/messages")
addon.responseheaders(flow)
assert flow.response.stream is True