ЛР5: закрыть review края broker, staging replay и полной валидации изображений
This commit is contained in:
@@ -0,0 +1,229 @@
|
||||
"""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:8085"))
|
||||
return c, *c.bootstrap()
|
||||
|
||||
|
||||
def upload(scenario, data, mime, expected):
|
||||
c, alice, _, _, chat = scenario
|
||||
result = c.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=edge.png",
|
||||
202 if expected == 201 else expected,
|
||||
actor=alice,
|
||||
raw=data,
|
||||
headers={"Content-Type": mime},
|
||||
schema="Attachment" if expected == 201 else None,
|
||||
)
|
||||
if expected == 201:
|
||||
result["json"] = c.wait_ready(alice, result["json"])
|
||||
return result
|
||||
|
||||
|
||||
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_zero_count_with_static_fallback_is_rejected(scenario):
|
||||
# Pillow warns and falls back to one valid static PNG frame. The raw acTL
|
||||
# count must still be rejected rather than trusting Pillow's n_frames=1.
|
||||
data = apng()
|
||||
result, position, controls = bytearray(data[:8]), 8, 0
|
||||
while position < len(data):
|
||||
length = int.from_bytes(data[position : position + 4], "big")
|
||||
kind = data[position + 4 : position + 8]
|
||||
payload = data[position + 8 : position + 8 + length]
|
||||
position += length + 12
|
||||
if kind == b"acTL":
|
||||
payload = bytes(4) + payload[4:]
|
||||
if kind == b"fcTL":
|
||||
controls += 1
|
||||
if controls > 1:
|
||||
continue
|
||||
if kind == b"fdAT":
|
||||
continue
|
||||
result += (
|
||||
struct.pack(">I", len(payload))
|
||||
+ kind
|
||||
+ payload
|
||||
+ struct.pack(">I", zlib.crc32(kind + payload))
|
||||
)
|
||||
upload(scenario, bytes(result), "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)
|
||||
@@ -50,3 +50,23 @@ def test_valid_trace_context():
|
||||
"tracestate": "test=value",
|
||||
}
|
||||
assert validate_delivery(json.dumps(body)) == body
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body", ["[" * 2000 + "]" * 2000, "[" * 20000 + "]" * 20000, b" " * 8193 + b"{}"]
|
||||
)
|
||||
def test_deep_and_oversize_envelopes_reject_safely(body):
|
||||
with pytest.raises(ValueError):
|
||||
validate_delivery(body)
|
||||
|
||||
|
||||
def test_uuid_uppercase_is_normalized_before_storage():
|
||||
value = "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA"
|
||||
parsed = validate_delivery(json.dumps({**VALID, "job_id": value, "attachment_id": value}))
|
||||
assert parsed["job_id"] == parsed["attachment_id"] == value.lower()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["job_id", "attachment_id"])
|
||||
def test_uuid_urn_is_rejected_before_storage(field):
|
||||
with pytest.raises(ValueError):
|
||||
validate_delivery(json.dumps({**VALID, field: "urn:uuid:" + VALID[field]}))
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import base64
|
||||
import codecs
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from uuid import uuid4
|
||||
|
||||
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
|
||||
|
||||
|
||||
def requests_for(alice, chat):
|
||||
return [
|
||||
(
|
||||
"/api/v1/users",
|
||||
{
|
||||
"username": "utf_" + uuid4().hex[:12],
|
||||
"display_name": "Имя\0",
|
||||
"password": "synthetic-password-123",
|
||||
},
|
||||
),
|
||||
("/api/v1/chats", {"title": "Чат\0", "member_ids": [alice["id"]]}),
|
||||
(f"/api/v1/chats/{chat['id']}/messages", {"text": "Сообщение\0"}),
|
||||
]
|
||||
|
||||
|
||||
def test_utf8_and_escaped_nul_remain_valid(encoding_scenario):
|
||||
c, alice, _, _, chat = encoding_scenario
|
||||
for path, body in requests_for(alice, chat):
|
||||
c.call(
|
||||
"POST",
|
||||
path,
|
||||
201,
|
||||
actor=alice,
|
||||
raw=json.dumps(body, ensure_ascii=False).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json", "Idempotency-Key": uuid4().hex},
|
||||
)
|
||||
Reference in New Issue
Block a user