The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(net): sanitize bracketed-IPv6 NO_PROXY entries so bare httpx clients construct
brooklyncf98cef46a44
diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.pyindex 2a57e0c29d2..8065b84d50f 100644--- a/hermes_cli/auth_codex.py+++ b/hermes_cli/auth_codex.py@@ -23,7 +23,7 @@ from hermes_cli.auth_constants import (_decode_jwt_claims, AUTH_LOCK_TIMEOUT_SECONDS, AuthError,CODEX_ACCESS_TOKEN_REFRESH_SKEW_SECONDS, CODEX_OAUTH_CLIENT_ID, CODEX_OAUTH_TOKEN_URL,CODEX_OAUTH_USER_AGENT, CODEX_RATE_LIMITED_CODE, DEFAULT_CODEX_BASE_URL, _codex_err, httpx)-from utils import env_float+from utils import env_float, normalize_proxy_env_varsif TYPE_CHECKING: # annotation-only; the runtime import would be a cyclefrom hermes_cli.auth import ProviderConfig@@ -421,6 +421,8 @@ def _codex_http_client(**kwargs: Any) -> "httpx.Client":token refresh / device login / usage probes time out where the official Codex CLI (which races familiesper RFC 8305) works."""+ normalize_proxy_env_vars() # a bracketed-IPv6 NO_PROXY entry ([::1], Clash Verge/mihomo) makes the bare+ # trust_env client below raise InvalidURL at construction (#118159) — sanitize before building it.client = httpx.Client(event_hooks={"response": [_cap_codex_response_body]}, **kwargs)with suppress(Exception):from agent.process_bootstrap import enable_happy_eyeballs_on_clientdiff --git a/hermes_cli/doctor_connectivity.py b/hermes_cli/doctor_connectivity.pyindex f3a939f5fdd..889a234d460 100644--- a/hermes_cli/doctor_connectivity.py+++ b/hermes_cli/doctor_connectivity.py@@ -18,7 +18,7 @@ from urllib.parse import urlsplitfrom hermes_cli.colors import Colors, colorfrom hermes_cli.models import _HERMES_USER_AGENTfrom hermes_constants import OPENROUTER_MODELS_URL-from utils import base_url_host_matches+from utils import base_url_host_matches, normalize_proxy_env_vars_APIKEY_PROVIDERS_CACHE: list | None = None@@ -430,6 +430,9 @@ def run_probes(probes: list) -> list:"""# Disable boto3's EC2 instance-metadata probe (169.254.169.254, multi-second timeout off-EC2). Set on the# parent thread before submitting so it never races a worker; has_aws_credentials() already gates on real creds.+ normalize_proxy_env_vars() # a bracketed-IPv6 NO_PROXY entry ([::1], Clash Verge/mihomo) makes every bare+ # trust_env client a probe builds raise InvalidURL at construction (#118159) — sanitize once, before any+ # worker runs, so no probe ever reports "(Invalid port: :1])" as provider downtime._imds_prev = os.environ.get("AWS_EC2_METADATA_DISABLED")os.environ["AWS_EC2_METADATA_DISABLED"] = "true"try:diff --git a/tests/hermes_cli/test_auth_codex_no_proxy_ipv6.py b/tests/hermes_cli/test_auth_codex_no_proxy_ipv6.pynew file mode 100644index 00000000000..6f7e856d9ef--- /dev/null+++ b/tests/hermes_cli/test_auth_codex_no_proxy_ipv6.py@@ -0,0 +1,36 @@+"""``_codex_http_client`` survives a bracketed-IPv6 NO_PROXY environment (#118159).++Clash Verge / mihomo write ``[::1]`` into NO_PROXY; httpx 0.28.1 turns that into an+unparseable ``all://*[::1]`` proxy mount, so every bare ``httpx.Client()`` raised+``InvalidURL: Invalid port`` — codex device login died before its first request while chat+(explicit mounts) kept working. The client builder now sanitizes the env before construction.+"""++from __future__ import annotations++import pytest++pytest.importorskip("httpx")++# The exact environment Clash Verge / mihomo exports (issue #118159).+_CLASH_NO_PROXY = "127.0.0.1,localhost,::1,[::1]"+++def clash_env(monkeypatch):+ for key in ("NO_PROXY", "no_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY",+ "http_proxy", "https_proxy", "all_proxy"):+ monkeypatch.delenv(key, raising=False)+ monkeypatch.setenv("NO_PROXY", _CLASH_NO_PROXY)+ monkeypatch.setenv("no_proxy", _CLASH_NO_PROXY)+++def test_codex_http_client_constructs_under_clash_ipv6_no_proxy(clash_env):+ from hermes_cli.auth import _codex_http_client++ # Red on base: InvalidURL('Invalid port: :1]') is raised at httpx.Client construction.+ client = _codex_http_client(timeout=5.0)+ try:+ assert client._mounts is not None # constructed; the bypass mount is a real entry+ finally:+ client.close()diff --git a/tests/hermes_cli/test_doctor_no_proxy_ipv6.py b/tests/hermes_cli/test_doctor_no_proxy_ipv6.pynew file mode 100644index 00000000000..df39479dfff--- /dev/null+++ b/tests/hermes_cli/test_doctor_no_proxy_ipv6.py@@ -0,0 +1,58 @@+"""``hermes doctor`` probes survive a bracketed-IPv6 NO_PROXY environment (#118159).++Clash Verge / mihomo write ``[::1]`` into NO_PROXY; httpx 0.28.1 turns that into an+unparseable ``all://*[::1]`` mount, so every probe's bare ``httpx.get()``/``httpx.Client()``+raised ``InvalidURL: Invalid port`` and the probe table misreported broken connectivity for+every provider. ``run_probes`` (the single entry the doctor uses for the whole table) sanitizes+the environment once before any worker builds a client.+"""++from __future__ import annotations++import pytest++pytest.importorskip("httpx")++from hermes_cli import doctor_connectivity as dc++# The exact environment Clash Verge / mihomo exports (issue #118159).+_CLASH_NO_PROXY = "127.0.0.1,localhost,::1,[::1]"+++def clash_env(monkeypatch):+ for key in ("NO_PROXY", "no_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY",+ "http_proxy", "https_proxy", "all_proxy"):+ monkeypatch.delenv(key, raising=False)+ monkeypatch.setenv("NO_PROXY", _CLASH_NO_PROXY)+ monkeypatch.setenv("no_proxy", _CLASH_NO_PROXY)+++def test_run_probes_sanitizes_env_before_any_worker_builds_a_client(clash_env, monkeypatch):+ import httpx++ def probe_building_a_bare_client():+ # The probe body's exact defect: a bare trust_env httpx client. Red on base this raises+ # InvalidURL inside the worker; run_probes re-raises it from future.result().+ with httpx.Client() as client:+ assert client._mounts is not None+ return dc._row("stand-in", "ok")++ (result,) = dc.run_probes([("stand-in", probe_building_a_bare_client)])+ ((glyph, label, _detail),) = result.lines+ assert "✓" in glyph and label == "stand-in"+ # The seam did it: the in-place rewrite the rest of the process now sees.+ import os++ assert "[::1]" not in os.environ["NO_PROXY"]+ assert os.environ["no_proxy"] == "127.0.0.1,localhost,::1"+++def test_run_probes_leaves_a_clean_environment_untouched(clash_env, monkeypatch):+ monkeypatch.setenv("NO_PROXY", "example.com,10.0.0.0/8")+ monkeypatch.delenv("no_proxy", raising=False)+ (result,) = dc.run_probes([("stand-in", lambda: dc._row("stand-in", "ok"))])+ assert "✓" in result.lines[0][0]+ import os++ assert os.environ["NO_PROXY"] == "example.com,10.0.0.0/8"diff --git a/tests/test_utils_no_proxy_sanitize.py b/tests/test_utils_no_proxy_sanitize.pynew file mode 100644index 00000000000..fb276a36a8c--- /dev/null+++ b/tests/test_utils_no_proxy_sanitize.py@@ -0,0 +1,118 @@+"""NO_PROXY entries httpx cannot compile are rewritten to the bare-IPv6 form (#118159).++Clash Verge / mihomo export loopback bypasses in bracketed form (``[::1]``); httpx 0.28.1's+``get_environment_proxies`` sends any bracketed entry down its wildcard branch, producing+``all://*[::1]``, and ``URLPattern`` dies at ``Client.__init__`` with ``InvalidURL: Invalid port``.+Every bare ``httpx.Client()`` in the process then raises — codex login, doctor probes — while the+chat transport (explicit mounts) keeps working. ``utils.normalize_proxy_env_vars`` (already the+in-place env sanitizer called when chat transports are built) rewrites those entries to the bare+``::1`` literal that httpx compiles into a working ``all://[::1]`` bypass and that urllib, requests+and the repo's own ``agent.proxy_bypass`` matcher all understand.+"""++from __future__ import annotations++import pytest++import httpx++from utils import normalize_proxy_env_vars, sanitize_no_proxy_entries+++def proxy_env(monkeypatch):+ for key in ("NO_PROXY", "no_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY",+ "http_proxy", "https_proxy", "all_proxy"):+ monkeypatch.delenv(key, raising=False)+++# The exact environment Clash Verge / mihomo writes (issue #118159).+_CLASH_NO_PROXY = "127.0.0.1,localhost,::1,[::1]"+++class TestSanitizeNoProxyEntries:+ def test_bracketed_ipv6_becomes_bare_literal(self):+ assert sanitize_no_proxy_entries(_CLASH_NO_PROXY) == "127.0.0.1,localhost,::1"++ @pytest.mark.parametrize(+ "entry,expected",+ [+ ("[::1]", "::1"),+ ("[::1]:8080", "::1"), # httpx cannot express a port-scoped v6 bypass; the literal still bypasses every port+ ("[2001:db8::1]", "2001:db8::1"),+ ("[::ffff:127.0.0.1]", "::ffff:127.0.0.1"),+ ("[::1]/128", "::1"),+ ("::1/128", "::1"), # httpx cannot compile v6 CIDR bypasses at all; degrade to the bare literal+ ("2001:db8::/32", "2001:db8::"),+ ],+ )+ def test_bracketed_and_cidr_ipv6_entries_are_rewritten(self, entry, expected):+ assert sanitize_no_proxy_entries(f"example.com,{entry}") == f"example.com,{expected}"++ @pytest.mark.parametrize(+ "value",+ [+ "", # nothing set: nothing invented+ "*",+ "127.0.0.1,localhost,::1",+ "10.0.0.0/8,*.internal", # IPv4 CIDR / wildcard domains: httpx compiles these fine+ "[127.0.0.1]", # bracketed IPv4: not the broken form, untouched+ "[not-an-ip]", # bracketed junk: httpx's wildcard branch compiles it, untouched+ "example.com, spaced.internal ,10.0.0.5",+ "::1:8080", # a valid v6 address in its own right (hex), httpx compiles it+ ],+ )+ def test_unaffected_values_pass_through_byte_stable(self, value):+ assert sanitize_no_proxy_entries(value) == value+++class TestNormalizeProxyEnvVars:+ def test_rewrites_both_casings_in_place(self, proxy_env, monkeypatch):+ monkeypatch.setenv("NO_PROXY", _CLASH_NO_PROXY)+ monkeypatch.setenv("no_proxy", _CLASH_NO_PROXY)+ normalize_proxy_env_vars()+ assert os_get("NO_PROXY") == "127.0.0.1,localhost,::1"+ assert os_get("no_proxy") == "127.0.0.1,localhost,::1"++ def test_clean_environment_is_left_untouched(self, proxy_env, monkeypatch):+ monkeypatch.setenv("NO_PROXY", "example.com,10.0.0.0/8")+ normalize_proxy_env_vars()+ assert os_get("NO_PROXY") == "example.com,10.0.0.0/8"++ def test_socks_scheme_normalization_keeps_working(self, proxy_env, monkeypatch):+ monkeypatch.setenv("HTTPS_PROXY", "socks://127.0.0.1:7890")+ monkeypatch.setenv("NO_PROXY", _CLASH_NO_PROXY)+ normalize_proxy_env_vars()+ assert os_get("HTTPS_PROXY") == "socks5://127.0.0.1:7890" # pre-existing behavior intact+ assert os_get("NO_PROXY") == "127.0.0.1,localhost,::1"+++class TestSanitizedEnvYieldsAWorkingHttpxClient:+ def test_client_constructs_and_loopback_v6_bypasses(self, proxy_env, monkeypatch):+ monkeypatch.setenv("NO_PROXY", _CLASH_NO_PROXY)+ monkeypatch.setenv("no_proxy", _CLASH_NO_PROXY)+ normalize_proxy_env_vars()+ # Red on base: the unsanitized Clash env raises InvalidURL at construction.+ client = httpx.Client() # noqa: SIM115 - closed below+ try:+ assert any(+ pattern.matches(httpx.URL("http://[::1]:8080/")) and transport is None+ for pattern, transport in client._mounts.items()+ )+ finally:+ client.close()++ def test_bypass_still_matches_after_normalization(self, proxy_env, monkeypatch):+ from agent.proxy_bypass import should_bypass_proxy++ monkeypatch.setenv("NO_PROXY", _CLASH_NO_PROXY)+ normalize_proxy_env_vars()+ assert should_bypass_proxy("http://[::1]:8080/")+ assert should_bypass_proxy("https://[::1]/")+ assert not should_bypass_proxy("https://api.example.com/")+++def os_get(key: str) -> str:+ import os++ return os.environ[key]diff --git a/utils.py b/utils.pyindex b19741c9fd3..b266fa9336f 100644--- a/utils.py+++ b/utils.py@@ -4,6 +4,7 @@ import errnoimport jsonimport loggingimport os+import reimport shutilimport statimport tempfile@@ -646,6 +647,7 @@ def env_bool(key: str, default: bool = False) -> bool:_PROXY_ENV_KEYS = ("HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "https_proxy", "http_proxy", "all_proxy")+_NO_PROXY_ENV_KEYS = ("NO_PROXY", "no_proxy")def normalize_proxy_url(proxy_url: str | None) -> str | None:@@ -656,6 +658,54 @@ def normalize_proxy_url(proxy_url: str | None) -> str | None:return candidate or None+def _bare_ipv6_literal(entry: str) -> str | None:+ """The bare IPv6 literal a NO_PROXY entry should become, or None when the entry is not an+ IPv6 form httpx cannot compile (``[::1]``, ``[::1]:8080``, ``[2001:db8::1]/64``, ``::1/128``).++ httpx 0.28.1's ``get_environment_proxies`` routes bracketed entries through its wildcard+ branch (``all://*[::1]`` → ``InvalidURL: Invalid port`` at ``Client.__init__``) and cannot+ compile IPv6 CIDR bypasses at all, so both degrade to the bare literal — which httpx compiles+ into a working ``all://[<v6>]`` bypass and urllib, requests and ``agent.proxy_bypass`` all+ understand. A ``[<v6>]:port`` entry loses its port: httpx has no port-scoped IPv6 bypass form,+ and the portless literal still bypasses every port (the operator's intent superset). Bracketed+ or CIDR IPv4 is left alone (httpx compiles those forms fine).+ """+ import ipaddress++ candidate = str(entry or "").strip()+ m = (re.fullmatch(r"\[([0-9A-Fa-f:.]+)\](?:[/:].*)?", candidate)+ or re.fullmatch(r"([0-9A-Fa-f:.]+)/\d+", candidate))+ if not m:+ return None+ try:+ ip = ipaddress.ip_address(m.group(1))+ except ValueError:+ return None # bracketed junk: httpx's wildcard branch compiles it; not ours to touch+ return m.group(1) if ip.version == 6 else None+++def sanitize_no_proxy_entries(no_proxy_value: str | None) -> str:+ """Rewrite NO_PROXY entries httpx 0.28.1 cannot compile into the equivalent bare-IPv6 forms.++ Every other entry passes through verbatim, and the original string is returned byte-stable+ when nothing needed rewriting (an env without bracketed/CIDR IPv6 entries is untouched).+ """+ raw = str(no_proxy_value or "")+ entries = [part for part in re.split(r"[\s,]+", raw.strip()) if part]+ if not entries or "*" in entries: # a wildcard bypasses everything; httpx returns no mounts+ return raw+ rewritten: list[str] = []+ for entry in entries:+ bare = _bare_ipv6_literal(entry)+ if bare is None:+ rewritten.append(entry) # not ours to touch: IPv4, IPv4 CIDR, domains, junk+ elif bare not in rewritten:+ rewritten.append(bare)+ if rewritten == entries:+ return raw+ return ",".join(rewritten)++def normalize_proxy_env_vars() -> None:"""Rewrite supported proxy env vars to canonical URL forms in-place."""for key in _PROXY_ENV_KEYS:@@ -663,6 +713,12 @@ def normalize_proxy_env_vars() -> None:normalized = normalize_proxy_url(value)if normalized and normalized != value:os.environ[key] = normalized+ for key in _NO_PROXY_ENV_KEYS:+ value = os.getenv(key)+ if value:+ sanitized = sanitize_no_proxy_entries(value)+ if sanitized != value:+ os.environ[key] = sanitizeddef _parse_base_url(base_url: str):