#!/usr/bin/env python3 """Отрицательные проверки внутреннего mTLS к API (docker network).""" from __future__ import annotations import ssl import subprocess import tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] def check(cond, msg): if not cond: raise SystemExit("FAIL: " + msg) def probe(client_cert: str | None, client_key: str | None, ca: str, expect_ok: bool) -> None: """curl из контейнера в сети lab к api:8443 с заданным client cert.""" cmd = [ "docker", "run", "--rm", "--network", "mtusi-lab7-net", "-v", f"{ROOT / 'certs'}:/certs:ro", "curlimages/curl:8.10.1", "-sS", "-o", "/dev/null", "-w", "%{http_code}", "--cacert", "/certs/ca.crt", "--connect-timeout", "3", "--max-time", "5", ] if client_cert and client_key: cmd.extend(["--cert", client_cert, "--key", client_key]) cmd.append("https://api:8443/health/ready") # Map host paths already under /certs; pass container paths. if client_cert: cmd = [ "docker", "run", "--rm", "--network", "mtusi-lab7-net", "-v", f"{ROOT / 'certs'}:/certs:ro", "curlimages/curl:8.10.1", "-sS", "-o", "/dev/null", "-w", "%{http_code}", "--cacert", "/certs/ca.crt", "--cert", client_cert, "--key", client_key, "--connect-timeout", "3", "--max-time", "5", "https://api:8443/health/ready", ] else: cmd = [ "docker", "run", "--rm", "--network", "mtusi-lab7-net", "-v", f"{ROOT / 'certs'}:/certs:ro", "curlimages/curl:8.10.1", "-sS", "-o", "/dev/null", "-w", "%{http_code}", "--cacert", "/certs/ca.crt", "--connect-timeout", "3", "--max-time", "5", "https://api:8443/health/ready", ] proc = subprocess.run(cmd, capture_output=True, text=True) ok = proc.returncode == 0 and proc.stdout.strip() == "200" check(ok == expect_ok, f"mtls probe cert={client_cert} ok={ok} expected={expect_ok} out={proc.stdout!r} err={proc.stderr[-200:]!r}") def main(): # Без client cert → отказ probe(None, None, "/certs/ca.crt", expect_ok=False) # Правильная identity lb → успех probe("/certs/lb.crt", "/certs/private/lb.key", "/certs/ca.crt", expect_ok=True) # Чужой leaf того же CA (api-client) → отказ identity probe("/certs/api-client.crt", "/certs/private/api-client.key", "/certs/ca.crt", expect_ok=False) print("PASS: mTLS rejects missing/wrong identity; lb identity accepted") return 0 if __name__ == "__main__": raise SystemExit(main())