"""Defensive checks from inside the isolated lab7 network.""" import http.client import json import os from pathlib import Path import ssl from urllib.error import HTTPError from app.bao import CA_FILE, request, service_token def check_mtls(): for replica in ("app1", "app2"): for certificate in ("lb", None, "wrong-ca", "wrong-role"): context = ssl.create_default_context(cafile=CA_FILE) if certificate: base = "/run/identity/" + certificate context.load_cert_chain(base + ".crt", base + ".key") connection = http.client.HTTPSConnection(replica, 8443, context=context, timeout=4) try: connection.request("GET", "/health/live") response = connection.getresponse() accepted = response.status == 200 and json.loads(response.read()) == {"status": "ok"} except (ssl.SSLError, http.client.RemoteDisconnected, ConnectionResetError, BrokenPipeError): accepted = False finally: connection.close() assert accepted == (certificate == "lb"), (replica, certificate) print(f"PASS {replica}: correct LB certificate only") def check_openbao(): address = os.environ["BAO_ADDR"] context = ssl.create_default_context(cafile=CA_FILE) for role, other in (("api", "worker"), ("worker", "api")): token = service_token(address, context, Path("/run/identity") / role) try: own = request(address, f"messenger/data/{role}", context=context, token=token) keys = set(own["data"]["data"]) assert {"DATABASE_URL", "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY"} <= keys, role assert not keys & {"ROOT_TOKEN", "UNSEAL_KEY", "MINIO_ROOT_PASSWORD"} for scope, body in ( (f"messenger/data/{other}", None), ("sys/policies/acl/lab7-probe", {"policy": ""}), ): try: request(address, scope, context=context, token=token, data=body) except HTTPError as exc: assert exc.code == 403, (scope, exc.code) else: raise AssertionError(f"Unexpected access to {scope}") finally: request(address, "auth/token/revoke-self", context=context, token=token, data={}) print(f"PASS OpenBao {role}: own secret allowed, cross-role read and policy write denied") def check_ingest(): context = ssl.create_default_context(cafile=CA_FILE) connection = http.client.HTTPSConnection("telemetry", 8444, context=context, timeout=4) try: connection.request("POST", "/ingest/v1/metrics", body=b"") with connection.getresponse() as response: assert response.status == 401, response.status finally: connection.close() print("PASS telemetry does not allow ingestion without service credentials") if __name__ == "__main__": check_mtls() check_openbao() check_ingest()