"""Негативные интеграционные проверки вложений для уровня 4.""" import struct from urllib.parse import quote import uuid import zlib import pytest from tests.client import Client, ROOT @pytest.fixture(scope='module') def scenario(): client = Client() alice, bob, eve, chat = client.bootstrap() return client, alice, bob, eve, chat def upload(client, actor, chat, content, *, filename='sample.png', content_type='image/png', expected=201): return client.call( 'POST', f'/api/v1/chats/{chat["id"]}/attachments?filename={quote(filename, safe="")}', expected, actor=actor, raw=content, headers={'Content-Type': content_type}, schema='Attachment' if expected == 201 else None, ) def oversized_dimensions_png(content: bytes) -> bytes: data = bytearray(content) data[16:20] = struct.pack('>I', 10_000) data[20:24] = struct.pack('>I', 5_000) data[29:33] = struct.pack('>I', zlib.crc32(data[12:29]) & 0xFFFFFFFF) return bytes(data) def test_file_larger_than_10_mib_is_rejected(scenario): """Отклоняет файл размером больше 10 MiB.""" client, alice, _bob, _eve, chat = scenario upload(client, alice, chat, b'x' * (10 * 1024 * 1024 + 1), expected=413) def test_corrupted_image_is_rejected(scenario): """Отклоняет повреждённое изображение.""" client, alice, _bob, _eve, chat = scenario upload(client, alice, chat, b'not-a-png', expected=415) def test_mime_mismatch_is_rejected(scenario): """Отклоняет MIME, не совпадающий с содержимым.""" client, alice, _bob, _eve, chat = scenario content = (ROOT / 'tests/fixtures/sample.png').read_bytes() upload(client, alice, chat, content, content_type='image/jpeg', expected=415) def test_pixel_limit_is_checked_before_decode(scenario): """Проверяет лимит пикселей до полной декомпрессии.""" client, alice, _bob, _eve, chat = scenario content = oversized_dimensions_png((ROOT / 'tests/fixtures/sample.png').read_bytes()) upload(client, alice, chat, content, expected=413) @pytest.mark.parametrize( 'filename', ['../escape.png', 'folder\\escape.png', 'bad\x00name.png', 'bad\x85name.png'], ) def test_dangerous_filename_is_rejected(scenario, filename): """Отклоняет опасное отображаемое имя файла.""" client, alice, _bob, _eve, chat = scenario content = (ROOT / 'tests/fixtures/sample.png').read_bytes() upload(client, alice, chat, content, filename=filename, expected=400) def test_outsider_cannot_read_attachment(scenario): """Скрывает метаданные и содержимое от постороннего пользователя.""" client, alice, _bob, eve, chat = scenario content = (ROOT / 'tests/fixtures/sample.png').read_bytes() attachment = upload(client, alice, chat, content)['json'] client.call('GET', f'/api/v1/attachments/{attachment["id"]}', 404, actor=eve) client.call('GET', f'/api/v1/attachments/{attachment["id"]}/content', 404, actor=eve) def test_attachment_from_another_chat_cannot_be_linked(scenario): """Запрещает прикреплять вложение другого чата.""" client, alice, bob, _eve, chat = scenario other_chat = client.call( 'POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Другой чат', 'member_ids': [alice['id'], bob['id']]}, schema='Chat', )['json'] content = (ROOT / 'tests/fixtures/sample.png').read_bytes() attachment = upload(client, alice, other_chat, content)['json'] client.call( 'POST', f'/api/v1/chats/{chat["id"]}/messages', 404, actor=alice, body={'text': 'чужое вложение', 'attachment_ids': [attachment['id']]}, headers={'Idempotency-Key': uuid.uuid4().hex}, ) def test_idempotency_distinguishes_attachment_list(scenario): """Включает список вложений в сравнение идемпотентного запроса.""" client, alice, _bob, _eve, chat = scenario content = (ROOT / 'tests/fixtures/sample.png').read_bytes() attachment = upload(client, alice, chat, content)['json'] key = uuid.uuid4().hex first = client.message( alice, chat, 'идемпотентное вложение', key=key, attachments=[attachment['id']], )['json'] replay = client.message( alice, chat, 'идемпотентное вложение', key=key, attachments=[attachment['id']], )['json'] assert replay == first client.call( 'POST', f'/api/v1/chats/{chat["id"]}/messages', 409, actor=alice, body={'text': 'идемпотентное вложение', 'attachment_ids': []}, headers={'Idempotency-Key': key}, ) def test_missing_attachment_ids_equals_empty_list_for_idempotency(scenario): """Считает отсутствие attachment_ids эквивалентным пустому списку.""" client, alice, _bob, _eve, chat = scenario key = uuid.uuid4().hex first = client.message(alice, chat, 'обычный текст', key=key)['json'] replay = client.call( 'POST', f'/api/v1/chats/{chat["id"]}/messages', 201, actor=alice, body={'text': 'обычный текст', 'attachment_ids': []}, headers={'Idempotency-Key': key}, schema='Message', )['json'] assert replay == first