Добавить приватное S3-хранилище, вложения, presigned upload, reconciler и доказательства.
177 lines
6.5 KiB
Python
177 lines
6.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Lab4 negative attachment checks: size, corruption, MIME, ownership, chat scope."""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import io
|
|
import struct
|
|
import uuid
|
|
import zlib
|
|
from urllib.parse import quote
|
|
|
|
from PIL import Image
|
|
|
|
from common import HttpClient, assert_status, error_code
|
|
|
|
MAX_UPLOAD = 10_485_760
|
|
|
|
|
|
def _png_chunk(kind: bytes, data: bytes) -> bytes:
|
|
return (
|
|
len(data).to_bytes(4, "big")
|
|
+ kind
|
|
+ data
|
|
+ struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
|
)
|
|
|
|
|
|
def png_bytes(width: int = 320, height: int = 200) -> bytes:
|
|
buffer = io.BytesIO()
|
|
Image.new("RGB", (width, height), (30, 120, 200)).save(buffer, format="PNG")
|
|
return buffer.getvalue()
|
|
|
|
|
|
def jpeg_bytes(width: int = 320, height: int = 200) -> bytes:
|
|
buffer = io.BytesIO()
|
|
Image.new("RGB", (width, height), (200, 80, 30)).save(buffer, format="JPEG")
|
|
return buffer.getvalue()
|
|
|
|
|
|
def png_header(width: int, height: int) -> bytes:
|
|
"""Valid signature/IHDR/IEND; enough for the pixel budget check, no decode."""
|
|
return (
|
|
b"\x89PNG\r\n\x1a\n"
|
|
+ _png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
|
|
+ _png_chunk(b"IEND", b"")
|
|
)
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--base-url", default="http://localhost:8080")
|
|
args = parser.parse_args()
|
|
client = HttpClient(args.base_url)
|
|
|
|
alice, alice_reg = client.register()
|
|
bob, bob_reg = client.register()
|
|
eve, _eve_reg = client.register()
|
|
alice_token = client.login(alice_reg)["token"]
|
|
bob_token = client.login(bob_reg)["token"]
|
|
eve_token = client.login(_eve_reg)["token"]
|
|
|
|
status, _h, chat, _r = client.call(
|
|
"POST",
|
|
"/api/v1/chats",
|
|
body={"title": "Attachment negatives", "member_ids": [alice["id"], bob["id"]]},
|
|
token=alice_token,
|
|
)
|
|
assert_status(status, 201, "create chat")
|
|
status, _h, other_chat, _r = client.call(
|
|
"POST",
|
|
"/api/v1/chats",
|
|
body={"title": "Another chat", "member_ids": [alice["id"], bob["id"]]},
|
|
token=alice_token,
|
|
)
|
|
assert_status(status, 201, "create other chat")
|
|
|
|
def upload(content: bytes, content_type: str, filename: str, token=alice_token, chat_id=None):
|
|
path = (
|
|
"/api/v1/chats/"
|
|
+ (chat_id or chat["id"])
|
|
+ "/attachments?filename="
|
|
+ quote(filename, safe="")
|
|
)
|
|
return client.raw(
|
|
"POST",
|
|
path,
|
|
data=content,
|
|
headers={"Authorization": "Bearer " + token, "Content-Type": content_type},
|
|
)
|
|
|
|
def expect(result, expected: int, label: str) -> dict:
|
|
status, headers, payload, _raw = result
|
|
assert_status(status, expected, label)
|
|
if status >= 400:
|
|
if not isinstance(payload, dict) or payload.get("error", {}).get("code") in (None, "internal_error"):
|
|
raise AssertionError(f"{label}: expected a typed user error, got {payload!r}")
|
|
if payload["error"]["request_id"] != headers.get("X-Request-Id"):
|
|
raise AssertionError(f"{label}: request_id mismatch")
|
|
return payload
|
|
|
|
png = png_bytes()
|
|
jpeg = jpeg_bytes()
|
|
|
|
attachment = expect(upload(png, "image/png", "ok.png"), 201, "valid PNG")
|
|
if attachment["status"] != "ready":
|
|
raise AssertionError("valid PNG did not become ready")
|
|
|
|
expect(
|
|
upload(b"\x89PNG\r\n\x1a\n" + b"x" * (MAX_UPLOAD + 1), "image/png", "big.png"),
|
|
413,
|
|
"oversized body",
|
|
)
|
|
expect(upload(b"", "image/png", "empty.png"), 415, "empty body")
|
|
expect(upload(b"\x89PNG\r\n\x1a\nnot-an-image", "image/png", "broken.png"), 415, "corrupted PNG")
|
|
expect(upload(jpeg, "image/png", "spoof.png"), 415, "JPEG bytes declared as PNG")
|
|
expect(upload(png, "image/jpeg", "spoof.jpg"), 415, "PNG bytes declared as JPEG")
|
|
expect(upload(png, "text/plain", "plain.txt"), 415, "unsupported content type")
|
|
expect(upload(png_header(10_000, 5_000), "image/png", "huge.png"), 413, "pixel budget")
|
|
expect(upload(png, "image/png", "../escape.png"), 400, "path traversal filename")
|
|
expect(upload(png, "image/png", "a/b.png"), 400, "slash filename")
|
|
expect(upload(png, "image/png", "a\\b.png"), 400, "backslash filename")
|
|
|
|
# A member of the chat still gets 404 for an unknown attachment id.
|
|
missing_id = str(uuid.uuid4())
|
|
status, _h, payload, _r = client.call(
|
|
"GET", "/api/v1/attachments/" + missing_id, token=bob_token
|
|
)
|
|
assert_status(status, 404, "unknown attachment metadata")
|
|
if error_code(payload) == "internal_error":
|
|
raise AssertionError("unknown attachment leaked a 500")
|
|
|
|
# A non-member cannot read metadata or bytes.
|
|
for suffix in ("", "/content"):
|
|
status, _h, payload, _r = client.call(
|
|
"GET", "/api/v1/attachments/" + attachment["id"] + suffix, token=eve_token
|
|
)
|
|
assert_status(status, 404, "outsider attachment read")
|
|
if error_code(payload) == "internal_error":
|
|
raise AssertionError("outsider read leaked a 500")
|
|
|
|
# Uploading into another chat and linking it here must be a 404, not a 500.
|
|
foreign = expect(upload(png, "image/png", "foreign.png", chat_id=other_chat["id"]), 201, "other-chat upload")
|
|
status, _h, payload, _r = client.call(
|
|
"POST",
|
|
"/api/v1/chats/" + chat["id"] + "/messages",
|
|
body={"text": "", "attachment_ids": [foreign["id"]]},
|
|
token=alice_token,
|
|
headers={"Idempotency-Key": uuid.uuid4().hex},
|
|
)
|
|
assert_status(status, 404, "attachment from another chat")
|
|
if error_code(payload) == "internal_error":
|
|
raise AssertionError("cross-chat attachment leaked a 500")
|
|
|
|
# Duplicate and too-many ids are request errors, not 500.
|
|
status, _h, _p, _r = client.call(
|
|
"POST",
|
|
"/api/v1/chats/" + chat["id"] + "/messages",
|
|
body={"text": "", "attachment_ids": [attachment["id"], attachment["id"]]},
|
|
token=alice_token,
|
|
headers={"Idempotency-Key": uuid.uuid4().hex},
|
|
)
|
|
assert_status(status, 400, "duplicate attachment ids")
|
|
status, _h, _p, _r = client.call(
|
|
"POST",
|
|
"/api/v1/chats/" + chat["id"] + "/messages",
|
|
body={"text": "", "attachment_ids": [attachment["id"]] * 11},
|
|
token=alice_token,
|
|
headers={"Idempotency-Key": uuid.uuid4().hex},
|
|
)
|
|
assert_status(status, 400, "too many attachment ids")
|
|
|
|
print("PASS: lab4 attachment negatives (size, corruption, MIME, filename, ownership, chat scope)")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|