"""Check the upload limits required by grade 3 before body reading/decoding.""" from email.message import Message from io import BytesIO from pathlib import Path import struct import sys from types import SimpleNamespace import zlib from PIL import Image ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'tests')) from client import Client, check from messenger.attachments import filename_value, validate_image from messenger.core import APIError from messenger.server import Handler def rejected(status, action): try: action() except APIError as error: check(error.status == status, 'Unexpected rejection code') else: raise AssertionError('Expected rejection') class NeverRead: def read(self, *_): raise AssertionError('Oversized body was read') def main(): headers = Message() headers['Content-Length'] = '10485761' headers['Content-Type'] = 'image/png' handler = SimpleNamespace(headers=headers, rfile=NeverRead()) rejected(413, lambda: Handler.read_body(handler, 10485760, ('image/png',))) original = (ROOT / 'tests/fixtures/sample.png').read_bytes() # Header-only dimension change: rejection must happen before decoding pixels. header = original[12:16] + struct.pack('!IIBBBBB', 8000, 5001, 8, 2, 0, 0, 0) huge = original[:12] + header + struct.pack('!I', zlib.crc32(header)) + original[33:] rejected(413, lambda: validate_image(huge, 'image/png', 40000000)) for name in ('../x.png', 'a\\x.png', 'a\0.png', 'a\n.png'): rejected(400, lambda: filename_value(name)) check(filename_value('фото.png') == 'фото.png', 'Unicode display filename changed') c = Client('http://lb:8080') alice, bob, _, chat = c.bootstrap() # Exact byte limit is legal; trailing PNG bytes must be returned unchanged. raw = original + b'\0' * (10485760 - len(original)) att = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=limit.png', 201, actor=alice, raw=raw, headers={'Content-Type': 'image/png'}, schema='Attachment')['json'] check(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == raw, '10 MiB original changed') del raw # Exact pixel limit: valid image, checked in one request without concurrency. buffer = BytesIO() with Image.new('RGB', (8000, 5000), 'black') as image: image.save(buffer, format='PNG') raw = buffer.getvalue() att = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=pixels.png', 201, actor=alice, raw=raw, headers={'Content-Type': 'image/png'}, schema='Attachment')['json'] check(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == raw, '40 million pixel original changed') print('PASS: 10 MiB and 40,000,000 pixels accepted; excess bytes rejected before read;') print('excess dimensions rejected before decode; unsafe filenames rejected; Unicode filename accepted.') if __name__ == '__main__': main()