"""Public-path ACL, bounded input, Argon2 rehash and shared admission measurements.""" import argparse import base64 from collections import Counter from concurrent.futures import ThreadPoolExecutor import hashlib import json from pathlib import Path import secrets import ssl import socket import subprocess import sys import time ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Client, check CA = str(ROOT / "secrets/authority/ca.crt") LOGIN = "/api/v1/auth/sessions" ME = "/api/v1/users/me" def basic(username, password): return {"Authorization": "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()} def db(query): proc = subprocess.run( ["docker", "compose", "exec", "-T", "-u", "postgres", "db", "psql", "-qAt", "-v", "ON_ERROR_STOP=1", "-d", "messenger"], input=query, text=True, capture_output=True, check=True) return proc.stdout.strip() def test_expiry(c): actor = c.user("expiry") c.call("GET", ME, actor=actor, schema="User") time.sleep(2.5) c.call("GET", ME, 401, actor=actor) print("PASS 2s TTL: immediate 200, after 2.5s 401") def test_http(c): alice, bob, eve, chat = c.bootstrap() attachment, _ = c.attachment(alice, chat) path = "/api/v1/attachments/" + attachment["id"] for endpoint in (path, path + "/content"): c.call("GET", endpoint, 404, actor=eve, headers={"X-User-Id": alice["id"]}) other = c.call("POST", "/api/v1/chats", 201, actor=eve, body={"title": "Чужой чат", "member_ids": [eve["id"]]}, schema="Chat")["json"] c.call("POST", "/api/v1/chats/" + other["id"] + "/messages", 404, actor=eve, body={"text": "", "attachment_ids": [attachment["id"]]}, headers={"Idempotency-Key": secrets.token_hex(8)}) c.call("GET", ME, 401, headers={"X-User-Id": alice["id"]}) actual = c.call("GET", ME, actor=eve, headers={"X-User-Id": alice["id"]}, schema="User")["json"] check(actual["id"] == eve["id"], "forged identity") c.call("DELETE", LOGIN + "/current", 204, actor=eve) c.call("GET", ME, 401, actor=eve) print("PASS outsider metadata/content/link 404; forged ID ignored; revoked token 401") upload = "/api/v1/chats/" + chat["id"] + "/attachments" c.call("POST", upload + "?filename=x.png", 413, actor=alice, raw=b"x" * (10_485_760 + 1), headers={"Content-Type": "image/png"}) c.call("POST", upload + "?filename=x.png", 415, actor=alice, raw=b"invalid", headers={"Content-Type": "image/png"}) c.call("POST", upload + "?filename=..%2Fx.png", 400, actor=alice, raw=b"x", headers={"Content-Type": "image/png"}) c.call("POST", "/api/v1/users", 413, raw=b"x" * 65_537, headers={"Content-Type": "application/json"}) print("PASS upload bytes/MIME/filename and JSON streaming limit") ctx = ssl.create_default_context(cafile=CA) try: with socket.create_connection(("localhost", 8443), timeout=3) as conn: ctx.wrap_socket(conn, server_hostname="wrong.lab7") except ssl.SSLCertVerificationError as exc: check(exc.verify_code == 62, "unexpected certificate verification failure") else: raise AssertionError("incorrect ingress hostname accepted") print("PASS ingress rejects hostname mismatch on reachable listener") username = alice["registration"]["username"] password = alice["registration"]["password"] command = [ "docker", "compose", "exec", "-T", "--index", "1", "api", "python", "-c", "from argon2 import PasswordHasher; import sys; " "print(PasswordHasher(memory_cost=8192,time_cost=1,parallelism=1).hash(sys.stdin.read()))", ] legacy = subprocess.run(command, input=password, text=True, capture_output=True, check=True).stdout.strip() db(f"UPDATE users SET password_hash='{legacy}' WHERE username='{username}';") fresh = c.call("POST", LOGIN, 201, headers=basic(username, password), schema="Session")["json"] stored = db(f"SELECT password_hash FROM users WHERE username='{username}';") check(stored != legacy and stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$"), "rehash absent") hashed_token = hashlib.sha256(fresh["token"].encode()).hexdigest() count = db(f"SELECT count(*) FROM sessions WHERE token_hash='{hashed_token}';") check(count == "1" and fresh["token"] != hashed_token, "session hash absent") print("PASS old Argon2id rehashed after login; DB stores SHA-256 of 256-bit bearer") def percentile(samples, p): values = sorted(samples) return round(1000 * values[min(len(values) - 1, int((len(values) - 1) * p))], 3) def test_budget(c): # A fixed window starts on first use. No competing harness should be running. time.sleep(10.2) wrong = basic("missing_" + secrets.token_hex(6), "synthetic_wrong_password") def attempt(_): res = c.call("POST", LOGIN, [401, 429], headers=wrong) if res["status"] == 429: check(res["headers"].get("Retry-After", "").isdigit(), "Retry-After missing") return res start = time.monotonic() serial = [attempt(i) for i in range(38)] seconds = time.monotonic() - start statuses = Counter(r["status"] for r in serial) aliases = sorted({r["headers"]["X-Instance-Id"] for r in serial}) check(seconds < 10 and statuses == {401: 24, 429: 14} and len(aliases) == 2, "shared limit") time.sleep(10.2) start = time.monotonic() with ThreadPoolExecutor(max_workers=12) as pool: burst = list(pool.map(attempt, range(72))) burst_seconds = time.monotonic() - start burst_counts = Counter(r["status"] for r in burst) check(burst_seconds < 10 and 0 < burst_counts[401] <= 24 and burst_counts[429] >= 48, "burst limit") time.sleep(10.2) check(attempt(0)["status"] == 401, "budget did not replenish") print(json.dumps({ "serial": {"requests": len(serial), "seconds": round(seconds, 3), "status": statuses, "replicas": len(aliases), "p95_401_ms": percentile( [r["elapsed"] for r in serial if r["status"] == 401], .95)}, "burst": {"requests": len(burst), "concurrency": 12, "seconds": round(burst_seconds, 3), "status": burst_counts, "p95_ms": percentile([r["elapsed"] for r in burst], .95)}, })) print("PASS shared login window, KDF concurrency bound, Retry-After and recovery") def main(): parser = argparse.ArgumentParser() parser.add_argument("scenario", choices=("http", "expiry", "budget")) args = parser.parse_args() {"http": test_http, "expiry": test_expiry, "budget": test_budget}[args.scenario](Client(ca_file=CA)) if __name__ == "__main__": main()