"""Lab 7 units without services: mTLS identity check, TLS contexts, Argon2id parameters, login limit, OpenBao client error handling, secret lookup order.""" from __future__ import annotations import asyncio import ssl import subprocess import sys from pathlib import Path from types import SimpleNamespace import pytest from messenger import bao, passwords, ratelimit, tls from messenger.config import ConfigError, Settings ROOT = Path(__file__).resolve().parents[2] PKI = ROOT / "secrets" / "pki" # ------------------------------------------------------------------ mTLS identity allowlist class FakeSSL: def __init__(self, sans): self.sans = sans def getpeercert(self): return {"subjectAltName": tuple(("DNS", s) for s in self.sans)} if self.sans is not None else {} class FakeTransport: def __init__(self, ssl_object): self.ssl_object, self.aborted = ssl_object, False def get_extra_info(self, name, default=None): return {"ssl_object": self.ssl_object, "peername": ("10.0.0.9", 4444)}.get(name, default) def abort(self): self.aborted = True def test_dns_names_only_from_subject_alt_name(): assert tls.dns_names({"subjectAltName": (("DNS", "lb"), ("IP Address", "10.0.0.1"))}) == ["lb"] assert tls.dns_names(None) == [] and tls.dns_names({}) == [] @pytest.mark.parametrize("sans, allowed", [(["lb"], True), (["worker"], False), (["lb.evil"], False), ([], False), (None, False)]) def test_protocol_aborts_every_identity_outside_the_allowlist(sans, allowed, monkeypatch): monkeypatch.setenv("MTLS_ALLOWED_CLIENTS", "lb") protocol_cls = tls.protocol_class() called = [] monkeypatch.setattr(tls.HttpToolsProtocol, "connection_made", lambda self, transport: called.append(transport)) transport = FakeTransport(FakeSSL(sans)) protocol_cls.connection_made(object.__new__(protocol_cls), transport) assert transport.aborted is (not allowed) assert bool(called) is allowed def test_protocol_aborts_a_plaintext_transport(monkeypatch): protocol_cls = tls.protocol_class() transport = FakeTransport(None) protocol_cls.connection_made(object.__new__(protocol_cls), transport) assert transport.aborted def test_allowlist_cannot_be_empty(monkeypatch): monkeypatch.setenv("MTLS_ALLOWED_CLIENTS", " , ") with pytest.raises(ValueError): tls.allowed_clients() @pytest.mark.skipif(not (PKI / "api.crt").exists(), reason="PKI not generated (scripts/init_pki.py)") def test_server_context_requires_client_certificates_of_the_internal_ca_only(): ctx = tls.server_context(str(PKI / "api.crt"), str(PKI / "api.key"), str(PKI / "internal-ca.crt")) assert ctx.verify_mode == ssl.CERT_REQUIRED and ctx.minimum_version == ssl.TLSVersion.TLSv1_2 subjects = [dict(x[0] for x in c["subject"])["commonName"] for c in ctx.get_ca_certs()] assert subjects == ["MTUSI lab7 internal CA"] # no system CAs, not the public CA client = tls.client_context(str(PKI / "internal-ca.crt")) assert client.check_hostname and client.verify_mode == ssl.CERT_REQUIRED # ------------------------------------------------------------------ Argon2id parameters def test_argon2_parameters_are_configurable_but_never_below_the_minimum(monkeypatch): monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z") monkeypatch.setenv("ARGON2_MEMORY_KIB", "47104") monkeypatch.setenv("ARGON2_ITERATIONS", "3") s = Settings.from_env(s3_credentials=False) assert (s.argon2_memory_kib, s.argon2_iterations, s.argon2_parallelism) == (47104, 3, 1) for name, bad in (("ARGON2_MEMORY_KIB", "19455"), ("ARGON2_ITERATIONS", "1"), ("ARGON2_PARALLELISM", "0")): monkeypatch.setenv(name, bad) with pytest.raises(ConfigError): Settings.from_env(s3_credentials=False) monkeypatch.delenv(name) def test_hash_carries_the_configured_parameters_and_old_hashes_still_verify(): async def run(): passwords.configure(1) old = await passwords.hash_password("correct horse battery") passwords.configure(1, memory_kib=32768, iterations=3) new = await passwords.hash_password("correct horse battery") assert new.startswith("$argon2id$v=19$m=32768,t=3,p=1$") assert await passwords.verify_password(old, "correct horse battery") # params come from the hash assert await passwords.verify_password(new, "correct horse battery") passwords.configure(2) asyncio.run(run()) # ------------------------------------------------------------------ login rate limit (process fallback) def limiter(user=3, ip=100): settings = SimpleNamespace(cache_timeout_seconds=0.5, login_user_limit=user, login_user_window_seconds=60, login_ip_limit=ip, login_ip_window_seconds=300) return ratelimit.LoginLimiter(settings, client=None) def test_limit_per_username_with_retry_after(): async def run(): lim = limiter(user=3) for _ in range(3): await lim.check("alice", "1.1.1.1") await lim.failed("alice", "1.1.1.1") with pytest.raises(ratelimit.RateLimited) as exc: await lim.check("alice", "2.2.2.2") # another IP does not help assert exc.value.status == 429 and exc.value.code == "rate_limited" assert 1 <= int(exc.value.headers["Retry-After"]) <= 60 await lim.check("bob", "1.1.1.1") # another user is not blocked asyncio.run(run()) def test_limit_per_ip_and_reset_on_success(): async def run(): lim = limiter(user=100, ip=4) for i in range(4): await lim.failed(f"user{i}", "9.9.9.9") with pytest.raises(ratelimit.RateLimited): await lim.check("someone-else", "9.9.9.9") # spraying many accounts from one IP lim2 = limiter(user=2) await lim2.failed("carol", "1.1.1.1") await lim2.succeeded("carol") # success resets the username window await lim2.failed("carol", "1.1.1.1") await lim2.check("carol", "1.1.1.1") asyncio.run(run()) # ------------------------------------------------------------------ OpenBao client / secret lookup order def test_secrets_come_from_openbao_first(monkeypatch): monkeypatch.setenv("BAO_ADDR", "https://openbao:8200") monkeypatch.setattr(bao, "_cache", {"database_url": "postgresql://from-bao/x"}) monkeypatch.setenv("DATABASE_URL", "postgresql://from-env/x") assert Settings.from_env(s3_credentials=False).database_url == "postgresql://from-bao/x" monkeypatch.delenv("BAO_ADDR") assert Settings.from_env(s3_credentials=False).database_url == "postgresql://from-env/x" def test_openbao_refusal_is_a_config_error_without_retry(monkeypatch, tmp_path): (tmp_path / "r").write_text("role") (tmp_path / "s").write_text("secret") monkeypatch.setattr(bao, "_cache", None) for k, v in {"BAO_ADDR": "https://127.0.0.1:1", "BAO_SECRET_PATH": "messenger/data/api", "BAO_ROLE_ID_FILE": str(tmp_path / "r"), "BAO_SECRET_ID_FILE": str(tmp_path / "s"), "BAO_STARTUP_TIMEOUT_SECONDS": "0", "DATABASE_URL": "postgresql://x/y"}.items(): monkeypatch.setenv(k, v) with pytest.raises(ConfigError, match="OpenBao unavailable"): # nothing listens: bounded wait, then stop Settings.from_env(s3_credentials=False) monkeypatch.delenv("BAO_SECRET_ID_FILE") monkeypatch.setattr(bao, "_cache", None) with pytest.raises(ConfigError, match="BAO_SECRET_ID_FILE"): Settings.from_env(s3_credentials=False) def test_pki_script_never_prints_key_material(tmp_path): """init_pki.py output names files only (run on a copy so the real ./secrets stays untouched).""" script = (ROOT / "scripts" / "init_pki.py").read_text(encoding="utf-8") (tmp_path / "scripts").mkdir() (tmp_path / "scripts" / "init_pki.py").write_text(script, encoding="utf-8") out = subprocess.run([sys.executable, str(tmp_path / "scripts" / "init_pki.py")], capture_output=True, text=True, check=True).stdout assert "BEGIN" not in out and "PRIVATE" not in out assert (tmp_path / "secrets" / "pki" / "internal-ca.key").exists()