Skip to content

Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.

fix(url_safety): let the configured HTTP proxy resolve inside the pinned scope

Tobi | Nordaluxd601422fed99
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 047c507..1cf9265 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- Every live fetch failed behind an HTTP proxy on loopback
+ (`HTTPS_PROXY=http://127.0.0.1:<port>`, the usual sandbox and CI setup): the
+ pinned resolver refused to resolve the proxy's own address as non-public. The
+ proxy host `requests` selects for the URL is now exempt from that check, and
+ only that host. (#280)
+
## [2.2.6] - 2026-09-10
### Security
diff --git a/scripts/url_safety.py b/scripts/url_safety.py
index 91b163a..5dfb279 100644
--- a/scripts/url_safety.py
+++ b/scripts/url_safety.py
@@ -355,6 +355,24 @@ def validate_url_strict(url: str) -> tuple[str, str]:
return url, pinned
+def _proxy_hosts(url: str, proxies: Optional[dict] = None) -> frozenset:
+ """Hostnames ``requests`` will connect to instead of ``url``'s host.
+
+ Mirrors the proxy selection ``requests`` performs for a plain call:
+ environment proxies (``HTTPS_PROXY`` and friends, honouring ``NO_PROXY``)
+ overridden by an explicit ``proxies`` mapping. Returns the empty set when
+ the request goes direct.
+ """
+ merged = dict(requests.utils.get_environ_proxies(url))
+ if proxies:
+ merged.update(proxies)
+ proxy = requests.utils.select_proxy(url, merged)
+ if not proxy:
+ return frozenset()
+ host = urlparse(requests.utils.prepend_scheme_if_needed(proxy, "http")).hostname
+ return frozenset({host.lower()}) if host else frozenset()
+
+
# A single non-blocking lock guards the global getaddrinfo monkey-patch.
# This is a deliberate choice: claude-seo scripts run one URL fetch at a
# time, and we'd rather raise loudly than silently corrupt resolver state
@@ -363,7 +381,12 @@ _dns_patch_lock = threading.Lock()
@contextmanager
-def _pin_dns(hostname: str, pinned_ip: str, port: int) -> Iterator[None]:
+def _pin_dns(
+ hostname: str,
+ pinned_ip: str,
+ port: int,
+ exempt_hosts: frozenset = frozenset(),
+) -> Iterator[None]:
"""
Temporarily override ``socket.getaddrinfo`` so the named host resolves
only to ``pinned_ip``, AND every other hostname looked up during the
@@ -372,6 +395,13 @@ def _pin_dns(hostname: str, pinned_ip: str, port: int) -> Iterator[None]:
which ``requests`` surfaces as ``ConnectionError`` — the caller's
existing error path.
+ ``exempt_hosts`` are resolved by the real resolver without validation.
+ It carries the configured HTTP proxy, if any (see :func:`_proxy_hosts`):
+ the proxy is the process's own egress and commonly sits on loopback, so
+ refusing it refused every fetch. Behind a CONNECT proxy the target is
+ resolved by the proxy, and :func:`validate_url_strict`'s pre-flight
+ check remains the guard for it.
+
The fall-through validation is the v2 fix for redirect-target DNS
rebinding: ``requests.Session.get(allow_redirects=True)`` may follow
30x redirects to a *different* hostname; without this guard, the
@@ -408,6 +438,9 @@ def _pin_dns(hostname: str, pinned_ip: str, port: int) -> Iterator[None]:
f"IPv4 host {host}",
)
+ if host and host.lower() in exempt_hosts:
+ return original_getaddrinfo(host, requested_port, *args, **kwargs)
+
# Branch 2: every OTHER hostname (redirect target, embedded
# subresource, library bookkeeping) gets resolved by the real
# resolver, then each returned record is checked. A single
@@ -450,7 +483,8 @@ def safe_requests_get(
parsed = urlparse(norm_url)
port = parsed.port or (443 if parsed.scheme == "https" else 80)
assert parsed.hostname is not None # validate_url_strict guarantees this
- with _pin_dns(parsed.hostname, pinned_ip, port):
+ exempt = _proxy_hosts(norm_url, kwargs.get("proxies"))
+ with _pin_dns(parsed.hostname, pinned_ip, port, exempt_hosts=exempt):
return requests.get(norm_url, timeout=timeout, **kwargs)
@@ -470,7 +504,8 @@ def safe_requests_head(
parsed = urlparse(norm_url)
port = parsed.port or (443 if parsed.scheme == "https" else 80)
assert parsed.hostname is not None
- with _pin_dns(parsed.hostname, pinned_ip, port):
+ exempt = _proxy_hosts(norm_url, kwargs.get("proxies"))
+ with _pin_dns(parsed.hostname, pinned_ip, port, exempt_hosts=exempt):
return requests.head(norm_url, timeout=timeout, **kwargs)
@@ -486,7 +521,8 @@ def safe_requests_session(url: str) -> Iterator[requests.Session]:
port = parsed.port or (443 if parsed.scheme == "https" else 80)
assert parsed.hostname is not None
session = requests.Session()
- with _pin_dns(parsed.hostname, pinned_ip, port):
+ exempt = _proxy_hosts(norm_url, session.proxies)
+ with _pin_dns(parsed.hostname, pinned_ip, port, exempt_hosts=exempt):
try:
yield session
finally:
diff --git a/tests/test_url_safety.py b/tests/test_url_safety.py
index da6f467..86de415 100644
--- a/tests/test_url_safety.py
+++ b/tests/test_url_safety.py
@@ -20,6 +20,7 @@ from types import SimpleNamespace
from unittest.mock import patch
import pytest
+import requests
_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")
if _SCRIPTS not in sys.path:
@@ -321,8 +322,9 @@ def test_safe_requests_head_uses_strict_validation_and_dns_pin() -> None:
response = SimpleNamespace(status_code=200)
@contextmanager
- def fake_pin(hostname: str, pinned_ip: str, port: int):
+ def fake_pin(hostname: str, pinned_ip: str, port: int, exempt_hosts=frozenset()):
captured["pin"] = (hostname, pinned_ip, port)
+ captured["exempt"] = exempt_hosts
yield
with patch.object(
@@ -616,3 +618,103 @@ def test_load_oauth_token_remediates_legacy_0o644(tmp_path, monkeypatch) -> None
data = google_auth._load_oauth_token()
assert data == {"access_token": "x"}
assert target.stat().st_mode & 0o777 == 0o600
+
+
+# ---------------------------------------------------------------------------
+# Configured HTTP proxy (issue #280): the proxy host must resolve
+# ---------------------------------------------------------------------------
+
+
+def _addrinfo(ip: str, port: int) -> list:
+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, port))]
+
+
+def _system_proxies(monkeypatch, mapping: dict) -> None:
+ """Pin what ``requests`` sees as the environment's proxies. Going through
+ the real ``getproxies`` would pick up the developer's own HTTPS_PROXY, or
+ the Windows registry proxy, and make these tests machine-dependent."""
+ monkeypatch.setattr(url_safety.requests.utils, "getproxies", lambda: dict(mapping))
+
+
+def test_proxy_hosts_reads_environment_and_honours_no_proxy(monkeypatch) -> None:
+ _system_proxies(monkeypatch, {"https": "http://127.0.0.1:3128"})
+ monkeypatch.setenv("NO_PROXY", "direct.example")
+ assert url_safety._proxy_hosts("https://example.com/") == frozenset({"127.0.0.1"})
+ assert url_safety._proxy_hosts("https://direct.example/") == frozenset()
+ assert url_safety._proxy_hosts("http://example.com/") == frozenset()
+
+
+def test_proxy_hosts_prefers_explicit_proxies_mapping(monkeypatch) -> None:
+ _system_proxies(monkeypatch, {"https": "http://127.0.0.1:3128"})
+ explicit = {"https": "proxy.corp.example:8080"}
+ assert url_safety._proxy_hosts("https://example.com/", explicit) == frozenset(
+ {"proxy.corp.example"}
+ )
+
+
+def test_proxy_hosts_is_empty_without_a_proxy(monkeypatch) -> None:
+ _system_proxies(monkeypatch, {})
+ assert url_safety._proxy_hosts("https://example.com/") == frozenset()
+
+
+def test_pin_dns_lets_the_exempt_proxy_host_resolve_to_loopback() -> None:
+ original_getaddrinfo = socket.getaddrinfo
+
+ def fake_getaddrinfo(host, port, *args, **kwargs):
+ if host == "127.0.0.1":
+ return _addrinfo("127.0.0.1", port or 3128)
+ return original_getaddrinfo(host, port, *args, **kwargs)
+
+ with patch.object(url_safety.socket, "getaddrinfo", side_effect=fake_getaddrinfo):
+ # Without the exemption the loopback proxy is refused (the #280 symptom).
+ with url_safety._pin_dns("pinned.example", "8.8.8.8", 443):
+ with pytest.raises(socket.gaierror, match="non-public IP"):
+ socket.getaddrinfo("127.0.0.1", 3128)
+ with url_safety._pin_dns(
+ "pinned.example", "8.8.8.8", 443, exempt_hosts=frozenset({"127.0.0.1"})
+ ):
+ assert socket.getaddrinfo("127.0.0.1", 3128)[0][4][0] == "127.0.0.1"
+
+
+def test_pin_dns_exemption_does_not_leak_to_other_hosts() -> None:
+ """Only the proxy host is exempt; a redirect target on loopback still fails."""
+ original_getaddrinfo = socket.getaddrinfo
+
+ def fake_getaddrinfo(host, port, *args, **kwargs):
+ if host == "redirected.example":
+ return _addrinfo("127.0.0.1", port or 80)
+ return original_getaddrinfo(host, port, *args, **kwargs)
+
+ with patch.object(url_safety.socket, "getaddrinfo", side_effect=fake_getaddrinfo):
+ with url_safety._pin_dns(
+ "pinned.example", "8.8.8.8", 443, exempt_hosts=frozenset({"127.0.0.1"})
+ ):
+ with pytest.raises(socket.gaierror, match="non-public IP"):
+ socket.getaddrinfo("redirected.example", 80)
+
+
+def test_safe_requests_get_reaches_a_loopback_proxy(monkeypatch) -> None:
+ """End to end, offline: with HTTPS_PROXY on loopback the request must get
+ as far as the proxy socket. A closed port turns that into a plain
+ connection refusal, whereas before the fix url_safety refused to resolve
+ the proxy at all."""
+ probe = socket.socket()
+ probe.bind(("127.0.0.1", 0))
+ closed_port = probe.getsockname()[1]
+ probe.close()
+ _system_proxies(monkeypatch, {"https": f"http://127.0.0.1:{closed_port}"})
+ monkeypatch.delenv("NO_PROXY", raising=False)
+
+ original_getaddrinfo = socket.getaddrinfo
+
+ def fake_getaddrinfo(host, port, *args, **kwargs):
+ if host == "example.com":
+ return _addrinfo("93.184.216.34", port or 443)
+ if host == "127.0.0.1":
+ return _addrinfo("127.0.0.1", port or closed_port)
+ return original_getaddrinfo(host, port, *args, **kwargs)
+
+ with patch.object(url_safety.socket, "getaddrinfo", side_effect=fake_getaddrinfo):
+ with pytest.raises(requests.exceptions.ProxyError) as excinfo:
+ url_safety.safe_requests_get("https://example.com/", timeout=5)
+ assert "url_safety: refused to resolve" not in str(excinfo.value)