feat: add private attachments and safe reconciliation experiment

This commit is contained in:
2026-11-06 17:55:51 +03:00
parent ec540a1a72
commit 59b2f031bc
35 changed files with 3341 additions and 20 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:8081"))
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)
+201
View File
@@ -0,0 +1,201 @@
"""Black-box regressions derived from the contract and teacher review comments."""
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:8084"))
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=201):
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 == 201 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"] == "ready" and a["variants"] == []
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", 404, 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,
)
+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:8081"))
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"]
+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}
)