Files
mtusi2026lab4/student-tests/grade45.py
T

247 lines
11 KiB
Python

#!/usr/bin/env python3
"""Негативные вложения, приватный bucket, память и трек сверки. Стенд уже запущен."""
import json
import subprocess
import threading
import time
import urllib.error
import urllib.request
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
BASE = "http://127.0.0.1:8080"
EVIDENCE = ROOT / "evidence"
def req(method, path, body=None, headers=None, content_type=None):
data = body if isinstance(body, bytes) else (None if body is None else json.dumps(body).encode())
h = dict(headers or {})
if content_type:
h["Content-Type"] = content_type
elif data is not None and not isinstance(body, bytes):
h["Content-Type"] = "application/json"
request = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
try:
with urllib.request.urlopen(request, timeout=60) as resp:
return resp.status, resp.headers, resp.read()
except urllib.error.HTTPError as exc:
return exc.code, exc.headers, exc.read()
def user(prefix):
name = prefix + uuid.uuid4().hex[:8]
status, _, raw = req("POST", "/api/v1/users", {"username": name, "display_name": prefix, "password": "correct-horse-1"})
assert status == 201, raw
body = json.loads(raw)
token = basic_session(name, "correct-horse-1")
return body, token
def basic_session(username, password):
import base64
raw = base64.b64encode(f"{username}:{password}".encode()).decode()
status, _, body = req("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + raw})
assert status == 201, body
return json.loads(body)["token"]
def auth(token):
return {"Authorization": "Bearer " + token}
def chat(token, title, members):
status, _, raw = req("POST", "/api/v1/chats", {"title": title, "member_ids": members}, headers=auth(token))
assert status == 201, raw
return json.loads(raw)
def upload(token, chat_id, filename, body, content_type="image/png"):
return req(
"POST",
f"/api/v1/chats/{chat_id}/attachments?filename={filename}",
body,
headers=auth(token),
content_type=content_type,
)
def psql(sql):
out = subprocess.check_output(
["docker", "compose", "--env-file", ".env", "exec", "-T", "postgres", "sh", "-c",
'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -At -c ' + json.dumps(sql)],
cwd=ROOT, text=True)
return [line for line in out.splitlines() if line.strip()]
def s3(cmd, key, body=b""):
proc = subprocess.run(
["docker", "compose", "--env-file", ".env", "run", "--rm", "-T", "--no-deps", "api", cmd, key],
cwd=ROOT, input=body, capture_output=True)
if proc.returncode != 0:
raise SystemExit(proc.stderr.decode()[-500:])
def reconcile(apply=False, grace=5):
args = ["docker", "compose", "--env-file", ".env", "run", "--rm", "-T", "--no-deps",
"-e", f"RECONCILE_GRACE_SECONDS={grace}", "api", "reconcile"]
if apply:
args.append("--apply")
proc = subprocess.run(args, cwd=ROOT, capture_output=True, text=True)
if proc.returncode != 0:
raise SystemExit(proc.stderr[-500:])
return json.loads(proc.stdout)
def main():
EVIDENCE.mkdir(exist_ok=True)
png = (ROOT / "tests/fixtures/sample.png").read_bytes()
alice, ta = user("alice")
bob, tb = user("bob")
eve, te = user("eve")
room = chat(ta, "негативные", [alice["id"], bob["id"]])
other = chat(ta, "чужой", [alice["id"]])
lines = []
def check(name, status, raw, expected):
ok = status == expected and b"internal_error" not in raw
lines.append(f"{name}: HTTP {status} expected {expected} {'PASS' if ok else 'FAIL'} body={raw[:180]!r}")
if not ok:
raise SystemExit("\n".join(lines))
status, _, raw = upload(ta, room["id"], "a/b.png", png)
check("slash filename", status, raw, 400)
status, _, raw = upload(ta, room["id"], "a\\b.png", png)
check("backslash filename", status, raw, 400)
status, _, raw = upload(ta, room["id"], "note.png", b"not-an-image")
check("text as png", status, raw, 415)
status, _, raw = upload(ta, room["id"], "swap.png", b"\xff\xd8\xff\xe0" + b"\x00" * 32, "image/png")
check("mime swap", status, raw, 415)
status, _, raw = upload(ta, room["id"], "cut.png", png[:80])
check("truncated png", status, raw, 415)
status, _, raw = upload(ta, room["id"], "big.bin", b"\x00" * (10 * 1024 * 1024 + 1))
check("over 10MiB", status, raw, 413)
before = psql("SELECT count(*) FROM attachments")[0]
status, _, raw = upload(ta, room["id"], "pixels.png", pixel_bomb())
check("pixel bomb", status, raw, 413)
after = psql("SELECT count(*) FROM attachments")[0]
lines.append(f"rejected uploads left attachment rows {before}->{after} {'PASS' if before == after else 'FAIL'}")
status, _, raw = upload(ta, room["id"], "ok.png", png)
check("good upload", status, raw, 201)
att = json.loads(raw)
status, _, raw = req("POST", f"/api/v1/chats/{room['id']}/messages",
{"text": "x", "attachment_ids": [str(uuid.uuid4())]},
headers={**auth(ta), "Idempotency-Key": uuid.uuid4().hex})
check("unknown attachment", status, raw, 404)
status, _, foreign_raw = upload(ta, other["id"], "foreign.png", png)
check("other chat upload", status, foreign_raw, 201)
foreign = json.loads(foreign_raw)
status, _, raw = req("POST", f"/api/v1/chats/{room['id']}/messages",
{"text": "", "attachment_ids": [foreign["id"]]},
headers={**auth(ta), "Idempotency-Key": uuid.uuid4().hex})
check("attachment from other chat", status, raw, 404)
status, _, raw = req("GET", f"/api/v1/attachments/{att['id']}/content", headers=auth(te))
check("outsider download", status, raw, 404)
key = psql(f"SELECT object_key FROM attachments WHERE id = '{att['id']}'")[0]
code = subprocess.check_output(
["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",
f"http://127.0.0.1:9000/messenger-attachments/{key}"], text=True).strip()
lines.append(f"anonymous S3 GET {code} {'PASS' if code in ('403', '401') else 'FAIL'}")
console = subprocess.run(["curl", "-s", "-o", "/dev/null", "-m", "2", "-w", "%{http_code}", "http://127.0.0.1:9001/"],
capture_output=True, text=True)
lines.append(f"console on host http_code={console.stdout.strip() or 'no-response'} err={console.returncode}")
# 10 одновременных загрузок по 1 МиБ мусора: каждая обрезается лимитом чтения, 500 быть не должно.
junk = b"\x00" * (1 * 1024 * 1024)
codes = []
peak = {"mem": 0}
def one():
status, _, _ = upload(ta, room["id"], "junk.png", junk)
codes.append(status)
def sample():
end = time.time() + 8
while time.time() < end:
out = subprocess.check_output(
["docker", "stats", "--no-stream", "--format", "{{.Name}} {{.MemUsage}}"], text=True)
for line in out.splitlines():
if "api" not in line:
continue
mem = line.split()[1]
num = float(mem.replace("MiB", "").replace("GiB", ""))
if "GiB" in mem:
num *= 1024
peak["mem"] = max(peak["mem"], num)
time.sleep(0.3)
sampler = threading.Thread(target=sample)
sampler.start()
threads = [threading.Thread(target=one) for _ in range(10)]
t0 = time.perf_counter()
for t in threads:
t.start()
for t in threads:
t.join()
sampler.join()
elapsed = time.perf_counter() - t0
lines.append(f"10 parallel 1MiB uploads statuses={sorted(codes)} seconds={elapsed:.2f} peak_api_MiB={peak['mem']:.1f}")
if any(c == 500 for c in codes) or len(codes) != 10:
raise SystemExit("\n".join(lines))
# Трек 2. grace 5 секунд.
status, _, raw = upload(ta, room["id"], "used.png", png)
used = json.loads(raw)
req("POST", f"/api/v1/chats/{room['id']}/messages",
{"text": "", "attachment_ids": [used["id"]]},
headers={**auth(ta), "Idempotency-Key": uuid.uuid4().hex})
status, _, raw = upload(ta, room["id"], "loose.png", png)
loose = json.loads(raw)
s3("s3-put", "o/orphan-old", b"orphan-old")
time.sleep(6)
for row_id in (used["id"], loose["id"]):
object_key = psql(f"SELECT object_key FROM attachments WHERE id = '{row_id}'")[0]
s3("s3-rm", object_key)
status, _, raw = upload(ta, room["id"], "fresh.png", png)
fresh = json.loads(raw)
s3("s3-put", "o/orphan-fresh", b"orphan-fresh")
dry1 = reconcile(False)
dry2 = reconcile(False)
lines.append("dry-run-1 " + json.dumps(dry1, ensure_ascii=False))
lines.append("dry-run-2 same=" + str(dry1["deleted_objects"] == 0 and dry2["deleted_objects"] == 0 and dry1["orphan_stale"] == dry2["orphan_stale"]))
applied = reconcile(True)
lines.append("apply " + json.dumps(applied, ensure_ascii=False))
again = reconcile(True)
lines.append("apply-again " + json.dumps({k: again[k] for k in ("deleted_objects", "deleted_rows", "orphan_stale", "missing_stale_unreferenced")}))
status, _, _ = req("GET", f"/api/v1/attachments/{used['id']}", headers=auth(tb))
lines.append(f"referenced metadata after apply HTTP {status}")
status, _, _ = req("GET", f"/api/v1/attachments/{used['id']}/content", headers=auth(tb))
lines.append(f"referenced bytes missing HTTP {status}")
status, _, _ = req("GET", f"/api/v1/attachments/{loose['id']}", headers=auth(ta))
lines.append(f"stale unreferenced metadata HTTP {status}")
status, _, content = req("GET", f"/api/v1/attachments/{fresh['id']}/content", headers=auth(tb))
lines.append(f"fresh download HTTP {status} same_bytes={content == png}")
(EVIDENCE / "reconcile-apply.json").write_text(json.dumps({"dry": dry1, "apply": applied, "again": again}, indent=2) + "\n")
(EVIDENCE / "grade45.txt").write_text("\n".join(lines) + "\n")
print("\n".join(lines))
def pixel_bomb():
# Минимальный PNG 1×1 с подменой IHDR на 20000×2001 и пересчитанным CRC.
import struct
import zlib
sig = b"\x89PNG\r\n\x1a\n"
def chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
ihdr = struct.pack(">IIBBBBB", 20000, 2001, 8, 2, 0, 0, 0)
raw = b"\x00" + b"\x00\x00\x00"
return sig + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
if __name__ == "__main__":
main()