feat(lab4): MinIO S3 private bucket, streaming image validation, attachment endpoints, Grade 5 Track 2 reconciler
This commit is contained in:
@@ -0,0 +1,446 @@
|
||||
#!/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"<html>not-an-image</html>", 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()
|
||||
@@ -0,0 +1,234 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade 5 Track 2: Two-Store (PostgreSQL <-> S3) Reconciler experiment for Lab 4.
|
||||
1. Seeds >=25 healthy active attachments (some referenced by messages).
|
||||
2. Injects faults on BOTH sides:
|
||||
- 3 aged orphan S3 objects (> grace) without DB rows
|
||||
- 1 aged missing-S3 'ready' attachment (referenced in message; S3 object deleted out-of-band)
|
||||
- 1 aged missing-S3 'pending' attachment in DB (never committed to S3)
|
||||
- 1 fresh orphan S3 object INSIDE grace period (simulating in-flight upload)
|
||||
3. Runs Reconciler in --dry-run (proves 0 mutations, detects exact anomalies, skips fresh grace).
|
||||
4. Runs Reconciler in --apply (deletes aged orphans & stale pending row, marks missing ready attachment as failed, preserves fresh grace & all >=25 healthy objects).
|
||||
5. Runs Reconciler a second time (proves strict idempotency: 0 mutations, 0 anomalies).
|
||||
6. Verifies all >=25 healthy attachments remain downloadable with exact SHA-256 and captures traversal cost.
|
||||
"""
|
||||
import base64
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
FIXTURE_PNG = ROOT / "tests" / "fixtures" / "sample.png"
|
||||
EVIDENCE_PATH = ROOT / "evidence" / "track2_reconciler.json"
|
||||
BASE_URL = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
|
||||
|
||||
|
||||
def run_cmd(cmd, input_text=None):
|
||||
return subprocess.run(cmd, cwd=str(ROOT), input=input_text, text=True, capture_output=True, check=True)
|
||||
|
||||
|
||||
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)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
raw = resp.read()
|
||||
ct = resp.headers.get("Content-Type", "")
|
||||
parsed = json.loads(raw.decode("utf-8")) if (raw and "application/json" in ct) else None
|
||||
return resp.code, parsed, raw
|
||||
except urllib.error.HTTPError as err:
|
||||
raw = err.read()
|
||||
ct = err.headers.get("Content-Type", "")
|
||||
parsed = json.loads(raw.decode("utf-8")) if (raw and "application/json" in ct) else None
|
||||
return err.code, parsed, raw
|
||||
|
||||
|
||||
def register_and_login():
|
||||
uname = f"rec_{uuid.uuid4().hex[:8]}"
|
||||
pw = f"Track2Pass-{uuid.uuid4().hex}"
|
||||
st, u, _ = http_call("POST", "/api/v1/users", {"username": uname, "display_name": "Reconciler", "password": pw})
|
||||
assert st == 201
|
||||
basic = base64.b64encode(f"{uname}:{pw}".encode("utf-8")).decode("ascii")
|
||||
st, sess, _ = http_call("POST", "/api/v1/auth/sessions", headers={"Authorization": f"Basic {basic}"})
|
||||
assert st == 201
|
||||
return {"id": u["id"], "headers": {"Authorization": f"Bearer {sess['token']}"}}
|
||||
|
||||
|
||||
def mc_exec(s3_cid, script_body):
|
||||
cmd = ["docker", "exec", "-i", s3_cid, "/bin/sh", "-e"]
|
||||
return run_cmd(cmd, input_text=script_body).stdout
|
||||
|
||||
|
||||
def s3_object_exists(s3_cid, obj_key):
|
||||
res = subprocess.run(
|
||||
["docker", "exec", s3_cid, "/bin/sh", "-c",
|
||||
f"mc alias set local http://127.0.0.1:9000 minio_admin_local minio_admin_secret_lab4 >/dev/null && mc stat local/messenger-attachments/{obj_key} >/dev/null 2>&1"],
|
||||
cwd=str(ROOT), text=True, capture_output=True,
|
||||
)
|
||||
return res.returncode == 0
|
||||
|
||||
|
||||
def main():
|
||||
api_cid = run_cmd(["docker", "compose", "--env-file", ".env", "ps", "-q", "api"]).stdout.strip().splitlines()[0].strip()
|
||||
pg_cid = run_cmd(["docker", "compose", "--env-file", ".env", "ps", "-q", "postgres"]).stdout.strip()
|
||||
s3_cid = run_cmd(["docker", "compose", "--env-file", ".env", "ps", "-q", "s3"]).stdout.strip()
|
||||
|
||||
sample = FIXTURE_PNG.read_bytes()
|
||||
expected_sha = hashlib.sha256(sample).hexdigest()
|
||||
|
||||
actor = register_and_login()
|
||||
st, chat, _ = http_call("POST", "/api/v1/chats", {
|
||||
"title": "Track 2 Reconciler Chat",
|
||||
"member_ids": [actor["id"]],
|
||||
}, headers=actor["headers"])
|
||||
assert st == 201
|
||||
|
||||
# 1. Upload 25 healthy active attachments (and link first 10 to messages)
|
||||
healthy = []
|
||||
for i in range(25):
|
||||
st, att, _ = http_call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=healthy_{i}.png",
|
||||
raw_bytes=sample,
|
||||
headers={**actor["headers"], "Content-Type": "image/png"},
|
||||
)
|
||||
assert st == 201
|
||||
healthy.append(att)
|
||||
if i < 10:
|
||||
st_m, _, _ = http_call("POST", f"/api/v1/chats/{chat['id']}/messages", {
|
||||
"text": f"Attached #{i}",
|
||||
"attachment_ids": [att["id"]],
|
||||
}, headers={**actor["headers"], "Idempotency-Key": f"rec-msg-{i}-{uuid.uuid4().hex[:8]}"})
|
||||
assert st_m == 201
|
||||
|
||||
# 2. Upload 1 legitimate attachment that will suffer out-of-band S3 object loss (Fault C)
|
||||
st, victim_att, _ = http_call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=victim.png",
|
||||
raw_bytes=sample,
|
||||
headers={**actor["headers"], "Content-Type": "image/png"},
|
||||
)
|
||||
assert st == 201
|
||||
st_m, _, _ = http_call("POST", f"/api/v1/chats/{chat['id']}/messages", {
|
||||
"text": "Message referencing S3-lost attachment",
|
||||
"attachment_ids": [victim_att["id"]],
|
||||
}, headers={**actor["headers"], "Idempotency-Key": f"rec-victim-{uuid.uuid4().hex[:8]}"})
|
||||
assert st_m == 201
|
||||
|
||||
victim_key = f"attachments/{chat['id']}/{victim_att['id']}"
|
||||
|
||||
# Inject Fault A (3 orphan S3 objects) & remove victim_key out-of-band (Fault C)
|
||||
orphan_keys = [f"attachments/{chat['id']}/orphan_{uuid.uuid4()}" for _ in range(3)]
|
||||
mc_script = "mc alias set local http://127.0.0.1:9000 minio_admin_local minio_admin_secret_lab4 >/dev/null\n"
|
||||
for k in orphan_keys:
|
||||
mc_script += f"printf 'orphan-bytes-%s' '{k}' | mc pipe local/messenger-attachments/{k} >/dev/null\n"
|
||||
mc_script += f"mc rm local/messenger-attachments/{victim_key} >/dev/null\n"
|
||||
mc_exec(s3_cid, mc_script)
|
||||
|
||||
# Inject Fault D: aged 'pending' DB row without S3 object
|
||||
stale_pending_id = str(uuid.uuid4())
|
||||
run_cmd([
|
||||
"docker", "exec", "-i", pg_cid, "psql", "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger",
|
||||
], input_text=f"""
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status, error_code, created_at, updated_at)
|
||||
VALUES ('{stale_pending_id}'::uuid, '{chat['id']}'::uuid, '{actor['id']}'::uuid, 'stale_pending.png', 'image/png', 100, '{expected_sha}', 'attachments/{chat['id']}/{stale_pending_id}', 'pending', NULL, NOW() - INTERVAL '20 seconds', NOW() - INTERVAL '20 seconds');
|
||||
""")
|
||||
|
||||
# Wait 7 seconds so Faults A/C/D cross the 5s grace threshold
|
||||
time.sleep(7.0)
|
||||
|
||||
# Inject Fault B: FRESH orphan S3 object INSIDE grace period (age ~0s < 5s)
|
||||
fresh_key = f"attachments/{chat['id']}/fresh_{uuid.uuid4()}"
|
||||
mc_exec(s3_cid, f"""
|
||||
mc alias set local http://127.0.0.1:9000 minio_admin_local minio_admin_secret_lab4 >/dev/null
|
||||
printf 'inflight-upload' | mc pipe local/messenger-attachments/{fresh_key} >/dev/null
|
||||
""")
|
||||
|
||||
# 3. Run Reconciler in --dry-run (grace=5s)
|
||||
dry_raw = run_cmd([
|
||||
"docker", "exec", api_cid, "/app/messenger", "-reconcile-once", "-dry-run", "-grace-seconds=5",
|
||||
]).stdout
|
||||
dry_report = json.loads(dry_raw)
|
||||
assert dry_report["lock_acquired"] is True
|
||||
for k in orphan_keys:
|
||||
assert k in dry_report["orphan_s3_found"], f"Dry-run missed orphan {k}"
|
||||
assert fresh_key in dry_report["orphan_s3_skipped_grace"], "Dry-run must skip fresh in-flight S3 object inside grace"
|
||||
assert victim_att["id"] in dry_report["missing_s3_found"]
|
||||
assert stale_pending_id in dry_report["missing_s3_found"]
|
||||
assert dry_report["orphan_s3_deleted"] == []
|
||||
assert dry_report["missing_s3_marked_failed"] == []
|
||||
assert dry_report["missing_s3_deleted"] == []
|
||||
assert dry_report["healthy_preserved"] >= 25
|
||||
print(f"PASS: dry-run scanned {dry_report['s3_objects_scanned']} S3 objs, {dry_report['db_rows_scanned']} DB rows in {dry_report['duration_ms']}ms")
|
||||
|
||||
# 4. Run Reconciler in --apply (grace=5s)
|
||||
apply_raw = run_cmd([
|
||||
"docker", "exec", api_cid, "/app/messenger", "-reconcile-once", "-grace-seconds=5",
|
||||
]).stdout
|
||||
apply_report = json.loads(apply_raw)
|
||||
assert set(orphan_keys).issubset(set(apply_report["orphan_s3_deleted"]))
|
||||
assert fresh_key in apply_report["orphan_s3_skipped_grace"], "Apply must NOT delete fresh object inside grace!"
|
||||
assert victim_att["id"] in apply_report["missing_s3_marked_failed"]
|
||||
assert stale_pending_id in apply_report["missing_s3_deleted"]
|
||||
assert apply_report["healthy_preserved"] >= 25
|
||||
|
||||
# Verify S3 state: aged orphans gone, fresh orphan STILL present!
|
||||
for k in orphan_keys:
|
||||
assert not s3_object_exists(s3_cid, k), f"Aged orphan {k} was not removed"
|
||||
assert s3_object_exists(s3_cid, fresh_key), "Fresh object inside grace was wrongly deleted!"
|
||||
|
||||
# Verify DB/API state: victim attachment marked failed & download returns 409; stale pending deleted!
|
||||
st_v, _, _ = http_call("GET", f"/api/v1/attachments/{victim_att['id']}/content", headers=actor["headers"])
|
||||
assert st_v == 409, f"Expected 409 on missing_s3_object download, got {st_v}"
|
||||
|
||||
# 5. Re-run Reconciler immediately (repeatability / idempotency check!)
|
||||
rerun_raw = run_cmd([
|
||||
"docker", "exec", api_cid, "/app/messenger", "-reconcile-once", "-grace-seconds=5",
|
||||
]).stdout
|
||||
rerun_report = json.loads(rerun_raw)
|
||||
assert rerun_report["orphan_s3_deleted"] == []
|
||||
assert rerun_report["missing_s3_marked_failed"] == []
|
||||
assert rerun_report["missing_s3_deleted"] == []
|
||||
assert rerun_report["healthy_preserved"] >= 25
|
||||
|
||||
# 6. Verify ALL 25 healthy active attachments remain downloadable with exact SHA-256
|
||||
for att in healthy:
|
||||
st_h, _, raw_h = http_call("GET", f"/api/v1/attachments/{att['id']}/content", headers=actor["headers"])
|
||||
assert st_h == 200 and hashlib.sha256(raw_h).hexdigest() == expected_sha
|
||||
|
||||
# Cleanup our synthetic fresh_key test artifact in S3 so bucket stays tidy
|
||||
mc_exec(s3_cid, f"mc alias set local http://127.0.0.1:9000 minio_admin_local minio_admin_secret_lab4 >/dev/null && mc rm local/messenger-attachments/{fresh_key} >/dev/null")
|
||||
|
||||
out = {
|
||||
"timestamp_utc": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"healthy_attachments_verified": len(healthy),
|
||||
"injected_faults": {
|
||||
"aged_orphan_s3_objects": len(orphan_keys),
|
||||
"fresh_orphan_s3_inside_grace": 1,
|
||||
"missing_s3_ready_referenced": 1,
|
||||
"missing_s3_pending_stale": 1,
|
||||
},
|
||||
"dry_run_report": dry_report,
|
||||
"apply_report": apply_report,
|
||||
"idempotent_rerun_report": rerun_report,
|
||||
"status": "PASS",
|
||||
}
|
||||
EVIDENCE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
EVIDENCE_PATH.write_text(json.dumps(out, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"PASS: Track 2 two-store reconciler experiment verified; evidence saved to {EVIDENCE_PATH}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user