import uuid import hashlib import json import sys import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Client, check BASE_URL = "http://localhost:8080" IMAGE = ROOT / "tests" / "fixtures" / "sample.png" def response_json(response): return json.loads(response["bytes"].decode("utf-8")) def create_upload(client, actor, chat, content, filename="sample.png"): """Create a presigned upload and return its metadata.""" response = client.call( "POST", f"/api/v1/chats/{chat['id']}/attachments/presigned", 201, actor=actor, body={ "filename": filename, "content_type": "image/png", "size_bytes": len(content), "sha256": hashlib.sha256(content).hexdigest(), }, ) return response_json(response) def create_upload_with_metadata( client, actor, chat, content, expected_size=None, expected_sha256=None, ): """Create an upload with deliberately supplied expected metadata.""" response = client.call( "POST", f"/api/v1/chats/{chat['id']}/attachments/presigned", 201, actor=actor, body={ "filename": "sample.png", "content_type": "image/png", "size_bytes": ( len(content) if expected_size is None else expected_size ), "sha256": ( hashlib.sha256(content).hexdigest() if expected_sha256 is None else expected_sha256 ), }, ) return response_json(response) def put_to_s3(upload, content): """Upload bytes directly to S3 using the presigned URL.""" request = urllib.request.Request( upload["upload_url"], data=content, headers=upload["headers"], method="PUT", ) with urllib.request.urlopen(request, timeout=30) as response: check( response.status in (200, 201, 204), "S3 upload failed", ) def complete_upload(client, actor, upload_id, expected_status=200): return client.call( "POST", f"/api/v1/attachments/uploads/{upload_id}/complete", expected_status, actor=actor, ) def main(): content = IMAGE.read_bytes() digest = hashlib.sha256(content).hexdigest() client = Client(BASE_URL) alice, bob, eve, chat = client.bootstrap() # 1. Incorrect SHA-256 must be rejected. wrong_digest = "0" * 64 check(wrong_digest != digest, "test checksum unexpectedly matches") upload = create_upload_with_metadata( client, alice, chat, content, expected_sha256=wrong_digest, ) put_to_s3(upload, content) complete_upload( client, alice, upload["upload_id"], expected_status=409, ) print("PASS: incorrect SHA-256 rejected with HTTP 409") # 2. Incorrect expected size must be rejected. upload = create_upload_with_metadata( client, alice, chat, content, expected_size=len(content) + 1, ) put_to_s3(upload, content) complete_upload( client, alice, upload["upload_id"], expected_status=409, ) print("PASS: incorrect file size rejected with HTTP 409") # 3. Corrupted image must be rejected. corrupt_content = b"This is not a valid PNG image" upload = create_upload( client, alice, chat, corrupt_content, ) put_to_s3(upload, corrupt_content) complete_upload( client, alice, upload["upload_id"], expected_status=415, ) print("PASS: corrupted image rejected with HTTP 415") # 4. Another user must not complete Alice's upload. upload = create_upload( client, alice, chat, content, ) put_to_s3(upload, content) complete_upload( client, eve, upload["upload_id"], expected_status=404, ) print("PASS: foreign user cannot complete another user's upload") # The legitimate owner must still be able to complete it. owner_response = complete_upload( client, alice, upload["upload_id"], expected_status=200, ) attachment = response_json(owner_response) check( attachment["status"] == "ready", "owner's attachment is not ready", ) check( attachment["owner_id"] == alice["id"], "attachment owner does not match", ) check( attachment["sha256"] == digest, "attachment checksum mismatch", ) print("PASS: legitimate owner can complete the upload") # 5. Proxy upload must reject files larger than 10 MiB. oversized_content = b"\x00" * (10 * 1024 * 1024 + 1) client.call( "POST", f"/api/v1/chats/{chat['id']}/attachments?filename=oversized.png", expected=413, actor=alice, raw=oversized_content, headers={"Content-Type": "image/png"}, ) print("PASS: oversized proxy upload rejected with HTTP 413") # 6. PNG content must not be accepted as JPEG. client.call( "POST", f"/api/v1/chats/{chat['id']}/attachments?filename=mismatch.jpg", expected=415, actor=alice, raw=content, headers={"Content-Type": "image/jpeg"}, ) print("PASS: MIME mismatch rejected with HTTP 415") # 7. Create a ready attachment in Alice and Bob's chat. attachment, _ = client.attachment(alice, chat) attachment_id = attachment["id"] # Eve is not a member of Alice and Bob's chat. client.call( "GET", f"/api/v1/attachments/{attachment_id}", expected=404, actor=eve, ) print("PASS: non-member cannot access attachment metadata") # 8. A non-member must not download the attachment. client.call( "GET", f"/api/v1/attachments/{attachment_id}/content", expected=404, actor=eve, ) print("PASS: non-member cannot download attachment") # 9. Create another chat where Alice and Eve are members. second_chat = client.call( "POST", "/api/v1/chats", 201, actor=alice, body={ "title": "Cross-chat attachment test", "member_ids": [alice["id"], eve["id"]], }, schema="Chat", )["json"] # Try to attach a file from the first chat to a message in the second. client.call( "POST", f"/api/v1/chats/{second_chat['id']}/messages", expected=404, actor=alice, body={ "text": "Cross-chat attachment test", "attachment_ids": [attachment_id], }, headers={"Idempotency-Key": uuid.uuid4().hex}, ) print("PASS: attachment from another chat rejected with HTTP 404") print() print("PASS: all presigned negative scenarios") if __name__ == "__main__": main()