forked from mtusi2026/mtusi2026lab4
103 lines
6.9 KiB
Python
103 lines
6.9 KiB
Python
#!/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)
|