"""Public security assertions using disposable users and fixtures only.""" import base64 import hashlib import json import subprocess import socket import ssl import sys import time from pathlib import Path from uuid import uuid4 ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Client, check sys.path.insert(0, str(ROOT)) from scripts.operator import settings def db(sql): result = subprocess.run( ["docker", "compose", "exec", "-T", "postgres", "psql", "-XAt", "-U", "owner", "-d", "messenger", "--set=ON_ERROR_STOP=1"], input=sql.encode(), capture_output=True, check=True, cwd=ROOT, ) return result.stdout.decode().strip() def basic(username, password): return {"Authorization": "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()} def main(): port = settings().get("HTTPS_PORT", "8443") ca = str(ROOT / "secrets/trust/edge.crt") client = Client(f"https://localhost:{port}", ca) verifier = ssl.create_default_context(cafile=ca) with socket.create_connection(("127.0.0.1", int(port)), timeout=3) as sock: try: with verifier.wrap_socket(sock, server_hostname="wrong.lab7"): raise AssertionError("certificate accepted for an unrelated hostname") except ssl.SSLCertVerificationError: pass alice, bob, eve, chat = client.bootstrap() attachment, _ = client.attachment(alice, chat) fake = {"X-User-Id": alice["id"]} for suffix in ("", "/content"): client.call("GET", "/api/v1/attachments/" + attachment["id"] + suffix, 404, actor=eve, headers=fake) me = client.call("GET", "/api/v1/users/me", actor=eve, headers=fake, schema="User")["json"] check(me["id"] == eve["id"], "header overrode Bearer identity") other = client.call("POST", "/api/v1/chats", 201, actor=eve, schema="Chat", body={"title": "Synthetic", "member_ids": [eve["id"], bob["id"]]})["json"] client.call("POST", f"/api/v1/chats/{other['id']}/messages", (400, 404, 409), actor=eve, body={"text": "synthetic", "attachment_ids": [attachment["id"]]}, headers={"Idempotency-Key": uuid4().hex}) client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=eve) client.call("GET", "/api/v1/users/me", 401, actor=eve) digest = hashlib.sha256(bob["token"].encode()).hexdigest() db(f"UPDATE sessions SET expires_at=created_at+interval '1 second' WHERE token_hash='{digest}';") time.sleep(1.2) client.call("GET", "/api/v1/users/me", 401, actor=bob) username = "old_" + uuid4().hex[:12] password = "Synthetic-" + uuid4().hex client.call("POST", "/api/v1/users", 201, body={"username": username, "display_name": "Rehash", "password": password}) old_hash = subprocess.run( ["docker", "compose", "exec", "-T", "api", "python", "-c", "import sys; from argon2 import PasswordHasher; print(PasswordHasher(time_cost=2,memory_cost=19456,parallelism=1).hash(sys.stdin.read()))"], input=password.encode(), capture_output=True, check=True, cwd=ROOT, ).stdout.decode().strip() check(old_hash.startswith("$argon2id$"), "failed to create legacy fixture") db(f"UPDATE users SET password_hash='{old_hash}' WHERE username='{username}';") check(db(f"SELECT password_hash LIKE '%m=19456,t=2,p=1%' FROM users WHERE username='{username}';") == "t", "legacy fixture missing") client.call("POST", "/api/v1/auth/sessions", 201, headers=basic(username, password)) check(db(f"SELECT password_hash LIKE '%m=24576,t=2,p=1%' FROM users WHERE username='{username}';") == "t", "password not upgraded") name = "limit_" + uuid4().hex[:12] while time.time() % 10 > 6: time.sleep(0.1) workers = set() codes = [] for _ in range(10): reply = client.call("POST", "/api/v1/auth/sessions", (401, 429), headers=basic(name, "Wrong-synthetic-secret")) codes.append(reply["status"]) workers.add(reply["headers"]["X-Instance-Id"]) if reply["status"] == 429: check(1 <= int(reply["headers"]["Retry-After"]) <= 10, "missing retry window") check(codes.count(401) == 8 and codes.count(429) == 2, "shared rate limit did not engage at 8") check(len(workers) >= 2, "rate test must see both replicas") print(json.dumps({"hostname_mismatch": "PASS", "acl": "PASS", "logout": "PASS", "expiry": "PASS", "argon2_rehash": "PASS", "login_attempt_statuses": codes, "replica_count": len(workers)}, ensure_ascii=False)) if __name__ == "__main__": main()