lab4 s3 lvl4

This commit is contained in:
2026-11-01 01:18:40 +03:00
parent ec540a1a72
commit 6c0a3d8912
27 changed files with 1945 additions and 0 deletions
+19
View File
@@ -0,0 +1,19 @@
"""Synthetic image builders (stdlib only). No large fixtures are stored in Git."""
import base64, os, struct, zlib
JPEG_SMALL = base64.b64decode("/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAgADADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxnTpHgRuQjSbiwtyoTgYAH1PoeNx6ZONrSw5jiaJmMo+ZtwXYNpP93sCC3Q4OOck7q1m+CRA4WSIhQ24KSA3QcEHO1u3f252YCp8oBEm2ZYFAQQoxhl3Hk4DEDJxj8+Wvl1/sn2uO93XnbS/Vrbz3vp1+69ptqbo4mjR8kFiig7cn16YPYjtgc4xXU6UzW0ku0rIWLIGdG+XG4tuJP3M57/8A18bT4Xi8mU5+Zvkj+YKHP+6TnsRzxjgda2dKdQiSxwtthAEi4IUq27oRngZHbOPxz4eKy3mT00Pk681Rkm9Jd3vb/hm338k9DX0eVHxHKpDhzgSk5LZBIyAVHBK8jpweuB01vui2wSAqq5L7QMuMffBA+6Ap75G7HGKxrSUtCkN5CXkR1dYIVDHGOBg9F6cckZIwOK2bWBImjnmWSF8FAFYNuOCCeo75PXnOexrwcTlib1R8xi60oxtF32v00638/Vq60tqfOWjvPEiywzJOZF2ggqdrg7TkjBwc8cHBI9TnobMAs1ybbYFKklgVbgbdpYkD0PXnpg55w9PeLz3V5FCJKWVs5AcEDO3r0PY8kck5zXR6TE/2qAG3kMasjs0hzgkdiCR0I68cfl+94rLLXdj9GxFXmSgndX9bPv18/L7tNnT5VadkFxKUAKFEADLkfMcZyDw3GPl4Arbs0ihDt9lCFSjNHJzxyGI7cnH8zwax9KFwbeQQXE0nzEKNpY44PTOF6n5hxkdRgVvBBcRSJhmTfuZtxbYNuASeeNuDkZ3evyivCxGV62t/X4Hy2Nrtw5+urV/nt8W3y0N20jS6sTIINszsxXYAvmgnJxnJPHsD+tbemxS2MqybAsG7IyQAOpHOOD8zc8HAIwOKzdPtpI4vMYPIxYLHOF2OMcFWJx9OTzz7Ct+xZbaeLehec9WWMLyflGPUkMxwD2+pr5/EZdukro+dxr1VSfuyVtdP6be9lpazuf/Z")
def _chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
def png(width, height, color_type=0, bit_depth=8, noise=False, level=6):
"""Valid PNG. color_type 0=gray, 2=RGB. noise=True -> incompressible rows (big files)."""
channels = {0: 1, 2: 3}[color_type]
row_bytes = (width * channels * bit_depth + 7) // 8
comp = zlib.compressobj(level)
parts = []
zero = b"\x00" * (row_bytes + 1)
for _ in range(height):
parts.append(comp.compress(b"\x00" + os.urandom(row_bytes) if noise else zero))
parts.append(comp.flush())
ihdr = struct.pack(">IIBBBBB", width, height, bit_depth, color_type, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", ihdr) + _chunk(b"IDAT", b"".join(parts)) + _chunk(b"IEND", b"")
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
"""Focused Lab 3 level-4 checks; run only against the local synthetic Compose stack."""
from concurrent.futures import ThreadPoolExecutor
import json, time, uuid
import sys, pathlib
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "tests"))
from client import Client, Failure, arguments, check, run
def main():
args = arguments("Concurrent idempotency and replica diversity checks")
c = Client(args.base_url, args.ca_file, timeout=5)
alice, bob, eve, chat = c.bootstrap()
instances = set()
for _ in range(40):
instances.add(c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers'].get('X-Instance-Id',''))
instances.discard('')
check(len(instances) >= 2, 'load balancer did not expose at least two distinct API instances')
key = 'parallel-' + uuid.uuid4().hex
body = {'text':'Одна запись при конкурентном повторе'}
def send(_):
return c.call('POST', '/api/v1/chats/'+chat['id']+'/messages', expected=201, actor=alice, body=body,
headers={'Idempotency-Key':key}, schema='Message')
with ThreadPoolExecutor(max_workers=12) as pool:
responses = list(pool.map(send, range(12)))
ids = {r['json']['id'] for r in responses}
check(len(ids) == 1, 'concurrent identical keys produced different message IDs')
check(all(r['status'] == 201 for r in responses), 'identical retry must return HTTP 201')
changed = c.call('POST', '/api/v1/chats/'+chat['id']+'/messages', expected=409, actor=alice,
body={'text':'Другой текст'}, headers={'Idempotency-Key':key})
missing = c.call('POST', '/api/v1/chats/'+chat['id']+'/messages', expected=400, actor=alice,
body={'text':'Без ключа'}, headers={})
invalid = c.call('POST', '/api/v1/chats/'+chat['id']+'/messages', expected=400, actor=alice,
body={'text':'Неверный ключ'}, headers={'Idempotency-Key':'bad key'})
print(json.dumps({'distinct_instances':sorted(instances), 'parallel_requests':len(responses),
'distinct_message_ids':len(ids), 'changed_body_status':changed['status'],
'missing_key_status':missing['status'], 'invalid_key_status':invalid['status']}, ensure_ascii=False))
print('PASS: concurrent cross-replica idempotency, key validation, and instance visibility')
if __name__ == '__main__':
run(main)
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env python3
"""Level-4 negative/safety suite for attachments. Run only against the synthetic local stack."""
import hashlib, sys, uuid, urllib.error, urllib.request
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path[:0] = [str(ROOT / "tests"), str(Path(__file__).parent)]
from client import Client, arguments, check, run
import imagegen
MAX = 10 * 1024 * 1024
statuses = []
def up(c, actor, chat, data, ctype="image/png", name="a.png", expected=201, raw_name=None):
q = raw_name if raw_name is not None else quote(name)
r = c.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename={q}", expected, actor=actor, raw=data, headers={"Content-Type": ctype},
schema="Attachment" if expected == 201 else None)
statuses.append(r["status"])
return r
def main():
args = arguments("Level 4 attachment checks")
c = Client(args.base_url, args.ca_file, timeout=30)
alice, bob, eve, chat = c.bootstrap()
sample = (ROOT / "tests/fixtures/sample.png").read_bytes()
jpg = imagegen.JPEG_SMALL
# --- happy paths: png, jpeg, unicode filename, sha256 + headers, no redirect
a1 = up(c, alice, chat, sample)["json"]
a2 = up(c, alice, chat, jpg, "image/jpeg", "фото №1.jpg")["json"]
check(a2["filename"] == "фото №1.jpg" and a2["content_type"] == "image/jpeg", "jpeg/unicode filename")
d = c.call("GET", f"/api/v1/attachments/{a1['id']}/content", actor=bob)
check(hashlib.sha256(d["bytes"]).hexdigest() == a1["sha256"] and "Location" not in d["headers"], "download checksum / redirect")
big_ok = imagegen.png(1500, 1500, color_type=2, noise=True, level=0) # ~6.4 MiB: spool rolls over to temp file
check(len(big_ok) < MAX, "fixture size")
b = up(c, alice, chat, big_ok)["json"]
check(c.call("GET", f"/api/v1/attachments/{b['id']}/content", actor=bob)["bytes"] == big_ok, "big image roundtrip")
edge = up(c, alice, chat, imagegen.png(8000, 5000, bit_depth=1))["json"] # exactly 40 000 000 px: accepted
# --- size / pixels
up(c, alice, chat, b"\x89PNG\r\n\x1a\n" + b"0" * MAX, expected=413) # MAX+8 bytes
up(c, alice, chat, imagegen.png(8000, 5001, bit_depth=1), expected=413) # 40 008 000 px bomb, ~1 KB
up(c, alice, chat, imagegen.png(30000, 30000, bit_depth=1), expected=413) # far beyond Pillow's own limit
# --- corrupted
up(c, alice, chat, sample[: len(sample) // 2], expected=415) # truncated PNG
flipped = bytearray(sample); flipped[5000:5016] = b"\xde\xad\xbe\xef" * 4
up(c, alice, chat, bytes(flipped), expected=415) # CRC/zlib damage
up(c, alice, chat, b"\x89PNG\r\n\x1a\n" + bytes(range(256)) * 8, expected=415) # signature + garbage
up(c, alice, chat, jpg[: len(jpg) // 2], "image/jpeg", expected=415) # truncated JPEG
up(c, alice, chat, b"", expected=415)
# --- MIME spoofing
up(c, alice, chat, b"<html><script>alert(1)</script></html>", expected=415)
up(c, alice, chat, b"<svg xmlns='http://www.w3.org/2000/svg'/>", "image/png", expected=415)
up(c, alice, chat, b"GIF89a" + b"\x00" * 64, "image/png", expected=415)
up(c, alice, chat, jpg, "image/png", expected=415) # real JPEG declared PNG
up(c, alice, chat, sample, "image/jpeg", expected=415) # real PNG declared JPEG
up(c, alice, chat, sample, "text/plain", expected=415)
up(c, alice, chat, sample, "application/octet-stream", expected=415)
# --- filename
for bad in ("a%2Fb.png", "a%5Cb.png", "a%00b.png", "a%0Ab.png", "..", "%20%20", "x" * 256, ""):
up(c, alice, chat, sample, raw_name=bad, expected=400)
c.call("POST", f"/api/v1/chats/{chat['id']}/attachments", 400, actor=alice, raw=sample, headers={"Content-Type": "image/png"})
up(c, alice, chat, sample, raw_name="x" * 255)
# --- access control on upload / metadata / bytes
up(c, eve, chat, sample, expected=404)
for suffix in ("", "/content"):
c.call("GET", f"/api/v1/attachments/{a1['id']}{suffix}", 404, actor=eve)
c.call("GET", f"/api/v1/attachments/{uuid.uuid4()}", 404, actor=alice)
c.call("GET", f"/api/v1/attachments/{a1['id']}", 401)
c.call("GET", f"/api/v1/attachments/{a1['id']}/content?variant=thumbnail", 400, actor=alice)
# --- attachment binding rules
chat_b = c.call("POST", "/api/v1/chats", 201, actor=bob, body={"title": "B", "member_ids": [bob["id"], eve["id"]]}, schema="Chat")["json"]
chat_c = c.call("POST", "/api/v1/chats", 201, actor=alice, body={"title": "C", "member_ids": [alice["id"], bob["id"]]}, schema="Chat")["json"]
def msg(actor, ch, body, key=None, expected=201):
return c.call("POST", f"/api/v1/chats/{ch['id']}/messages", expected, actor=actor, body=body, headers={"Idempotency-Key": key or uuid.uuid4().hex},
schema="Message" if expected == 201 else None)
msg(bob, chat_b, {"text": "x", "attachment_ids": [a1["id"]]}, expected=404) # foreign chat's attachment (Bob not a member of chat)
msg(alice, chat_c, {"text": "x", "attachment_ids": [a1["id"]]}, expected=404) # same user, other chat
msg(alice, chat, {"text": "x", "attachment_ids": [str(uuid.uuid4())]}, expected=404)
msg(alice, chat, {"text": "x", "attachment_ids": [a1["id"], str(uuid.uuid4())]}, expected=404)
msg(alice, chat, {"text": "x", "attachment_ids": [a1["id"], a1["id"]]}, expected=400)
msg(alice, chat, {"text": "x", "attachment_ids": ["not-a-uuid"]}, expected=400)
msg(alice, chat, {"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]}, expected=400)
msg(alice, chat, {"text": " ", "attachment_ids": []}, expected=400)
msg(alice, chat, {"text": "x", "attachment_ids": None}, expected=400)
# --- success + idempotency + order + history
key = uuid.uuid4().hex
m1 = msg(bob, chat, {"text": "", "attachment_ids": [a2["id"], a1["id"]]}, key)["json"]
check(m1["attachment_ids"] == [a2["id"], a1["id"]], "attachment order lost")
check(msg(bob, chat, {"attachment_ids": [a2["id"], a1["id"]], "text": ""}, key)["json"] == m1, "idempotent replay differs")
msg(bob, chat, {"text": "", "attachment_ids": [a1["id"]]}, key, expected=409)
hist = c.call("GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", actor=alice, schema="MessagePage")["json"]["items"]
check(any(m == m1 for m in hist), "history lost attachment_ids")
# --- 10 parallel uploads stay correct
def one(_): return up(c, alice, chat, sample)["json"]["sha256"]
with ThreadPoolExecutor(10) as pool:
check(set(pool.map(one, range(10))) == {hashlib.sha256(sample).hexdigest()}, "parallel uploads")
check(max(statuses) < 500, "a user mistake produced HTTP 5xx: " + str(sorted(set(statuses))))
print("statuses seen:", sorted(set(statuses)))
print("PASS: level-4 attachment checks (no 5xx for user errors)")
if __name__ == "__main__":
run(main)
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""Peak-RAM experiment: N concurrent uploads, reads VmHWM (peak RSS) of every API replica process.
Docker mode (default): `docker compose exec -T api` is not enough to pick each replica, so we iterate
`docker compose ps -q api` and `docker exec <id> cat /proc/1/status`. Local mode: --pids 123,456.
Run on a fresh stack (restart api first) so VmHWM starts from the idle baseline.
"""
import argparse, json, re, subprocess, sys, time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
sys.path[:0] = [str(Path(__file__).resolve().parents[1] / "tests"), str(Path(__file__).parent)]
from client import Client, check, run
import imagegen
def reset_peak(args):
"""Writing 5 to /proc/PID/clear_refs resets VmHWM to the current RSS (own process, no privileges)."""
if args.pids:
for pid in args.pids.split(","):
Path(f"/proc/{pid}/clear_refs").write_text("5")
else:
for cid in subprocess.check_output(["docker", "compose", "ps", "-q", "api"], text=True).split():
subprocess.check_call(["docker", "exec", cid, "sh", "-c", "echo 5 > /proc/1/clear_refs"])
def read_status(args):
out = {}
if args.pids:
for pid in args.pids.split(","):
out[pid] = Path(f"/proc/{pid}/status").read_text()
else:
for cid in subprocess.check_output(["docker", "compose", "ps", "-q", "api"], text=True).split():
out[cid[:12]] = subprocess.check_output(["docker", "exec", cid, "cat", "/proc/1/status"], text=True)
res = {}
for k, t in out.items():
g = lambda n: int(re.search(n + r":\s+(\d+) kB", t).group(1)) // 1024
res[k] = {"VmRSS_MiB": g("VmRSS"), "VmHWM_MiB": g("VmHWM")}
return res
def main():
p = argparse.ArgumentParser()
p.add_argument("--base-url", default=None); p.add_argument("--ca-file", default=None)
p.add_argument("--concurrency", type=int, default=10); p.add_argument("--pids", default="")
p.add_argument("--profile", choices=["big-bytes", "max-pixels"], default="big-bytes")
p.add_argument("--output", default=None)
args = p.parse_args()
check(args.concurrency >= 10, "the lab requires >= 10 concurrent uploads")
c = Client(args.base_url, args.ca_file, timeout=120)
alice, bob, eve, chat = c.bootstrap()
if args.profile == "big-bytes": # ~9.6 MiB incompressible RGB PNG: stresses body streaming
data = imagegen.png(1830, 1830, color_type=2, noise=True, level=0)
else: # exactly 40 MP, tiny file: stresses the decoder
data = imagegen.png(8000, 5000, bit_depth=8, color_type=0)
check(len(data) <= 10 * 1024 * 1024, "payload above the limit")
reset_peak(args)
before = read_status(args)
def one(_):
t = time.monotonic(); r = c.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=m.png", 201, actor=alice, raw=data, headers={"Content-Type": "image/png"}, schema="Attachment")
return time.monotonic() - t
t0 = time.monotonic()
with ThreadPoolExecutor(args.concurrency) as pool:
lat = sorted(pool.map(one, range(args.concurrency)))
after = read_status(args)
rep = {"profile": args.profile, "concurrency": args.concurrency, "payload_bytes": len(data), "wall_seconds": round(time.monotonic() - t0, 2),
"latency_s": {"min": round(lat[0], 2), "max": round(lat[-1], 2)}, "before": before, "after_peak": after,
"naive_estimate_MiB": round(args.concurrency * len(data) / 2**20 * 2)}
print(json.dumps(rep, indent=2))
if args.output: Path(args.output).write_text(json.dumps(rep, indent=2) + "\n")
if __name__ == "__main__":
run(main)
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
"""Docker-stack check of the orphan sweeper: fresh survives, old orphan removed, referenced object never removed.
Run on the local synthetic compose stack: python3 student-tests/orphan_sweep_check.py"""
import subprocess, sys, time
from pathlib import Path
sys.path[:0] = [str(Path(__file__).resolve().parents[1] / "tests")]
from client import Client, check, run
def compose(container: str, *cmd: str) -> str:
return subprocess.check_output(
["docker", "compose", "run", "--rm", "--no-deps", "-T", container, *cmd],
text=True,
)
def main():
c = Client(timeout=30)
alice, bob, eve, chat = c.bootstrap()
att, content = c.attachment(alice, chat)
# injector → api (app-креды, есть PutObject)
key = compose("api", "python", "scripts/s3_fault_inject.py").strip().splitlines()[-1]
# sweeper → s3_sweeper (sweeper-креды, есть ListBucket)
out = compose("s3_sweeper", "python", "scripts/s3_sweep.py", "--apply", "--grace-seconds", "3600")
check("deleted=0" in out, "fresh orphan was deleted inside the grace period: " + out)
time.sleep(6)
out = compose("s3_sweeper", "python", "scripts/s3_sweep.py", "--grace-seconds", "5")
check("WOULD-DELETE " + key in out and "deleted=0" in out, "dry-run must report the orphan and delete nothing: " + out)
out = compose("s3_sweeper", "python", "scripts/s3_sweep.py", "--apply", "--grace-seconds", "5")
check("DELETE " + key in out, "orphan not deleted: " + out)
check(c.call("GET", f"/api/v1/attachments/{att['id']}/content", actor=bob)["bytes"] == content, "referenced attachment damaged by sweeper")
out = compose("s3_sweeper", "python", "scripts/s3_sweep.py", "--apply", "--grace-seconds", "5")
check("orphans=0" in out, "second run must be a no-op: " + out)
print("PASS: grace period, dry-run, orphan removal, referenced object preserved, idempotent re-run")
if __name__ == "__main__":
run(main)
+60
View File
@@ -0,0 +1,60 @@
"""Deterministic proof of compensation: S3 PUT succeeded but the metadata INSERT/COMMIT failed.
Needs: pip install -r requirements.txt httpx (no running services: S3, PostgreSQL are replaced by fakes)."""
import sys, unittest, uuid
from contextlib import contextmanager
from pathlib import Path
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(Path(__file__).parent))
import imagegen
from fastapi.testclient import TestClient
from src import main
import psycopg
class Compensation(unittest.TestCase):
def setUp(self):
self.puts, self.deletes = [], []
self.client = TestClient(main.app, raise_server_exceptions=False)
self.patches = [
mock.patch.object(main, "current_user", lambda r: {"id": uuid.uuid4()}),
mock.patch.object(main, "ensure_member", lambda a, c: None),
mock.patch.object(main, "s3_put", lambda key, spool, size, ct: self.puts.append(key)),
mock.patch.object(main, "s3_delete_quietly", lambda key: self.deletes.append(key)),
]
for p in self.patches: p.start()
self.url = f"/api/v1/chats/{uuid.uuid4()}/attachments?filename=a.png"
self.png = imagegen.png(16, 16)
def tearDown(self):
for p in self.patches: p.stop()
def post(self, data=None, ctype="image/png"):
return self.client.post(self.url, content=data or self.png, headers={"Content-Type": ctype})
def test_db_failure_after_put_deletes_object(self):
@contextmanager
def broken_db():
raise psycopg.OperationalError("simulated COMMIT failure")
yield
with mock.patch.object(main, "db", broken_db):
r = self.post()
self.assertEqual(r.status_code, 503)
self.assertEqual(len(self.puts), 1)
self.assertEqual(self.deletes, self.puts) # exactly the object that was written
def test_corrupt_image_never_reaches_s3(self):
r = self.post(self.png[:40])
self.assertEqual(r.status_code, 415)
self.assertEqual((self.puts, self.deletes), ([], []))
def test_put_failure_is_compensated_and_503(self):
def failing_put(key, spool, size, ct):
self.puts.append(key); raise main.BotoCoreError()
with mock.patch.object(main, "s3_put", failing_put):
r = self.post()
self.assertEqual(r.status_code, 503)
self.assertEqual(self.deletes, self.puts) # a PUT with a lost reply may have stored the object
if __name__ == "__main__":
unittest.main()