#!/usr/bin/env python3 """Presigned direct-upload track (lab4 level 5). The mandatory proxy endpoint stays available; this script exercises the optional extension: presign -> direct PUT to S3 -> complete -> message. Run against a live stand: python3 student-tests/presign_flow.py --base-url http://localhost:8080 Set PRESIGN_EXPIRY_WAIT=seconds to also verify that an expired URL is rejected (the stand must run with a matching S3_PRESIGN_TTL). """ import hashlib import json import os import sys import time import urllib.error import urllib.request import uuid from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) from client import Client, Failure, arguments, check, run # noqa: E402 FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png' def presign(client, actor, chat, content, filename='presigned.png', content_type='image/png'): body = { 'filename': filename, 'content_type': content_type, 'size_bytes': len(content), 'sha256': hashlib.sha256(content).hexdigest(), } response = client.call( 'POST', '/api/v1/chats/' + chat['id'] + '/attachments/presign', 201, actor=actor, body=body, ) return json.loads(response['bytes']) def put(url, content, content_type='image/png'): request = urllib.request.Request( url, data=content, method='PUT', headers={'Content-Type': content_type}, ) try: with urllib.request.urlopen(request, timeout=15) as response: return response.status except urllib.error.HTTPError as error: return error.code def complete(client, actor, attachment_id, digest, expected=202): return client.call( 'POST', '/api/v1/attachments/' + attachment_id + '/complete', expected, actor=actor, body={'sha256': digest}, schema='Attachment' if expected == 202 else None, ) def main(): args = arguments('Presigned upload flow (lab4 track 1)') client = Client(args.base_url, args.ca_file) alice, bob, eve, chat = client.bootstrap() content = FIXTURE.read_bytes() digest = hashlib.sha256(content).hexdigest() # Happy path: direct PUT, completion, message, download. presigned = presign(client, alice, chat, content) check(presigned['method'] == 'PUT', 'presign method must be PUT') check('content-length' in presigned['upload_url'], 'content-length must be signed into the URL') check(put(presigned['upload_url'], content) == 200, 'direct PUT failed') attachment = complete(client, alice, presigned['attachment_id'], digest)['json'] check(attachment['sha256'] == digest and attachment['size_bytes'] == len(content), 'completed metadata mismatch') attachment = client.wait_ready(alice, attachment) print('happy path: direct PUT 200, complete queued, ready after worker') client.message(alice, chat, '', attachments=[attachment['id']]) download = client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob) check(download['bytes'] == content, 'download differs from the presigned original') print('message with attachment downloaded as the second chat member') # Completion is idempotent. again = complete(client, alice, presigned['attachment_id'], digest)['json'] check(again['id'] == attachment['id'], 'repeated complete returned another attachment') check(again['status'] in ('queued', 'processing', 'ready'), 'repeated complete returned an invalid state') print('repeated complete is idempotent') # A foreign user cannot complete someone else's pending upload. pending = presign(client, alice, chat, content) complete(client, bob, pending['attachment_id'], digest, expected=404) print('foreign complete: 404') # Incomplete upload: complete before PUT. incomplete = presign(client, alice, chat, content) complete(client, alice, incomplete['attachment_id'], digest, expected=409) print('complete before PUT: 409') # Wrong checksum: the object is rejected and removed. mismatch = presign(client, alice, chat, content) check(put(mismatch['upload_url'], content) == 200, 'direct PUT failed') complete(client, alice, mismatch['attachment_id'], '0' * 64, expected=409) print('wrong completion checksum: 409') # Content-Length is signed, so S3 rejects a different number of bytes at # write time instead of storing an oversized staging object. oversized = presign(client, alice, chat, content) check(put(oversized['upload_url'], content + b'x') == 403, 'oversized PUT must be rejected by S3') complete(client, alice, oversized['attachment_id'], digest, expected=409) print('oversized direct PUT: 403 from S3; complete: 409 (nothing stored)') # Last PUT wins before completion; the declared checksum must describe it. # The replacement is the same length because Content-Length is signed. overwrite = presign(client, alice, chat, content) corrupt = bytearray(content) corrupt[0] ^= 0xFF check(put(overwrite['upload_url'], bytes(corrupt)) == 200, 'first PUT failed') check(put(overwrite['upload_url'], content) == 200, 'second PUT failed') overwritten = complete(client, alice, overwrite['attachment_id'], digest)['json'] check(overwritten['sha256'] == digest, 'last PUT was not the completed object') print('same-size overwrite: last PUT wins, checksum verified') # A user outside the chat cannot obtain a presigned URL. other = client.call( 'POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Приватный чат', 'member_ids': [alice['id'], eve['id']]}, schema='Chat', )['json'] client.call( 'POST', '/api/v1/chats/' + other['id'] + '/attachments/presign', 404, actor=bob, body={ 'filename': 'x.png', 'content_type': 'image/png', 'size_bytes': len(content), 'sha256': digest, }, ) wait = float(os.environ.get('PRESIGN_EXPIRY_WAIT', '0')) if wait > 0: expired = presign(client, alice, chat, content) time.sleep(wait) status = put(expired['upload_url'], content) check(status == 403, 'expired presigned URL must be 403, got ' + str(status)) print('EXPIRED: presigned URL rejected after', wait, 'seconds') print('PASS: lab4 presigned upload flow') if __name__ == '__main__': run(main)