Files
alzeo/tests/test_proxy_tls.py
Hasan Basbunar 2b39f7da47 tls test: a proxy that does not refuse the cert is killed, the test fails loud
test_unusable_cert_refuses_to_start waited proc.wait(timeout=10) and, when
the proxy did not refuse the unusable certificate, let TimeoutExpired escape
with the proxy (port 0) still running after the test: 37 orphans of exactly
this test were found on the box on 2026-11-19. On TimeoutExpired the test now
kills that process by its own pid and fails with a clear message. Proven by
mutation against a proxy whose refusal is removed: before, a process outlives
the test (pid seen alive after the run); after, the test fails with "did not
refuse ... (pid ..., killed)" and no process remains. The test stays green
against the real proxy.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:50:17 +01:00

197 lines
7.9 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)
try:
rc = proc.wait(timeout=10)
except subprocess.TimeoutExpired:
# the proxy did not refuse: kill it by its own pid (this test's process) and fail loudly,
# instead of leaving it running on its port after the test (37 orphans of exactly this
# test were found on the box on 2026-11-19)
proc.kill()
proc.wait(timeout=5)
err = proc.stderr.read().decode()
proc.stderr.close()
self.fail(f"keepalive-proxy.py did not refuse the unusable certificate: still running "
f"after 10 s (pid {proc.pid}, killed); stderr: {err[-300:]}")
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)