Files
fetch-mcp/smoke_proxy.py
omar 5d36fddd30
ci / static (push) Failing after 27s
ci / test-3.12 (push) Skipped
ci / test-3.13 (push) Skipped
ci / image (push) Skipped
ci / smoke (push) Skipped
ci / publish (push) Skipped
Add fetch MCP server with proxy routing, challenge solving and failure reports
Live reads go through an operator proxy pool (round-robin over the newest 100
entries, cooling on connect failures, no direct fallback); stored clearances are
replayed only on the exit that earned them. Identity, clearance, solver and
Turnstile rungs escalate automatically. fetch_pages reads up to 12 URLs four at
a time with per-item isolation. report/reports/reports_update keep a durable
queue of unreadable pages for the operator.

Ships a pinned multi-stage image (non-root 10001, data in /data), an ordered CI
with static gates, tests on 3.12 and 3.13 at 85% coverage, an offline image
smoke, and sha/latest publishing gated on main.
2026-11-28 19:29:46 +03:00

403 lines
15 KiB
Python

"""Local stand: proxy pool behaviour without external networks.
Starts throwaway target, HTTP, HTTPS, SOCKS5 and dead servers on loopback, then
drives transport directly. Run: uv run smoke_proxy.py
"""
import base64
import contextlib
import datetime
import ipaddress
import socket
import ssl
import struct
import tempfile
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlsplit
import proxy
import transport
REQUESTS: dict[str, int] = {"ok": 0, "429": 0, "slow": 0}
class Target(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_GET(self) -> None:
path = urlsplit(self.path).path
REQUESTS[path.strip("/")] = REQUESTS.get(path.strip("/"), 0) + 1
if path == "/429" and REQUESTS["429"] == 1:
body = b"wait"
self.send_response(429)
self.send_header("Retry-After", "1")
elif path == "/429toomuch":
body = b"wait"
self.send_response(429)
self.send_header("Retry-After", "120")
elif path == "/slow":
time.sleep(1.0)
body = b"slow"
self.send_response(200)
else:
body = b"OK"
self.send_response(200)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args: object) -> None:
pass
class Server:
"""A listener that counts accepted connections."""
def __init__(self, handler) -> None:
self.sock = socket.socket()
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(("127.0.0.1", 0))
self.sock.listen(16)
self.port = self.sock.getsockname()[1]
self.hits = 0
self.handler = handler
self.alive = True
threading.Thread(target=self.loop, daemon=True).start()
def loop(self) -> None:
while self.alive:
try:
client, _ = self.sock.accept()
except OSError:
return
self.hits += 1
threading.Thread(target=self.wrap, args=(client,), daemon=True).start()
def wrap(self, client: socket.socket) -> None:
try:
self.handler(client)
finally:
client.close()
def close(self) -> None:
self.alive = False
self.sock.close()
def tunnel(client: socket.socket, host: str, port: int) -> None:
upstream = socket.create_connection((host, port), timeout=5)
try:
client.settimeout(None)
threading.Thread(target=_pipe, args=(upstream, client), daemon=True).start()
_pipe(client, upstream)
finally:
upstream.close()
def _pipe(src: socket.socket, dst: socket.socket) -> None:
try:
while data := src.recv(65536):
dst.sendall(data)
except OSError:
pass
finally:
with contextlib.suppress(OSError):
dst.shutdown(socket.SHUT_WR)
def read_headers(client: socket.socket) -> str:
buffer = b""
while b"\r\n\r\n" not in buffer and len(buffer) < 65536:
chunk = client.recv(4096)
if not chunk:
break
buffer += chunk
return buffer.decode("latin-1")
def http_proxy(credentials: tuple[str, str] | None = None):
def handle(client: socket.socket) -> None:
head = read_headers(client)
lines = head.split("\r\n")
if credentials and len(lines) > 1:
expected = "Basic " + base64.b64encode(("{}:{}".format(*credentials)).encode()).decode()
sent = [line.split(": ", 1)[1].strip() for line in lines[1:] if ":" in line]
if expected not in sent:
client.sendall(b"HTTP/1.1 407 Proxy Authentication Required\r\n\r\n")
return
method, target, _ = lines[0].split(" ")
if method == "CONNECT":
host, port = target.rsplit(":", 1)
client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
tunnel(client, host, int(port))
return
parts = urlsplit(target)
upstream = socket.create_connection((parts.hostname, parts.port or 80), timeout=5)
rest = head.split("\r\n", 1)[1]
path = parts.path + (f"?{parts.query}" if parts.query else "")
upstream.sendall(f"{method} {path} HTTP/1.1\r\n{rest}".encode("latin-1"))
_pipe(upstream, client)
upstream.close()
return handle
def https_proxy(context: ssl.SSLContext):
inner = http_proxy()
def handle(client: socket.socket) -> None:
try:
wrapped = context.wrap_socket(client, server_side=True)
except ssl.SSLError:
return
try:
inner(wrapped)
finally:
wrapped.close()
return handle
def socks5(credentials: tuple[str, str] | None = None):
def handle(client: socket.socket) -> None:
version, count = client.recv(2)
methods = client.recv(count)
want = 2 if credentials else 0
if want not in methods:
client.sendall(b"\x05\xff")
return
client.sendall(bytes([5, want]))
if credentials:
_, length = client.recv(2)
user = client.recv(length).decode()
_, length = client.recv(2)
password = client.recv(length).decode()
client.sendall(b"\x01\x00" if (user, password) == credentials else b"\x01\x01")
if (user, password) != credentials:
return
_, command, _, address_type = client.recv(4)
if address_type == 1:
host = socket.inet_ntoa(client.recv(4))
elif address_type == 3:
host = client.recv(client.recv(1)[0]).decode()
else:
host = socket.inet_ntop(socket.AF_INET6, client.recv(16))
port = struct.unpack("!H", client.recv(2))[0]
if command != 1:
client.sendall(b"\x05\x07\x00\x01" + b"\x00" * 6)
return
client.sendall(b"\x05\x00\x00\x01" + b"\x00" * 6)
tunnel(client, host, port)
return handle
def selfsigned() -> tuple[Path, ssl.SSLContext]:
"""Create a throwaway CA plus a 127.0.0.1 leaf it signs; return CA path and server TLS."""
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
now = datetime.datetime.now(datetime.UTC)
ca_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
ca_name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "fetch-mcp test CA")])
ca = (
x509.CertificateBuilder()
.subject_name(ca_name)
.issuer_name(ca_name)
.public_key(ca_key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(now - datetime.timedelta(minutes=5))
.not_valid_after(now + datetime.timedelta(days=1))
.add_extension(x509.BasicConstraints(ca=True, path_length=0), True)
.add_extension(
x509.KeyUsage(
digital_signature=True,
key_cert_sign=True,
crl_sign=True,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
encipher_only=False,
decipher_only=False,
),
True,
)
.sign(ca_key, hashes.SHA256())
)
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
cert = (
x509.CertificateBuilder()
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "127.0.0.1")]))
.issuer_name(ca_name)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(now - datetime.timedelta(minutes=5))
.not_valid_after(now + datetime.timedelta(days=1))
.add_extension(x509.BasicConstraints(ca=False, path_length=None), True)
.add_extension(
x509.SubjectAlternativeName(
[
x509.DNSName("127.0.0.1"),
x509.IPAddress(ipaddress.ip_address("127.0.0.1")),
]
),
False,
)
.sign(ca_key, hashes.SHA256())
)
folder = Path(tempfile.mkdtemp())
ca_path = folder / "ca.pem"
ca_path.write_bytes(ca.public_bytes(serialization.Encoding.PEM))
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(_pair(folder, cert, key))
return ca_path, context
def _pair(folder: Path, cert, key) -> str:
from cryptography.hazmat.primitives import serialization
path = folder / "pair.pem"
path.write_bytes(
cert.public_bytes(serialization.Encoding.PEM)
+ key.private_bytes(
serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, serialization.NoEncryption()
)
)
return str(path)
def pool_of(*urls: str) -> proxy.Pool:
result = proxy.Pool(_route="proxy")
result.load_literal("[" + ",".join(f'"{u}"' for u in urls) + "]")
return result
def check(label: str, condition: bool, detail: str = "") -> None:
print(("PASS " if condition else "FAIL ") + label + (f" - {detail}" if detail and not condition else ""))
if not condition:
raise SystemExit(1)
def main() -> None:
target = Server(Target.__init__ and None) # placeholder, replaced below
target.close()
target = ThreadingHTTPServer(("127.0.0.1", 0), Target)
target_port = target.server_address[1]
threading.Thread(target=target.serve_forever, daemon=True).start()
base = f"http://127.0.0.1:{target_port}"
pem, tls = selfsigned()
import os
os.environ["MCP_PROXY_CA"] = str(pem)
os.environ["MCP_HTTP_MAX_RETRIES"] = "2"
http_a, http_b = Server(http_proxy()), Server(http_proxy(("user", "pa ss")))
https_a = Server(https_proxy(tls))
socks5_a = Server(socks5())
socks5h_a = Server(socks5())
dead = Server(http_proxy())
dead.close()
transport.POOL = pool_of(
f"http://127.0.0.1:{http_a.port}",
f"https://127.0.0.1:{https_a.port}",
f"socks5://127.0.0.1:{socks5_a.port}",
f"socks5h://127.0.0.1:{socks5h_a.port}",
f"http://user:pa%20ss@127.0.0.1:{http_b.port}",
)
# Every scheme reaches the target.
for label in ("http", "https", "socks5", "socks5h", "http+credentials"):
result = transport.download(base + "/ok", allow_private=True)
check(f"scheme {label}", result.body == b"OK" and result.route == "proxy", result.body.decode(errors="replace"))
# Round-robin distributes over distinct proxies.
before = {s.port: s.hits for s in (http_a, https_a, socks5_a, socks5h_a, http_b)}
for _ in range(5):
transport.download(base + "/ok", allow_private=True)
moved = {s.port: s.hits - before[s.port] for s in (http_a, https_a, socks5_a, socks5h_a, http_b)}
check("round-robin spreads load", all(count >= 1 for count in moved.values()), str(moved))
# One dead proxy cools and the next one serves.
transport.POOL = pool_of(f"http://127.0.0.1:{dead.port}", f"http://127.0.0.1:{http_a.port}")
check("dead proxy fails over", transport.download(base + "/ok", allow_private=True).body == b"OK")
check("dead proxy cools down", transport.POOL.snapshot()[0]["available"] is False)
# Whole pool dead: no silent direct fallback.
transport.POOL = pool_of(f"http://127.0.0.1:{dead.port}")
try:
transport.download(base + "/ok", allow_private=True)
check("pool down reports", False)
except transport.FetchError as error:
check("pool down reports proxy_unavailable", error.code == "proxy_unavailable", error.code)
# 429 honours Retry-After and then succeeds on the same site.
transport.POOL = pool_of(f"http://127.0.0.1:{http_a.port}")
REQUESTS["429"] = 0
started = time.monotonic()
result = transport.download(base + "/429", allow_private=True)
waited = time.monotonic() - started
check("429 waits then succeeds", result.body == b"OK" and waited >= 0.9, f"{waited:.2f}s")
# 429 beyond the deadline surfaces retry_at instead of blocking.
try:
transport.download(base + "/429toomuch", allow_private=True, deadline=3)
check("long 429 reports", False)
except transport.FetchError as error:
check("long 429 reports retry_at", error.code == "rate_limited" and error.retry_at is not None, error.code)
# Replacement during an in-flight request lets the old one finish.
transport._pauses._until.clear()
transport.POOL = pool_of(f"http://127.0.0.1:{http_a.port}")
outcome: list[str] = []
def slow_call() -> None:
try:
outcome.append(transport.download(base + "/slow", allow_private=True).body.decode())
except transport.FetchError as error: # pragma: no cover
outcome.append(error.code)
worker = threading.Thread(target=slow_call)
worker.start()
time.sleep(0.2)
transport.POOL._apply(proxy.parse_list(f"http://user:pa%20ss@127.0.0.1:{http_b.port}\n"))
worker.join(10)
check("in-flight survives replacement", outcome == ["slow"], str(outcome))
after = transport.download(base + "/ok", allow_private=True)
check("replacement proxy is used", after.proxy is not None and str(http_b.port) in after.proxy, str(after.proxy))
# A pin keeps the same exit even though rotation would move on.
transport.POOL = pool_of(f"http://127.0.0.1:{http_a.port}", f"http://127.0.0.1:{socks5_a.port}")
pinned_url = transport.POOL.snapshot()[0]["proxy"]
start_hits = socks5_a.hits
for _ in range(3):
kept = transport.download(base + "/ok", allow_private=True, pin=pinned_url)
check("pin reuses the exit", str(http_a.port) in (kept.proxy or ""), str(kept.proxy))
check("pin does not touch the other exit", socks5_a.hits == start_hits)
# Wrong proxy credentials are a proxy fault: cool it and use the next exit.
bad = Server(http_proxy(("user", "wrong")))
transport._pauses._until.clear()
transport.POOL = pool_of(f"http://user:pa%20ss@127.0.0.1:{bad.port}", f"http://127.0.0.1:{http_a.port}")
check("bad credentials rotate", transport.download(base + "/ok", allow_private=True).body == b"OK")
check("bad credentials cool the exit", transport.POOL.snapshot()[0]["available"] is False)
# Direct route keeps working and ignores the pool.
transport.POOL = proxy.Pool(_route="direct")
direct = transport.download(base + "/ok", allow_private=True)
check("direct route is separate", direct.route == "direct" and direct.body == b"OK")
print("PASS: four schemes, credentials, round-robin, failover, pool outage, 429, live replacement, direct")
if __name__ == "__main__":
main()