Calls to this computer's own servers skip the system proxy (tuner, tune session, launch self-check)

This commit is contained in:
Niko1221 committed 2026-10-20 17:00:00 +02:00
1 parent c6a0e739be
commit af189129a4
5 files changed
+85 -7

No files matched your search

+3 -1
View File
@@ -15,6 +15,8 @@ import urllib.error
import urllib.request
from dataclasses import dataclass
from strata_control import loopback
#: harness id -> the endpoint family it speaks (the others use chat completions)
WIRE = {"codex": "responses", "claude-code": "messages"}
@@ -37,7 +39,7 @@ def _post(url: str, key: str, body: dict, headers: dict | None = None, timeout:
h["Authorization"] = "Bearer " + key
h["x-api-key"] = key
req = urllib.request.Request(url, data=json.dumps(body).encode("utf-8"), headers=h, method="POST")
with urllib.request.urlopen(req, timeout=timeout) as r:
with loopback.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8", "replace"))
+28
View File
@@ -0,0 +1,28 @@
"""HTTP calls to this computer's own servers (127.0.0.1, localhost, ::1) never go through a proxy.
`urllib.request.urlopen` follows the system proxy (HTTP_PROXY, the Windows registry, a PAC file). A school or office PC sends
`http://127.0.0.1:PORT/health` to that proxy, which cannot reach it, and Strata then reports a healthy server as "did not answer".
Everything that talks to a local server uses `urlopen` below; any other address is passed on unchanged.
"""
from __future__ import annotations
import urllib.request
from urllib.parse import urlsplit
_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
_LOCAL = {"127.0.0.1", "localhost", "::1"}
def is_loopback(url: str) -> bool:
try:
return (urlsplit(url).hostname or "").lower() in _LOCAL
except ValueError:
return False
def urlopen(request, timeout: float | None = None):
url = request if isinstance(request, str) else request.full_url
if is_loopback(url):
return _OPENER.open(request, timeout=timeout)
return urllib.request.urlopen(request, timeout=timeout)
+3 -2
View File
@@ -34,6 +34,7 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from strata_control import loopback
from strata_control.tune_engine import EngineMeasurement, MeasurementError, process_tree_peak_mib
@@ -94,7 +95,7 @@ class ApiHarness:
f"the worker exited with code {self._proc.returncode} before becoming ready"
+ self._log_tail())
try:
with urllib.request.urlopen(f"{self.url}/health", timeout=2) as response:
with loopback.urlopen(f"{self.url}/health", timeout=2) as response:
if response.status == 200:
return
except (urllib.error.URLError, OSError):
@@ -172,7 +173,7 @@ class ApiHarness:
usage: dict[str, Any] = {}
finish: str | None = None
try:
with urllib.request.urlopen(request, timeout=self.request_timeout_s) as response:
with loopback.urlopen(request, timeout=self.request_timeout_s) as response:
for raw in response:
line = raw.decode("utf-8", errors="replace").strip()
if not line.startswith("data:"):
+4 -4
View File
@@ -31,7 +31,7 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable, Iterator, Protocol
from strata_control import tune_machine
from strata_control import loopback, tune_machine
# --------------------------------------------------------------------------- the contract
@@ -304,7 +304,7 @@ class WorkerEngine:
def _model_id(self) -> None:
try:
req = urllib.request.Request(f"http://127.0.0.1:{self.port}/v1/models", headers=self._h())
with urllib.request.urlopen(req, timeout=10) as r:
with loopback.urlopen(req, timeout=10) as r:
data = json.loads(r.read())
self.model = ((data.get("data") or [{}])[0]).get("id") or self.model
except Exception: # noqa: BLE001
@@ -326,7 +326,7 @@ class WorkerEngine:
req = urllib.request.Request(f"http://127.0.0.1:{self.port}/v1/chat/completions",
data=json.dumps(body).encode(), headers=self._h(), method="POST")
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
with loopback.urlopen(req, timeout=timeout) as r:
data = json.loads(r.read())
except urllib.error.HTTPError as e:
raise StartFailed("NO_TOKENS", f"the worker refused the request ({e.code}): {e.read()[:200]!r}") from None
@@ -488,7 +488,7 @@ class WorkerSession:
try:
req = urllib.request.Request(f"http://127.0.0.1:{port}/health",
headers={"authorization": f"Bearer {key}"})
with urllib.request.urlopen(req, timeout=2) as r:
with loopback.urlopen(req, timeout=2) as r:
if r.status == 200:
ready = True
break
+47
View File
@@ -0,0 +1,47 @@
"""Calls to this computer's own servers must ignore the system proxy (a company proxy cannot reach 127.0.0.1)."""
import http.server
import os
import threading
import unittest
from unittest import mock
from strata_control import loopback
class Hello(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b"ok")
def log_message(self, *a):
pass
class LoopbackTests(unittest.TestCase):
def test_is_loopback(self):
for u in ("http://127.0.0.1:1/x", "http://localhost:2/", "http://[::1]:3/"):
self.assertTrue(loopback.is_loopback(u), u)
for u in ("https://example.com/", "http://192.168.1.5:8080/", "not a url"):
self.assertFalse(loopback.is_loopback(u), u)
def test_local_server_is_reached_with_a_dead_proxy_set(self):
srv = http.server.HTTPServer(("127.0.0.1", 0), Hello)
threading.Thread(target=srv.serve_forever, daemon=True).start()
try:
env = {"HTTP_PROXY": "http://127.0.0.1:9", "http_proxy": "http://127.0.0.1:9", "NO_PROXY": "", "no_proxy": ""}
with mock.patch.dict(os.environ, env):
with loopback.urlopen(f"http://127.0.0.1:{srv.server_port}/", timeout=5) as r:
self.assertEqual(r.read(), b"ok")
finally:
srv.shutdown()
def test_other_addresses_still_use_urllib(self):
with mock.patch("urllib.request.urlopen", return_value="remote") as m:
self.assertEqual(loopback.urlopen("https://example.com/", timeout=3), "remote")
m.assert_called_once()
if __name__ == "__main__":
unittest.main()