forked from mtusi2026/mtusi2026lab5
Аудит 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
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Аудит F02: допустимые по контракту progressive JPEG ~40 Мпикс не должны ронять API.
|
||||
|
||||
docker compose --profile tools run --rm checks /app/student-tests/progressive_upload.py \
|
||||
--base-url http://lb:8080 --output /app/evidence/progressive-upload.json
|
||||
|
||||
Файлы маленькие (~0,5–0,9 MB, гладкая картинка), но декодирование progressive JPEG требует
|
||||
буфер коэффициентов всего кадра: 4:2:0 ~140 MiB, 4:4:4 ~250 MiB (замер на Pillow 13).
|
||||
Одновременно загружаются 4 progressive 4:4:4 + 1 progressive 4:2:0 + 1 baseline: при двух
|
||||
репликах за round-robin LB на каждую приходится по 2 тяжёлых декодирования одновременно. Ожидаем:
|
||||
все 202, все ready, thumbnail 256x256. Что реплики API не были убиты (RestartCount, OOMKilled),
|
||||
проверяет хост-обёртка api_negative_lab5.py.
|
||||
"""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
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
|
||||
|
||||
SIDE = 6324 # 39 992 976 пикселей (< 40 000 000)
|
||||
|
||||
|
||||
def make(kind, seed):
|
||||
g = Image.radial_gradient("L").resize((SIDE, SIDE))
|
||||
img = Image.merge("RGB", (g, g.rotate(90 * seed), g.transpose(Image.Transpose.FLIP_TOP_BOTTOM)))
|
||||
kw = {"baseline": {}, "progressive_420": {"progressive": True},
|
||||
"progressive_444": {"progressive": True, "subsampling": 0}}[kind]
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, "JPEG", quality=85, **kw)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
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=60)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
files = [("progressive_444", make("progressive_444", i)) for i in range(4)] + \
|
||||
[("progressive_420", make("progressive_420", 1)), ("baseline", make("baseline", 0))]
|
||||
|
||||
def up(item):
|
||||
kind, data = item
|
||||
t = time.monotonic()
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=%s.jpg" % (chat["id"], kind), [202, 413, 502, 503, 504],
|
||||
actor=alice, raw=data, headers={"Content-Type": "image/jpeg"}, schema="Attachment")
|
||||
return {"kind": kind, "bytes": len(data), "status": r["status"], "seconds": round(time.monotonic() - t, 2),
|
||||
"instance": r["headers"].get("X-Instance-Id"),
|
||||
"id": r["json"]["id"] if r["status"] == 202 else None,
|
||||
"error": r["json"]["error"]["code"] if r["status"] != 202 else None}
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(len(files)) as pool:
|
||||
results = list(pool.map(up, files))
|
||||
for r in results:
|
||||
print(json.dumps(r), flush=True)
|
||||
for r in results:
|
||||
check(r["status"] == 202, "%s upload: %s %s" % (r["kind"], r["status"], r["error"]))
|
||||
for r in results:
|
||||
att = c.wait_ready(bob, {"id": r["id"]}, wait_seconds=120)
|
||||
thumb = [v for v in att["variants"] if v["name"] == "thumbnail"][0]
|
||||
check((thumb["width"], thumb["height"]) == (256, 256), "thumbnail size")
|
||||
r["ready"] = True
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps({"side": SIDE, "pixels": SIDE * SIDE, "uploads": results},
|
||||
indent=1) + "\n")
|
||||
print("PASS: %d concurrent ~40 Mpx JPEG (progressive 4:4:4/4:2:0, baseline) -> 202 -> ready" % len(results))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -63,8 +63,14 @@ def main():
|
||||
n = Image.effect_noise((6300, 6300), 80)
|
||||
Image.merge("RGBA", [n, n.transpose(Image.Transpose.ROTATE_90), n, n]).save(buf, "PNG", compress_level=1)
|
||||
heavy = buf.getvalue()
|
||||
# Аудит F02: progressive 4:4:4 ~40 Мпикс — допустимый вход, ~250 MiB на декодирование.
|
||||
g = Image.radial_gradient("L").resize((6324, 6324))
|
||||
buf = io.BytesIO()
|
||||
Image.merge("RGB", (g, g.rotate(90), g)).save(buf, "JPEG", quality=85, progressive=True, subsampling=0)
|
||||
prog = buf.getvalue()
|
||||
cases = [
|
||||
("valid 640x480", ok, "image/png", {}, 40000000, "ok"),
|
||||
("40 Mpx progressive 4:4:4 JPEG, default limits", prog, "image/jpeg", {}, 40000000, "ok"),
|
||||
("49 Mpx PNG (> MAX_IMAGE_PIXELS)", png((7000, 7000)), "image/png", {}, 40000000, "image_too_large"),
|
||||
("36 Mpx PNG, normal limits", big, "image/png", {}, 40000000, "ok"),
|
||||
("36 Mpx PNG, memory limit 160 MiB", big, "image/png", {"TRANSFORM_MEMORY_LIMIT_MB": "160"}, 40000000,
|
||||
|
||||
@@ -7,7 +7,10 @@
|
||||
Для каждого входа: ready, ровно 3 варианта, метаданные = фактическим байтам (размер, SHA-256,
|
||||
декодированные размеры, формат), оригинал неизменен. Thumbnail: JPEG, вписан в 256x256 без
|
||||
увеличения, округление вниз; EXIF orientation применена; alpha -> белый. Crop: JPEG 128x128.
|
||||
Optimized: WebP, вписан в 1280x1280 без увеличения. В вариантах нет EXIF/ICC.
|
||||
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
|
||||
@@ -36,6 +39,36 @@ def encode(img, 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 должна стать белой.
|
||||
@@ -51,6 +84,21 @@ def cases():
|
||||
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")
|
||||
@@ -102,9 +150,20 @@ def main():
|
||||
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")
|
||||
no_meta = not img.getexif() and "icc_profile" not in img.info and "exif" not in img.info
|
||||
check(no_meta, name + ": metadata leaked into " + v["name"])
|
||||
item = {"size": list(img.size), "format": fmt, "bytes": len(b), "no_exif_icc": no_meta}
|
||||
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,))
|
||||
|
||||
Reference in New Issue
Block a user