"""Public authorization, logout, expiry, input limits and shared login throttle.""" import base64 import hashlib import http.client import json import ssl import subprocess from grade3 import Client, PROJECT, check, run, upload def report(case, **fields): print(json.dumps({"case": case, "status": "PASS", **fields}), flush=True) def main(): c = Client("https://127.0.0.1:8443", "secrets/ca/public.crt") alice, bob, eve, chat = c.bootstrap() path = "/api/v1/chats/" + chat["id"] attachment = upload(c, alice, chat)["json"] c.wait_ready(alice, attachment) file_path = "/api/v1/attachments/" + attachment["id"] pretend = {"X-User-Id": alice["id"]} c.call("GET", path, 404, actor=eve, headers=pretend) c.call("GET", file_path, 404, actor=eve, headers=pretend) c.call("GET", file_path + "/content", 404, actor=eve, headers=pretend) c.call("POST", path + "/messages", 404, actor=eve, body={ "text": "", "attachment_ids": [attachment["id"]] }, headers={**pretend, "Idempotency-Key": "denied-review"}) c.call("GET", "/api/v1/users/me", 401, headers=pretend) report("chat and attachment ACL; spoofed X-User-Id cannot override Bearer", secret_error_bodies=False) c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=eve) c.call("GET", "/api/v1/users/me", 401, actor=eve) report("logout invalidates Bearer", logout=204, reuse=401) digest = hashlib.sha256(bob["token"].encode()).hexdigest() update = ("UPDATE sessions SET created_at=now()-interval '2 hours',expires_at=now()-interval '1 hour' " f"WHERE token_hash=decode('{digest}','hex');") proc = subprocess.run([ "docker", "compose", "--project-name", PROJECT, "exec", "-T", "postgres", "psql", "-X", "-v", "ON_ERROR_STOP=1", "-U", "postgres", "-d", "messenger", ], input=update, text=True, capture_output=True) check(proc.returncode == 0 and "UPDATE 1" in proc.stdout, "synthetic expiry clock adjustment failed") c.call("GET", "/api/v1/users/me", 401, actor=bob) report("expired existing session rejected on lookup", code=401) oversized = c.call("POST", "/api/v1/users", 413, raw=b"x" * 65537, headers={"Content-Type": "application/json"}) check(oversized["json"]["error"]["code"] == "payload_too_large", "wrong oversized body code") tls = ssl.create_default_context(cafile="secrets/ca/public.crt") with_chunk = http.client.HTTPSConnection("127.0.0.1", 8443, context=tls, timeout=5) try: with_chunk.request("POST", "/api/v1/users", [b"x" * 32769, b"x" * 32769], {"Content-Type": "application/json"}, encode_chunked=True) response = with_chunk.getresponse() check(response.status == 413 and json.load(response)["error"]["code"] == "payload_too_large", "chunked oversized request accepted") finally: with_chunk.close() upload(c, alice, chat, b"x" * (10 * 1024 * 1024 + 1), expected=413) report("fixed length and chunked body guard, image >10 MiB", code=413) basic = base64.b64encode(b"lab_review_unknown:synthetic-password-only").decode() denied, instances = 0, set() for _ in range(35): response = c.call("POST", "/api/v1/auth/sessions", [401, 429], headers={"Authorization": "Basic " + basic}) if response["status"] == 429: check(response["json"]["error"]["code"] == "rate_limited", "unexpected rate error") check(response["headers"]["Retry-After"] == "30", "missing Retry-After") check(denied > 0 and instances == {"api1", "api2"}, "rate test did not exercise both replicas") report("shared login limit", preceding_denials=denied, replicas=sorted(instances), code=429, retry_after=30) break denied += 1 instances.add(response["headers"]["X-Instance-Id"]) else: raise AssertionError("Route never rate limited") if __name__ == "__main__": run(main)