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.
307 lines
10 KiB
Python
307 lines
10 KiB
Python
"""Loopback fixtures: a target site plus HTTP, HTTPS and SOCKS5 proxies."""
|
|
|
|
import base64
|
|
import contextlib
|
|
import datetime
|
|
import ipaddress
|
|
import socket
|
|
import ssl
|
|
import struct
|
|
import tempfile
|
|
import threading
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from pathlib import Path
|
|
from urllib.parse import urlsplit
|
|
|
|
|
|
class Target(BaseHTTPRequestHandler):
|
|
protocol_version = "HTTP/1.1"
|
|
|
|
def do_GET(self) -> None:
|
|
path = urlsplit(self.path).path
|
|
hits = self.server.hits
|
|
hits[path] = hits.get(path, 0) + 1
|
|
status = 200
|
|
body = b"OK"
|
|
extra: dict[str, str] = {}
|
|
if path == "/429" and hits["/429"] == 1:
|
|
status = 429
|
|
extra["Retry-After"] = "1"
|
|
body = b"wait"
|
|
elif path == "/429forever":
|
|
status = 429
|
|
extra["Retry-After"] = "120"
|
|
body = b"wait"
|
|
elif path == "/429once":
|
|
status = 429
|
|
extra["Retry-After"] = "0"
|
|
body = b"wait"
|
|
elif path == "/challenge":
|
|
status = 403
|
|
extra["cf-mitigated"] = "challenge"
|
|
body = b'<html><title>Just a moment...</title><div id="challenge-stage"></div></html>'
|
|
elif path == "/html":
|
|
body = b"<html><body><h1>Hello</h1><p>text</p></body></html>"
|
|
elif path == "/json":
|
|
body = b'{"a": 1, "b": [1, 2]}'
|
|
elif path == "/big":
|
|
body = b"x" * (2 * 1024 * 1024 + 10)
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", "application/json" if path == "/json" else "text/html; charset=utf-8")
|
|
for name, value in extra.items():
|
|
self.send_header(name, value)
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def log_message(self, *args: object) -> None:
|
|
pass
|
|
|
|
|
|
class _Daemon(ThreadingHTTPServer):
|
|
daemon_threads = True
|
|
block_on_close = False
|
|
|
|
|
|
class Site:
|
|
def __init__(self) -> None:
|
|
self.server = _Daemon(("127.0.0.1", 0), Target)
|
|
self.server.hits = {}
|
|
self.port = self.server.server_address[1]
|
|
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
|
|
|
@property
|
|
def hits(self) -> dict[str, int]:
|
|
return self.server.hits
|
|
|
|
def url(self, path: str = "/ok") -> str:
|
|
return f"http://127.0.0.1:{self.port}{path}"
|
|
|
|
def close(self) -> None:
|
|
self.server.shutdown()
|
|
self.server.server_close()
|
|
|
|
|
|
class Server:
|
|
"""A proxy listener that counts accepted connections and can be killed."""
|
|
|
|
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 url(self, scheme: str = "http") -> str:
|
|
return f"{scheme}://127.0.0.1:{self.port}"
|
|
|
|
def close(self) -> None:
|
|
self.alive = False
|
|
self.sock.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 _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 _read_heads(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_heads(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)
|
|
path = parts.path + (f"?{parts.query}" if parts.query else "")
|
|
# Keep the client's own header block, including its terminator, and
|
|
# only rewrite the request line to origin form.
|
|
upstream.sendall((f"{method} {path} HTTP/1.1" + head[len(lines[0]) :]).encode("latin-1"))
|
|
_pipe(upstream, client)
|
|
upstream.close()
|
|
|
|
return handle
|
|
|
|
|
|
def socks5(credentials: tuple[str, str] | None = None):
|
|
def handle(client: socket.socket) -> None:
|
|
_, 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()
|
|
ok = (user, password) == credentials
|
|
client.sendall(b"\x01\x00" if ok else b"\x01\x01")
|
|
if not ok:
|
|
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 _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 ca_and_tls() -> tuple[str, ssl.SSLContext]:
|
|
"""Throwaway CA and a 127.0.0.1 leaf it signs."""
|
|
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 str(ca_path), context
|
|
|
|
|
|
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
|