from http.client import HTTPResponse, RemoteDisconnected import json import socket import ssl import time from pathlib import Path BASE = Path("/audit-secrets") def context(role=None, trust=True): ctx = ( ssl.create_default_context(cafile=str(BASE / "public/ca.crt")) if trust else ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ) if role: ctx.load_cert_chain(str(BASE / role / "service.crt"), str(BASE / role / "service.key")) return ctx def http( host, port, path, role=None, method="GET", body=b"", trust=True, hostname=None, headers=None ): with socket.create_connection((host, port), timeout=4) as raw: with context(role, trust).wrap_socket(raw, server_hostname=hostname or host) as connection: request = ( f"{method} {path} HTTP/1.1\r\nHost: {hostname or host}\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {len(body)}\r\n\r\n".encode() + body ) if headers: extra = "".join(k + ": " + v + "\r\n" for k, v in headers.items()).encode() request = request.replace(b"\r\n\r\n", b"\r\n" + extra + b"\r\n", 1) connection.sendall(request) response = HTTPResponse(connection) response.begin() data = response.read() return response.status, data def deny_http(*args, **kwargs): try: status, _ = http(*args, **kwargs) except (ssl.SSLError, ConnectionResetError, RemoteDisconnected): return "tls_rejected" assert status in (400, 401, 403), f"Expected identity rejection, received {status}" return status def broker(role, host="broker", port=6379, identity="worker"): values = json.loads((BASE / "operator/credentials.json").read_text())["roles"][identity] with socket.create_connection((host, port), timeout=4) as raw: with context(role).wrap_socket(raw, server_hostname=host) as connection: username = values["broker_user"] if host == "broker" else "api" password = values["broker_password"] if host == "broker" else values["cache_password"] command = f"AUTH {username} {password}\r\nPING\r\n".encode() connection.sendall(command) result = connection.recv(1024) if b"+OK" in result and b"+PONG" not in result: result += connection.recv(1024) return b"+PONG" in result def main(): result = {} addresses = sorted( {row[4][0] for row in socket.getaddrinfo("api", 8443, type=socket.SOCK_STREAM)} ) assert len(addresses) == 2, "Expected two separate API addresses" for index, address in enumerate(addresses): assert http(address, 8443, "/health/ready", "lb", hostname="api")[0] == 200 result["api_" + str(index + 1)] = { "valid_lb": 200, "no_certificate": deny_http(address, 8443, "/health/ready", hostname="api"), "wrong_identity_same_ca": deny_http( address, 8443, "/health/ready", "intruder", hostname="api" ), "foreign_ca": deny_http(address, 8443, "/health/ready", "foreign", hostname="api"), } for role in ("api", "worker", "dispatcher"): assert http("otel-collector", 4318, "/v1/traces", role, "POST", b"{}")[0] == 200 result["collector"] = { "allowed_roles": ["api", "worker", "dispatcher"], "no_certificate": deny_http( "otel-collector", 4318, "/v1/traces", method="POST", body=b"{}" ), "wrong_identity_same_ca": deny_http( "otel-collector", 4318, "/v1/traces", "intruder", "POST", b"{}" ), "foreign_ca": deny_http("otel-collector", 4318, "/v1/traces", "foreign", "POST", b"{}"), } assert broker("worker") for role in (None, "intruder", "foreign"): try: assert not broker(role), "Unauthorized broker certificate accepted" except (ssl.SSLError, ConnectionResetError): pass result["broker"] = { "valid_worker": True, "no_certificate_denied": True, "foreign_ca_denied": True, "wrong_identity_with_correct_password_denied": True, } for host, port, path, role in [ ("prometheus", 9090, "/api/v1/status/buildinfo", "grafana"), ("loki", 3100, "/ready", "grafana"), ("tempo", 3200, "/ready", "grafana"), ("otel-collector", 8889, "/metrics", "prometheus"), ]: deadline = time.monotonic() + 35 status = http(host, port, path, role)[0] while status == 503 and time.monotonic() < deadline: time.sleep(1) status = http(host, port, path, role)[0] assert status == 200, (host, port, status) result[host + ":" + str(port)] = { "allowed": role, "wrong_worker": deny_http(host, port, path, "worker"), "no_certificate": deny_http(host, port, path), } assert broker("api", "redis", 6380, "api") for denied_role in (None, "worker", "foreign"): try: assert not broker(denied_role, "redis", 6380, "api") except (ssl.SSLError, ConnectionResetError): pass result["redis_cache"] = dict( valid_api=True, no_certificate_denied=True, wrong_worker_with_correct_cache_password_denied=True, foreign_ca_denied=True, ) import base64 password = (BASE / "operator/grafana_password").read_text().strip() auth = base64.b64encode(("admin:" + password).encode()).decode() assert http("grafana", 3000, "/api/datasources")[0] == 401 assert ( http("grafana", 3000, "/api/datasources", headers={"Authorization": "Basic " + auth})[0] == 200 ) result["grafana_admin"] = dict(anonymous_denied=401, authenticated_tls=200) assert http("openbao", 8200, "/v1/sys/seal-status")[0] == 200 assert http("minio", 9000, "/minio/health/ready")[0] == 200 for host, port, path in [ ("lb", 8443, "/health/ready"), ("minio", 9000, "/minio/health/ready"), ("openbao", 8200, "/v1/sys/seal-status"), ]: for kwargs in ({"trust": False}, {"hostname": "untrusted.invalid"}): try: http(host, port, path, **kwargs) except ssl.SSLCertVerificationError: continue raise AssertionError("Server trust verification did not fail") result["server_trust"] = "untrusted CA and hostname rejected on ingress/S3/OpenBao" for port in (16379, 16380, 14318, 19090, 13100, 13200, 18888, 18889, 13000): try: socket.create_connection(("gateway", port), timeout=2).close() except ConnectionRefusedError: continue raise AssertionError("Local plaintext backend externally reachable") result["plaintext_bypass"] = "nine loopback backend ports inaccessible from application network" print(json.dumps({"status": "PASS", "matrix": result}, indent=2)) if __name__ == "__main__": main()