146 lines
7.4 KiB
Python
146 lines
7.4 KiB
Python
"""Grade 4 image semantics, actual decoded bytes and upload rejection checks.
|
|
|
|
Run explicitly against the running lab5 stand:
|
|
python student-tests/lab5_images.py --base-url http://localhost:8080
|
|
Requires Pillow, also present in the application image.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import io
|
|
import json
|
|
import struct
|
|
import zlib
|
|
|
|
from PIL import Image
|
|
|
|
from lab5_helpers import Client, Failure, check, encoded, upload
|
|
|
|
|
|
def assert_variants(client, actor, att, source, expected_thumb, expected_optimized,
|
|
*, white_corner=False, green_crop=False):
|
|
ready = client.wait_ready(actor, att)
|
|
check(ready["sha256"] == hashlib.sha256(source).hexdigest(), "original SHA-256 changed")
|
|
check(ready["size_bytes"] == len(source), "original byte count changed")
|
|
check(ready["error_code"] is None, "ready has error_code")
|
|
by_name = {item["name"]: item for item in ready["variants"]}
|
|
check(len(ready["variants"]) == 3 and set(by_name) == {"thumbnail", "crop", "optimized"},
|
|
"ready must contain exactly the three promised variants")
|
|
check(not any(k in json.dumps(ready) for k in ("object_key", "staging_key", "broker_url")),
|
|
"storage internals leaked into metadata")
|
|
original = client.call("GET", f"/api/v1/attachments/{att['id']}/content", actor=actor)
|
|
check(original["bytes"] == source, "original was re-encoded or changed")
|
|
check(original["headers"].get_content_type() == ready["content_type"],
|
|
"original Content-Type changed")
|
|
for name, expected_size, expected_format, mime in (
|
|
("thumbnail", expected_thumb, "JPEG", "image/jpeg"),
|
|
("crop", (128, 128), "JPEG", "image/jpeg"),
|
|
("optimized", expected_optimized, "WEBP", "image/webp"),
|
|
):
|
|
variant = by_name[name]
|
|
response = client.call("GET", f"/api/v1/attachments/{att['id']}/content?variant={name}",
|
|
actor=actor)
|
|
data = response["bytes"]
|
|
check(response["headers"].get_content_type() == mime, f"{name}: wrong MIME")
|
|
check(variant["content_type"] == mime, f"{name}: wrong metadata MIME")
|
|
check(variant["size_bytes"] == len(data), f"{name}: wrong size_bytes")
|
|
check(variant["sha256"] == hashlib.sha256(data).hexdigest(), f"{name}: wrong SHA-256")
|
|
with Image.open(io.BytesIO(data)) as image:
|
|
image.load()
|
|
check(image.format == expected_format, f"{name}: wrong actual format")
|
|
check(image.size == expected_size, f"{name}: wrong actual dimensions {image.size}")
|
|
check((variant["width"], variant["height"]) == expected_size,
|
|
f"{name}: dimensions metadata differs from bytes")
|
|
check(not image.getexif(), f"{name}: EXIF was retained")
|
|
if white_corner and name == "thumbnail":
|
|
check(min(image.convert("RGB").getpixel((0, 0))) > 245,
|
|
"transparent JPEG background is not white")
|
|
if green_crop and name == "crop":
|
|
pixel = image.convert("RGB").getpixel((10, 64))
|
|
check(pixel[1] > 180 and pixel[0] < 40 and pixel[2] < 40,
|
|
"crop is not taken from the centered square")
|
|
return ready
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--base-url", default=None)
|
|
args = parser.parse_args()
|
|
client = Client(args.base_url, timeout=40)
|
|
alice, bob, eve, chat = client.bootstrap()
|
|
|
|
image = Image.new("RGB", (400, 200), (0, 220, 0))
|
|
image.paste((220, 0, 0), (0, 0, 100, 200))
|
|
image.paste((0, 0, 220), (300, 0, 400, 200))
|
|
source = encoded(image)
|
|
att = upload(client, alice, chat, source)
|
|
assert_variants(client, bob, att, source, (256, 128), (400, 200), green_crop=True)
|
|
for suffix in ("", "/content", "/content?variant=thumbnail", "/content?variant=crop",
|
|
"/content?variant=optimized"):
|
|
client.call("GET", f"/api/v1/attachments/{att['id']}{suffix}", 404, actor=eve)
|
|
print("PASS centered crop, three real variants, checksums, original bytes and ACL", flush=True)
|
|
|
|
for size, thumb, optimized in (
|
|
((11, 7), (11, 7), (11, 7)),
|
|
((513, 201), (256, 100), (513, 201)),
|
|
((1701, 1003), (256, 150), (1280, 754)),
|
|
):
|
|
source = encoded(Image.new("RGB", size, (30, 80, 170)))
|
|
att = upload(client, alice, chat, source)
|
|
assert_variants(client, bob, att, source, thumb, optimized)
|
|
print("PASS no upscaling and floor rounding for thumbnail/optimized", flush=True)
|
|
|
|
source = encoded(Image.new("RGBA", (320, 200), (200, 30, 30, 0)))
|
|
att = upload(client, alice, chat, source)
|
|
assert_variants(client, bob, att, source, (256, 160), (320, 200), white_corner=True)
|
|
print("PASS transparent PNG composited onto white JPEG", flush=True)
|
|
|
|
exif = Image.Exif()
|
|
exif[274] = 6
|
|
exif[270] = "student test metadata must be stripped"
|
|
source = encoded(Image.new("RGB", (320, 200), (90, 20, 170)), "JPEG", exif=exif)
|
|
att = upload(client, alice, chat, source, filename="rotated.jpg", mime="image/jpeg")
|
|
assert_variants(client, bob, att, source, (160, 256), (200, 320))
|
|
print("PASS EXIF orientation applied to variants and metadata removed", flush=True)
|
|
|
|
path = f"/api/v1/chats/{chat['id']}/attachments?filename=bad.png"
|
|
for data, mime, expected in ((b"this is not a PNG", "image/png", 415),
|
|
(source, "image/png", 415),
|
|
(b"x" * (10485760 + 1), "image/png", 413)):
|
|
client.call("POST", path, expected, actor=alice, raw=data, headers={"Content-Type": mime})
|
|
def png_chunk(kind, data):
|
|
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
|
|
bad_filter = (b"\x89PNG\r\n\x1a\n"
|
|
+ png_chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0))
|
|
+ png_chunk(b"IDAT", zlib.compress(b"\x05\x00\x00\x00"))
|
|
+ png_chunk(b"IEND", b""))
|
|
client.call("POST", path, 415, actor=alice, raw=bad_filter,
|
|
headers={"Content-Type": "image/png"})
|
|
with Image.new("RGB", (4100, 4000), "blue") as large:
|
|
progressive = encoded(large, "JPEG", progressive=True)
|
|
scan = progressive.index(b"\xff\xda")
|
|
client.call("POST", path, 415, actor=alice, raw=progressive[:scan + 4] + b"\xff\xd9",
|
|
headers={"Content-Type": "image/jpeg"})
|
|
print("PASS malformed PNG filter and truncated >16MP progressive JPEG rejected before 202", flush=True)
|
|
ihdr = struct.pack(">IIBBBBB", 10001, 4000, 8, 2, 0, 0, 0)
|
|
chunk = b"IHDR" + ihdr
|
|
oversized = b"\x89PNG\r\n\x1a\n" + struct.pack(">I", len(ihdr)) + chunk + struct.pack(">I", zlib.crc32(chunk))
|
|
client.call("POST", path, 413, actor=alice, raw=oversized,
|
|
headers={"Content-Type": "image/png"})
|
|
from urllib.parse import quote
|
|
for bad_name in ("../x.png", "a\\b.png", "a\x00.png", "a\n.png"):
|
|
client.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename={quote(bad_name, safe='')}",
|
|
400, actor=alice, raw=encoded(Image.new("RGB", (2, 2))),
|
|
headers={"Content-Type": "image/png"})
|
|
print("PASS invalid/MIME mismatch 415, >10MiB and >40M pixels 413, unsafe filenames 400", flush=True)
|
|
print("PASS: lab5 grade4 image checks")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except (Failure, ValueError, OSError) as exc:
|
|
print("FAIL:", str(exc), flush=True)
|
|
raise SystemExit(1)
|