"""Black-box grade-4 checks for variants, source preservation, and upload limits.""" from __future__ import annotations from hashlib import sha256 from io import BytesIO import json from pathlib import Path import struct import sys import zlib from PIL import Image ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Failure, arguments, run, Client # noqa: E402 MAX_UPLOAD_BYTES = 10 * 1024 * 1024 def _synthetic_jpeg_with_exif() -> bytes: image = Image.new("RGB", (640, 480), (32, 128, 210)) exif = Image.Exif() exif[0x010E] = "synthetic test metadata" output = BytesIO() image.save(output, format="JPEG", quality=90, exif=exif) image.close() return output.getvalue() def _oversized_png_header() -> bytes: source = bytearray((ROOT / "tests/fixtures/sample.png").read_bytes()) # Change only the valid IHDR width/height and CRC. The API must reject the # dimensions before it tries to decode or verify the intentionally tiny body. source[16:24] = struct.pack(">II", 7000, 7000) crc = zlib.crc32(b"IHDR" + source[16:29]) & 0xFFFFFFFF source[29:33] = struct.pack(">I", crc) return bytes(source[:33]) def main() -> None: args = arguments(__doc__, lambda parser: parser.add_argument("--output", default="evidence/grade4-pipeline.json")) client = Client(args.base_url, args.ca_file) alice, _bob, _eve, chat = client.bootstrap() source = _synthetic_jpeg_with_exif() with Image.open(BytesIO(source)) as original_image: if not original_image.getexif(): raise Failure("synthetic JPEG did not contain EXIF metadata") upload = client.call( "POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=synthetic.jpg", 202, actor=alice, raw=source, headers={"Content-Type": "image/jpeg"}, schema="Attachment", )["json"] if upload["status"] != "queued" or upload["sha256"] != sha256(source).hexdigest(): raise Failure("upload was not durably accepted as queued with the source checksum") client.message(alice, chat, "Grade 4 pipeline fixture", attachments=[upload["id"]]) ready = client.wait_ready(alice, upload) by_name = {item["name"]: item for item in ready["variants"]} expected = {"thumbnail", "crop", "optimized"} if set(by_name) != expected or len(ready["variants"]) != len(expected): raise Failure("ready attachment does not contain exactly the three required variants") expected_dimensions = {"thumbnail": (256, 192), "crop": (128, 128), "optimized": (640, 480)} expected_types = {"thumbnail": "image/jpeg", "crop": "image/jpeg", "optimized": "image/webp"} outputs = {} original = client.call( "GET", "/api/v1/attachments/" + upload["id"] + "/content?variant=original", actor=alice, ) if original["bytes"] != source or sha256(original["bytes"]).hexdigest() != upload["sha256"]: raise Failure("the original was changed by image processing") for name in sorted(expected): metadata = by_name[name] response = client.call( "GET", "/api/v1/attachments/" + upload["id"] + "/content?variant=" + name, actor=alice, ) if response["headers"].get_content_type() != expected_types[name]: raise Failure(name + " has the wrong content type") if len(response["bytes"]) != metadata["size_bytes"] or sha256(response["bytes"]).hexdigest() != metadata["sha256"]: raise Failure(name + " size/checksum does not match metadata") with Image.open(BytesIO(response["bytes"])) as image: dimensions = image.size if image.getexif(): raise Failure(name + " retained EXIF metadata") if dimensions != expected_dimensions[name] or (dimensions[0] > 1280 or dimensions[1] > 1280): raise Failure(name + " has unexpected dimensions") if (metadata["width"], metadata["height"]) != dimensions: raise Failure(name + " dimensions do not match metadata") outputs[name] = { "content_type": expected_types[name], "dimensions": list(dimensions), "size_bytes": len(response["bytes"]), "sha256": metadata["sha256"], "exif_removed": True, } corrupt = client.call( "POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=corrupt.png", 415, actor=alice, raw=b"not an image", headers={"Content-Type": "image/png"}, ) wrong_mime = client.call( "POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=spoofed.jpg", 415, actor=alice, raw=(ROOT / "tests/fixtures/sample.png").read_bytes(), headers={"Content-Type": "image/jpeg"}, ) too_many_pixels = client.call( "POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=too-large.png", 413, actor=alice, raw=_oversized_png_header(), headers={"Content-Type": "image/png"}, ) too_many_bytes = client.call( "POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=too-many-bytes.png", 413, actor=alice, raw=b"x" * (MAX_UPLOAD_BYTES + 1), headers={"Content-Type": "image/png"}, ) result = { "result": "PASS", "accepted_status": upload["status"], "final_status": ready["status"], "source_bytes": len(source), "source_sha256": upload["sha256"], "original_unchanged": True, "variants": outputs, "rejected_inputs": { "corrupt_image": corrupt["status"], "mime_mismatch": wrong_mime["status"], "pixel_limit": too_many_pixels["status"], "byte_limit": too_many_bytes["status"], }, } output_path = ROOT / args.output output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") print(json.dumps(result, separators=(",", ":"))) if __name__ == "__main__": run(main)