Files
mtusi2026lab7/student-tests/test_tls_boundary.py
T

233 lines
8.1 KiB
Python

"""Identity and prefix negative probes use a real local TLS server, no mocked TLS."""
import http.client
import json
import socket
import socketserver
import ssl
import threading
from pathlib import Path
import pytest
from messenger.tls_gateway import HTTPHandler, HTTPServer, TCPHandler, TCPServer, role
ROOT = Path(__file__).resolve().parents[1]
def cfg(name, allowed, upstream, **extra):
return dict(
cert=str(ROOT / f"secrets/pki/{name}/cert.pem"),
key=str(ROOT / f"secrets/pki/{name}/key.pem"),
ca=str(ROOT / "secrets/ca.pem"),
allowed=allowed,
upstream=upstream,
**extra,
)
def client(identity=None):
ctx = ssl.create_default_context(cafile=str(ROOT / "secrets/ca.pem"))
if identity:
ctx.load_cert_chain(
ROOT / f"secrets/pki/{identity}/cert.pem", ROOT / f"secrets/pki/{identity}/key.pem"
)
return ctx
class Echo(socketserver.BaseRequestHandler):
def handle(self):
while data := self.request.recv(1024):
self.request.sendall(data)
@pytest.fixture
def tcp_boundary(monkeypatch, tmp_path):
revoked = tmp_path / "revoked.json"
revoked.write_text("[]")
monkeypatch.setenv("TLS_REVOKED_FILE", str(revoked))
with socketserver.ThreadingTCPServer(("127.0.0.1", 0), Echo) as echo:
threading.Thread(target=echo.serve_forever, daemon=True).start()
with TCPServer(("127.0.0.1", 0), TCPHandler) as proxy:
proxy.cfg = cfg("api", ["lb"], echo.server_address[1])
proxy.slots = threading.BoundedSemaphore(32)
threading.Thread(target=proxy.serve_forever, daemon=True).start()
yield proxy.server_address[1], revoked
proxy.shutdown()
echo.shutdown()
def exchange(port, ctx, hostname="api"):
with socket.create_connection(("127.0.0.1", port), timeout=2) as raw:
with ctx.wrap_socket(raw, server_hostname=hostname) as conn:
conn.sendall(b"positive")
return conn.recv(1024)
def test_allowed_lb_identity(tcp_boundary):
assert exchange(tcp_boundary[0], client("lb")) == b"positive"
@pytest.mark.parametrize("identity", [None, "worker", "operator"])
def test_missing_or_trusted_wrong_identity_denied(tcp_boundary, identity):
try:
result = exchange(tcp_boundary[0], client(identity))
except (OSError, ssl.SSLError):
result = b""
assert result == b""
def test_wrong_hostname(tcp_boundary):
with pytest.raises(ssl.SSLCertVerificationError):
exchange(tcp_boundary[0], client("lb"), "wrong-service")
def test_empty_ca(tcp_boundary):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.load_cert_chain(ROOT / "secrets/pki/lb/cert.pem", ROOT / "secrets/pki/lb/key.pem")
with pytest.raises(ssl.SSLCertVerificationError):
exchange(tcp_boundary[0], ctx)
def test_revocation_new_connection(tcp_boundary):
port, revoked = tcp_boundary
assert exchange(port, client("lb")) == b"positive"
cert = ssl._ssl._test_decode_cert(str(ROOT / "secrets/pki/lb/cert.pem"))
revoked.write_text(json.dumps([cert["serialNumber"].lstrip("0").lower()]))
try:
result = exchange(port, client("lb"))
except (OSError, ssl.SSLError):
result = b""
assert result == b""
@pytest.mark.parametrize(
"method,path,headers",
[
("PUT", "/messenger/private/secret", {}),
("PUT", "/messenger/staging/new", {}),
("GET", "/other-bucket/secret", {}),
("GET", "/messenger/staging/../private/secret", {}),
("GET", "/messenger/staging/%2e%2e/private/secret", {}),
("GET", "/messenger/staging/%252e%252e/private/secret", {}),
(
"PUT",
"/messenger/attachments/id/v1/original",
{"x-amz-copy-source": "/messenger/private/secret"},
),
("GET", "/messenger?list-type=2", {}),
("GET", "https://storage:8443/messenger/staging/id", {}),
("GET", "/messenger/staging/id#fragment", {}),
],
)
def test_worker_prefix_and_copy_bypasses_denied(tmp_path, monkeypatch, method, path, headers):
revoked = tmp_path / "revoke.json"
revoked.write_text("[]")
monkeypatch.setenv("TLS_REVOKED_FILE", str(revoked))
with HTTPServer(("127.0.0.1", 0), HTTPHandler) as proxy:
proxy.cfg = cfg("storage", ["api", "worker", "operator"], 1, http=True, s3=True)
proxy.slots = threading.BoundedSemaphore(32)
threading.Thread(target=proxy.serve_forever, daemon=True).start()
conn = http.client.HTTPSConnection(
"127.0.0.1", proxy.server_address[1], context=client("worker"), timeout=2
)
conn.request(method, path, headers={"Host": "storage:8443", **headers})
assert conn.getresponse().status == 403
conn.close()
proxy.shutdown()
def test_exactly_one_allowed_san():
with pytest.raises(ssl.SSLError):
role({"subjectAltName": [("DNS", "worker"), ("DNS", "lb")]}, ["lb", "worker"])
def test_expired_certificate_rejected(tcp_boundary, tmp_path):
import subprocess
import time
assert exchange(tcp_boundary[0], client("lb")) == b"positive"
cert = tmp_path / "expired.pem"
subprocess.run(
[
"openssl",
"x509",
"-req",
"-in",
str(ROOT / "operator-private/lb.csr"),
"-CA",
str(ROOT / "operator-private/ca.pem"),
"-CAkey",
str(ROOT / "operator-private/ca-key.pem"),
"-set_serial",
"999999",
"-days",
"0",
"-extfile",
str(ROOT / "operator-private/lb.ext"),
"-out",
str(cert),
],
check=True,
capture_output=True,
)
time.sleep(1)
ctx = client()
ctx.load_cert_chain(cert, ROOT / "secrets/pki/lb/key.pem")
try:
result = exchange(tcp_boundary[0], ctx)
except (OSError, ssl.SSLError):
result = b""
assert result == b""
def test_http_forward_preserves_object_bytes(tmp_path, monkeypatch):
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class Object(BaseHTTPRequestHandler):
def do_GET(self):
body = b"original-bytes"
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *_):
pass
revoked = tmp_path / "revoked.json"
revoked.write_text("[]")
monkeypatch.setenv("TLS_REVOKED_FILE", str(revoked))
with ThreadingHTTPServer(("127.0.0.1", 0), Object) as upstream:
threading.Thread(target=upstream.serve_forever, daemon=True).start()
with HTTPServer(("127.0.0.1", 0), HTTPHandler) as proxy:
proxy.cfg = cfg("storage", ["worker"], upstream.server_address[1], http=True, s3=True)
proxy.slots = threading.BoundedSemaphore(32)
threading.Thread(target=proxy.serve_forever, daemon=True).start()
conn = http.client.HTTPSConnection(
"127.0.0.1", proxy.server_address[1], context=client("worker"), timeout=2
)
conn.request("GET", "/messenger/staging/id", headers={"Host": "storage:8443"})
response = conn.getresponse()
assert response.status == 200
assert response.read() == b"original-bytes"
conn.close()
proxy.shutdown()
upstream.shutdown()
def test_revocation_existing_connection_before_next_command(tcp_boundary):
port, revoked = tcp_boundary
with socket.create_connection(("127.0.0.1", port), timeout=2) as raw:
with client("lb").wrap_socket(raw, server_hostname="api") as conn:
conn.sendall(b"before-revocation")
assert conn.recv(1024) == b"before-revocation"
cert = ssl._ssl._test_decode_cert(str(ROOT / "secrets/pki/lb/cert.pem"))
revoked.write_text(json.dumps([cert["serialNumber"].lstrip("0").lower()]))
try:
conn.sendall(b"must-not-forward")
data = conn.recv(1024)
except OSError:
data = b""
assert data == b""