forked from mtusi2026/mtusi2026lab4
172 lines
6.5 KiB
Python
172 lines
6.5 KiB
Python
"""Grade-4 negative cases. User mistakes must stay 4xx, never 500."""
|
|
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import uuid
|
|
import zlib
|
|
from pathlib import Path
|
|
from urllib.parse import quote
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "tests"))
|
|
from client import Client, Failure, check # noqa: E402
|
|
|
|
FIXTURE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
|
|
|
|
|
def chunk(tag: bytes, data: bytes) -> bytes:
|
|
crc = zlib.crc32(tag + data) & 0xFFFFFFFF
|
|
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", crc)
|
|
|
|
|
|
def pixel_bomb() -> bytes:
|
|
ihdr = struct.pack(">IIBBBBB", 20000, 20000, 8, 2, 0, 0, 0)
|
|
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IEND", b"")
|
|
|
|
|
|
def jpeg_bytes() -> bytes:
|
|
raw = subprocess.check_output(
|
|
[
|
|
"docker",
|
|
"exec",
|
|
"mtusi-api-1",
|
|
"python",
|
|
"-c",
|
|
"import io,base64; from PIL import Image; b=io.BytesIO(); "
|
|
"Image.new('RGB',(8,8),(12,34,56)).save(b,format='JPEG',quality=85); "
|
|
"print(base64.b64encode(b.getvalue()).decode())",
|
|
],
|
|
text=True,
|
|
)
|
|
return base64.b64decode(raw.strip())
|
|
|
|
|
|
def main() -> None:
|
|
client = Client("http://127.0.0.1:8080", timeout=60)
|
|
client.call("GET", "/health/live", schema="Health")
|
|
alice = client.user("n_alice")
|
|
bob = client.user("n_bob")
|
|
eve = client.user("n_eve")
|
|
chat = client.call(
|
|
"POST",
|
|
"/api/v1/chats",
|
|
201,
|
|
actor=alice,
|
|
body={"title": "Негативные", "member_ids": [alice["id"], bob["id"]]},
|
|
schema="Chat",
|
|
)["json"]
|
|
other = client.call(
|
|
"POST",
|
|
"/api/v1/chats",
|
|
201,
|
|
actor=alice,
|
|
body={"title": "Чужой", "member_ids": [alice["id"], eve["id"]]},
|
|
schema="Chat",
|
|
)["json"]
|
|
|
|
def upload(actor, chat_id, payload, filename, content_type, expected):
|
|
path = f"/api/v1/chats/{chat_id}/attachments?filename=" + quote(filename, safe="")
|
|
schema = "Attachment" if expected == 201 else None
|
|
return client.call(
|
|
"POST",
|
|
path,
|
|
expected,
|
|
actor=actor,
|
|
raw=payload,
|
|
headers={"Content-Type": content_type},
|
|
schema=schema,
|
|
)
|
|
|
|
jpeg = jpeg_bytes()
|
|
created = upload(alice, chat["id"], jpeg, "фото.jpg", "image/jpeg", 201)["json"]
|
|
check(created["content_type"] == "image/jpeg", "jpeg content type was not stored")
|
|
check(created["sha256"] == hashlib.sha256(jpeg).hexdigest(), "jpeg checksum mismatch")
|
|
downloaded = client.call("GET", "/api/v1/attachments/" + created["id"] + "/content", actor=bob)
|
|
check(downloaded["bytes"] == jpeg, "jpeg download mismatch")
|
|
check(downloaded["headers"].get_content_type() == "image/jpeg", "jpeg response type mismatch")
|
|
|
|
big = upload(alice, chat["id"], b"\x89PNG\r\n\x1a\n" + b"0" * (10 * 1024 * 1024), "big.png", "image/png", 413)
|
|
check(big["json"]["error"]["code"] == "payload_too_large", "oversize code")
|
|
bomb = upload(alice, chat["id"], pixel_bomb(), "bomb.png", "image/png", 413)
|
|
check(bomb["json"]["error"]["code"] == "payload_too_large", "pixel bomb code")
|
|
corrupt = upload(alice, chat["id"], FIXTURE[:-80], "broken.png", "image/png", 415)
|
|
check(corrupt["json"]["error"]["code"] == "unsupported_media_type", "corrupt code")
|
|
spoof = upload(alice, chat["id"], FIXTURE, "spoof.jpg", "image/jpeg", 415)
|
|
check(spoof["json"]["error"]["code"] == "unsupported_media_type", "mime spoof code")
|
|
garbage = upload(alice, chat["id"], b"not an image", "note.png", "image/png", 415)
|
|
check(garbage["json"]["error"]["code"] == "unsupported_media_type", "garbage code")
|
|
plain = upload(alice, chat["id"], FIXTURE, "note.png", "text/plain", 415)
|
|
check(plain["json"]["error"]["code"] == "unsupported_media_type", "declared text code")
|
|
|
|
for name in ("../secret.png", "a/b.png", "a\\b.png", "bad\nname.png", "bad\x00name.png", " ", "."):
|
|
refused = upload(alice, chat["id"], FIXTURE, name, "image/png", 400)
|
|
check(refused["json"]["error"]["code"] == "invalid_request", "dangerous filename was not 400")
|
|
|
|
missing = client.call("GET", "/api/v1/attachments/" + str(uuid.uuid4()), 404, actor=alice)
|
|
check(missing["json"]["error"]["code"] == "not_found", "random attachment code")
|
|
foreign = upload(alice, other["id"], FIXTURE, "other.png", "image/png", 201)["json"]
|
|
attached = client.call(
|
|
"POST",
|
|
"/api/v1/chats/" + chat["id"] + "/messages",
|
|
404,
|
|
actor=alice,
|
|
body={"text": "чужое вложение", "attachment_ids": [foreign["id"]]},
|
|
headers={"Idempotency-Key": uuid.uuid4().hex},
|
|
)
|
|
check(attached["json"]["error"]["code"] == "not_found", "cross-chat attachment code")
|
|
hidden = client.call("GET", "/api/v1/attachments/" + created["id"], 404, actor=eve)
|
|
check(hidden["json"]["error"]["code"] == "not_found", "outsider metadata code")
|
|
hidden_bytes = client.call("GET", "/api/v1/attachments/" + created["id"] + "/content", 404, actor=eve)
|
|
check(hidden_bytes["json"]["error"]["code"] == "not_found", "outsider bytes code")
|
|
|
|
client.call(
|
|
"POST",
|
|
"/api/v1/chats/" + chat["id"] + "/messages",
|
|
400,
|
|
actor=alice,
|
|
body={"text": " "},
|
|
headers={"Idempotency-Key": uuid.uuid4().hex},
|
|
)
|
|
client.call(
|
|
"POST",
|
|
"/api/v1/chats/" + chat["id"] + "/messages",
|
|
400,
|
|
actor=alice,
|
|
body={"text": "привет", "extra": 1},
|
|
headers={"Idempotency-Key": uuid.uuid4().hex},
|
|
)
|
|
client.call("POST", "/api/v1/users", 400, body={"username": "ab", "display_name": "Имя", "password": "short-pass"})
|
|
client.call(
|
|
"POST",
|
|
"/api/v1/chats",
|
|
400,
|
|
actor=alice,
|
|
body={"title": "Дубли", "member_ids": [alice["id"], alice["id"]]},
|
|
)
|
|
page = client.call(
|
|
"GET",
|
|
"/api/v1/chats/" + chat["id"] + "/messages?limit=1",
|
|
actor=alice,
|
|
schema="MessagePage",
|
|
)["json"]
|
|
if page["next_cursor"]:
|
|
client.call(
|
|
"GET",
|
|
"/api/v1/chats/" + other["id"] + "/messages?limit=1&cursor=" + quote(page["next_cursor"], safe=""),
|
|
400,
|
|
actor=alice,
|
|
)
|
|
print("PASS: negative attachment and validation cases stayed in 4xx")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except (Failure, Exception) as exc:
|
|
print("FAIL:", exc)
|
|
raise SystemExit(1)
|