Files
mtusi2026lab4/student-tests/upload_boundaries.py
T

59 lines
2.6 KiB
Python

"""Exact byte limit and chunked overflow using a valid PNG ancillary chunk."""
import hashlib
import http.client
import json
from pathlib import Path
import struct
import sys
from urllib.parse import urlsplit
import zlib
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run, shape
def main():
args = arguments('Exact 10 MiB and chunked overflow')
c = Client(args.base_url or 'http://127.0.0.1:8084', args.ca_file, timeout=65)
alice, bob, _, chat = c.bootstrap()
base = (ROOT / 'tests/fixtures/sample.png').read_bytes()
limit = 10485760
# Insert a real tEXt chunk before IEND; no trailing bytes after the PNG end.
size = limit - len(base) - 12
text = b'padding\0' + b'x' * (size - 8)
chunk = struct.pack('>I', size) + b'tEXt' + text + struct.pack('>I', zlib.crc32(b'tEXt' + text))
data = base[:-12] + chunk + base[-12:]
check(len(data) == limit, 'incorrect boundary fixture size')
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=limit.png'
a = c.call('POST', path, 201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
check(a['size_bytes'] == limit and a['sha256'] == hashlib.sha256(data).hexdigest(), 'boundary metadata mismatch')
downloaded = c.call('GET', '/api/v1/attachments/' + a['id'] + '/content', actor=bob)
check(downloaded['bytes'] == data, '10 MiB original changed')
print('PASS: real PNG exactly 10 MiB accepted; original bytes/checksum preserved')
target = urlsplit(c.base)
check(target.scheme == 'http', 'chunked boundary scenario is local HTTP only')
def pieces():
for offset in range(0, len(data), 32768):
yield data[offset:offset+32768]
yield b'x'
connection = http.client.HTTPConnection(target.hostname, target.port or 80, timeout=65)
try:
connection.request('POST', path, body=pieces(), encode_chunked=True,
headers={'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'})
response = connection.getresponse()
body = json.loads(response.read())
check(response.status == 413, 'chunked size overflow did not return 413')
shape(body, 'Error')
check(body['error']['request_id'] == response.headers.get('X-Request-Id'), 'request ID mismatch')
check(bool(response.headers.get('X-Instance-Id')), 'missing API instance ID')
finally:
connection.close()
print('PASS: chunked stream without Content-Length, 10 MiB+1 byte, returns 413 from API')
if __name__ == '__main__':
run(main)