#!/usr/bin/env python3 """Негативные и граничные сценарии вложений через работающий стенд. Создаёт синтетические данные.""" import hashlib import uuid from urllib.parse import quote from common import Client, MAX_BYTES, MAX_PIXELS, SAMPLE_JPEG, SAMPLE_PNG, arguments, check, png_with_size, run def main(): args = arguments('Attachment negative and boundary scenarios') c = Client(args.base_url, args.ca_file, timeout=60) alice, bob, eve, chat = c.bootstrap() other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Другой', 'member_ids': [alice['id']]}, schema='Chat')['json'] def upload(data, content_type='image/png', filename='a.png', actor=alice, target=chat, expected=201): path = '/api/v1/chats/' + target['id'] + '/attachments?filename=' + quote(filename, safe='') return c.call('POST', path, expected, actor=actor, raw=data, headers={'Content-Type': content_type}, schema='Attachment' if expected == 201 else None) def rejected(name, expected, data, **kwargs): response = upload(data, expected=expected, **kwargs) print('ok %-44s -> %d %s' % (name, expected, response['json']['error']['code'])) half = SAMPLE_PNG[:len(SAMPLE_PNG) // 2] flipped = bytearray(SAMPLE_PNG) flipped[len(flipped) // 2] ^= 0xff rejected('файл на байт больше лимита', 413, SAMPLE_PNG + b'\0' * (MAX_BYTES - len(SAMPLE_PNG) + 1)) rejected('размеры на пиксель больше лимита', 413, png_with_size(MAX_PIXELS + 1, 1)) rejected('«бомба» 100000x100000', 413, png_with_size(100000, 100000)) # Без Content-Length размер неизвестен заранее: лимит должен сработать при чтении. rejected('chunked: файл на байт больше лимита', 413, iter([SAMPLE_PNG, b'\0' * (MAX_BYTES - len(SAMPLE_PNG) + 1)])) rejected('заголовок PNG без пикселей', 415, png_with_size(16, 16)) rejected('обрезанный PNG', 415, half) rejected('изменённый байт PNG', 415, bytes(flipped)) rejected('обрезанный JPEG', 415, SAMPLE_JPEG[:len(SAMPLE_JPEG) // 2], content_type='image/jpeg') rejected('JPEG: только сигнатура', 415, b'\xff\xd8\xff', content_type='image/jpeg') rejected('текст вместо картинки', 415, b'') rejected('пустое тело', 415, b'') rejected('подмена: объявлен JPEG, внутри PNG', 415, SAMPLE_PNG, content_type='image/jpeg') rejected('подмена: объявлен PNG, внутри JPEG', 415, SAMPLE_JPEG, content_type='image/png') rejected('неподдерживаемый Content-Type', 415, SAMPLE_PNG, content_type='image/gif') for name in ('../etc/passwd', 'a\\b.png', 'a\x00.png', 'a\nb.png', '..', ' ', 'x' * 256): rejected('опасное имя %r' % name[:16], 400, SAMPLE_PNG, filename=name) rejected('посторонний загружает в чужой чат', 404, SAMPLE_PNG, actor=eve) rejected('посторонний: размер не важнее доступа', 404, b'\0' * (MAX_BYTES + 1), actor=eve) exact = SAMPLE_PNG + b'\0' * (MAX_BYTES - len(SAMPLE_PNG)) att = upload(exact)['json'] check(att['size_bytes'] == MAX_BYTES, 'size mismatch at limit') got = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob) check(got['bytes'] == exact, 'byte-exact download failed at limit') print('ok файл ровно 10 MiB принят и скачан побайтно') jpeg = upload(SAMPLE_JPEG, content_type='image/jpeg', filename='фото.jpg')['json'] got = c.call('GET', '/api/v1/attachments/' + jpeg['id'] + '/content', actor=bob) check(got['headers'].get_content_type() == 'image/jpeg', 'wrong JPEG content type') check(hashlib.sha256(got['bytes']).hexdigest() == jpeg['sha256'], 'JPEG checksum mismatch') print('ok JPEG с именем не ASCII принят и скачан, SHA-256 совпал') for suffix in ('', '/content'): c.call('GET', '/api/v1/attachments/' + jpeg['id'] + suffix, 404, actor=eve) c.call('GET', '/api/v1/attachments/' + jpeg['id'] + suffix, 401) c.call('GET', '/api/v1/attachments/not-a-uuid', 400, actor=alice) c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()), 404, actor=alice) print('ok посторонний 404, без сессии 401, неверный UUID 400, несуществующий 404') foreign = upload(SAMPLE_PNG, target=other)['json'] messages = '/api/v1/chats/' + chat['id'] + '/messages' key = {'Idempotency-Key': uuid.uuid4().hex} c.call('POST', messages, 404, actor=alice, headers=key, body={'text': 'x', 'attachment_ids': [foreign['id']]}) c.call('POST', messages, 404, actor=alice, headers=key, body={'text': 'x', 'attachment_ids': [str(uuid.uuid4())]}) c.call('POST', messages, 400, actor=alice, headers=key, body={'text': '', 'attachment_ids': []}) c.call('POST', messages, 400, actor=alice, headers=key, body={'text': 'x', 'attachment_ids': [jpeg['id'], jpeg['id']]}) # Чужой файл: Eve загрузила его в свой чат, а Alice ссылается на него в своём и пытается прочитать. eve_chat = c.call('POST', '/api/v1/chats', 201, actor=eve, body={'title': 'Чат Eve', 'member_ids': [eve['id']]}, schema='Chat')['json'] eve_file = upload(SAMPLE_PNG, actor=eve, target=eve_chat)['json'] c.call('POST', messages, 404, actor=alice, headers=key, body={'text': 'x', 'attachment_ids': [eve_file['id']]}) for suffix in ('', '/content'): c.call('GET', '/api/v1/attachments/' + eve_file['id'] + suffix, 404, actor=alice) # Смешанный список: одно своё вложение не даёт привязать чужое, сообщение не создаётся. before = c.call('GET', messages + '?limit=100', actor=alice, schema='MessagePage')['json']['items'] c.call('POST', messages, 404, actor=alice, headers={'Idempotency-Key': uuid.uuid4().hex}, body={'text': 'x', 'attachment_ids': [jpeg['id'], foreign['id']]}) after = c.call('GET', messages + '?limit=100', actor=alice, schema='MessagePage')['json']['items'] check(len(after) == len(before), 'message was created with a foreign attachment') print('ok вложение чужого чата 404, чужой пользователь 404, неизвестное 404, пустое сообщение 400, дубли 400, смешанный список без записи') sent = c.message(alice, chat, 'с файлами', attachments=[att['id'], jpeg['id']])['json'] page = c.call('GET', messages + '?limit=100', actor=bob, schema='MessagePage')['json'] found = [m for m in page['items'] if m['id'] == sent['id']] check(len(found) == 1 and found[0]['attachment_ids'] == [att['id'], jpeg['id']], 'attachment order lost in history') print('ok второй участник читает сообщение, порядок вложений сохранён') print('PASS: attachment negative and boundary scenarios') if __name__ == '__main__': run(main)