Files
mtusi2026lab7/scripts/check_mtls.py
T

59 lines
2.3 KiB
Python

"""Verify the lab ingress and all API replicas using local fixture identities."""
import socket
import ssl
from http.client import HTTPResponse, RemoteDisconnected
from pathlib import Path
TLS = Path("/run/tls")
def context(identity=None, ca="ca.crt"):
result = ssl.create_default_context(cafile=str(TLS / ca))
if identity:
result.load_cert_chain(TLS / (identity + ".crt"), TLS / (identity + ".key"))
return result
def get(address, port, name, tls):
with socket.create_connection((address, port), timeout=5) as connection:
with tls.wrap_socket(connection, server_hostname=name) as encrypted:
encrypted.sendall(
f"GET /health/live HTTP/1.1\r\nHost: {name}\r\nConnection: close\r\n\r\n".encode()
)
with HTTPResponse(encrypted) as response:
response.begin()
return response.status, response.getheader("X-Instance-Id")
def rejected(address, port, name, tls):
try:
get(address, port, name, tls)
except (ssl.SSLError, RemoteDisconnected, ConnectionResetError, BrokenPipeError):
return
raise AssertionError("An untrusted TLS connection returned an HTTP response")
def main():
assert get("lb", 8443, "localhost", context())[0] == 200
rejected("lb", 8443, "localhost", context(ca="foreign-ca.crt"))
rejected("lb", 8443, "wrong.lab7.internal", context())
print("PASS: ingress verified CA and SAN; foreign CA and mismatched hostname rejected")
replicas = {info[4][0] for info in socket.getaddrinfo("api", 8080, type=socket.SOCK_STREAM)}
assert len(replicas) >= 2, "Expected at least two independent replicas"
instances = set()
for address in sorted(replicas):
status, instance = get(address, 8080, "api", context("lb.lab7.internal"))
assert status == 200 and instance
rejected(address, 8080, "api", context())
rejected(address, 8080, "api", context("foreign-lb.lab7.internal"))
rejected(address, 8080, "api", context("unrelated.lab7.internal"))
assert get(address, 8080, "api", context("lb.lab7.internal")) == (200, instance)
instances.add(instance)
print(f"PASS: {instance}: accepted LB, rejected missing cert, foreign CA and wrong signed SAN")
assert len(instances) == len(replicas)
if __name__ == "__main__":
main()