#!/usr/bin/env python3 """Lab5 track 1: presigned direct upload plus the mandatory proxy fallback.""" from __future__ import annotations import argparse import hashlib import io import uuid from PIL import Image from common import HttpClient, assert_status, error_code def png_bytes(width: int = 640, height: int = 400) -> bytes: buffer = io.BytesIO() Image.new("RGB", (width, height), (20, 160, 90)).save(buffer, format="PNG") return buffer.getvalue() def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--base-url", default="http://localhost:8080") args = parser.parse_args() client = HttpClient(args.base_url) alice, alice_reg = client.register() bob, bob_reg = client.register() alice_token = client.login(alice_reg)["token"] bob_token = client.login(bob_reg)["token"] status, _h, chat, _r = client.call( "POST", "/api/v1/chats", body={"title": "Presigned upload", "member_ids": [alice["id"], bob["id"]]}, token=alice_token, ) assert_status(status, 201, "create chat") content = png_bytes() digest = hashlib.sha256(content).hexdigest() body = { "filename": "direct.png", "content_type": "image/png", "size_bytes": len(content), "sha256": digest, } status, _h, presign, _r = client.call( "POST", "/api/v1/chats/" + chat["id"] + "/attachments/presign", body=body, token=alice_token, ) assert_status(status, 201, "presign") if presign["method"] != "PUT" or not presign["upload_url"].startswith("http"): raise AssertionError("presign response is missing a usable PUT URL") # The mandatory proxy endpoint still works. status, _h, proxy, _r = client.raw( "POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=proxy.png", data=content, headers={"Authorization": "Bearer " + alice_token, "Content-Type": "image/png"}, ) assert_status(status, 201, "proxy upload remains available") # Direct PUT to the private bucket through the short-lived signature. status, _h, _p, _r = client.raw( "PUT", presign["upload_url"], data=content, headers=presign["headers"], ) assert_status(status, 200, "presigned PUT") status, _h, ready, _r = client.call( "POST", "/api/v1/attachments/" + presign["attachment_id"] + "/complete", body={"sha256": digest, "size_bytes": len(content)}, token=alice_token, ) assert_status(status, 200, "complete") if ready["status"] != "ready" or ready["sha256"] != digest: raise AssertionError("completed attachment is not ready with the expected checksum") # A chat member can read the bytes through the API; no redirect is used. status, headers, _p, raw = client.raw( "GET", "/api/v1/attachments/" + presign["attachment_id"] + "/content", headers={"Authorization": "Bearer " + bob_token}, ) assert_status(status, 200, "download direct upload") if raw != content or headers.get_content_type() != "image/png": raise AssertionError("direct-upload download differs from the original") # Complete is idempotent for the same parameters. status, _h, again, _r = client.call( "POST", "/api/v1/attachments/" + presign["attachment_id"] + "/complete", body={"sha256": digest, "size_bytes": len(content)}, token=alice_token, ) assert_status(status, 200, "idempotent complete") if again["id"] != ready["id"]: raise AssertionError("idempotent complete returned another attachment") # Negative: a ready attachment cannot be completed with different values. for payload, label in ( ({"sha256": "0" * 64, "size_bytes": len(content)}, "ready checksum mismatch"), ({"sha256": digest, "size_bytes": len(content) + 1}, "ready size mismatch"), ): status, _h, error, _r = client.call( "POST", "/api/v1/attachments/" + presign["attachment_id"] + "/complete", body=payload, token=alice_token, ) assert_status(status, 409, label) if error_code(error) == "internal_error": raise AssertionError(label + " leaked a 500") # Negative: wrong bytes that are never promoted (checksum/size mismatch). for wrong, label in ( (png_bytes(641, 400), "checksum mismatch"), (content + b"x", "size mismatch"), ): status, _h, bad_upload, _r = client.call( "POST", "/api/v1/chats/" + chat["id"] + "/attachments/presign", body=body, token=alice_token, ) assert_status(status, 201, label + " presign") status, _h, _p, _r = client.raw( "PUT", bad_upload["upload_url"], data=wrong, headers=bad_upload["headers"], ) assert_status(status, 200, label + " PUT") status, _h, error, _r = client.call( "POST", "/api/v1/attachments/" + bad_upload["attachment_id"] + "/complete", body={"sha256": digest, "size_bytes": len(content)}, token=alice_token, ) assert_status(status, 400, label) if error_code(error) == "internal_error": raise AssertionError(label + " leaked a 500") # Negative: another user cannot complete Alice's pending upload. status, _h, pending, _r = client.call( "POST", "/api/v1/chats/" + chat["id"] + "/attachments/presign", body=body, token=alice_token, ) assert_status(status, 201, "second presign") status, _h, error, _r = client.call( "POST", "/api/v1/attachments/" + pending["attachment_id"] + "/complete", body={"sha256": digest, "size_bytes": len(content)}, token=bob_token, ) assert_status(status, 404, "foreign complete") if error_code(error) == "internal_error": raise AssertionError("foreign complete leaked a 500") # Negative: completing before PUT is a typed 409. status, _h, error, _r = client.call( "POST", "/api/v1/attachments/" + pending["attachment_id"] + "/complete", body={"sha256": digest, "size_bytes": len(content)}, token=alice_token, ) assert_status(status, 409, "incomplete direct upload") if error_code(error) == "internal_error": raise AssertionError("incomplete upload leaked a 500") # Negative: bad presign input. for bad, expected in ( ({**body, "content_type": "image/gif"}, 415), ({**body, "size_bytes": 10_485_761}, 400), ({**body, "sha256": "ABC"}, 400), ({**body, "filename": "../x.png"}, 400), ): status, _h, error, _r = client.call( "POST", "/api/v1/chats/" + chat["id"] + "/attachments/presign", body=bad, token=alice_token, ) assert_status(status, expected, "bad presign input") if error_code(error) == "internal_error": raise AssertionError("bad presign input leaked a 500") print( "PASS: presigned upload, complete, checksum verification, proxy fallback, " "idempotency and negative cases" ) if __name__ == "__main__": main()