#!/usr/bin/env python3 """Grade 4 verification suite for Lab 4: 1. Validation & security negative tests (413 bytes, 413 >40M pixels bomb, 415 corrupted PNG/JPEG, 415 MIME spoof, 400 bad filenames, 404 cross-chat/foreign). 2. Cross-replica attachment download after stopping the uploading API replica + zero leftover temp files on API. 3. Private bucket & MinIO console isolation + least-privilege credentials + idempotent s3-init. 4. S3 unavailability graceful 503 handling (no 500). 5. >=10 concurrent streaming multi-MB uploads with API peak memory measurement. """ import base64 from concurrent.futures import ThreadPoolExecutor import datetime as dt import hashlib import json from pathlib import Path import struct import subprocess import sys import time import urllib.error import urllib.request import uuid import zlib ROOT = Path(__file__).resolve().parents[1] FIXTURE_PNG = ROOT / "tests" / "fixtures" / "sample.png" EVIDENCE_PATH = ROOT / "evidence" / "grade4_checks.json" BASE_URL = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080" def run_cmd(cmd, check=True): return subprocess.run(cmd, cwd=str(ROOT), text=True, capture_output=True, check=check) def http_call(method, path, body=None, raw_bytes=None, headers=None, timeout=15): h = {"Accept": "application/json"} data = raw_bytes if body is not None: data = json.dumps(body).encode("utf-8") h["Content-Type"] = "application/json" if headers: h.update(headers) req = urllib.request.Request(BASE_URL + path, data=data, headers=h, method=method) start = time.monotonic() try: with urllib.request.urlopen(req, timeout=timeout) as resp: raw = resp.read() hdrs = {k.lower(): v for k, v in resp.headers.items()} ct = hdrs.get("content-type", "") parsed = json.loads(raw.decode("utf-8")) if (raw and "application/json" in ct) else None return resp.code, hdrs, parsed, raw, time.monotonic() - start except urllib.error.HTTPError as err: raw = err.read() hdrs = {k.lower(): v for k, v in err.headers.items()} ct = hdrs.get("content-type", "") parsed = json.loads(raw.decode("utf-8")) if (raw and "application/json" in ct) else None return err.code, hdrs, parsed, raw, time.monotonic() - start def wait_ready(timeout_s=45): deadline = time.monotonic() + timeout_s while time.monotonic() < deadline: try: st, _, _, _, _ = http_call("GET", "/health/ready", timeout=2) if st == 200: return except Exception: pass time.sleep(0.5) raise RuntimeError("LB/API did not become ready within timeout") def register_and_login(label): username = f"g4_{label}_{uuid.uuid4().hex[:8]}" password = f"Grade4Pass-{uuid.uuid4().hex}" st, _, user, _, _ = http_call("POST", "/api/v1/users", { "username": username, "display_name": f"Student {label}", "password": password, }) assert st == 201 basic = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii") st, _, sess, _, _ = http_call("POST", "/api/v1/auth/sessions", headers={"Authorization": f"Basic {basic}"}) assert st == 201 return {"id": user["id"], "headers": {"Authorization": f"Bearer {sess['token']}"}} def png_chunk(chunk_type, data): return struct.pack(">I", len(data)) + chunk_type + data + struct.pack(">I", zlib.crc32(chunk_type + data) & 0xFFFFFFFF) def make_synthetic_png(width, height, compress_level=6, color=2): # color=2 -> RGB (3 bytes/px) ihdr = struct.pack(">IIBBBBB", width, height, 8, color, 0, 0, 0) row = b"\x00" + (b"\x2a\x7f\xc1" * width) raw = row * height compressed = zlib.compress(raw, level=compress_level) return b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", ihdr) + png_chunk(b"IDAT", compressed) + png_chunk(b"IEND", b"") def make_pixel_bomb_png(width=7000, height=7000): # Valid IHDR declaring 49M pixels (> 40M limit) with tiny valid IDAT so DecodeConfig catches it in <4KB RAM ihdr = struct.pack(">IIBBBBB", width, height, 8, 0, 0, 0, 0) tiny_idat = zlib.compress(b"\x00\x00", level=1) return b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", ihdr) + png_chunk(b"IDAT", tiny_idat) + png_chunk(b"IEND", b"") def get_api_containers(): cids = run_cmd(["docker", "compose", "--env-file", ".env", "ps", "-q", "api"]).stdout.strip().splitlines() out = [] for cid in cids: cid = cid.strip() if not cid: continue info = json.loads(run_cmd(["docker", "inspect", cid]).stdout)[0] out.append({ "id": cid, "short_id": cid[:12], "name": info["Name"].lstrip("/"), "env": info["Config"]["Env"], "ports": info["NetworkSettings"]["Ports"], }) return out def wait_two_instances(headers, timeout_s=30): deadline = time.monotonic() + timeout_s seen = set() while time.monotonic() < deadline: try: st, hdrs, _, _, _ = http_call("GET", "/api/v1/users/me", headers=headers, timeout=2) if st == 200 and hdrs.get("x-instance-id"): seen.add(hdrs["x-instance-id"]) if len(seen) >= 2: return sorted(seen) except Exception: pass time.sleep(0.2) raise RuntimeError(f"Expected >=2 active instances, saw {seen}") def test_negative_validation(): alice = register_and_login("neg_a") bob = register_and_login("neg_b") eve = register_and_login("neg_e") st, _, chat1, _, _ = http_call("POST", "/api/v1/chats", { "title": "Chat 1", "member_ids": [alice["id"], bob["id"]], }, headers=alice["headers"]) assert st == 201 st, _, chat2, _, _ = http_call("POST", "/api/v1/chats", { "title": "Chat 2", "member_ids": [alice["id"]], }, headers=alice["headers"]) assert st == 201 sample = FIXTURE_PNG.read_bytes() # 1. Oversized bytes (> 10 MiB) -> 413 oversized = b"\x89PNG\r\n\x1a\n" + (b"\x00" * (10 * 1024 * 1024 + 128)) st, _, err, _, _ = http_call("POST", f"/api/v1/chats/{chat1['id']}/attachments?filename=big.png", raw_bytes=oversized, headers={**alice["headers"], "Content-Type": "image/png"}) assert st == 413 and err["error"]["code"] == "payload_too_large", f"Expected 413 for >10MiB, got {st}" # 2. Pixel bomb (> 40M pixels) -> 413 bomb = make_pixel_bomb_png(7000, 7000) st, _, err, _, _ = http_call("POST", f"/api/v1/chats/{chat1['id']}/attachments?filename=bomb.png", raw_bytes=bomb, headers={**alice["headers"], "Content-Type": "image/png"}) assert st == 413 and err["error"]["code"] == "payload_too_large", f"Expected 413 for pixel bomb, got {st}" # 3. Corrupted PNG (truncated before IEND) -> 415 corrupt_png = sample[:len(sample) // 2] st, _, err, _, _ = http_call("POST", f"/api/v1/chats/{chat1['id']}/attachments?filename=bad.png", raw_bytes=corrupt_png, headers={**alice["headers"], "Content-Type": "image/png"}) assert st == 415 and err["error"]["code"] == "unsupported_media_type", f"Expected 415 for corrupt PNG, got {st}" # 4. Corrupted JPEG -> 415 corrupt_jpg = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00garbage-truncated" st, _, err, _, _ = http_call("POST", f"/api/v1/chats/{chat1['id']}/attachments?filename=bad.jpg", raw_bytes=corrupt_jpg, headers={**alice["headers"], "Content-Type": "image/jpeg"}) assert st == 415 and err["error"]["code"] == "unsupported_media_type", f"Expected 415 for corrupt JPEG, got {st}" # 5. MIME spoof (HTML/text labeled as image/png + PNG bytes labeled as image/jpeg) -> 415 st, _, _, _, _ = http_call("POST", f"/api/v1/chats/{chat1['id']}/attachments?filename=fake.png", raw_bytes=b"not-an-image", headers={**alice["headers"], "Content-Type": "image/png"}) assert st == 415 st, _, _, _, _ = http_call("POST", f"/api/v1/chats/{chat1['id']}/attachments?filename=wrong.jpg", raw_bytes=sample, headers={**alice["headers"], "Content-Type": "image/jpeg"}) assert st == 415 # 6. Bad filenames -> 400 for bad_name in ["../secret.png", "dir/file.png", "dir\\file.png", " "]: from urllib.parse import quote st, _, _, _, _ = http_call("POST", f"/api/v1/chats/{chat1['id']}/attachments?filename={quote(bad_name, safe='')}", raw_bytes=sample, headers={**alice["headers"], "Content-Type": "image/png"}) assert st == 400, f"Expected 400 for filename {bad_name!r}, got {st}" # 7. Upload valid attachment in chat1, then test outsider & cross-chat attachment isolation st, _, att1, _, _ = http_call("POST", f"/api/v1/chats/{chat1['id']}/attachments?filename=valid.png", raw_bytes=sample, headers={**alice["headers"], "Content-Type": "image/png"}) assert st == 201 st, _, _, _, _ = http_call("GET", f"/api/v1/attachments/{att1['id']}", headers=eve["headers"]) assert st == 404 st, _, _, _, _ = http_call("GET", f"/api/v1/attachments/{att1['id']}/content", headers=eve["headers"]) assert st == 404 st, _, _, _, _ = http_call("POST", f"/api/v1/chats/{chat2['id']}/messages", { "text": "stealing attachment from chat1", "attachment_ids": [att1["id"]], }, headers=alice["headers"], timeout=5) # Must add Idempotency-Key! st, _, _, _, _ = http_call("POST", f"/api/v1/chats/{chat2['id']}/messages", { "text": "stealing attachment from chat1", "attachment_ids": [att1["id"]], }, headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex}) assert st == 404, f"Cross-chat attachment must return 404, got {st}" # Unknown attachment UUID -> 404 st, _, _, _, _ = http_call("POST", f"/api/v1/chats/{chat1['id']}/messages", { "text": "missing att", "attachment_ids": [str(uuid.uuid4())], }, headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex}) assert st == 404 return { "status": "PASS", "oversized_10mib_status": 413, "pixel_bomb_49mp_status": 413, "corrupted_png_status": 415, "corrupted_jpg_status": 415, "mime_spoof_status": 415, "bad_filename_status": 400, "outsider_and_cross_chat_status": 404, "sample_attachment": att1, } def test_cross_replica_and_no_local_files(att): bob = register_and_login("cross_b") # Actually use a shared chat between uploader and downloader alice = register_and_login("cross_a") st, _, chat, _, _ = http_call("POST", "/api/v1/chats", { "title": "Cross Replica Chat", "member_ids": [alice["id"], bob["id"]], }, headers=alice["headers"]) assert st == 201 wait_two_instances(alice["headers"]) sample = FIXTURE_PNG.read_bytes() expected_sha = hashlib.sha256(sample).hexdigest() st, hdrs, uploaded, _, _ = http_call( "POST", f"/api/v1/chats/{chat['id']}/attachments?filename=cross.png", raw_bytes=sample, headers={**alice["headers"], "Content-Type": "image/png"}, ) assert st == 201 uploader_inst = hdrs["x-instance-id"] containers = get_api_containers() uploader_c = next(c for c in containers if c["short_id"] == uploader_inst) other_c = next(c for c in containers if c["short_id"] != uploader_inst) # Confirm NO leftover temp files on API containers leftover = run_cmd(["docker", "exec", uploader_c["id"], "find", "/tmp", "-name", "lab4-upload-*"]).stdout.strip() assert leftover == "", f"Leftover temp files found on API: {leftover}" # Stop the uploading API replica, then download via remaining replica! run_cmd(["docker", "stop", "-t", "5", uploader_c["id"]]) try: time.sleep(2.2) st, dl_hdrs, _, dl_bytes, _ = http_call("GET", f"/api/v1/attachments/{uploaded['id']}/content", headers=bob["headers"]) assert st == 200, f"Download after stopping uploader failed: {st}" assert dl_hdrs["x-instance-id"] == other_c["short_id"] assert hashlib.sha256(dl_bytes).hexdigest() == expected_sha assert dl_bytes == sample finally: run_cmd(["docker", "start", uploader_c["id"]]) wait_two_instances(alice["headers"]) return { "status": "PASS", "uploaded_by": uploader_inst, "downloaded_from_after_stop": other_c["short_id"], "sha256_verified": True, "api_temp_files_remaining": 0, "object_key_internal": f"attachments/{chat['id']}/{uploaded['id']}", } def test_private_bucket_and_least_privilege(object_key): containers = get_api_containers() # Verify NO API container exposes ports and NO MinIO root credentials exist in API env for c in containers: for p, binds in (c["ports"] or {}).items(): assert not binds, f"API exposes host port {p}: {binds}" env_map = dict(item.split("=", 1) for item in c["env"] if "=" in item) assert "MINIO_ROOT_USER" not in env_map and "MINIO_ROOT_PASSWORD" not in env_map, "API must not receive MinIO root creds" assert env_map.get("S3_ACCESS_KEY_ID") == "messenger_api_key" s3_info = json.loads(run_cmd(["docker", "inspect", run_cmd(["docker", "compose", "--env-file", ".env", "ps", "-q", "s3"]).stdout.strip()]).stdout)[0] for p, binds in (s3_info["NetworkSettings"]["Ports"] or {}).items(): assert not binds, f"S3/console must not expose ports to host, got {p}: {binds}" # Direct unauthenticated HTTP GET to private S3 bucket inside network -> must return 403 unauth = run_cmd( ["docker", "exec", containers[0]["id"], "wget", "-q", "-S", "-O", "/dev/null", f"http://s3:9000/messenger-attachments/{object_key}"], check=False, ) combined = (unauth.stdout + unauth.stderr) assert unauth.returncode != 0 and ("403" in combined or "Forbidden" in combined), f"Expected 403 from private bucket, got: {combined}" # Verify idempotent re-run of s3-init exits 0 cleanly run_cmd(["docker", "compose", "--env-file", ".env", "up", "--exit-code-from", "s3-init", "s3-init"]) return { "status": "PASS", "s3_exposed_host_ports": 0, "minio_console_disabled": True, "api_uses_scoped_credentials": "messenger_api_key", "direct_unauth_s3_get": "403 Forbidden", "s3_init_idempotent_rerun": 0, } def test_s3_outage_handling(att_id, headers): s3_cid = run_cmd(["docker", "compose", "--env-file", ".env", "ps", "-q", "s3"]).stdout.strip() sample = FIXTURE_PNG.read_bytes() alice = register_and_login("s3out") st, _, chat, _, _ = http_call("POST", "/api/v1/chats", {"title": "Outage", "member_ids": [alice["id"]]}, headers=alice["headers"]) assert st == 201 st, _, ok_att, _, _ = http_call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=ok.png", raw_bytes=sample, headers={**alice["headers"], "Content-Type": "image/png"}) assert st == 201 run_cmd(["docker", "stop", "-t", "5", s3_cid]) try: # HAProxy /health/ready will notice 503 too, so query API directly or via LB expecting 503 (never 500!) c0 = get_api_containers()[0] direct_ready = run_cmd(["docker", "exec", c0["id"], "wget", "-q", "-S", "-O", "/dev/null", "http://127.0.0.1:8080/health/ready"], check=False).stderr assert "503" in direct_ready, f"Expected 503 on /health/ready during S3 outage, got {direct_ready}" # Test upload/download during S3 outage via LB -> must return 503 (never 500) st_up, _, err_up, _, _ = http_call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=down.png", raw_bytes=sample, headers={**alice["headers"], "Content-Type": "image/png"}) assert st_up == 503 and (err_up is None or err_up["error"]["code"] == "unavailable"), f"Expected 503 on upload during S3 outage, got {st_up}" st_dl, _, err_dl, _, _ = http_call("GET", f"/api/v1/attachments/{ok_att['id']}/content", headers=alice["headers"]) assert st_dl == 503 and (err_dl is None or err_dl["error"]["code"] == "unavailable"), f"Expected 503 on download during S3 outage, got {st_dl}" finally: run_cmd(["docker", "start", s3_cid]) wait_ready(45) return {"status": "PASS", "ready_during_s3_outage": 503, "upload_during_s3_outage": 503, "download_during_s3_outage": 503} def test_concurrent_streaming_memory(): alice = register_and_login("conc") st, _, chat, _, _ = http_call("POST", "/api/v1/chats", {"title": "Concurrent Uploads", "member_ids": [alice["id"]]}, headers=alice["headers"]) assert st == 201 # Valid ~4.6 MiB uncompressed PNG (1400x1100 RGB = 1.54M pixels <= 40M limit) big_png = make_synthetic_png(1400, 1100, compress_level=0) expected_sha = hashlib.sha256(big_png).hexdigest() size_mb = round(len(big_png) / (1024 * 1024), 2) containers = get_api_containers() baseline_stats = {} for line in run_cmd(["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.MemUsage}}"]).stdout.strip().splitlines(): n, m = line.split("\t") if n.startswith("lab4-api"): baseline_stats[n] = m.strip() peak_stats = {} def upload_one(idx): return http_call( "POST", f"/api/v1/chats/{chat['id']}/attachments?filename=big_{idx}.png", raw_bytes=big_png, headers={**alice["headers"], "Content-Type": "image/png"}, timeout=30, ) def poll_stats(): time.sleep(0.5) for line in run_cmd(["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.MemUsage}}\t{{.CPUPerc}}"]).stdout.strip().splitlines(): parts = line.split("\t") if len(parts) == 3 and parts[0].startswith("lab4-"): peak_stats[parts[0]] = {"mem": parts[1].strip(), "cpu": parts[2].strip()} t0 = time.monotonic() with ThreadPoolExecutor(max_workers=13) as pool: stat_fut = pool.submit(poll_stats) up_futs = [pool.submit(upload_one, i) for i in range(12)] stat_fut.result() results = [f.result() for f in up_futs] elapsed = round(time.monotonic() - t0, 3) for st_c, _, att, _, _ in results: assert st_c == 201, f"Concurrent upload failed with {st_c}" assert att["size_bytes"] == len(big_png) assert att["sha256"] == expected_sha for c in containers: leftover = run_cmd(["docker", "exec", c["id"], "find", "/tmp", "-name", "lab4-upload-*"]).stdout.strip() assert leftover == "", f"Leftover temp file on {c['name']}: {leftover}" return { "status": "PASS", "concurrent_uploads": 12, "file_size_bytes": len(big_png), "file_size_mib": size_mb, "total_payload_mib": round(12 * len(big_png) / (1024 * 1024), 2), "elapsed_seconds": elapsed, "api_memory_baseline": baseline_stats, "stats_during_concurrent_upload": peak_stats, "api_temp_files_after": 0, } def main(): wait_ready() report = { "timestamp_utc": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "base_url": BASE_URL, "checks": {}, } neg = test_negative_validation() report["checks"]["negative_validation"] = {k: v for k, v in neg.items() if k != "sample_attachment"} print("PASS: negative_validation", flush=True) cross = test_cross_replica_and_no_local_files(neg["sample_attachment"]) report["checks"]["cross_replica_failover_download"] = cross print("PASS: cross_replica_failover_download", flush=True) priv = test_private_bucket_and_least_privilege(cross["object_key_internal"]) report["checks"]["private_bucket_and_iam"] = priv print("PASS: private_bucket_and_iam", flush=True) outage = test_s3_outage_handling(neg["sample_attachment"]["id"], {}) report["checks"]["s3_outage_handling"] = outage print("PASS: s3_outage_handling", flush=True) conc = test_concurrent_streaming_memory() report["checks"]["concurrent_streaming_memory"] = conc print("PASS: concurrent_streaming_memory", flush=True) EVIDENCE_PATH.parent.mkdir(parents=True, exist_ok=True) EVIDENCE_PATH.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") print(f"PASS: all Grade 4 checks succeeded; evidence saved to {EVIDENCE_PATH}") if __name__ == "__main__": main()