fix: bound full image validation and cover progressive JPEG and APNG

This commit is contained in:
2026-11-06 19:08:18 +03:00
parent 8de05d3899
commit de36c967cc
8 changed files with 617 additions and 62 deletions
+199
View File
@@ -0,0 +1,199 @@
"""Full-range JPEG and bounded multi-frame PNG regressions."""
import os
import struct
import zlib
from io import BytesIO
import pytest
from client import Client
from PIL import Image
@pytest.fixture(scope="module")
def scenario():
c = Client(os.getenv("BASE_URL", "http://127.0.0.1:8084"))
return c, *c.bootstrap()
def upload(scenario, data, mime, expected):
c, alice, _, _, chat = scenario
return c.call(
"POST",
f"/api/v1/chats/{chat['id']}/attachments?filename=edge.png",
expected,
actor=alice,
raw=data,
headers={"Content-Type": mime},
schema="Attachment" if expected == 201 else None,
)
def progressive_jpeg():
output = BytesIO()
image = Image.new("RGB", (6000, 6000), "blue")
try:
image.save(output, "JPEG", quality=90, progressive=True, subsampling=0)
finally:
image.close()
return output.getvalue()
def apng(size=(16, 16), default_image=False):
output = BytesIO()
first, second = Image.new("RGB", size, "red"), Image.new("RGB", size, "blue")
try:
first.save(
output,
"PNG",
save_all=True,
append_images=[second],
duration=100,
loop=0,
default_image=default_image,
)
finally:
first.close()
second.close()
return output.getvalue()
def broken_later_frame(data):
result, position = bytearray(data[:8]), 8
while position < len(data):
length = struct.unpack(">I", data[position : position + 4])[0]
kind = data[position + 4 : position + 8]
payload = data[position + 8 : position + 8 + length]
if kind == b"fdAT":
payload = payload[:4] + b"not-a-valid-deflate-stream"
result += (
struct.pack(">I", len(payload))
+ kind
+ payload
+ struct.pack(">I", zlib.crc32(kind + payload))
)
position += length + 12
return bytes(result)
def test_36m_progressive_jpeg_is_valid_and_unchanged(scenario):
data = progressive_jpeg()
attachment = upload(scenario, data, "image/jpeg", 201)["json"]
c, _, bob, _, _ = scenario
assert (
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)["bytes"] == data
)
def test_apng_corrupt_later_frame_is_rejected(scenario):
upload(scenario, broken_later_frame(apng()), "image/png", 415)
def test_valid_small_apng_is_accepted_and_unchanged(scenario):
data = apng()
attachment = upload(scenario, data, "image/png", 201)["json"]
c, _, bob, _, _ = scenario
assert (
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)["bytes"] == data
)
def test_apng_cumulative_canvas_limit(scenario):
# Two 25M-pixel canvases exceed the total 40M decode budget.
upload(scenario, apng((5000, 5000)), "image/png", 413)
def test_apng_forged_frame_count_cannot_hide_bad_frame(scenario):
data = bytearray(broken_later_frame(apng()))
position = 8
while position < len(data):
length = struct.unpack(">I", data[position : position + 4])[0]
kind = bytes(data[position + 4 : position + 8])
if kind == b"acTL":
data[position + 8 : position + 12] = struct.pack(">I", 1)
payload = bytes(data[position + 8 : position + 8 + length])
data[position + 8 + length : position + 12 + length] = struct.pack(
">I", zlib.crc32(kind + payload)
)
break
position += length + 12
upload(scenario, bytes(data), "image/png", 415)
def test_apng_exact_cumulative_limit_is_accepted(scenario):
upload(scenario, apng((4000, 5000)), "image/png", 201)
def test_40m_cmyk_progressive_jpeg_is_accepted(scenario):
output = BytesIO()
image = Image.new("CMYK", (8000, 5000), (0, 128, 128, 0))
try:
image.save(output, "JPEG", quality=90, progressive=True, subsampling=0)
finally:
image.close()
data = output.getvalue()
attachment = upload(scenario, data, "image/jpeg", 201)["json"]
c, _, bob, _, _ = scenario
assert (
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)["bytes"] == data
)
def test_repeated_large_image_sequence_stays_available(scenario):
# Formerly retained APNG canvases could overlap the next CMYK decoder.
c, _, bob, _, _ = scenario
data = apng((4000, 5000))
attachment = upload(scenario, data, "image/png", 201)["json"]
assert (
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)["bytes"] == data
)
del data
test_40m_cmyk_progressive_jpeg_is_accepted(scenario)
test_36m_progressive_jpeg_is_valid_and_unchanged(scenario)
data = BytesIO()
image = Image.new("RGB", (16, 16), "green")
image.save(data, "PNG")
image.close()
attachment = upload(scenario, data.getvalue(), "image/png", 201)["json"]
assert (
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)["bytes"]
== data.getvalue()
)
@pytest.mark.parametrize("progressive", [False, True])
def test_small_cmyk_jpeg(progressive, scenario):
output = BytesIO()
image = Image.new("CMYK", (24, 18), (0, 128, 128, 0))
image.save(output, "JPEG", progressive=progressive)
image.close()
upload(scenario, output.getvalue(), "image/jpeg", 201)
def test_invalid_zero_frame_count_is_rejected(scenario):
data = apng()
result, position, controls = bytearray(data[:8]), 8, 0
while position < len(data):
length = struct.unpack(">I", data[position : position + 4])[0]
kind = data[position + 4 : position + 8]
payload = data[position + 8 : position + 8 + length]
position += length + 12
if kind == b"fcTL":
controls += 1
if controls > 1:
continue
if kind == b"fdAT":
continue
if kind == b"acTL":
payload = bytes(4) + payload[4:]
result += (
struct.pack(">I", len(payload))
+ kind
+ payload
+ struct.pack(">I", zlib.crc32(kind + payload))
)
upload(scenario, bytes(result), "image/png", 415)
def test_valid_apng_default_image(scenario):
upload(scenario, apng(default_image=True), "image/png", 201)
+140
View File
@@ -0,0 +1,140 @@
import base64
import codecs
import json
import os
import uuid
import pytest
from client import Client
ENCODINGS = [
"utf-16",
"utf-16-le",
"utf-16-be",
"utf-16-be-bom",
"utf-32",
"utf-32-le",
"utf-32-be",
"utf-32-be-bom",
]
def encoded(body, encoding):
text = json.dumps(body, ensure_ascii=False)
if encoding == "utf-16-be-bom":
return codecs.BOM_UTF16_BE + text.encode("utf-16-be")
if encoding == "utf-32-be-bom":
return codecs.BOM_UTF32_BE + text.encode("utf-32-be")
return text.encode(encoding)
@pytest.fixture(scope="module")
def encoding_scenario():
c = Client(os.environ["BASE_URL"])
return c, *c.bootstrap()
@pytest.mark.parametrize("encoding", ENCODINGS)
def test_non_utf8_registration_has_no_write(encoding_scenario, encoding):
c, *_ = encoding_scenario
body = {
"username": "enc_" + uuid.uuid4().hex[:14],
"display_name": "Никита\u0000имя",
"password": "Пароль:тестовый-12345",
}
c.call(
"POST",
"/api/v1/users",
400,
raw=encoded(body, encoding),
headers={"Content-Type": "application/json"},
)
# UNIQUE username proves the rejected request did not insert a user.
created = c.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
assert created["display_name"] == body["display_name"]
@pytest.mark.parametrize("encoding", ENCODINGS)
def test_non_utf8_chat_has_no_write(encoding_scenario, encoding):
c, alice, *_ = encoding_scenario
before = c.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]
body = {"title": "Чат\u0000" + uuid.uuid4().hex, "member_ids": [alice["id"]]}
c.call(
"POST",
"/api/v1/chats",
400,
actor=alice,
raw=encoded(body, encoding),
headers={"Content-Type": "application/json"},
)
after = c.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]
assert before == after
assert (
c.call("POST", "/api/v1/chats", 201, actor=alice, body=body, schema="Chat")["json"]["title"]
== body["title"]
)
@pytest.mark.parametrize("encoding", ENCODINGS)
def test_non_utf8_message_has_no_write(encoding_scenario, encoding):
c, alice, _, _, chat = encoding_scenario
path = f"/api/v1/chats/{chat['id']}/messages"
key = uuid.uuid4().hex
body = {"text": "Сообщение\u0000" + key}
c.call(
"POST",
path,
400,
actor=alice,
raw=encoded(body, encoding),
headers={"Content-Type": "application/json", "Idempotency-Key": key},
)
history = c.call("GET", path + "?limit=100", actor=alice, schema="MessagePage")["json"]["items"]
assert all(item["text"] != body["text"] for item in history)
good = c.call(
"POST",
path,
201,
actor=alice,
body=body,
headers={"Idempotency-Key": key},
schema="Message",
)["json"]
repeat = c.call(
"POST",
path,
201,
actor=alice,
body=body,
headers={"Idempotency-Key": key},
schema="Message",
)["json"]
assert good == repeat and good["text"] == body["text"]
@pytest.mark.parametrize("encoding", ["utf-8", "utf-8-sig"])
def test_valid_utf8_registration_and_login(encoding_scenario, encoding):
c, *_ = encoding_scenario
body = {
"username": "utf8_" + uuid.uuid4().hex[:14],
"display_name": "Юникод\u0000😀",
"password": "Пароль:тестовый-12345",
}
user = c.call(
"POST",
"/api/v1/users",
201,
raw=encoded(body, encoding),
headers={"Content-Type": "application/json"},
schema="User",
)["json"]
assert user["display_name"] == body["display_name"]
credential = base64.b64encode((body["username"] + ":" + body["password"]).encode()).decode()
session = c.call(
"POST",
"/api/v1/auth/sessions",
201,
headers={"Authorization": "Basic " + credential},
schema="Session",
)["json"]
assert session["user"] == user
+57
View File
@@ -0,0 +1,57 @@
"""Process boundary failures must stay bounded and map to contract errors."""
import signal
import subprocess
from io import BytesIO
import pytest
from messenger.attachments import validate_image
from messenger.domain import Failure
class FakeProcess:
pid = 999999999
returncode = 0
def __init__(self, output=b'{"ok":["image/png",1,1]}', crash=False, timeout=False):
self.output, self.timeout, self.calls = output, timeout, 0
self.returncode = -11 if crash else 0
def __enter__(self):
return self
def __exit__(self, *args):
pass
def communicate(self, input=None, timeout=None):
self.calls += 1
if self.timeout and self.calls == 1:
raise subprocess.TimeoutExpired("validator", 5)
return self.output, b""
def test_timeout_kills_group_and_returns_415(monkeypatch):
process = FakeProcess(timeout=True)
killed = []
monkeypatch.setattr("messenger.attachments.subprocess.Popen", lambda *a, **k: process)
monkeypatch.setattr(
"messenger.attachments.os.killpg", lambda pid, sig: killed.append((pid, sig))
)
with pytest.raises(Failure) as failure:
validate_image(BytesIO(b"synthetic"), "image/png")
assert failure.value.status == 415
assert killed == [(process.pid, signal.SIGKILL)]
assert process.calls == 2
@pytest.mark.parametrize(
"output,crash", [(b"", True), (b"not-json", False), (b"null", False), (b"[]", False)]
)
def test_crash_or_malformed_child_result_returns_415(monkeypatch, output, crash):
monkeypatch.setattr(
"messenger.attachments.subprocess.Popen", lambda *a, **k: FakeProcess(output, crash=crash)
)
with pytest.raises(Failure) as failure:
validate_image(BytesIO(b"synthetic"), "image/png")
assert failure.value.status == 415