Files
de-praxis/scripts/proxy_smoke.py
T
juli adaee5b536 Move the relay's default port to 1337
Server default, Caddy upstream, env template, smoke scripts and docs.
2026-10-25 00:08:13 +02:00

109 lines
5.9 KiB
Python

#!/usr/bin/env python3
"""Isolated HTTPS integration QA. Trusts a temporary Caddy CA only in child test processes."""
import argparse
import json
import os
from pathlib import Path
import socket
import ssl
import subprocess
import tempfile
import time
import urllib.error
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser()
parser.add_argument("--caddy", required=True, help="Path to a trusted installed Caddy executable")
args = parser.parse_args()
def port():
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
with tempfile.TemporaryDirectory(prefix="de-praxis-proxy-qa-") as directory:
root = Path(directory)
upstream, edge = port(), port()
assert upstream != edge
origin = f"https://localhost:{edge}"
environment = os.environ.copy()
environment.pop("ADMIN_TOKEN", None)
environment.update(HOST="127.0.0.1", PORT=str(upstream), DATA_DIR=str(root / "data"),
PUBLIC_ORIGIN=origin, TRUSTED_PROXY_IPS="127.0.0.1,::1", ADMIN_REMOTE_ACCESS="false",
LLM_URL="", LLM_API_KEY="", LLM_ALLOWED_HOSTS="127.0.0.1,localhost,::1", MAX_ROOMS="8",
JAVA_OPTS="-Dsun.net.httpserver.maxReqTime=2", XDG_DATA_HOME=str(root / "caddy-data"),
XDG_CONFIG_HOME=str(root / "caddy-config"))
config = (ROOT / "deploy/Caddyfile").read_text()
config = config.replace("{\n", "{\n admin off\n auto_https disable_redirects\n skip_install_trust\n", 1)
config = config.replace("relay.example.com {", origin + " {\n tls internal")
config = config.replace("127.0.0.1:1337", f"127.0.0.1:{upstream}")
(root / "Caddyfile").write_text(config)
children = []
try:
with (root / "server.log").open("w") as server_log, (root / "caddy.log").open("w") as proxy_log:
children.append(subprocess.Popen([str(ROOT / "server/build/install/server/bin/server")], env=environment, stdout=server_log, stderr=subprocess.STDOUT))
children.append(subprocess.Popen([args.caddy, "run", "--config", str(root / "Caddyfile"), "--adapter", "caddyfile"], env=environment, stdout=proxy_log, stderr=subprocess.STDOUT))
for _ in range(100):
roots = list((root / "caddy-data").rglob("root.crt"))
try:
if roots:
context = ssl.create_default_context(cafile=str(roots[0]))
with urllib.request.urlopen(origin + "/health", context=context, timeout=1) as response:
assert response.status == 200
break
except (OSError, AssertionError):
pass
if any(child.poll() is not None for child in children):
raise RuntimeError("QA process exited: " + (root / "server.log").read_text() + (root / "caddy.log").read_text())
time.sleep(0.1)
else:
raise RuntimeError("HTTPS relay did not become ready: " + (root / "caddy.log").read_text())
test_environment = environment.copy()
test_environment["SSL_CERT_FILE"] = str(roots[0])
subprocess.run(["python3", str(ROOT / "scripts/security_smoke.py"), origin], env=test_environment, check=True)
subprocess.run(["python3", str(ROOT / "scripts/smoke.py"), origin], env=test_environment, check=True)
# A caller cannot bypass per-client creation limits with forged forwarding headers.
for index in range(4):
req = urllib.request.Request(origin + "/rooms", data=b'{"name":"quota-test"}',
headers={"Content-Type":"application/json", "X-Real-IP":f"203.0.113.{index + 1}"})
try:
with urllib.request.urlopen(req, context=context, timeout=3) as response:
assert index < 3 and response.status == 201
except urllib.error.HTTPError as error:
assert index == 3 and error.code == 429
# The loopback administration surface remains accessible for SSH forwarding.
with urllib.request.urlopen(f"http://127.0.0.1:{upstream}/admin", timeout=3) as response:
assert response.status == 200
admin_key = (root / "data/admin.key").read_text().strip()
admin_origin = f"http://127.0.0.1:{upstream}"
req = urllib.request.Request(admin_origin + "/admin/api/settings", headers={"Authorization":"Bearer " + admin_key})
with urllib.request.urlopen(req, timeout=3) as response:
settings = json.load(response)
assert "apiKey" not in settings
settings["endpoint"] = "http://203.0.113.44/v1/chat/completions"
req = urllib.request.Request(admin_origin + "/admin/api/settings", data=json.dumps(settings).encode(),
headers={"Authorization":"Bearer " + admin_key, "Content-Type":"application/json"})
try:
urllib.request.urlopen(req, timeout=3)
raise AssertionError("Backend allowlist was bypassed")
except urllib.error.HTTPError as error:
assert error.code == 400
# Shortened JVM deadline proves incomplete headers cannot occupy a worker forever.
with socket.create_connection(("127.0.0.1", upstream), timeout=2) as slow:
slow.settimeout(6)
slow.sendall(f"GET /health HTTP/1.1\r\nHost: 127.0.0.1:{upstream}\r\nX-Slow: ".encode())
assert slow.recv(1) == b"", "Incomplete request was not closed by the HTTP deadline"
print("PASS: complete HTTPS multiplayer flow, spoof-resistant rate limits, local admin, backend allowlist, slow-header deadline")
finally:
for child in children:
child.terminate()
for child in children:
try:
child.wait(timeout=10)
except subprocess.TimeoutExpired:
child.kill()
child.wait()