Files
mtusi2026lab5/student-tests/variants_check.py
T
zemiles eac741349a Аудит F02, F04–F07: проверка JPEG в подпроцессе, фильтры PNG, tRNS, метаданные
- F04: Pillow 13.0.0, urllib3 2.8.0, minio 7.2.20
- F02: пробное декодирование JPEG вынесено в src/jpeg_probe.py (RLIMIT_AS,
  RLIMIT_CPU, oom_score_adj); замер progressive 4:4:4 ~40 Мпикс — 252 MiB;
  DECODE_CONCURRENCY=1, память API 512 MiB; до исправления 6 одновременных
  загрузок убивали обе реплики (evidence/before-fix/progressive-oom.txt)
- F05: проверка байта фильтра каждой строки PNG (включая Adam7), PLTE, IEND
- F06: прозрачность tRNS у RGB и L
- F07: info очищается перед сохранением вариантов; тест проверяет сырые
  маркеры JPEG и чанки WebP
2026-11-13 20:40:07 +03:00

188 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Проверка вариантов по контракту (запускается В КОНТЕЙНЕРЕ checks, где есть Pillow):
docker compose --profile tools run --rm checks /app/student-tests/variants_check.py \
--base-url http://lb:8080 --output /app/evidence/variants-check.json
Для каждого входа: ready, ровно 3 варианта, метаданные = фактическим байтам (размер, SHA-256,
декодированные размеры, формат), оригинал неизменен. Thumbnail: JPEG, вписан в 256x256 без
увеличения, округление вниз; EXIF orientation применена; alpha -> белый. Crop: JPEG 128x128.
Optimized: WebP, вписан в 1280x1280 без увеличения. В вариантах нет метаданных — проверяются
СЫРЫЕ байты (аудит F07): в JPEG нет маркеров COM, APP1 (Exif/XMP), APP2 (ICC); в WebP нет
чанков EXIF, XMP, ICCP. Прозрачность tRNS у RGB и L (аудит F06) тоже даёт белый фон в JPEG
и alpha=0 в WebP.
"""
import argparse
import hashlib
import io
import json
import sys
import time
from pathlib import Path
sys.path.insert(0, "/app/tests")
from client import Client, check # noqa: E402
from PIL import Image # noqa: E402
FIXTURE = Path("/app/tests/fixtures/sample.png").read_bytes()
def fit(w, h, box):
if w <= box and h <= box:
return w, h
return (box, max(1, h * box // w)) if w >= h else (max(1, w * box // h), box)
def encode(img, fmt, **kw):
buf = io.BytesIO()
img.save(buf, fmt, **kw)
return buf.getvalue()
def jpeg_markers(b):
"""Маркеры сегментов JPEG до начала скана (SOS)."""
out, i = [], 2
while i + 4 <= len(b) and b[i] == 0xFF:
m = b[i + 1]
if m == 0xDA:
break
out.append(m)
i += 2 + int.from_bytes(b[i + 2:i + 4], "big")
return out
def webp_chunks(b):
out, i = [], 12
while i + 8 <= len(b):
name, size = b[i:i + 4], int.from_bytes(b[i + 4:i + 8], "little")
out.append(name.decode("latin-1"))
i += 8 + size + (size & 1)
return out
def no_metadata(b, fmt):
if fmt == "JPEG":
bad = {0xFE: "COM", 0xE1: "APP1", 0xE2: "APP2"}
found = [bad[m] for m in jpeg_markers(b) if m in bad]
else:
found = [c for c in webp_chunks(b) if c.strip() in ("EXIF", "XMP", "ICCP")]
return found
def cases():
out = [("fixture 320x200 PNG", FIXTURE, "image/png", (320, 200), None)]
# RGBA: левая половина прозрачная -> в JPEG должна стать белой.
rgba = Image.new("RGBA", (300, 300), (200, 20, 20, 255))
rgba.paste((0, 0, 0, 0), (0, 0, 150, 300))
out.append(("RGBA 300x300 half transparent", encode(rgba, "PNG"), "image/png", (300, 300), "alpha"))
# EXIF orientation 6 (поворот 90° по часовой): хранится 400x200, показывается 200x400.
# Верхняя половина ХРАНИМОГО кадра красная -> после поворота красной становится правая половина.
raw = Image.new("RGB", (400, 200), (0, 0, 255))
raw.paste((255, 0, 0), (0, 0, 400, 100))
exif = Image.Exif()
exif[0x0112] = 6
exif[0x010F] = "MTUSI test camera" # Make: проверяем, что EXIF не утёк в варианты
out.append(("JPEG 400x200 EXIF orientation=6", encode(raw, "JPEG", quality=95, exif=exif.tobytes()),
"image/jpeg", (200, 400), "orientation"))
# Все виды метаданных сразу: комментарий, EXIF, XMP, ICC (аудит F07).
from PIL import ImageCms
icc = ImageCms.ImageCmsProfile(ImageCms.createProfile("sRGB")).tobytes()
meta = Image.new("RGB", (500, 300), (30, 90, 160))
meta_exif = Image.Exif()
meta_exif[0x010F] = "PRIVATE-CAMERA" # Make, без orientation
out.append(("JPEG with COM+EXIF+XMP+ICC", encode(meta, "JPEG", quality=90, comment=b"PRIVATE-COMMENT",
exif=meta_exif.tobytes(), icc_profile=icc,
xmp=b"<x:xmpmeta xmlns:x='adobe:ns:meta/'>PRIVATE-XMP</x:xmpmeta>"),
"image/jpeg", (500, 300), "metadata"))
# tRNS у RGB и L (аудит F06): весь кадр — «прозрачный цвет».
out.append(("RGB PNG with tRNS (fully transparent)", encode(Image.new("RGB", (300, 200), (255, 0, 0)), "PNG",
transparency=(255, 0, 0)), "image/png", (300, 200), "alpha_full"))
out.append(("L PNG with tRNS (fully transparent)", encode(Image.new("L", (200, 300), 0), "PNG", transparency=0),
"image/png", (200, 300), "alpha_full"))
out.append(("tiny PNG 10x5 (no upscale)", encode(Image.new("RGB", (10, 5), (9, 200, 9)), "PNG"),
"image/png", (10, 5), None))
big = Image.radial_gradient("L").resize((3000, 2000)).convert("RGB")
out.append(("JPEG 3000x2000", encode(big, "JPEG", quality=90), "image/jpeg", (3000, 2000), None))
tall = Image.new("RGB", (100, 1000), (50, 60, 70))
out.append(("tall PNG 100x1000", encode(tall, "PNG"), "image/png", (100, 1000), None))
pal = Image.new("P", (64, 64), 1)
pal.putpalette([255, 255, 255, 10, 200, 10] + [0] * 762)
out.append(("palette PNG with transparency", encode(pal, "PNG", transparency=1), "image/png", (64, 64), "alpha"))
return out
def main():
p = argparse.ArgumentParser()
p.add_argument("--base-url", default="http://lb:8080")
p.add_argument("--output")
args = p.parse_args()
c = Client(args.base_url, timeout=30)
alice, bob, _eve, chat = c.bootstrap()
results = []
pending = []
for name, data, ctype, (ow, oh), special in cases():
att = c.call("POST", "/api/v1/chats/%s/attachments?filename=v.%s" % (chat["id"], ctype.split("/")[1]), 202,
actor=alice, raw=data, headers={"Content-Type": ctype}, schema="Attachment")["json"]
pending.append((name, data, ctype, ow, oh, special, att["id"]))
for name, data, ctype, ow, oh, special, att_id in pending:
deadline = time.monotonic() + 60
while True:
att = c.call("GET", "/api/v1/attachments/" + att_id, actor=bob, schema="Attachment")["json"]
if att["status"] in ("ready", "failed") or time.monotonic() > deadline:
break
time.sleep(0.3)
check(att["status"] == "ready", "%s: status %s" % (name, att["status"]))
r = {"case": name, "source_oriented": [ow, oh], "variants": {}}
orig = c.call("GET", "/api/v1/attachments/%s/content" % att_id, actor=bob)
check(orig["bytes"] == data and orig["headers"].get_content_type() == ctype, name + ": original changed")
check(sorted(v["name"] for v in att["variants"]) == ["crop", "optimized", "thumbnail"], name + ": variants")
expect = {"thumbnail": ("image/jpeg", "JPEG", fit(ow, oh, 256)),
"crop": ("image/jpeg", "JPEG", (128, 128)),
"optimized": ("image/webp", "WEBP", fit(ow, oh, 1280))}
for v in att["variants"]:
ct, fmt, size = expect[v["name"]]
body = c.call("GET", "/api/v1/attachments/%s/content?variant=%s" % (att_id, v["name"]), actor=bob)
b = body["bytes"]
img = Image.open(io.BytesIO(b))
img.load()
check(v["content_type"] == ct and body["headers"].get_content_type() == ct, name + ": content type")
check(img.format == fmt, name + ": real format " + str(img.format))
check((v["width"], v["height"]) == size == img.size, "%s %s: size %s meta %s expected %s" % (
name, v["name"], img.size, (v["width"], v["height"]), size))
check(v["size_bytes"] == len(b) and v["sha256"] == hashlib.sha256(b).hexdigest(), name + ": checksum")
leaked = no_metadata(b, fmt)
check(not leaked and not img.getexif() and "icc_profile" not in img.info,
"%s: metadata leaked into %s: %s" % (name, v["name"], leaked))
check(b"PRIVATE" not in b, name + ": private text found in bytes of " + v["name"])
item = {"size": list(img.size), "format": fmt, "bytes": len(b), "metadata_markers": leaked}
if special == "alpha_full":
if v["name"] == "optimized":
a = img.convert("RGBA").getpixel((img.size[0] // 2, img.size[1] // 2))[3]
check(a == 0, name + ": WebP alpha must be 0, got %d" % a)
item["webp_alpha"] = a
else:
px = img.convert("RGB").getpixel((img.size[0] // 2, img.size[1] // 2))
check(min(px) >= 245, name + ": transparent area is not white: %s" % (px,))
item["center_rgb"] = list(px)
if special == "alpha" and v["name"] in ("thumbnail", "crop"):
px = img.convert("RGB").getpixel((1, img.size[1] // 2))
check(min(px) >= 245, name + ": transparent area is not white: %s" % (px,))
item["transparent_pixel_rgb"] = list(px)
if special == "orientation" and v["name"] == "thumbnail":
w, h = img.size
left, right = img.getpixel((w // 4, h // 2)), img.getpixel((3 * w // 4, h // 2))
check(right[0] > 200 and right[2] < 60 and left[2] > 200, name + ": orientation not applied")
item["left_rgb"], item["right_rgb"] = list(left), list(right)
r["variants"][v["name"]] = item
results.append(r)
print("PASS %-36s %s" % (name, {k: tuple(x["size"]) for k, x in r["variants"].items()}), flush=True)
c.call("GET", "/api/v1/attachments/%s/content?variant=bogus" % pending[0][6], 400, actor=bob)
if args.output:
Path(args.output).write_text(json.dumps({"cases": results, "unknown_variant_status": 400},
ensure_ascii=False, indent=1) + "\n")
print("PASS: %d inputs, all variants match contract" % len(results))
if __name__ == "__main__":
main()