mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
fix(proxy): recognise every local spelling of the proxy in the cc-switch loop guard (#4405)
## Description The cc-switch reconciler's loop guard compared `ANTHROPIC_BASE_URL` with the exact string `http://127.0.0.1:{port}`. `http://localhost:{port}`, `http://LOCALHOST:{port}/v1/` and `http://127.0.0.1:{port}/v1` were therefore captured as the proxy's own upstream, so requests looped back to the proxy. The guard now compares scheme, port and host, where host is `localhost` or the proxy's own bind address. `[::1]` is a different socket from the `127.0.0.1` the proxy binds, so a provider on `[::1]:{port}` is still captured (review feedback, second commit). Fixes #4400 ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - `headroom/proxy/cc_switch_reconciler.py`: add `CCSwitchReconciler._is_self()` (urlsplit; host is `localhost` or the host of `proxy_url`, same scheme and port) and use it in the loop guard. - `tests/test_proxy/test_cc_switch_reconciler.py`: 5 spellings that must not be captured; 5 URLs (other port, https, `[::1]` provider on the same port, third party) that must still be captured; one test that `[::1]` is the proxy only when `proxy_url` is `[::1]`. ## 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 First commit, with only its source change reverted (new tests kept): ```text FAILED tests/test_proxy/test_cc_switch_reconciler.py::test_proxy_own_url_spellings_are_not_captured[http://127.0.0.1:8787/v1] FAILED tests/test_proxy/test_cc_switch_reconciler.py::test_proxy_own_url_spellings_are_not_captured[http://localhost:8787] FAILED tests/test_proxy/test_cc_switch_reconciler.py::test_proxy_own_url_spellings_are_not_captured[http://LOCALHOST:8787/v1/] FAILED tests/test_proxy/test_cc_switch_reconciler.py::test_proxy_own_url_spellings_are_not_captured[http://[::1]:8787] ========================= 4 failed, 22 passed in 1.33s ========================= ``` First commit with the fix: 26 passed. Second commit (`[::1]` follow-up), with only its source change reverted (its test changes kept): ```text FAILED tests/test_proxy/test_cc_switch_reconciler.py::test_other_ports_and_hosts_are_still_captured[http://[::1]:8787] FAILED tests/test_proxy/test_cc_switch_reconciler.py::test_ipv6_proxy_address_is_self_only_for_ipv6_bind ========================= 2 failed, 25 passed in 0.84s ========================= ``` With the second commit: ```text ============================== 27 passed in 0.76s ============================== ``` `ruff check` and `ruff format --check` on both changed files: All checks passed / 2 files already formatted. `mypy` was not run. ## Real Behavior Proof - Environment: WSL2 Ubuntu (Linux 6.18 x86_64), Python 3.12.15, uvicorn 0.54.0, fastapi 0.158.1, starlette 1.9.0; base `e995eb9f`; `headroom/_core.abi3.so` copied (untracked, not committed) from the official `headroom_ai-0.41.0` wheel. - Exact command / steps: stub upstream on 127.0.0.1:18821 that logs every POST; `CLAUDE_CONFIG_DIR=<dir> HEADROOM_CC_SWITCH_RECONCILE=1 ANTHROPIC_TARGET_API_URL=http://127.0.0.1:18821 python -P -m headroom.proxy.server --host 127.0.0.1 --port 18820 --no-cache --no-rate-limit`, with `<dir>/settings.json` = `{"env": {"ANTHROPIC_BASE_URL": "http://localhost:18820", ...}}`; then one `POST /v1/messages` to 127.0.0.1:18820 (40 s client timeout). Before = parent source (this change reverted with `git apply -R`), after = this change. - Observed result: before, the reconciler logs `captured upstream=http://localhost:18820`, rewrites settings.json to `http://127.0.0.1:18820`, the client times out and the stub receives 0 requests. After, settings.json is left unchanged, the client gets HTTP 200 and the stub receives 1 `POST /v1/messages`. Control with the fix and a real third-party URL (`http://127.0.0.1:18821`): still captured, settings.json rewritten to the proxy, HTTP 200, stub receives 1 request. - Second proof (review feedback): a provider stub on `[::1]:18820`, the proxy on `127.0.0.1:18820`, a different stub on `127.0.0.1:18821` as `ANTHROPIC_TARGET_API_URL`, settings.json `ANTHROPIC_BASE_URL=http://[::1]:18820`, same client request. Before the second commit settings.json is left on `[::1]` and the request reaches the 18821 default upstream, not the provider (provider received none). After it, the reconciler logs `captured upstream=http://[::1]:18820`, settings.json is rewritten to `http://127.0.0.1:18820`, and the provider on `[::1]` receives the `POST /v1/messages` (default upstream: none). - Not tested: real cc-switch overwriting settings.json; a real Anthropic upstream; Windows/macOS; the Rust proxy. Raw output: ```text == BEFORE settings.json after reconcile: {"env":{"ANTHROPIC_BASE_URL":"http://127.0.0.1:18820",...}} client: TimeoutError timed out cc-switch reconciler: captured upstream=http://localhost:18820, base_url -> http://127.0.0.1:18820 stub upstream received: (count: 0) == AFTER settings.json after reconcile: {"env":{"ANTHROPIC_BASE_URL":"http://localhost:18820",...}} client: HTTP 200 {"id": "msg_stub", ...} stub upstream received: STUB-UPSTREAM POST /v1/messages (count: 1) == CONTROL (fix, third-party URL) cc-switch reconciler: captured upstream=http://127.0.0.1:18821, base_url -> http://127.0.0.1:18820 client: HTTP 200 {"id": "msg_stub", ...} stub upstream received: STUB-UPSTREAM POST /v1/messages (count: 1) == SECOND PROOF, BEFORE the [::1] commit settings.json after reconcile: {"env":{"ANTHROPIC_BASE_URL":"http://[::1]:18820",...}} provider on [::1]:18820 received: none default upstream 127.0.0.1:18821 received: STUB-DEFAULT-UPSTREAM POST /v1/messages == SECOND PROOF, AFTER cc-switch reconciler: captured upstream=http://[::1]:18820, base_url -> http://127.0.0.1:18820 settings.json after reconcile: {"env":{"ANTHROPIC_BASE_URL":"http://127.0.0.1:18820",...}} provider on [::1]:18820 received: STUB-PROVIDER-ON-IPV6 POST /v1/messages default upstream 127.0.0.1:18821 received: none ``` ## Runtime Rollout Safety - Rollout-managed feature(s): none (opt-in `HEADROOM_CC_SWITCH_RECONCILE=1`) - Minimum rollout channel: n/a - Stable/default behavior changed: no; the reconciler is off by default - Kill switch / disable path: leave `HEADROOM_CC_SWITCH_RECONCILE` unset - Unsafe override required: no - Qualification impact: none expected - Rollback path: revert this commit ## 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 - [x] I did **not** edit `CHANGELOG.md` — it is generated by release-please from my Conventional Commit PR title (a CI guard enforces this) ## Screenshots (if applicable) N/A ## Additional Notes - Documentation checklist item: N/A, no user-facing doc changes. - Scope: only the loop guard; the stale-upstream handling and `_atomic_write` are untouched. - Produced with AI assistance (Claude Code) operated by me (HetCreep); the reproduction was run on my machine on a clone of the repository. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
6c3d747507
commit
d9958bfdff
@@ -50,6 +50,7 @@ import logging
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -98,6 +99,23 @@ class CCSwitchReconciler:
|
||||
self._task: asyncio.Task | None = None
|
||||
self._last_mtime_ns: int | None = None
|
||||
|
||||
def _is_self(self, url: str) -> bool:
|
||||
"""True if ``url`` names this proxy (``localhost`` or its bind address, any path).
|
||||
|
||||
Loopback families are distinct sockets: ``[::1]`` is not the proxy when it is
|
||||
bound to ``127.0.0.1``, so another local provider on that address is captured.
|
||||
"""
|
||||
try:
|
||||
want = urlsplit(self.proxy_url)
|
||||
got = urlsplit(url)
|
||||
return (
|
||||
(got.hostname or "").lower() in {"localhost", (want.hostname or "").lower()}
|
||||
and got.scheme == want.scheme
|
||||
and got.port == want.port
|
||||
)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
async def start(self) -> None:
|
||||
if self._task is not None:
|
||||
return
|
||||
@@ -178,7 +196,7 @@ class CCSwitchReconciler:
|
||||
return False
|
||||
|
||||
# Already pointing at us: nothing to do (loop guard).
|
||||
if url.rstrip("/") == self.proxy_url:
|
||||
if self._is_self(url):
|
||||
return False
|
||||
|
||||
# Third-party / custom endpoint: capture it as upstream, point Claude at us.
|
||||
|
||||
@@ -66,6 +66,66 @@ def test_no_rewrite_loop(tmp_path):
|
||||
assert r.tick() is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"url",
|
||||
[
|
||||
"http://127.0.0.1:8787",
|
||||
"http://127.0.0.1:8787/",
|
||||
"http://127.0.0.1:8787/v1",
|
||||
"http://localhost:8787",
|
||||
"http://LOCALHOST:8787/v1/",
|
||||
],
|
||||
)
|
||||
def test_proxy_own_url_spellings_are_not_captured(tmp_path, url):
|
||||
r, sf, captured = _make(tmp_path)
|
||||
_write(sf, {"env": {"ANTHROPIC_BASE_URL": url}})
|
||||
assert r.tick() is False
|
||||
assert captured == []
|
||||
assert r.current_upstream is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"url",
|
||||
[
|
||||
"http://127.0.0.1:8788",
|
||||
"http://localhost:9999/v1",
|
||||
"https://127.0.0.1:8787",
|
||||
"http://[::1]:8787",
|
||||
"https://api.deepseek.com/anthropic",
|
||||
],
|
||||
)
|
||||
def test_other_ports_and_hosts_are_still_captured(tmp_path, url):
|
||||
r, sf, captured = _make(tmp_path)
|
||||
_write(sf, {"env": {"ANTHROPIC_BASE_URL": url}})
|
||||
assert r.tick() is True
|
||||
assert captured == [url]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", ["http://127.0.0.1:99999", "http://[::1"])
|
||||
def test_unparseable_base_url_is_not_treated_as_the_proxy(tmp_path, url):
|
||||
# urlsplit raises ValueError for these; such a URL is not this proxy.
|
||||
r, sf, captured = _make(tmp_path)
|
||||
_write(sf, {"env": {"ANTHROPIC_BASE_URL": url}})
|
||||
assert r.tick() is True
|
||||
assert captured == [url]
|
||||
|
||||
|
||||
def test_ipv6_proxy_address_is_self_only_for_ipv6_bind(tmp_path):
|
||||
sf = tmp_path / "settings.json"
|
||||
captured: list[str] = []
|
||||
r = CCSwitchReconciler(
|
||||
proxy_url="http://[::1]:8787",
|
||||
default_upstream=DEFAULT,
|
||||
set_upstream=captured.append,
|
||||
path=sf,
|
||||
)
|
||||
_write(sf, {"env": {"ANTHROPIC_BASE_URL": "http://[::1]:8787"}})
|
||||
assert r.tick() is False
|
||||
_write(sf, {"env": {"ANTHROPIC_BASE_URL": "http://127.0.0.1:8787"}})
|
||||
assert r.tick() is True
|
||||
assert captured == ["http://127.0.0.1:8787"]
|
||||
|
||||
|
||||
def test_switching_provider_recaptures(tmp_path):
|
||||
r, sf, captured = _make(tmp_path)
|
||||
_write(
|
||||
|
||||
Reference in New Issue
Block a user