Implement bounded OTLP observability across API and asynchronous image pipeline

This commit is contained in:
2026-11-15 22:30:03 +03:00
parent 470d9d6f1e
commit 2701db5106
60 changed files with 6118 additions and 49 deletions
+201
View File
@@ -0,0 +1,201 @@
import base64
import os
import threading
import uuid
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import quote
import pytest
from client import LAB, Client
@pytest.fixture
def scenario():
c = Client(os.environ.get("BASE_URL", "http://127.0.0.1:8085"))
return c, *c.bootstrap()
@pytest.mark.parametrize(
"body",
[
{"text": ""},
{"text": " \n\t"},
{"text": 1},
{"text": True},
{"text": None},
{"text": "x", "sender_id": str(uuid.uuid4())},
{"text": "x", "unknown": 1},
{"text": "x" * 4001},
{},
[],
],
)
def test_invalid_message(scenario, body):
c, alice, _, _, chat = scenario
c.call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
400,
actor=alice,
body=body,
headers={"Idempotency-Key": uuid.uuid4().hex},
)
def test_malformed_json(scenario):
c, alice, _, _, chat = scenario
c.call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
400,
actor=alice,
raw=b'{"text":',
headers={"Content-Type": "application/json", "Idempotency-Key": uuid.uuid4().hex},
)
def test_acl_and_unknown_chat(scenario):
c, alice, _, eve, chat = scenario
for cid in [chat["id"], str(uuid.uuid4())]:
for suffix in ["", "/messages"]:
c.call("GET", f"/api/v1/chats/{cid}{suffix}", 404, actor=eve)
c.call(
"POST",
f"/api/v1/chats/{cid}/messages",
404,
actor=eve,
body={"text": "x"},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
c.call("GET", "/api/v1/chats/not-a-uuid", 400, actor=alice)
@pytest.mark.parametrize("name", ["ab", "UPPER", "a-b", "a" * 33, "имя", "abc\n"])
def test_username_validation(scenario, name):
c, alice, *_ = scenario
body = {**alice["registration"], "username": name}
c.call("POST", "/api/v1/users", 400, body=body)
def test_unicode_and_limits(scenario):
c, alice, _, _, chat = scenario
text = "Ё👩‍💻漢字" * 500
assert c.message(alice, chat, text)["json"]["text"] == text
c.call(
"POST",
"/api/v1/users",
400,
body={
**alice["registration"],
"username": "u_" + uuid.uuid4().hex[:12],
"display_name": " ",
},
)
@pytest.mark.parametrize("value", ["0", "101", "1.5", "true", "-1", "", "1&limit=2"])
def test_invalid_limit(scenario, value):
c, alice, _, _, chat = scenario
c.call("GET", f"/api/v1/chats/{chat['id']}/messages?limit={value}", 400, actor=alice)
def test_pagination_and_cursor_scope(scenario):
c, alice, bob, _, chat = scenario
expected = [c.message(alice, chat, str(i))["json"] for i in range(13)]
path = f"/api/v1/chats/{chat['id']}/messages"
result, cursor, first = [], None, None
for i in range(20):
url = path + f"?limit={2 if i == 0 else 3}"
if cursor:
url += "&cursor=" + quote(cursor, safe="")
data = c.call("GET", url, actor=bob, schema="MessagePage")["json"]
result += data["items"]
cursor = data["next_cursor"]
first = first or cursor
if cursor is None:
break
assert result == sorted(expected, key=lambda m: (m["created_at"], m["id"]))
other = c.call(
"POST",
"/api/v1/chats",
201,
actor=alice,
body={"title": "другой", "member_ids": [alice["id"]]},
schema="Chat",
)["json"]
c.call("GET", f"/api/v1/chats/{other['id']}/messages?cursor={first}", 400, actor=alice)
c.call("GET", path + "?cursor=broken", 400, actor=alice)
def test_chat_validation_and_atomicity(scenario):
c, alice, bob, _, _ = scenario
before = c.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]
for members in [
[bob["id"]],
[alice["id"], alice["id"]],
[alice["id"], str(uuid.uuid4())],
[],
[123],
]:
c.call(
"POST",
"/api/v1/chats",
400,
actor=alice,
body={"title": "не должен появиться", "member_ids": members},
)
after = c.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]
assert before == after
def test_concurrent_messages(scenario):
c, alice, bob, _, chat = scenario
barrier = threading.Barrier(10)
def sender(i):
local = Client(c.base)
barrier.wait()
return [local.message(alice, chat, f"{i}:{j}")["json"] for j in range(10)]
with ThreadPoolExecutor(max_workers=10) as pool:
sent = [m for batch in pool.map(sender, range(10)) for m in batch]
data = c.call(
"GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", actor=bob, schema="MessagePage"
)["json"]
assert len(sent) == len({m["id"] for m in sent}) == len(data["items"]) == 100
assert {m["id"] for m in sent} == {m["id"] for m in data["items"]}
assert data["next_cursor"] is None
def test_registration_race(scenario):
c, alice, *_ = scenario
body = {**alice["registration"], "username": "race_" + uuid.uuid4().hex[:12]}
barrier = threading.Barrier(10)
def register(_):
local = Client(c.base)
barrier.wait()
return local.call("POST", "/api/v1/users", [201, 409], body=body)["status"]
with ThreadPoolExecutor(max_workers=10) as pool:
statuses = list(pool.map(register, range(10)))
assert statuses.count(201) == 1
assert statuses.count(409) == 9
@pytest.mark.skipif(LAB < 2, reason="Сессии появляются в ЛР2")
def test_sessions(scenario):
c, alice, _, eve, _ = scenario
credential = base64.b64encode(
(alice["registration"]["username"] + ":wrong-password").encode()
).decode()
c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Basic " + credential})
c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": alice["id"]})
assert (
c.call(
"GET", "/api/v1/users/me", actor=alice, headers={"X-User-Id": eve["id"]}, schema="User"
)["json"]
== alice["user"]
)
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
c.call("GET", "/api/v1/users/me", 401, actor=alice)
+203
View File
@@ -0,0 +1,203 @@
"""Black-box regressions for attachment contract boundaries."""
import hashlib
import os
import struct
import uuid
import zlib
from io import BytesIO
from urllib.parse import quote
import pytest
from client import Client
from PIL import Image
@pytest.fixture(scope="module")
def scenario():
c = Client(os.environ.get("BASE_URL", "http://127.0.0.1:8085"))
return c, *c.bootstrap()
def image_bytes(fmt="PNG", size=(32, 20)):
stream = BytesIO()
Image.new("RGB", size, (100, 130, 200)).save(stream, fmt)
return stream.getvalue()
def upload(scenario, data=None, name="sample.png", mime="image/png", actor=None, status=202):
c, alice, _, _, chat = scenario
return c.call(
"POST",
f"/api/v1/chats/{chat['id']}/attachments?filename={quote(name, safe='')}",
status,
actor=actor or alice,
raw=data if data is not None else image_bytes(),
headers={"Content-Type": mime},
schema="Attachment" if status == 202 else None,
)
def test_roundtrip_acl_and_variant(scenario):
c, alice, bob, eve, chat = scenario
data = image_bytes()
a = upload(scenario, data)["json"]
assert a["sha256"] == hashlib.sha256(data).hexdigest()
assert a["status"] == "queued"
a = c.wait_ready(alice, a)
assert {v["name"] for v in a["variants"]} == {"thumbnail", "crop", "optimized"}
path = f"/api/v1/attachments/{a['id']}"
assert c.call("GET", path + "/content", 200, actor=bob)["bytes"] == data
c.call("GET", path, 404, actor=eve)
c.call("GET", path + "/content", 404, actor=eve)
c.call("GET", path + "/content?variant=thumbnail", 200, actor=alice)
c.call("GET", path + "/content?variant=unknown", 400, actor=alice)
message = c.call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
201,
actor=alice,
body={"text": "", "attachment_ids": [a["id"]]},
headers={"Idempotency-Key": uuid.uuid4().hex},
schema="Message",
)["json"]
assert message["text"] == "" and message["attachment_ids"] == [a["id"]]
@pytest.mark.parametrize(
"name", [" ", "../x.png", "a\\b.png", "a\0.png", "a\x7f.png", "a\x85.png", "a\n.png"]
)
def test_bad_filename(scenario, name):
upload(scenario, name=name, status=400)
def chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
def png_with_data(data, width=1, height=1, color=2, palette=b""):
return (
b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, color, 0, 0, 0))
+ (chunk(b"PLTE", palette) if palette else b"")
+ chunk(b"IDAT", data)
+ chunk(b"IEND", b"")
)
@pytest.mark.parametrize(
"data,mime",
[
(image_bytes()[:33], "image/png"),
(image_bytes()[:-15], "image/png"),
(png_with_data(b"broken-zlib"), "image/png"),
(png_with_data(zlib.compress(b"\x05\0\0\0")), "image/png"),
(png_with_data(zlib.compress(b"\0\0"), color=3, palette=bytes(771)), "image/png"),
(bytes.fromhex("ffd8ffc0000b080001000101011100ffda0008010100003f00ffd9"), "image/jpeg"),
(bytes.fromhex("ffd8ffc00008080001000101ffda0002ffd9"), "image/jpeg"),
(image_bytes(), "image/jpeg"),
(b"not-an-image", "image/png"),
],
)
def test_corrupt_or_spoofed_image(scenario, data, mime):
upload(scenario, data=data, mime=mime, status=415)
@pytest.mark.parametrize("size", [(8000, 5001), (20000, 10000)])
def test_pixel_limit_before_decode(scenario, size):
data = png_with_data(b"", width=size[0], height=size[1])
upload(scenario, data=data, status=413)
def test_byte_limit_and_exact_boundary(scenario):
data = image_bytes()
exact = data + bytes(10 * 1024 * 1024 - len(data))
a = upload(scenario, data=exact)["json"]
assert a["size_bytes"] == len(exact)
upload(scenario, data=exact + b"x", status=413)
@pytest.mark.parametrize(
"body",
[
{"attachment_ids": []},
{"text": None},
{"text": "x", "attachment_ids": None},
{"text": "x", "attachment_ids": [123]},
],
)
def test_strict_message_fields(scenario, body):
c, alice, _, _, chat = scenario
c.call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
400,
actor=alice,
body=body,
headers={"Idempotency-Key": uuid.uuid4().hex},
)
def test_foreign_unknown_and_ordered_attachments(scenario):
c, alice, _, _, chat = scenario
first, second = upload(scenario)["json"], upload(scenario)["json"]
other = c.call(
"POST",
"/api/v1/chats",
201,
actor=alice,
body={"title": "other", "member_ids": [alice["id"]]},
schema="Chat",
)["json"]
for aid in [first["id"], str(uuid.uuid4())]:
c.call(
"POST",
f"/api/v1/chats/{other['id']}/messages",
404,
actor=alice,
body={"text": "", "attachment_ids": [aid]},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
key = uuid.uuid4().hex
body = {"text": "with files", "attachment_ids": [second["id"], first["id"]]}
p = f"/api/v1/chats/{chat['id']}/messages"
sent = c.call(
"POST", p, 201, actor=alice, body=body, headers={"Idempotency-Key": key}, schema="Message"
)["json"]
repeat = c.call(
"POST", p, 201, actor=alice, body=body, headers={"Idempotency-Key": key}, schema="Message"
)["json"]
assert repeat == sent
c.call(
"POST",
p,
409,
actor=alice,
body={**body, "attachment_ids": list(reversed(body["attachment_ids"]))},
headers={"Idempotency-Key": key},
)
history = c.call("GET", p, 200, actor=alice, schema="MessagePage")["json"]["items"]
assert next(m for m in history if m["id"] == sent["id"]) == sent
def test_nul_message_roundtrip(scenario):
c, alice, _, _, chat = scenario
assert c.message(alice, chat, "abc\0def")["json"]["text"] == "abc\0def"
def test_truncated_jpeg_with_forged_eoi(scenario):
import random
stream = BytesIO()
Image.frombytes("RGB", (512, 512), random.Random(42).randbytes(512 * 512 * 3)).save(
stream, "JPEG", quality=95
)
original = stream.getvalue()
upload(scenario, data=original, name="real.jpg", mime="image/jpeg")
upload(
scenario,
data=original[: len(original) // 2] + b"\xff\xd9",
name="broken.jpg",
mime="image/jpeg",
status=415,
)
+39
View File
@@ -0,0 +1,39 @@
import base64
import json
from uuid import uuid4
import pytest
from messenger.domain import Failure, boundary
@pytest.mark.parametrize(
"version,date",
[
(True, "2026-01-01T00:00:00Z"),
(1.0, "2026-01-01T00:00:00Z"),
(1, "2026-W01-1T00:00:00Z"),
(1, "20260101T000000Z"),
(1, "2026-01-01 00:00:00Z"),
(1, "2026-01-01X00:00:00Z"),
(1, "2026-02-30T00:00:00Z"),
(1, "2026-01-01T00:00:00.1234567Z"),
],
)
def test_boundary_rejects_python_iso_extensions(version, date):
payload = [version, "scope", date, str(uuid4())]
cursor = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
with pytest.raises(Failure) as error:
boundary("scope", cursor)
assert error.value.status == 400
@pytest.mark.parametrize(
"date", ["2026-01-01T00:00:00Z", "2026-01-01T00:00:00.1Z", "2026-01-01T00:00:00.123456Z"]
)
def test_boundary_preserves_generated_format(date):
uid = str(uuid4())
cursor = (
base64.urlsafe_b64encode(json.dumps([1, "scope", date, uid]).encode()).decode().rstrip("=")
)
assert boundary("scope", cursor) == (date, uid)
+49
View File
@@ -0,0 +1,49 @@
import base64
import json
import os
import uuid
import pytest
from client import Client
@pytest.fixture(scope="module")
def shared():
client = Client(os.getenv("BASE_URL", "http://127.0.0.1:8085"))
return client, *client.bootstrap()
@pytest.mark.parametrize(
"date",
[
"2026-W01-1T00:00:00Z",
"20260101T000000Z",
"2026-01-01 00:00:00Z",
"2026-01-01X00:00:00Z",
"2026-01-01T00:00:00+00:00",
"2026-02-30T00:00:00Z",
"2026-01-01T24:00:00Z",
"2026-01-01T00:00:00.1234567Z",
],
)
def test_cursor_rejects_noncanonical_dates_over_http(shared, date):
c, alice, _, _, chat = shared
for path, scope in [
("/api/v1/chats", "chats:" + alice["id"]),
(f"/api/v1/chats/{chat['id']}/messages", "messages:" + chat["id"]),
]:
payload = [1, scope, date, str(uuid.uuid4())]
cursor = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
c.call("GET", path + "?cursor=" + cursor, 400, actor=alice)
@pytest.mark.parametrize("version", [True, 1.0])
def test_cursor_rejects_noninteger_version_over_http(shared, version):
c, alice, _, _, chat = shared
for path, scope in [
("/api/v1/chats", "chats:" + alice["id"]),
(f"/api/v1/chats/{chat['id']}/messages", "messages:" + chat["id"]),
]:
payload = [version, scope, "2026-01-01T00:00:00Z", str(uuid.uuid4())]
cursor = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
c.call("GET", path + "?cursor=" + cursor, 400, actor=alice)
+99
View File
@@ -0,0 +1,99 @@
import base64
import json
import os
import uuid
from urllib.parse import quote
import pytest
from client import LAB, Client
@pytest.fixture
def edge_scenario():
client = Client(os.environ.get("BASE_URL", "http://127.0.0.1:8085"))
return client, *client.bootstrap()
def encoded_cursor(value):
return base64.urlsafe_b64encode(json.dumps(value).encode()).decode().rstrip("=")
@pytest.mark.parametrize("identity", ["missing", "malformed", "unknown"])
def test_invalid_identity(edge_scenario, identity):
client, _, _, _, chat = edge_scenario
headers = {}
if identity == "malformed":
headers["X-User-Id"] = "not-a-uuid"
elif identity == "unknown":
headers["X-User-Id"] = str(uuid.uuid4())
for path in ["/api/v1/users/me", "/api/v1/chats", f"/api/v1/chats/{chat['id']}/messages"]:
client.call("GET", path, 401, headers=headers)
@pytest.mark.parametrize("uid", [None, [], {}, 123, True, "not-a-uuid"])
def test_cursor_rejects_non_uuid_boundary(edge_scenario, uid):
client, alice, _, _, chat = edge_scenario
payload = [1, "messages:" + chat["id"], "2026-10-30T12:00:00.000000Z", uid]
cursor = quote(encoded_cursor(payload), safe="")
client.call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor={cursor}", 400, actor=alice)
@pytest.mark.parametrize(
"payload", [None, {}, [], [1], [1, "wrong-scope", "2026-10-30T12:00:00Z", str(uuid.uuid4())]]
)
def test_cursor_rejects_wrong_shape(edge_scenario, payload):
client, alice, _, _, chat = edge_scenario
cursor = quote(encoded_cursor(payload), safe="")
client.call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor={cursor}", 400, actor=alice)
def test_request_id_is_present_and_not_reused(edge_scenario):
client, alice, _, _, _ = edge_scenario
first = client.call("GET", "/health/live", schema="Health")
second = client.call("GET", "/health/ready", schema="Health")
error = client.call("GET", "/api/v1/chats/malformed", 400, actor=alice)
values = [r["headers"]["X-Request-Id"] for r in [first, second, error]]
assert len(set(values)) == 3
assert error["json"]["error"]["request_id"] == values[-1]
def test_unicode_codepoint_boundaries(edge_scenario):
client, alice, _, _, chat = edge_scenario
username = "unicode_" + uuid.uuid4().hex[:12]
registration = {"username": username, "display_name": "😀" * 100}
if LAB >= 2:
registration["password"] = "unicode-test-" + uuid.uuid4().hex
user = client.call(
"POST",
"/api/v1/users",
201,
body=registration,
schema="User",
)["json"]
assert user["display_name"] == "😀" * 100
client.call(
"POST", "/api/v1/users", 400, body={"username": username + "x", "display_name": "😀" * 101}
)
message = client.message(alice, chat, "😀" * 4000)["json"]
assert message["text"] == "😀" * 4000
client.call(
"POST", f"/api/v1/chats/{chat['id']}/messages", 400, actor=alice, body={"text": "😀" * 4001}
)
def test_empty_history_and_cursor_exhaustion(edge_scenario):
client, alice, _, _, chat = edge_scenario
path = f"/api/v1/chats/{chat['id']}/messages"
empty = client.call("GET", path, actor=alice, schema="MessagePage")["json"]
assert empty == {"items": [], "next_cursor": None}
message = client.message(alice, chat, "одна запись")["json"]
data = client.call("GET", path + "?limit=1", actor=alice, schema="MessagePage")["json"]
assert data == {"items": [message], "next_cursor": None}
def test_missing_chat_is_hidden_like_foreign_chat(edge_scenario):
client, _, _, eve, chat = edge_scenario
foreign = client.call("GET", f"/api/v1/chats/{chat['id']}", 404, actor=eve)["json"]
missing = client.call("GET", f"/api/v1/chats/{uuid.uuid4()}", 404, actor=eve)["json"]
assert foreign["error"]["code"] == missing["error"]["code"] == "not_found"
assert foreign["error"]["message"] == missing["error"]["message"]
+229
View File
@@ -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)
+72
View File
@@ -0,0 +1,72 @@
import json
import pytest
from messenger.worker import validate_delivery
VALID = {
"schema_version": 1,
"job_id": "11111111-1111-4111-8111-111111111111",
"type": "attachment.process.v1",
"attachment_id": "22222222-2222-4222-8222-222222222222",
"pipeline_version": 1,
"attempt": 1,
"created_at": "2026-11-06T00:00:00Z",
}
@pytest.mark.parametrize(
"key,value",
[
("job_id", 123),
("job_id", []),
("attachment_id", {}),
("schema_version", True),
("pipeline_version", True),
("attempt", 0),
("created_at", 123),
("created_at", "2026-11-06"),
("created_at", "2026-11-06T12Z"),
("created_at", "2026-99-99T00:00:00Z"),
("traceparent", 123),
("tracestate", []),
],
)
def test_invalid_envelopes_are_bounded_validation_errors(key, value):
with pytest.raises(ValueError):
validate_delivery(json.dumps({**VALID, key: value}))
@pytest.mark.parametrize("body", [b"\xff", "null", "[]", "{}", "not json"])
def test_invalid_json(body):
with pytest.raises(ValueError):
validate_delivery(body)
def test_valid_trace_context():
body = {
**VALID,
"traceparent": "00-" + "a" * 32 + "-" + "b" * 16 + "-01",
"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]}))
+169
View File
@@ -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},
)
+46
View File
@@ -0,0 +1,46 @@
from io import BytesIO
import pytest
from PIL import Image
from messenger.image_pipeline import fitted_size, render
@pytest.mark.parametrize(
"source,expected",
[((319, 200), (256, 160)), ((320, 200), (256, 160)), ((10, 4), (10, 4)), ((1, 1000), (1, 256))],
)
def test_fits_contract(source, expected):
assert fitted_size(*source, 256) == expected
def test_variants_alpha_and_metadata(tmp_path):
source = BytesIO()
Image.new("RGBA", (319, 200), (255, 0, 0, 0)).save(source, "PNG")
source.seek(0)
variants = render(source, tmp_path)
assert {v["name"] for v in variants} == {"thumbnail", "crop", "optimized"}
with Image.open(tmp_path / "thumbnail") as thumb:
assert thumb.format == "JPEG"
assert thumb.size == (256, 160)
assert all(channel > 245 for channel in thumb.getpixel((0, 0)))
assert not thumb.getexif()
with Image.open(tmp_path / "crop") as crop:
assert crop.size == (128, 128)
with Image.open(tmp_path / "optimized") as optimized:
assert optimized.format == "WEBP"
assert optimized.size == (319, 200)
def test_exif_orientation_without_upscale(tmp_path):
source = BytesIO()
exif = Image.Exif()
exif[274] = 6
Image.new("RGB", (80, 40), "blue").save(source, "JPEG", exif=exif)
original = source.getvalue()
source.seek(0)
render(source, tmp_path)
assert source.getvalue() == original
with Image.open(tmp_path / "thumbnail") as thumbnail:
assert thumbnail.size == (40, 80)
assert not thumbnail.getexif()
+62
View File
@@ -0,0 +1,62 @@
import base64
import uuid
import pytest
from client import Client
@pytest.mark.parametrize("password", ["x" * 11, "x" * 129, "😀" * 129, 123, None, True])
def test_password_contract(password):
import os
c = Client(os.environ["BASE_URL"])
c.call(
"POST",
"/api/v1/users",
400,
body={
"username": "pwd_" + uuid.uuid4().hex[:12],
"display_name": "Тест",
"password": password,
},
)
def test_full_unicode_password_and_colon():
import os
c = Client(os.environ["BASE_URL"])
username = "pwd_" + uuid.uuid4().hex[:12]
password = "😀" * 126 + ":Я"
user = c.call(
"POST",
"/api/v1/users",
201,
body={"username": username, "display_name": "Пароль128", "password": password},
schema="User",
)["json"]
good = base64.b64encode((username + ":" + password).encode()).decode()
session = c.call(
"POST",
"/api/v1/auth/sessions",
201,
headers={"Authorization": "bAsIc " + good},
schema="Session",
)["json"]
actor = {"id": user["id"], "token": session["token"]}
assert session["user"] == user
bad = base64.b64encode((username + ":" + password[:-1] + "Б").encode()).decode()
c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Basic " + bad})
c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Basic " + good})
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=actor)
c.call("GET", "/api/v1/users/me", 401, actor=actor)
@pytest.mark.parametrize("credential", ["Basic !invalid", "Basic", "Bearer abc", "", "Basic YTpi"])
def test_invalid_basic(credential):
import os
Client(os.environ["BASE_URL"]).call(
"POST", "/api/v1/auth/sessions", 401, headers={"Authorization": credential}
)
+19
View File
@@ -0,0 +1,19 @@
import pytest
from pydantic import ValidationError
from messenger.models import CreateChat, CreateMessage, CreateUser
@pytest.mark.parametrize('scalar',['\ud800','\udfff'])
def test_unpaired_surrogates_rejected(scalar):
for factory in (
lambda: CreateUser(username='valid_user',display_name=scalar,password='valid-pass-123'),
lambda: CreateUser(username='valid_user',display_name='Valid',password='valid-pass-'+scalar),
lambda: CreateChat(title=scalar,member_ids=['00000000-0000-4000-8000-000000000001']),
lambda: CreateMessage(text=scalar),
):
with pytest.raises(ValidationError):
factory()
def test_valid_unicode_and_nul():
assert CreateMessage(text='😀\x00').text=='😀\x00'