fix(doctor): recognize IPv6 loopback and case-insensitive proxy routing URLs (#3255)

## Description

`headroom doctor`'s routing check matches the configured
`ANTHROPIC_BASE_URL` against:

```python
_LOOPBACK_URL_RE = re.compile(r"https?://(?:127\.0\.0\.1|localhost):(\d+)")
```

This misses two loopback URL forms that route correctly through the
proxy, so `check_claude_routing` (and `check_codex_routing`, which uses
the parallel `_CODEX_BASE_URL_RE`) reports a **correctly-routed**
session as "not routed" and sends the user off to debug a working setup:

1. **IPv6 loopback literal** — `http://[::1]:8787` never matches, so an
IPv6-configured route reads as unrouted.
2. **Case** — the regex is case-sensitive, but URL schemes and hostnames
are not. `HTTP://Localhost:8787` or `http://LOCALHOST:8787` (valid) both
fail to match.

```text
http://127.0.0.1:8787   -> MATCH
http://[::1]:8787       -> NO MATCH  -> doctor: "not routed" (false negative)
HTTP://Localhost:8787   -> NO MATCH  -> doctor: "not routed" (false negative)
```

This is the same false-negative class the routing check was already
corrected for twice (#3205, #3213): a diagnostic that tells a routed
user they are not routed is actively misleading.

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

- Replace loopback URL prefix matching with a shared
urllib.parse.urlsplit classifier. Require an exact loopback host,
HTTP(S), an explicit valid port, and no userinfo; support IPv6 loopback
and case-insensitive schemes/hosts.
- Retain active Codex provider selection and classify its extracted
base_url through the same parser. Remote URLs, hostname-suffix
lookalikes and malformed ports remain warnings.
- Add routing/classifier regressions for accepted URL variants and
rejected lookalikes. Health probes retain current main behavior; this
change does not add IPv6-only health probing.

## Testing

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

### Test Output

```text
tests/test_cli_doctor.py  ->  95 passed in 1.19s
(4 of the 5 new variants FAIL on pre-fix code — [::1] and the upper-cased URLs — verified via git stash)
uvx ruff@0.16.2 check headroom/cli/doctor.py tests/test_cli_doctor.py  ->  All checks passed!
uvx mypy@1.20.2 headroom/cli/doctor.py  ->  Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.12.11, project venv, pytest 9.1.1,
ruff 0.16.2 and mypy 1.20.2 via uvx.
- Exact command / steps: with `ANTHROPIC_BASE_URL=http://[::1]:8787`
(and the upper-cased variants) in a settings file,
`check_claude_routing(path, 8787)` returned WARN "not routed" before the
fix and PASS "routed" after; `http://127.0.0.1:8788` still WARNs on the
port mismatch and `https://gateway.corp.example/v1` still WARNs as
non-proxy.
- Observed result: IPv6 and case-variant loopback URLs now classify as
routed; port-mismatch and non-loopback WARNs are unchanged.
- Not tested: no live `headroom doctor` invocation against a running
proxy; the pure classifier `check_claude_routing` is exercised directly
(it is what the command calls).

## Runtime Rollout Safety

- Rollout-managed feature(s): none. This is the `headroom doctor`
diagnostic classifier, not a rollout-channel-gated runtime feature.
- Minimum rollout channel: N/A.
- Stable/default behavior changed: only the false-negative is corrected
— additional valid loopback forms now classify as routed. Port-mismatch,
Ollama-collision, and non-loopback WARNs are unchanged, and no URL that
was previously WARNed as non-proxy now passes except genuine loopback
forms.
- Kill switch / disable path: N/A.
- Unsafe override required: no.
- Qualification impact: none.
- Rollback path: revert this PR.

## 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 (N/A:
internal behavior)
- [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`

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3255"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

### Maintainer current-main requalification

Exact head `922badceae5536e91e63f299685d77ff3bc3ce29`, upstream main
`c01cf07d943d816cfd9d97e6838ed4e38f1ff9a4`.

Clean mechanical sync with upstream main
c01cf07d94. Re-read current discussion and
all three Devin notes. Exact URL parsing preserves active-provider
selection, IPv6/mixed-case support and rejection of userinfo, suffix
lookalikes, invalid ports and remote hosts. Current-main port-discovery
behavior is retained. All131 doctor tests pass;2-file Ruff lint/format
and main-relative whitespace pass. Devin IPv6-only health-probe
observation concerns the unchanged IPv4-only doctor probe implementation
already on main; this PR changes routing classification, not
health-probe binding, so the inherited limitation is not used to
withhold source approval. No fresh live IPv6-only doctor/proxy or
provider call is claimed; current verification is classifier/CLI tests,
not broader runtime proof. The description Changes Made section is being
corrected to describe urlsplit rather than the superseded regex
implementation. No contributor routing logic rewritten. Formal approval
awaits exact-head hosted qualification; 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: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
Abhay Singh
2026-11-06 10:18:02 -06:00
committed by GitHub
co-authored by JerrettDavis
parent da6d9736cd
commit 2b0315b2d4
2 changed files with 154 additions and 4 deletions
+60 -4
View File
@@ -20,6 +20,7 @@ from dataclasses import asdict, dataclass
from datetime import datetime
from pathlib import Path
from typing import Any
from urllib.parse import urlsplit
import click
@@ -56,11 +57,61 @@ SKIP = "skip"
DEFAULT_PROXY_PORT = 8787
_LOOPBACK_URL_RE = re.compile(r"https?://(?:127\.0\.0\.1|localhost):(\d+)")
# The loopback host forms a proxy URL can take: IPv4, the ``localhost`` alias,
# and the IPv6 literal ``::1`` (``urlsplit`` strips the ``[...]`` brackets and
# lowercases the host, so ``HTTP://Localhost`` and ``http://[::1]`` normalize
# into this set).
_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "::1", "localhost"})
# Codex TOML routes via a quoted ``base_url``. Capture the quoted value only and
# classify it with the shared URL parser below — a prefix/regex match on the URL
# would accept userinfo and hostname-suffix lookalikes such as
# ``http://localhost:8787@evil.example`` as loopback. Anchored to a line start so
# an indented key is matched consistently, and paired with the active
# ``model_provider`` so only the routed provider's block is inspected.
_CODEX_BASE_URL_RE = re.compile(r'(?m)^[ \t]*base_url\s*=\s*"([^"\r\n]+)"')
_CODEX_MODEL_PROVIDER_RE = re.compile(r'(?m)^[ \t]*model_provider\s*=\s*"([^"\r\n]+)"')
_CODEX_OPENAI_BASE_URL_RE = re.compile(r'(?m)^[ \t]*openai_base_url\s*=\s*"([^"\r\n]+)"')
def _loopback_route_port(url: str) -> int | None:
"""Return the port if ``url`` is a well-formed loopback proxy route.
Classifies by parsing the URL rather than prefix-matching it: the scheme
must be http(s), there must be no userinfo, the host must be *exactly* a
loopback literal, and the port must be present and valid. This is what makes
``doctor`` a URL classifier rather than a string matcher, so lookalikes that
a prefix match accepts are correctly rejected:
* userinfo — ``http://localhost:8787@evil.example/v1`` parses to host
``evil.example`` (the ``localhost:8787`` is credentials), and any URL
carrying userinfo is refused outright;
* hostname suffix — ``http://localhost.evil.example:8787`` and
``http://127.0.0.1.evil.example:8787`` are not exact loopback hosts.
A correctly-routed loopback URL (including ``[::1]`` and an upper-cased
scheme/host) still classifies, preserving the #3205 / #3213 fix.
"""
try:
parts = urlsplit(url.strip())
except ValueError:
return None
if parts.scheme.lower() not in ("http", "https"):
return None
# Reject any credentials in the authority: a real Headroom route never
# carries userinfo, and userinfo is the vector that masks the true host.
if parts.username is not None or parts.password is not None:
return None
try:
host = parts.hostname # lowercased, brackets stripped
port = parts.port # raises ValueError on an out-of-range port
except ValueError:
return None
if host is None or host not in _LOOPBACK_HOSTS or port is None:
return None
return port
# Ollama's fixed default port. `ollama launch claude` writes
# ``ANTHROPIC_BASE_URL=http://127.0.0.1:11434`` into the launched Claude Code
# child, which outranks the persistent-install env block and silently bypasses
@@ -642,7 +693,13 @@ def check_codex_routing(
summary="not routed (no active provider base_url in config.toml)",
hint="wrap it: headroom wrap codex",
)
config_path, text, provider_id, base_url = found
# base_url is the active provider's, already extracted and None-checked
# above. Classify it through the shared URL parser so a lookalike or remote
# base_url (userinfo, hostname suffix, non-loopback) is a WARN, not a PASS.
routing = _classify_routing_url(name, base_url, port, source=str(config_path))
if routing.status != PASS:
return routing
@@ -912,14 +969,13 @@ def check_shell_env(environ: Mapping[str, str], port: int) -> CheckResult:
def _classify_routing_url(name: str, url: str, port: int, *, source: str) -> CheckResult:
match = _LOOPBACK_URL_RE.match(url.strip())
if match is None:
found_port = _loopback_route_port(url)
if found_port is None:
return CheckResult(
name=name,
status=WARN,
summary=f"points at {url}, not the local Headroom proxy ({source})",
)
found_port = int(match.group(1))
if found_port != port:
if found_port == _OLLAMA_DEFAULT_PORT:
# Not a mis-probed Headroom port — this is Ollama's endpoint, so
+94
View File
@@ -167,6 +167,28 @@ class TestClaudeRouting:
)
assert check_claude_routing(path, 8787).status == PASS
@pytest.mark.parametrize(
"base_url",
[
"http://localhost:8787",
"http://[::1]:8787", # IPv6 loopback literal
"http://[::1]:8787/v1",
"HTTP://Localhost:8787", # scheme/host are case-insensitive
"http://LOCALHOST:8787",
],
)
def test_loopback_url_variants_pass(self, tmp_path, base_url):
"""A correctly-routed loopback URL must not read as 'not routed'.
The routing regex only matched lowercase ``127.0.0.1``/``localhost`` with
an explicit port, so an IPv6 (``[::1]``) or upper-cased loopback URL — a
valid route — produced a misleading WARN (the false-negative class of
#3205 / #3213).
"""
path = tmp_path / "settings.json"
path.write_text(json.dumps({"env": {"ANTHROPIC_BASE_URL": base_url}}), encoding="utf-8")
assert check_claude_routing(path, 8787).status == PASS
def test_port_mismatch_warns(self, tmp_path):
path = tmp_path / "settings.json"
path.write_text(
@@ -187,6 +209,28 @@ class TestClaudeRouting:
assert result.status == WARN
assert "gateway.corp.example" in result.summary
@pytest.mark.parametrize(
"base_url",
[
# Userinfo lookalike: a prefix match sees "localhost:8787" but the
# URL's real host is evil.example (the loopback text is credentials).
"http://localhost:8787@evil.example/v1",
"http://127.0.0.1:8787@evil.example/v1",
# Userinfo present at all — a real Headroom route never carries it.
"http://evil.example@127.0.0.1:8787",
# Hostname-suffix lookalikes: not an exact loopback host.
"http://localhost.evil.example:8787",
"http://127.0.0.1.evil.example:8787",
],
)
def test_loopback_lookalikes_warn(self, tmp_path, base_url):
"""URL classification (not prefix matching) must reject userinfo and
hostname-suffix lookalikes that resolve to a non-loopback host, so
``doctor`` never reports an attacker-controlled destination as routed."""
path = tmp_path / "settings.json"
path.write_text(json.dumps({"env": {"ANTHROPIC_BASE_URL": base_url}}), encoding="utf-8")
assert check_claude_routing(path, 8787).status == WARN
def test_foundry_url_passes(self, tmp_path):
# In Foundry mode ANTHROPIC_BASE_URL is absent by design; routing lives
# in ANTHROPIC_FOUNDRY_BASE_URL. doctor must recognize it as routed.
@@ -643,6 +687,56 @@ class TestCodexRouting:
path.write_text('model = "gpt-5"\n', encoding="utf-8")
assert check_codex_routing(path, 8787).status == WARN
@pytest.mark.parametrize(
"base_url",
[
"http://localhost:8787@evil.example/v1", # userinfo lookalike
"http://localhost.evil.example:8787/v1", # hostname suffix lookalike
"https://gateway.corp.example/v1", # plainly remote
],
)
def test_non_loopback_base_url_warns(self, tmp_path, base_url):
"""The Headroom block's base_url is classified through the same URL
parser, so a non-loopback (or lookalike) base_url reads as not routed
rather than passing on a prefix match."""
path = tmp_path / "config.toml"
path.write_text(
f'[model_providers.headroom]\nbase_url = "{base_url}"\n',
encoding="utf-8",
)
result = check_codex_routing(path, 8787)
assert result.status == WARN
def test_base_url_read_from_headroom_block_not_earlier_provider(self, tmp_path):
"""A base_url in an earlier provider block must not be mistaken for the
Headroom route; only the Headroom block's own base_url counts."""
path = tmp_path / "config.toml"
path.write_text(
"[model_providers.openai]\n"
'base_url = "https://api.openai.com/v1"\n'
"\n"
"[model_providers.headroom]\n"
'base_url = "http://127.0.0.1:8787/v1"\n',
encoding="utf-8",
)
assert check_codex_routing(path, 8787).status == PASS
def test_marker_block_without_base_url_warns(self, tmp_path):
"""A provider block that exists but has no base_url must not read as
routed: with no base_url there is nothing pointing Codex at the proxy,
so it WARNs rather than falling through to PASS."""
path = tmp_path / "config.toml"
path.write_text(
'model_provider = "headroom"\n'
"[model_providers.headroom]\n"
"requires_openai_auth = true\n",
encoding="utf-8",
)
result = check_codex_routing(path, 8787)
assert result.status == WARN
assert "base_url" in result.summary
assert "wrap" in (result.hint or "")
def test_garbage_bytes_warn_not_crash(self, tmp_path):
path = tmp_path / "config.toml"
path.write_bytes(b"\xff\xfe garbage \x00")