"""Lab 7, grade 3: negative proofs of the trust matrix (contracts/trust-matrix.md) on the running stand. Already covered elsewhere and kept: outsider 404 (test_api.test_foreign_chat_is_indistinguishable...), X-User-Id ignored, logout/expiry (test_api, test_sessions), no secrets in Loki/Tempo (test_observability), limits of request sizes (test_api, test_attachments), compose policy incl. per-service secrets and hardening (test_balancing.test_compose_policy_limits_ports_secrets_images). Here: external TLS (wrong hostname / empty trust / plaintext), LB->API mTLS (scripts/mtls_check.sh), TLS + identities of every dependency (PostgreSQL roles, Valkey ACL, RabbitMQ users, S3 keys, Collector/Prometheus/Loki/Tempo client certificates), OpenBao policies + sealed behaviour, Argon2id PHC format, login rate limit (429 + Retry-After), X-Instance-Id alias, non-root/limits of the running containers, no secrets in Git or in the image. Every test restores what it changes. """ from __future__ import annotations import json import re import socket import ssl import subprocess import time import uuid import httpx2 as httpx import pytest from conftest import BASE_URL, CA_FILE, PASSWORD, REPLICAS, ROOT, TLS, basic, compose, lbctl, psql, wait_healthy, \ wait_stand pytestmark = pytest.mark.stack SECRETS = ROOT / "secrets" NO_PATHCONV = {"MSYS_NO_PATHCONV": "1"} def secret(name: str) -> str: return (SECRETS / name).read_text(encoding="utf-8").strip() def sh(service: str, script: str, stdin: str | None = None, timeout: float = 60) -> subprocess.CompletedProcess: """Run a shell script inside a running service container; secrets go via stdin, never argv. Bytes, not text: on Windows a text-mode pipe would turn "\\n" into "\\r\\n" (CR in the password).""" result = subprocess.run(["docker", "compose", "exec", "-T", service, "sh", "-c", script], cwd=ROOT, input=(stdin or "").encode("utf-8"), capture_output=True, timeout=timeout) return subprocess.CompletedProcess(result.args, result.returncode, result.stdout.decode("utf-8", "replace"), result.stderr.decode("utf-8", "replace")) # ------------------------------------------------------------------ external TLS (client -> LB) def tls_error(host: str, server_hostname: str, context: ssl.SSLContext) -> str | None: try: with socket.create_connection((host, 8443), timeout=5) as raw, \ context.wrap_socket(raw, server_hostname=server_hostname): return None except ssl.SSLCertVerificationError as exc: return exc.verify_message def test_ingress_verifies_ca_and_hostname(): assert tls_error("127.0.0.1", "localhost", TLS) is None # right CA + SAN assert "Hostname mismatch" in (tls_error("127.0.0.1", "evil.example", TLS) or "") # wrong name empty = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) # trusts nothing assert "unable to get local issuer certificate" in (tls_error("127.0.0.1", "localhost", empty) or "") internal = ssl.create_default_context(cafile=str(SECRETS / "pki" / "internal-ca.crt")) assert tls_error("127.0.0.1", "localhost", internal) is not None # internal CA is not the public one def test_no_plaintext_entry_point(): with socket.create_connection(("127.0.0.1", 8443), timeout=5) as s: # plain HTTP to the TLS port s.sendall(b"GET /health/live HTTP/1.1\r\nHost: localhost\r\n\r\n") assert not s.recv(256).startswith(b"HTTP/1.1 200") for port in (8080, 8404, 9090, 3100, 3200, 4318, 5432, 6379, 5671, 8200, 8333): with pytest.raises(OSError): socket.create_connection(("127.0.0.1", port), timeout=2).close() # ------------------------------------------------------------------ LB -> API mTLS def test_lb_to_api_mtls_refuses_foreign_and_wrong_identity(): result = subprocess.run(["sh", "scripts/mtls_check.sh"], cwd=ROOT, capture_output=True, text=True, encoding="utf-8", timeout=180) assert result.returncode == 0, result.stdout[-3000:] out = result.stdout assert f"PASS: mTLS LB->API, {REPLICAS} replica(s), 0 failure(s)" in out # the allowlist (not the CA chain) refused the worker certificate - the API logged that SAN assert '"client_san": ["worker"]' in out and '"mtls_identity_rejected"' in out def test_api_has_no_published_port_and_answers_only_mtls(): for item in lbctl.replicas(all_states=False): assert not json.loads(subprocess.run(["docker", "inspect", "-f", "{{json .HostConfig.PortBindings}}", item["id"]], capture_output=True, text=True).stdout or "{}") # ------------------------------------------------------------------ dependencies: TLS + identities def psql_as(role: str, sql: str, sslmode: str = "verify-full") -> subprocess.CompletedProcess: """Connect over TCP like a service: TLS verify-full against the internal CA, password via stdin.""" script = ('read -r PGPASSWORD; export PGPASSWORD; exec psql "host=localhost dbname=messenger user=messenger_%s ' 'sslmode=%s sslrootcert=/run/secrets/internal-ca.crt" -At -v ON_ERROR_STOP=1 -c "%s"') % (role, sslmode, sql) return sh("postgres", script, stdin=secret(f"pg_{role}_password") + "\n") def test_postgres_tls_only_and_roles_least_privilege(): assert psql("SHOW ssl") == "on" assert psql_as("api", "SELECT 1").stdout.strip() == "1" assert psql_as("api", "SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()").stdout.strip() == "t" refused = psql_as("api", "SELECT 1", sslmode="disable") assert refused.returncode != 0 and "no encryption" in refused.stderr, refused.stderr # superuser never over the network su = sh("postgres", 'read -r PGPASSWORD; export PGPASSWORD; psql "host=localhost user=postgres dbname=messenger ' 'sslmode=require" -c "SELECT 1"', stdin=secret("postgres_password") + "\n") assert su.returncode != 0 and "pg_hba.conf" in su.stderr denied = { "api": ["DELETE FROM messages", "SELECT count(*) FROM job_attempts", "CREATE TABLE x (i int)", "TRUNCATE users", "UPDATE users SET display_name = 'x'"], "relay": ["SELECT count(*) FROM users", "SELECT count(*) FROM messages", "DELETE FROM jobs"], "worker": ["SELECT count(*) FROM users", "SELECT count(*) FROM messages", "SELECT count(*) FROM sessions", "DELETE FROM attachments", "SELECT post_message_v3(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)"], "auditor": ["UPDATE jobs SET state = state", "INSERT INTO outbox (job_id, attempt) VALUES (gen_random_uuid(), 1)"], } for role, statements in denied.items(): for sql in statements: result = psql_as(role, sql) assert result.returncode != 0 and "permission denied" in result.stderr, (role, sql, result.stderr) allowed = {"api": "SELECT count(*) FROM users", "relay": "SELECT count(*) FROM outbox", "worker": "SELECT count(*) FROM jobs", "auditor": "SELECT count(*) FROM attachments"} for role, sql in allowed.items(): assert psql_as(role, sql).returncode == 0, role assert psql("SELECT rolsuper FROM pg_roles WHERE rolname LIKE 'messenger_%'").split() == ["f"] * 6 VALKEY = ('read -r REDISCLI_AUTH; export REDISCLI_AUTH; ' 'valkey-cli --tls --cacert /run/secrets/internal-ca.crt -h localhost --user api ') def test_valkey_tls_and_acl(): assert sh("valkey", VALKEY + "ping", stdin=secret("valkey_api_password") + "\n").stdout.strip() == "PONG" # (DEBUG is disabled server-wide anyway: enable-debug-command defaults to no) for command in ("flushall", "config get dir", "keys *", "acl list", "set other:key 1", "eval 'return 1' 0"): out = sh("valkey", VALKEY + command, stdin=secret("valkey_api_password") + "\n").stdout assert "NOPERM" in out, (command, out) # no plaintext: the only port speaks TLS; the default user is off assert "PONG" not in sh("valkey", "valkey-cli -h localhost -p 6379 ping 2>&1; true").stdout default = sh("valkey", "valkey-cli --tls --cacert /run/secrets/internal-ca.crt -h localhost ping 2>&1; true").stdout assert "PONG" not in default AMQP_PROBE = r''' import asyncio, sys, aio_pika from messenger.tls import client_context url = sys.stdin.readline().strip() async def main(): conn = await aio_pika.connect(url, ssl_context=client_context("/run/secrets/internal-ca.crt"), timeout=5) ch = await conn.channel() try: q = await ch.get_queue("messenger.attachment-jobs", ensure=False) await q.get(no_ack=False, fail=False) print("CONSUME_ALLOWED") except Exception as exc: print("CONSUME_REFUSED", type(exc).__name__) await conn.close() asyncio.run(main()) ''' def test_broker_tls_only_and_users_scoped(): # relay may not consume (its permission: write to the jobs exchange only) out = compose("exec", "-T", "relay", "python", "-c", AMQP_PROBE, check=False, stdin=secret("broker_url_relay") + "\n").stdout assert "CONSUME_REFUSED" in out, out # the plaintext AMQP port is closed (listeners.tcp = none) probe = "import socket\ntry:\n socket.create_connection(('broker', 5672), timeout=3); print('OPEN')\nexcept OSError: print('CLOSED')" assert compose("exec", "-T", "relay", "python", "-c", probe).stdout.strip() == "CLOSED" def test_s3_https_and_scoped_keys(): out = compose("run", "--rm", "--no-deps", "s3-init", timeout=180).stdout assert "api: write final: refused (AccessDenied) -> OK" in out assert "done: private buckets, least-privilege keys verified" in out probe = "import urllib.request\ntry:\n urllib.request.urlopen('http://s3:8333/healthz', timeout=3); print('PLAIN')\nexcept Exception: print('NO-PLAINTEXT')" assert compose("exec", "-T", "worker", "python", "-c", probe).stdout.strip() == "NO-PLAINTEXT" TELEMETRY_PROBE = r''' import ssl, sys, urllib.request ca = "/run/secrets/internal-ca.crt" for url in sys.argv[1:]: ctx = ssl.create_default_context(cafile=ca) # server verified, but NO client certificate try: urllib.request.urlopen(url, timeout=5, context=ctx); print(url, "ACCEPTED") except Exception as exc: print(url, "REFUSED", type(exc).__name__) ''' def test_telemetry_endpoints_require_client_certificates(): # A process WITHOUT a client certificate (the worker's python, no cert loaded) is refused by the # Collector; the backends are reachable only for the Collector/Grafana/Prometheus identities. out = compose("exec", "-T", "worker", "python", "-c", TELEMETRY_PROBE, "https://otel-collector:4318/v1/logs").stdout assert "REFUSED" in out and "ACCEPTED" not in out, out # Prometheus: a certificate of OUR CA but not in its SAN allowlist (the worker's) is refused allow = r''' import ssl, urllib.request ctx = ssl.create_default_context(cafile="/run/secrets/internal-ca.crt") ctx.load_cert_chain("/run/secrets/service.crt", "/run/secrets/service.key") try: urllib.request.urlopen("https://prometheus:9090/-/ready", timeout=5, context=ctx); print("ACCEPTED") except Exception as exc: print("REFUSED", type(exc).__name__) ''' # the worker is not on the telemetry backends' allowlist; it is on the `telemetry` network assert "REFUSED" in compose("exec", "-T", "worker", "python", "-c", allow).stdout # ------------------------------------------------------------------ OpenBao def test_openbao_policies_and_no_root_credential_in_apps(): result = subprocess.run(["sh", "scripts/bao_check.sh"], cwd=ROOT, capture_output=True, text=True, encoding="utf-8", timeout=300) assert result.returncode == 0, result.stdout[-4000:] assert result.stdout.count("FAIL") == 0 assert "PASS: OpenBao allow/deny and no root credential in the application" in result.stdout def test_openbao_not_dev_and_persistent(): status = json.loads(sh("openbao", "bao status -format=json").stdout) assert status["initialized"] and not status["sealed"] and status["storage_type"] == "raft" cmd = compose("ps", "--format", "json", "openbao").stdout assert "-dev" not in json.loads(cmd.splitlines()[0])["Command"] def test_sealed_openbao_keeps_running_replicas_and_blocks_new_ones(api): """Restart = sealed. Running API replicas keep serving (their secrets are in memory); a NEW replica cannot get its secrets and never becomes healthy; after the operator's unseal it starts.""" user = api.user("sealed") compose("restart", "openbao") try: assert json.loads(sh("openbao", "bao status -format=json").stdout)["sealed"] is True api.call("GET", "/api/v1/users/me", 200, token=user["token"]) # running replicas: fine compose("up", "-d", "--no-recreate", "--no-deps", "--scale", f"api={REPLICAS + 1}", "api") time.sleep(15) logs = compose("logs", "--no-log-prefix", "--since", "30s", "api").stdout assert "openbao_unavailable" in logs assert len([r for r in lbctl.replicas(all_states=False) if r["health"] == "healthy"]) == REPLICAS finally: subprocess.run(["python", "scripts/bao_operator.py", "unseal"], cwd=ROOT, check=True, capture_output=True) try: lbctl.wait_up(REPLICAS + 1, timeout=120) # the new one comes up now finally: compose("up", "-d", "--no-recreate", "--no-deps", "--scale", f"api={REPLICAS}", "api") wait_healthy("api", "relay", "worker", "openbao") wait_stand() # ------------------------------------------------------------------ passwords, login limit, instance id def test_argon2id_hash_carries_salt_and_parameters(api): a, b = api.register("phc"), api.register("phc") rows = psql("SELECT password_hash FROM users WHERE id IN ('%s', '%s')" % (a["id"], b["id"])).split() assert len(rows) == 2 for value in rows: assert re.fullmatch(r"\$argon2id\$v=19\$m=(\d+),t=(\d+),p=(\d+)\$[A-Za-z0-9+/]{22}\$[A-Za-z0-9+/]{43}", value) m, t, p = map(int, re.match(r"\$argon2id\$v=19\$m=(\d+),t=(\d+),p=(\d+)", value).groups()) assert m >= 19456 and t >= 2 and p >= 1 assert rows[0].split("$")[4] != rows[1].split("$")[4] # same password, different salts def test_failed_logins_are_rate_limited_with_retry_after(api): user = api.user("ratelimit") url = BASE_URL + "/api/v1/auth/sessions" codes = [httpx.post(url, headers={"Authorization": basic(user["username"], "Wrong-password-123")}, timeout=10) for _ in range(5)] assert [r.status_code for r in codes] == [401] * 5 blocked = httpx.post(url, headers={"Authorization": basic(user["username"], "Wrong-password-123")}, timeout=10) assert blocked.status_code == 429 and blocked.json()["error"]["code"] == "rate_limited" assert 1 <= int(blocked.headers["Retry-After"]) <= 60 assert blocked.headers.get("X-Instance-Id") and blocked.headers.get("X-Request-Id") # even the RIGHT password is 429 while blocked (no oracle), on every replica (shared counter) for _ in range(4): assert httpx.post(url, headers={"Authorization": basic(user["username"], PASSWORD)}, timeout=10).status_code == 429 # another account is not affected other = api.user("ratelimit2") assert httpx.post(url, headers={"Authorization": basic(other["username"], PASSWORD)}, timeout=10).status_code == 201 def test_x_instance_id_is_a_random_alias_without_hostname_or_ip(api): seen = {api.call("GET", "/health/live", 200).headers["X-Instance-Id"] for _ in range(20)} assert len(seen) == REPLICAS replicas = lbctl.replicas(all_states=False) hostnames = {r["hostname"] for r in replicas} ips = {ip for r in replicas for ip in r["ips"]} for alias in seen: assert re.fullmatch(r"i-[0-9a-f]{12}", alias) assert alias not in hostnames and not any(ip in alias for ip in ips) assert seen == {r["instance"] for r in replicas} # ------------------------------------------------------------------ hardening, secrets outside Git/images def test_running_containers_are_hardened(): ids = compose("ps", "-q").stdout.split() for item in json.loads(subprocess.run(["docker", "inspect", *ids], capture_output=True, text=True, check=True).stdout): name, host = item["Name"], item["HostConfig"] assert not host["Privileged"] and host["NetworkMode"] != "host" and host["PidMode"] != "host", name assert host["CapDrop"] == ["ALL"] and "no-new-privileges:true" in host["SecurityOpt"], name assert host["NanoCpus"] > 0 and host["Memory"] > 0, name assert not any("docker.sock" in m.get("Source", "") for m in item["Mounts"]), name for service in ("api", "relay", "worker"): for cid in compose("ps", "-q", service).stdout.split(): uid = subprocess.run(["docker", "exec", cid, "id", "-u"], capture_output=True, text=True).stdout.strip() caps = subprocess.run(["docker", "exec", cid, "sh", "-c", "grep CapEff /proc/1/status"], capture_output=True, text=True).stdout.split()[-1] assert uid == "10001" and int(caps, 16) == 0, (service, uid, caps) def test_no_secret_in_git_or_in_the_image(): tracked = subprocess.run(["git", "ls-files"], cwd=ROOT, capture_output=True, text=True, check=True).stdout.split() assert not [f for f in tracked if f.startswith("secrets/") or f.endswith((".key", ".pem")) or ".mtusi-lab7-operator" in f or f.endswith(".env")] values = [secret("postgres_password"), secret("pg_api_password"), secret("valkey_api_password"), secret("s3_api_secret_access_key"), secret("rabbitmq_worker_password"), secret("bao/api_secret_id")] for value in values: grep = subprocess.run(["git", "grep", "-q", "-F", value], cwd=ROOT) assert grep.returncode == 1 # not in any tracked file image = json.loads(compose("config", "--format", "json").stdout)["services"]["api"]["image"] script = ('n=0; while read -r v; do grep -rqsF -- "$v" /app /etc /usr/local/lib/python3.13/site-packages/messenger* ' '&& n=$((n+1)); done; find / -xdev \\( -name "*.key" -o -name "*.pem" \\) -not -path "/proc/*" ' '-not -path "/usr/*" -not -path "/etc/ssl/*" 2>/dev/null | wc -l; echo "hits=$n"') out = subprocess.run(["docker", "run", "--rm", "-i", "--entrypoint", "sh", image, "-c", script], input="\n".join(values) + "\n", capture_output=True, text=True, timeout=120).stdout.split() assert out[-1] == "hits=0" and out[-2] == "0", out