Files
alzeo/tests/test_proxy_tls.py
T
Hasan BasbunarandClaude Opus 5.5 8bb32a2d17 tests: the port a test starts a server on stays its own beside the other jobs
ci-local.sh runs the six jobs side by side on one machine, and three of
them run the same test files. Eleven files took a port number out of a
socket they then closed, to start a proxy on it or to have a port where
nothing listens. Anyone could be handed that port before the server bound
it: a stranger could then answer in its place, and a dead port could come
alive. run_suite.py ran those files one at a time, which kept them apart
inside the suite job and not from the other jobs (code review,
2026-10-28, never seen in three runs).

tests/localports.py gives three answers. held() keeps a port bound and
never listening: a connection to it is refused and no other program can
bind it. serve() starts a server of the test's process on a held port,
beside the socket that keeps it (SO_REUSEPORT), so an engine that stops
and starts again keeps its port in between. spawn() starts a proxy in a
process of its own and keeps it once the socket listening on its port is
its own, read in /proc, else starts it again on another port. The
certificate test passes port 0, since nobody connects to a proxy that
refuses to start, and now checks that the refusal is the certificate's.

test_localports.py proves each answer on the machine, and fails on a test
file that takes a port the old way: on the tree before this commit it
names the eleven. With none left, the suite runs them four at a time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 11:51:55 +01:00

186 lines
7.2 KiB
Python

#!/usr/bin/env python3
"""v6.16's TLS door: it opens only when a certificate is named, and when it
does, nothing plain is left beside it.
The dangerous bugs here are the obvious ones (plaintext still answering next
to the TLS socket, starting with a certificate that cannot be loaded,
wrapping too late so early children accepted plain) and one that is not: the
proxy's keepalive and abort logic leans on raw-socket behavior (setsockopt,
close orderings) that a wrapped socket might not offer. So these tests drive
the real production entry point, subprocess and all, against a fake engine.
The certificate is generated with openssl: self-signed, exactly like the
tailnet-CA certificate the feature is meant to use. The client here pins
nothing and trusts nothing (CERT_NONE): under test is the door's hinge, not
the chain of trust an operator brings.
"""
import http.server
import json
import socket
import ssl
import subprocess
import sys
import tempfile
import threading
import time
import unittest
import urllib.request
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import localports # noqa: E402
REPO = Path(__file__).resolve().parents[1]
class Engine(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *a):
pass
def do_POST(self):
n = int(self.headers.get("Content-Length") or "0")
self.rfile.read(n)
body = json.dumps({"id": "chatcmpl-test",
"choices": [{"message": {"role": "assistant", "content": "ok"}}]}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", "2")
self.end_headers()
self.wfile.write(b"OK")
def start_engine():
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Engine)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv, srv.server_address[1]
def base_env(upstream_port, extra=None):
env = {"PATH": "/usr/local/bin:/usr/bin:/bin", "HOME": tempfile.mkdtemp(),
"UPSTREAM": "http://127.0.0.1:%d" % upstream_port}
if extra:
env.update(extra)
return env
def run_proxy(env):
"""(process, port): a proxy on a port of its own."""
return localports.spawn(lambda port: subprocess.Popen(
[sys.executable, str(REPO / "keepalive-proxy.py"), str(port)], env=env, stderr=subprocess.DEVNULL),
within=10)
def https_post(port, path, obj):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
req = urllib.request.Request("https://127.0.0.1:%d%s" % (port, path),
data=json.dumps(obj).encode(),
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=15, context=ctx) as r:
return r.status, r.read()
def plain_post(port, path, obj):
req = urllib.request.Request("http://127.0.0.1:%d%s" % (port, path),
data=json.dumps(obj).encode(),
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=15) as r:
return r.status, r.read()
BODY = {"model": "x", "messages": []}
class TlsDoor(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.engine, cls.engine_port = start_engine()
tmp = tempfile.mkdtemp()
cert, key = tmp + "/cert.pem", tmp + "/key.pem"
subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048",
"-nodes", "-days", "2", "-subj", "/CN=localhost",
"-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1",
"-keyout", key, "-out", cert],
check=True, capture_output=True)
cls.cert, cls.key = cert, key
@classmethod
def tearDownClass(cls):
cls.engine.shutdown()
cls.engine.server_close()
def test_cert_named_speaks_tls_and_nothing_plain_answers_beside_it(self):
proc, port = run_proxy(base_env(self.engine_port, {"QWEN38_TLS_CERT": self.cert,
"QWEN38_TLS_KEY": self.key}))
try:
status, body = https_post(port, "/v1/chat/completions", BODY)
self.assertEqual(status, 200)
self.assertIn("chatcmpl-test", body.decode())
with self.assertRaises(Exception):
plain_post(port, "/v1/chat/completions", BODY)
finally:
proc.terminate()
proc.wait(timeout=5)
def test_no_cert_named_keeps_the_plain_socket_exactly_as_before(self):
proc, port = run_proxy(base_env(self.engine_port))
try:
status, _ = plain_post(port, "/v1/chat/completions", BODY)
self.assertEqual(status, 200)
with self.assertRaises(Exception):
https_post(port, "/v1/chat/completions", BODY)
finally:
proc.terminate()
proc.wait(timeout=5)
def test_a_silent_client_cannot_hold_the_accept_loop(self):
"""S6: the handshake used to run inside the accept loop, so one silent
TCP connection parked every other client until the handshake timed out.
With the handshake moved into the connection thread, the silent
client burns only its own thread and live clients are unaffected."""
proc, port = run_proxy(base_env(self.engine_port,
{"QWEN38_TLS_CERT": self.cert,
"QWEN38_TLS_KEY": self.key,
"QWEN38_TLS_HANDSHAKE_S": "2"}))
try:
silent = socket.create_connection(("127.0.0.1", port), timeout=5)
time.sleep(0.5) # let the proxy accept the silent connection
t0 = time.monotonic()
status, _body = https_post(port, "/v1/chat/completions", BODY)
elapsed = time.monotonic() - t0
self.assertEqual(status, 200)
self.assertLess(elapsed, 5.0,
"a silent TLS client delayed a live one: handshake "
"still runs in the accept loop")
finally:
silent.close()
proc.terminate()
proc.wait(timeout=5)
def test_unusable_cert_refuses_to_start(self):
# port 0, the kernel's own free port: the proxy binds it and leaves before anyone connects, so
# the refusal is the certificate's, never that of a port someone else took
proc = subprocess.Popen(
[sys.executable, str(REPO / "keepalive-proxy.py"), "0"],
env=base_env(self.engine_port, {"QWEN38_TLS_CERT": "/nonexistent/cert.pem"}),
stderr=subprocess.PIPE)
rc = proc.wait(timeout=10)
err = proc.stderr.read().decode()
proc.stderr.close()
self.assertNotEqual(rc, 0)
self.assertIn("refusing to start: certificate /nonexistent/cert.pem is not usable", err)
if __name__ == "__main__":
unittest.main(verbosity=2)