#!/usr/bin/env python3 import hashlib import os import struct import uuid import zlib from pathlib import Path from urllib.parse import quote from client import Client, arguments, check, run MAX_BYTES = 10 * 1024 * 1024 FIXTURE = ( Path(__file__).resolve().parent / "fixtures" / "sample.png" ) def make_png(width, height, noisy=False): """Отдельное изображение для проверки лимита байтов или пикселей.""" def chunk(kind, data): return ( struct.pack(">I", len(data)) + kind + data + struct.pack( ">I", zlib.crc32(kind + data) & 0xFFFFFFFF, ) ) compressor = zlib.compressobj(level=1) compressed = bytearray() for _ in range(height): row = os.urandom(width) if noisy else bytes(width) compressed.extend(compressor.compress(b"\x00" + row)) compressed.extend(compressor.flush()) header = struct.pack( ">IIBBBBB", width, height, 8, 0, 0, 0, 0, ) return ( b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", bytes(compressed)) + chunk(b"IEND", b"") ) def main(): args = arguments("Attachment negative tests") c = Client(args.base_url, args.ca_file, timeout=30) alice, bob, eve, chat = c.bootstrap() chat_path = "/api/v1/chats/" + chat["id"] original = FIXTURE.read_bytes() def expect_error(label, method, path, status, code, **kwargs): response = c.call(method, path, status, **kwargs) check( response["json"]["error"]["code"] == code, label + ": incorrect error code", ) print("PASS:", label, flush=True) def reject_upload( label, content, status, code, mime="image/png", filename="sample.png", actor=None, ): expect_error( label, "POST", chat_path + "/attachments?filename=" + quote(filename, safe=""), status, code, actor=alice if actor is None else actor, raw=content, headers={"Content-Type": mime}, ) def reject_message(label, target_chat, ids, status, code): expect_error( label, "POST", "/api/v1/chats/" + target_chat["id"] + "/messages", status, code, actor=alice, body={"text": "", "attachment_ids": ids}, headers={"Idempotency-Key": uuid.uuid4().hex}, ) # 1. Контрольная загрузка исходного sample.png. attachment, uploaded = c.attachment(alice, chat) check(uploaded == original, "Unexpected fixture content") downloaded = c.call( "GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=bob, ) check(downloaded["bytes"] == original, "Original bytes changed") check( attachment["sha256"] == hashlib.sha256(original).hexdigest(), "SHA-256 mismatch", ) print("PASS: original PNG upload and download", flush=True) # 2. Настоящий PNG больше 10 MiB, но меньше 40 млн пикселей. large = make_png(4096, 2700, noisy=True) check(len(large) > MAX_BYTES, "Fixture must exceed 10 MiB") reject_upload( "file larger than 10 MiB", large, 413, "payload_too_large", ) del large # 3. Небольшой по байтам PNG с 40 960 000 пикселями. many_pixels = make_png(6400, 6400) check(len(many_pixels) < MAX_BYTES, "Fixture exceeds byte limit") reject_upload( "image larger than 40 million pixels", many_pixels, 413, "payload_too_large", ) del many_pixels # 4. Повреждение создаётся в памяти, sample.png не меняется. reject_upload( "truncated PNG", original[:len(original) // 2], 415, "unsupported_media_type", ) reject_upload( "text disguised as PNG", b"This is not an image", 415, "unsupported_media_type", ) # 5. Реальный PNG объявлен как JPEG. reject_upload( "MIME spoofing", original, 415, "unsupported_media_type", mime="image/jpeg", filename="fake.jpg", ) reject_upload( "empty file", b"", 415, "unsupported_media_type", ) # 6. Опасные и недопустимые имена файлов. for filename in ( "../sample.png", "folder\\sample.png", "bad\x00name.png", "bad\nname.png", "", "x" * 256, ): reject_upload( "invalid filename " + repr(filename), original, 400, "invalid_request", filename=filename, ) # 7. Посторонний не может читать метаданные и оригинал. for suffix in ("", "/content"): expect_error( "outsider GET " + (suffix or "metadata"), "GET", "/api/v1/attachments/" + attachment["id"] + suffix, 404, "not_found", actor=eve, ) reject_upload( "outsider upload", original, 404, "not_found", actor=eve, ) # 8. Участник чата может прикрепить файл другого участника. message = c.message( bob, chat, "", attachments=[attachment["id"]], )["json"] check( message["attachment_ids"] == [attachment["id"]], "Chat member could not attach the file", ) print("PASS: chat member can attach the file", flush=True) # 9. Alice состоит в обоих чатах, но перенос вложения запрещён. second_chat = c.call( "POST", "/api/v1/chats", 201, actor=alice, body={ "title": "Second test chat", "member_ids": [alice["id"], bob["id"]], }, schema="Chat", )["json"] reject_message( "attachment from another chat", second_chat, [attachment["id"]], 404, "not_found", ) reject_message( "unknown attachment", chat, [str(uuid.uuid4())], 404, "not_found", ) reject_message( "duplicate attachment IDs", chat, [attachment["id"], attachment["id"]], 400, "invalid_request", ) # 10. Идемпотентность учитывает вложения. key = uuid.uuid4().hex first = c.message( alice, chat, "Photo", key=key, attachments=[attachment["id"]], )["json"] replay = c.message( alice, chat, "Photo", key=key, attachments=[attachment["id"]], )["json"] check(first == replay, "Idempotent replay differs") expect_error( "same key with different attachments", "POST", chat_path + "/messages", 409, "conflict", actor=alice, body={"text": "Photo", "attachment_ids": []}, headers={"Idempotency-Key": key}, ) text_key = uuid.uuid4().hex first = c.message( alice, chat, "Text only", key=text_key, )["json"] replay = c.message( alice, chat, "Text only", key=text_key, attachments=[], )["json"] check(first == replay, "Missing attachment_ids differs from []") print("PASS: missing attachment_ids equals []", flush=True) print("PASS: attachment negative tests completed", flush=True) if __name__ == "__main__": run(main)