Хранить вложения в приватном S3 и сверять их с PostgreSQL.

This commit is contained in:
2026-11-06 20:13:44 +03:00
parent ec540a1a72
commit a6bb7cbb8b
34 changed files with 3285 additions and 31 deletions
+50
View File
@@ -0,0 +1,50 @@
"""Eight parallel retries with one key must create one message."""
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check # noqa: E402
def main() -> None:
client = Client("http://127.0.0.1:8080", timeout=20)
alice = client.user("race_alice")
bob = client.user("race_bob")
chat = client.call(
"POST",
"/api/v1/chats",
201,
actor=alice,
body={"title": "Гонка", "member_ids": [alice["id"], bob["id"]]},
schema="Chat",
)["json"]
key = "race-" + alice["id"][:8]
text = "одно сообщение " + key
def once(_index):
local = Client("http://127.0.0.1:8080", timeout=20)
return local.message(alice, chat, text, key=key)["json"]
with ThreadPoolExecutor(max_workers=8) as pool:
bodies = list(pool.map(once, range(8)))
check(len({item["id"] for item in bodies}) == 1, "parallel retries created more than one message")
check(all(item == bodies[0] for item in bodies), "parallel retries returned different messages")
seen = client.call(
"GET",
"/api/v1/chats/" + chat["id"] + "/messages?limit=100",
actor=bob,
schema="MessagePage",
)["json"]["items"]
check(sum(1 for item in seen if item["text"] == text) == 1, "history contains duplicate race messages")
print("PASS: eight parallel idempotent retries created one message")
if __name__ == "__main__":
try:
main()
except (Failure, Exception) as exc:
print("FAIL:", exc)
raise SystemExit(1)
+171
View File
@@ -0,0 +1,171 @@
"""Grade-4 negative cases. User mistakes must stay 4xx, never 500."""
import base64
import hashlib
import json
import struct
import subprocess
import sys
import uuid
import zlib
from pathlib import Path
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check # noqa: E402
FIXTURE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
def chunk(tag: bytes, data: bytes) -> bytes:
crc = zlib.crc32(tag + data) & 0xFFFFFFFF
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", crc)
def pixel_bomb() -> bytes:
ihdr = struct.pack(">IIBBBBB", 20000, 20000, 8, 2, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IEND", b"")
def jpeg_bytes() -> bytes:
raw = subprocess.check_output(
[
"docker",
"exec",
"mtusi-api-1",
"python",
"-c",
"import io,base64; from PIL import Image; b=io.BytesIO(); "
"Image.new('RGB',(8,8),(12,34,56)).save(b,format='JPEG',quality=85); "
"print(base64.b64encode(b.getvalue()).decode())",
],
text=True,
)
return base64.b64decode(raw.strip())
def main() -> None:
client = Client("http://127.0.0.1:8080", timeout=60)
client.call("GET", "/health/live", schema="Health")
alice = client.user("n_alice")
bob = client.user("n_bob")
eve = client.user("n_eve")
chat = client.call(
"POST",
"/api/v1/chats",
201,
actor=alice,
body={"title": "Негативные", "member_ids": [alice["id"], bob["id"]]},
schema="Chat",
)["json"]
other = client.call(
"POST",
"/api/v1/chats",
201,
actor=alice,
body={"title": "Чужой", "member_ids": [alice["id"], eve["id"]]},
schema="Chat",
)["json"]
def upload(actor, chat_id, payload, filename, content_type, expected):
path = f"/api/v1/chats/{chat_id}/attachments?filename=" + quote(filename, safe="")
schema = "Attachment" if expected == 201 else None
return client.call(
"POST",
path,
expected,
actor=actor,
raw=payload,
headers={"Content-Type": content_type},
schema=schema,
)
jpeg = jpeg_bytes()
created = upload(alice, chat["id"], jpeg, "фото.jpg", "image/jpeg", 201)["json"]
check(created["content_type"] == "image/jpeg", "jpeg content type was not stored")
check(created["sha256"] == hashlib.sha256(jpeg).hexdigest(), "jpeg checksum mismatch")
downloaded = client.call("GET", "/api/v1/attachments/" + created["id"] + "/content", actor=bob)
check(downloaded["bytes"] == jpeg, "jpeg download mismatch")
check(downloaded["headers"].get_content_type() == "image/jpeg", "jpeg response type mismatch")
big = upload(alice, chat["id"], b"\x89PNG\r\n\x1a\n" + b"0" * (10 * 1024 * 1024), "big.png", "image/png", 413)
check(big["json"]["error"]["code"] == "payload_too_large", "oversize code")
bomb = upload(alice, chat["id"], pixel_bomb(), "bomb.png", "image/png", 413)
check(bomb["json"]["error"]["code"] == "payload_too_large", "pixel bomb code")
corrupt = upload(alice, chat["id"], FIXTURE[:-80], "broken.png", "image/png", 415)
check(corrupt["json"]["error"]["code"] == "unsupported_media_type", "corrupt code")
spoof = upload(alice, chat["id"], FIXTURE, "spoof.jpg", "image/jpeg", 415)
check(spoof["json"]["error"]["code"] == "unsupported_media_type", "mime spoof code")
garbage = upload(alice, chat["id"], b"not an image", "note.png", "image/png", 415)
check(garbage["json"]["error"]["code"] == "unsupported_media_type", "garbage code")
plain = upload(alice, chat["id"], FIXTURE, "note.png", "text/plain", 415)
check(plain["json"]["error"]["code"] == "unsupported_media_type", "declared text code")
for name in ("../secret.png", "a/b.png", "a\\b.png", "bad\nname.png", "bad\x00name.png", " ", "."):
refused = upload(alice, chat["id"], FIXTURE, name, "image/png", 400)
check(refused["json"]["error"]["code"] == "invalid_request", "dangerous filename was not 400")
missing = client.call("GET", "/api/v1/attachments/" + str(uuid.uuid4()), 404, actor=alice)
check(missing["json"]["error"]["code"] == "not_found", "random attachment code")
foreign = upload(alice, other["id"], FIXTURE, "other.png", "image/png", 201)["json"]
attached = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
404,
actor=alice,
body={"text": "чужое вложение", "attachment_ids": [foreign["id"]]},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
check(attached["json"]["error"]["code"] == "not_found", "cross-chat attachment code")
hidden = client.call("GET", "/api/v1/attachments/" + created["id"], 404, actor=eve)
check(hidden["json"]["error"]["code"] == "not_found", "outsider metadata code")
hidden_bytes = client.call("GET", "/api/v1/attachments/" + created["id"] + "/content", 404, actor=eve)
check(hidden_bytes["json"]["error"]["code"] == "not_found", "outsider bytes code")
client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
400,
actor=alice,
body={"text": " "},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
400,
actor=alice,
body={"text": "привет", "extra": 1},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
client.call("POST", "/api/v1/users", 400, body={"username": "ab", "display_name": "Имя", "password": "short-pass"})
client.call(
"POST",
"/api/v1/chats",
400,
actor=alice,
body={"title": "Дубли", "member_ids": [alice["id"], alice["id"]]},
)
page = client.call(
"GET",
"/api/v1/chats/" + chat["id"] + "/messages?limit=1",
actor=alice,
schema="MessagePage",
)["json"]
if page["next_cursor"]:
client.call(
"GET",
"/api/v1/chats/" + other["id"] + "/messages?limit=1&cursor=" + quote(page["next_cursor"], safe=""),
400,
actor=alice,
)
print("PASS: negative attachment and validation cases stayed in 4xx")
if __name__ == "__main__":
try:
main()
except (Failure, Exception) as exc:
print("FAIL:", exc)
raise SystemExit(1)
+38
View File
@@ -0,0 +1,38 @@
"""Anonymous S3 access is denied, and the console/API ports are not published."""
import json
import subprocess
import sys
def run(args):
return subprocess.check_output(args, text=True)
def main() -> None:
report = json.loads(run(["docker", "exec", "mtusi-api-1", "python", "-m", "app.admin", "check-private"]))
if not report.get("private"):
raise SystemExit("anonymous S3 access was not denied: " + json.dumps(report))
ports = json.loads(run(["docker", "inspect", "mtusi-minio", "--format", "{{json .NetworkSettings.Ports}}"]))
published = []
for bindings in (ports or {}).values():
if bindings:
published.extend(bindings)
if published:
raise SystemExit("MinIO published a host port, including the console if 9001 is mapped")
mounts = json.loads(run(["docker", "inspect", "mtusi-api-1", "--format", "{{json .Mounts}}"]))
if mounts:
raise SystemExit("API replica has a volume; originals must not live on the API filesystem")
env = run(["docker", "exec", "mtusi-api-1", "python", "-c", "import os; print('MINIO_ROOT_USER' in os.environ)"])
if env.strip() != "False":
raise SystemExit("API process can see the MinIO root user")
print(json.dumps({"private_bucket": report, "minio_published_ports": published, "api_mounts": mounts}, ensure_ascii=False))
print("PASS: private bucket, no published MinIO ports, API has no volume and no root credentials")
if __name__ == "__main__":
try:
main()
except Exception as exc:
print("FAIL:", exc)
raise SystemExit(1)