forked from mtusi2026/mtusi2026lab4
ЛР 4: вложения в S3 (MinIO), reconciler БД<->S3, отчёт и evidence
Перенесён минимум lab3. Добавлены загрузка/скачивание PNG/JPEG через API с потоковой проверкой целостности, метаданные в PostgreSQL и байты в приватном bucket, отдельный S3-пользователь с ограниченными правами, идемпотентный bootstrap bucket, компенсация и reconciler (трек 2), тесты отказов, эксперименты по памяти и согласованности.
This commit is contained in:
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/sh
|
||||
# Proves the bucket is private without going through the API: anonymous S3 requests from inside the compose
|
||||
# network are refused, and the MinIO console/ports are not published on the host.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
NET="$(docker compose ps -q minio | xargs docker inspect --format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}}{{end}}')"
|
||||
BUCKET=messenger-attachments
|
||||
echo "== published ports of minio (expect none) =="
|
||||
docker compose port minio 9000 2>&1 || true
|
||||
docker compose port minio 9001 2>&1 || true
|
||||
echo "== anonymous requests from inside the network =="
|
||||
for path in "$BUCKET/" "$BUCKET/attachments/does-not-matter" "$BUCKET?list-type=2"; do
|
||||
code="$(docker run --rm -i --network "$NET" python:3.12.8-slim-bookworm python - "$path" <<'PY'
|
||||
import sys, urllib.request, urllib.error
|
||||
try:
|
||||
print(urllib.request.urlopen("http://minio:9000/" + sys.argv[1], timeout=5).status)
|
||||
except urllib.error.HTTPError as e:
|
||||
print(e.code)
|
||||
PY
|
||||
)"
|
||||
echo "GET /$path -> $code"
|
||||
[ "$code" = 403 ] || { echo "FAIL: expected 403"; exit 1; }
|
||||
done
|
||||
echo "== bucket policy =="
|
||||
docker compose run --rm --no-deps --entrypoint sh minio-init -c \
|
||||
'mc alias set local http://minio:9000 "$(cat /run/secrets/minio_root_user)" "$(cat /run/secrets/minio_root_password)" >/dev/null && mc anonymous get local/messenger-attachments'
|
||||
echo "PASS: bucket is private"
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Peak API memory under N concurrent ~8.7 MB uploads. Samples `docker stats` for the api containers.
|
||||
python3 student-tests/memory_experiment.py --concurrency 10 --rounds 3"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import zlib
|
||||
import struct
|
||||
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 # noqa: E402
|
||||
|
||||
|
||||
def png(width, height):
|
||||
raw = b"".join(b"\0" + os.urandom(width * 3) for _ in range(height))
|
||||
def chunk(kind, body):
|
||||
return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body) & 0xFFFFFFFF)
|
||||
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
|
||||
+ chunk(b"IDAT", zlib.compress(raw, 1)) + chunk(b"IEND", b""))
|
||||
|
||||
|
||||
UNITS = {"B": 1, "KiB": 1024, "MiB": 1048576, "GiB": 1073741824}
|
||||
|
||||
|
||||
def mib(text):
|
||||
value, unit = re.match(r"([\d.]+)\s*([A-Za-z]+)", text).groups()
|
||||
return float(value) * UNITS[unit] / 1048576
|
||||
|
||||
|
||||
def sample(stop, out):
|
||||
while not stop.is_set():
|
||||
result = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}} {{.MemUsage}}"],
|
||||
cwd=ROOT, capture_output=True, text=True)
|
||||
for line in result.stdout.splitlines():
|
||||
name, usage = line.split(" ", 1)
|
||||
if "api-" in name:
|
||||
out.setdefault(name, []).append(mib(usage.split("/")[0].strip()))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--concurrency", type=int, default=10)
|
||||
parser.add_argument("--rounds", type=int, default=3)
|
||||
args = parser.parse_args()
|
||||
body = png(1700, 1700)
|
||||
print("payload bytes:", len(body))
|
||||
c = Client(timeout=60)
|
||||
alice = c.user("mem")
|
||||
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, body={"title": "mem", "member_ids": [alice["id"]]}, schema="Chat")["json"]
|
||||
path = "/api/v1/chats/%s/attachments?filename=big.png" % chat["id"]
|
||||
|
||||
def one(_):
|
||||
r = c.call("POST", path, [201, 429, 503], actor=alice, raw=body, headers={"Content-Type": "image/png"})
|
||||
return r["status"], r["elapsed"]
|
||||
|
||||
idle, peaks, statuses, times = {}, [], [], []
|
||||
probe = {}
|
||||
stop = threading.Event()
|
||||
t = threading.Thread(target=sample, args=(stop, probe)); t.start(); time.sleep(3); stop.set(); t.join()
|
||||
idle = {k: max(v) for k, v in probe.items()}
|
||||
for round_no in range(args.rounds):
|
||||
probe = {}
|
||||
stop = threading.Event()
|
||||
t = threading.Thread(target=sample, args=(stop, probe)); t.start()
|
||||
with ThreadPoolExecutor(args.concurrency) as pool:
|
||||
results = list(pool.map(one, range(args.concurrency)))
|
||||
stop.set(); t.join()
|
||||
peak = {k: max(v) for k, v in probe.items()}
|
||||
peaks.append(peak)
|
||||
statuses += [s for s, _ in results]
|
||||
times += [e for _, e in results]
|
||||
print("round %d peak MiB per api: %s statuses=%s" % (round_no + 1, {k: round(v, 1) for k, v in peak.items()}, sorted(set(s for s, _ in results))))
|
||||
summary = {
|
||||
"payload_mib": round(len(body) / 1048576, 2), "concurrency": args.concurrency, "rounds": args.rounds,
|
||||
"idle_mib": {k: round(v, 1) for k, v in idle.items()},
|
||||
"peak_mib": {k: round(max(p.get(k, 0) for p in peaks), 1) for k in idle},
|
||||
"container_limit_mib": 256,
|
||||
"statuses": {str(s): statuses.count(s) for s in sorted(set(statuses))},
|
||||
"upload_seconds_median": round(statistics.median(times), 2), "upload_seconds_max": round(max(times), 2),
|
||||
}
|
||||
print(json.dumps(summary, indent=2))
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Upload -> stop the serving replica -> download via the other; then restart everything and download again."""
|
||||
import hashlib
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check, run # noqa: E402
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True, capture_output=True)
|
||||
|
||||
|
||||
def wait_ready(c):
|
||||
for _ in range(60):
|
||||
try:
|
||||
c.call("GET", "/health/ready")
|
||||
return
|
||||
except Exception:
|
||||
time.sleep(2)
|
||||
check(False, "stack did not become ready")
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
att, content = c.attachment(alice, chat)
|
||||
served_by = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["headers"]["X-Instance-Id"]
|
||||
print("metadata served by", served_by)
|
||||
first = c.call("POST", "/api/v1/chats/%s/attachments?filename=x.png" % chat["id"], 201, actor=alice, raw=content,
|
||||
headers={"Content-Type": "image/png"}, schema="Attachment")
|
||||
uploader = first["headers"]["X-Instance-Id"]
|
||||
compose("stop", "-t", "3", uploader)
|
||||
try:
|
||||
time.sleep(3)
|
||||
got = c.call("GET", "/api/v1/attachments/%s/content" % first["json"]["id"], actor=bob)
|
||||
check(got["headers"]["X-Instance-Id"] != uploader, "download must be served by another replica")
|
||||
check(hashlib.sha256(got["bytes"]).hexdigest() == first["json"]["sha256"], "bytes differ after uploader stopped")
|
||||
print("ok uploaded via %s, downloaded via %s, identical sha256" % (uploader, got["headers"]["X-Instance-Id"]))
|
||||
finally:
|
||||
compose("start", uploader)
|
||||
wait_ready(c)
|
||||
compose("restart", "-t", "5", "postgres", "valkey", "minio", "api-1", "api-2", "nginx")
|
||||
wait_ready(c)
|
||||
got = c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=bob)
|
||||
check(got["bytes"] == content, "original lost after full restart")
|
||||
meta = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"]
|
||||
check(meta == att, "metadata changed after restart")
|
||||
print("ok restart of all stateful services keeps metadata and original")
|
||||
print("PASS: attachment failover + persistence")
|
||||
|
||||
|
||||
run(main)
|
||||
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Negative and boundary scenarios for attachments (grade 4). Needs the stack from README on BASE_URL."""
|
||||
import hashlib
|
||||
import os
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote, urlparse
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check, run # noqa: E402
|
||||
|
||||
SAMPLE = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def chunk(kind, body):
|
||||
return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def header_only_png(width, height):
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def upload(c, actor, chat, body, ctype, expected, filename="a.png"):
|
||||
path = "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], quote(filename, safe=""))
|
||||
return c.call("POST", path, expected, actor=actor, raw=body, headers={"Content-Type": ctype},
|
||||
schema="Attachment" if expected == 201 else None)
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
other = c.call("POST", "/api/v1/chats", 201, actor=alice,
|
||||
body={"title": "Второй", "member_ids": [alice["id"]]}, schema="Chat")["json"]
|
||||
eve_chat = c.call("POST", "/api/v1/chats", 201, actor=eve,
|
||||
body={"title": "Чат Евы", "member_ids": [eve["id"]]}, schema="Chat")["json"]
|
||||
|
||||
ok = upload(c, alice, chat, SAMPLE, "image/png", 201)["json"]
|
||||
check(ok["status"] == "ready" and ok["variants"] == [] and ok["error_code"] is None, "ready upload shape")
|
||||
got = c.call("GET", "/api/v1/attachments/" + ok["id"] + "/content", actor=bob)
|
||||
check(hashlib.sha256(got["bytes"]).hexdigest() == ok["sha256"], "bob downloads identical bytes")
|
||||
check(int(got["headers"]["Content-Length"]) == len(SAMPLE), "download Content-Length")
|
||||
c.call("GET", "/api/v1/attachments/" + ok["id"] + "/content?variant=thumbnail", 404, actor=bob)
|
||||
|
||||
upload(c, None, chat, SAMPLE, "image/png", 401)
|
||||
upload(c, eve, chat, SAMPLE, "image/png", 404)
|
||||
print("ok auth and membership on upload")
|
||||
|
||||
big = header_only_png(10, 10) + b"\0" * (10 * 1024 * 1024)
|
||||
upload(c, alice, chat, big, "image/png", 413)
|
||||
print("ok file over 10 MiB -> 413")
|
||||
upload(c, alice, chat, header_only_png(8000, 6000), "image/png", 413)
|
||||
print("ok 48 Mpx image -> 413 before decoding")
|
||||
upload(c, alice, chat, SAMPLE[: len(SAMPLE) // 2], "image/png", 415)
|
||||
upload(c, alice, chat, SAMPLE[:40] + b"garbage" * 50, "image/png", 415)
|
||||
print("ok corrupted image -> 415")
|
||||
upload(c, alice, chat, SAMPLE, "image/jpeg", 415)
|
||||
upload(c, alice, chat, b"\xff\xd8\xff\xe0" + b"\0" * 200, "image/png", 415)
|
||||
upload(c, alice, chat, b"MZ not an image at all", "image/png", 415)
|
||||
upload(c, alice, chat, b"<svg xmlns='http://www.w3.org/2000/svg'/>", "image/png", 415)
|
||||
upload(c, alice, chat, SAMPLE, "text/plain", 415)
|
||||
upload(c, alice, chat, SAMPLE, "image/gif", 415)
|
||||
print("ok MIME spoofing and unsupported types -> 415")
|
||||
upload(c, alice, chat, b"", "image/png", 400)
|
||||
for bad in ("../x.png", "a/b.png", "a\\b.png", "a\x00b.png", "a\nb.png", "", "x" * 256):
|
||||
upload(c, alice, chat, SAMPLE, "image/png", 400, filename=bad)
|
||||
print("ok dangerous filenames -> 400")
|
||||
unicode_name = upload(c, alice, chat, SAMPLE, "image/png", 201, filename="фото 🙂.png")["json"]
|
||||
check(unicode_name["filename"] == "фото 🙂.png", "display filename preserved")
|
||||
|
||||
own = upload(c, alice, other, SAMPLE, "image/png", 201)["json"]
|
||||
foreign = upload(c, eve, eve_chat, SAMPLE, "image/png", 201)["json"]
|
||||
msg = lambda actor, ch, ids, expected: c.call(
|
||||
"POST", "/api/v1/chats/%s/messages" % ch["id"], expected, actor=actor,
|
||||
body={"text": "", "attachment_ids": ids}, headers={"Idempotency-Key": uuid.uuid4().hex}, schema="Message" if expected == 201 else None)
|
||||
msg(alice, chat, [str(uuid.uuid4())], 404)
|
||||
msg(alice, chat, [foreign["id"]], 404)
|
||||
msg(alice, chat, [own["id"]], 404)
|
||||
msg(alice, chat, [ok["id"], ok["id"]], 400)
|
||||
msg(alice, chat, ["not-a-uuid"], 400)
|
||||
msg(alice, chat, [str(uuid.uuid4()) for _ in range(11)], 400)
|
||||
msg(eve, chat, [ok["id"]], 404)
|
||||
c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice, body={"text": " "},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex})
|
||||
print("ok unknown / foreign / other-chat attachment ids rejected, no 500")
|
||||
sent = msg(bob, chat, [ok["id"]], 201)["json"]
|
||||
check(sent["attachment_ids"] == [ok["id"]] and sent["text"] == "", "attachment-only message")
|
||||
history = c.call("GET", "/api/v1/chats/%s/messages" % chat["id"], actor=alice, schema="MessagePage")["json"]
|
||||
check(any(m["attachment_ids"] == [ok["id"]] for m in history["items"]), "history keeps attachment_ids")
|
||||
for suffix in ("", "/content"):
|
||||
c.call("GET", "/api/v1/attachments/" + foreign["id"] + suffix, 404, actor=alice)
|
||||
c.call("GET", "/api/v1/attachments/" + str(uuid.uuid4()) + suffix, 404, actor=alice)
|
||||
c.call("GET", "/api/v1/attachments/not-a-uuid" + suffix, 400, actor=alice)
|
||||
c.call("GET", "/api/v1/attachments/" + ok["id"] + suffix, 401)
|
||||
|
||||
parsed = urlparse(c.base)
|
||||
sock = socket.create_connection((parsed.hostname, parsed.port or 80), timeout=10)
|
||||
request = ("POST /api/v1/chats/%s/attachments?filename=cut.png HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer %s\r\n"
|
||||
"Content-Type: image/png\r\nContent-Length: %d\r\n\r\n" % (chat["id"], alice["token"], len(SAMPLE)))
|
||||
sock.sendall(request.encode() + SAMPLE[: len(SAMPLE) // 2])
|
||||
sock.close()
|
||||
print("ok client abort mid-upload sent; server must stay healthy")
|
||||
c.call("GET", "/health/ready", schema="Health")
|
||||
after = upload(c, alice, chat, SAMPLE, "image/png", 201)["json"]
|
||||
check(after["sha256"] == hashlib.sha256(SAMPLE).hexdigest(), "upload works after aborted one")
|
||||
print("PASS: attachment negative scenarios")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Hardening scenarios: corrupted images, filenames, attachment order, idempotency keys, oversized bodies."""
|
||||
import hashlib
|
||||
import os
|
||||
import struct
|
||||
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"))
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
from client import Client, check, run # noqa: E402
|
||||
from test_attachments import SAMPLE, chunk, header_only_png # noqa: E402
|
||||
|
||||
JPEG_STUB = bytes.fromhex("ffd8ffc0000b080001000101011100ffda0008010100003f00ffd9")
|
||||
|
||||
|
||||
def png(width, height, filter_byte=0, level=1, corrupt_idat=False, noise=False):
|
||||
row = bytes([filter_byte]) + (os.urandom(width * 3) if noise else b"\x10" * (width * 3))
|
||||
raw = row * height
|
||||
data = zlib.compress(raw, level)
|
||||
if corrupt_idat:
|
||||
mid = len(data) // 2
|
||||
data = data[:mid] + bytes(b ^ 0xFF for b in data[mid:mid + 40]) + data[mid + 40:]
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", data) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = "/api/v1/chats/%s/attachments?filename=" % chat["id"]
|
||||
|
||||
def up(body, ctype, expected, name="a.png", **kw):
|
||||
return c.call("POST", path + quote(name, safe=""), expected, actor=alice, raw=body,
|
||||
headers={"Content-Type": ctype}, schema="Attachment" if expected == 201 else None)
|
||||
|
||||
up(SAMPLE[:33], "image/png", 415)
|
||||
up(png(1, 1, filter_byte=5), "image/png", 415)
|
||||
up(png(1, 1, filter_byte=0xFF), "image/png", 415)
|
||||
up(png(64, 64, corrupt_idat=True), "image/png", 415)
|
||||
up(JPEG_STUB, "image/jpeg", 415)
|
||||
print("ok truncated PNG, bad filter byte, broken IDAT, 27-byte JPEG stub -> 415")
|
||||
up(png(3000, 2000, filter_byte=7), "image/png", 415)
|
||||
up(png(3000, 2000, corrupt_idat=True, noise=True), "image/png", 415)
|
||||
print("ok same defects in images above the full-decode threshold (6 Mpx) -> 415")
|
||||
up(png(3000, 2000), "image/png", 201)
|
||||
print("ok valid 6 Mpx PNG accepted")
|
||||
import time
|
||||
big = png(6000, 6000, level=9)
|
||||
started = time.monotonic()
|
||||
r = up(big, "image/png", 201, name="36mpx.png")
|
||||
took = time.monotonic() - started
|
||||
check(took < 15, "36 Mpx PNG must be checked quickly, took %.1fs" % took)
|
||||
print("ok valid 36 Mpx PNG (%d KiB on the wire, 108 MiB decoded) accepted in %.1fs" % (len(big) // 1024, took))
|
||||
up(png(6000, 6000, filter_byte=9, level=9), "image/png", 415)
|
||||
print("ok 36 Mpx PNG with bad filter byte -> 415")
|
||||
|
||||
for name in (" ", "\t", "bad\x7f.png", "bad\x85.png", ".", "..", "a
b.png"):
|
||||
up(SAMPLE, "image/png", 400, name=name)
|
||||
print("ok whitespace-only, DEL, C1 and dot filenames -> 400")
|
||||
|
||||
a = up(SAMPLE, "image/png", 201, name="a.png")["json"]
|
||||
b = up(SAMPLE, "image/png", 201, name="b.png")["json"]
|
||||
url = "/api/v1/chats/%s/messages" % chat["id"]
|
||||
key = uuid.uuid4().hex
|
||||
first = c.call("POST", url, 201, actor=alice, body={"text": "", "attachment_ids": [b["id"], a["id"]]},
|
||||
headers={"Idempotency-Key": key}, schema="Message")["json"]
|
||||
check(first["attachment_ids"] == [b["id"], a["id"]], "POST keeps attachment order")
|
||||
replay = c.call("POST", url, 201, actor=alice, body={"attachment_ids": [b["id"], a["id"]], "text": ""},
|
||||
headers={"Idempotency-Key": key}, schema="Message")["json"]
|
||||
check(replay == first, "replay returns the same message")
|
||||
c.call("POST", url, 409, actor=alice, body={"text": "", "attachment_ids": [a["id"], b["id"]]},
|
||||
headers={"Idempotency-Key": key})
|
||||
history = c.call("GET", url, actor=bob, schema="MessagePage")["json"]["items"]
|
||||
check([m for m in history if m["id"] == first["id"]][0]["attachment_ids"] == [b["id"], a["id"]],
|
||||
"history keeps attachment order")
|
||||
print("ok attachment order preserved in POST, replay and history; reordered body -> 409")
|
||||
|
||||
key2 = uuid.uuid4().hex
|
||||
plain = c.call("POST", url, 201, actor=alice, body={"text": "x"}, headers={"Idempotency-Key": key2}, schema="Message")["json"]
|
||||
same = c.call("POST", url, 201, actor=alice, body={"text": "x", "attachment_ids": []},
|
||||
headers={"Idempotency-Key": key2}, schema="Message")["json"]
|
||||
check(plain == same, "absent attachment_ids equals []")
|
||||
for bad in ("a b", "a/b", "k" * 129, ""):
|
||||
c.call("POST", url, 400, actor=alice, body={"text": "k"}, headers={"Idempotency-Key": bad})
|
||||
other = c.call("POST", url, 201, actor=bob, body={"text": "x"}, headers={"Idempotency-Key": key2}, schema="Message")["json"]
|
||||
check(other["id"] != plain["id"] and other["sender_id"] == bob["id"], "idempotency key is per user")
|
||||
print("ok idempotency: [] == absent, invalid keys -> 400, scoped per user")
|
||||
|
||||
huge = b"\x89PNG\r\n\x1a\n" + b"\0" * (12 * 1024 * 1024)
|
||||
r = c.call("POST", path + "big.png", 413, actor=alice, raw=huge, headers={"Content-Type": "image/png"})
|
||||
check(r["headers"].get_content_type() == "application/json", "413 above the nginx limit is API-shaped JSON")
|
||||
print("ok 12 MiB body -> JSON 413")
|
||||
print("PASS: input hardening")
|
||||
|
||||
|
||||
run(main)
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python3
|
||||
"""S3 down: upload/download answer 503 (never 500), no partial rows are exposed, service recovers."""
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check, run # noqa: E402
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True, capture_output=True)
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
att, content = c.attachment(alice, chat)
|
||||
path = "/api/v1/chats/%s/attachments?filename=x.png" % chat["id"]
|
||||
compose("stop", "-t", "2", "minio")
|
||||
try:
|
||||
time.sleep(4)
|
||||
c.call("POST", path, 503, actor=alice, raw=content, headers={"Content-Type": "image/png"})
|
||||
c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", 503, actor=bob)
|
||||
c.call("GET", "/health/ready", 503)
|
||||
c.call("GET", "/health/ready", 503)
|
||||
c.message(alice, chat, "текст без S3")
|
||||
c.call("GET", "/health/live", schema="Health")
|
||||
c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")
|
||||
c.call("GET", "/api/v1/chats/%s/messages" % chat["id"], actor=bob, schema="MessagePage")
|
||||
print("ok S3 down: upload/download/ready -> 503 JSON, metadata and text messages still served through the LB (no 502)")
|
||||
finally:
|
||||
compose("start", "minio")
|
||||
got = None
|
||||
started = time.monotonic()
|
||||
while time.monotonic() - started < 90:
|
||||
got = c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", [200, 503], actor=bob)
|
||||
if got["status"] == 200:
|
||||
break
|
||||
time.sleep(2)
|
||||
check(got["status"] == 200, "download did not recover after S3 came back")
|
||||
print("ok recovered %.0fs after S3 start" % (time.monotonic() - started))
|
||||
check(got["bytes"] == content, "original intact after S3 outage")
|
||||
streak = 0
|
||||
for _ in range(60):
|
||||
streak = streak + 1 if c.call("GET", "/health/ready", [200, 503])["status"] == 200 else 0
|
||||
if streak >= 6:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
check(streak >= 6, "both replicas must report ready again")
|
||||
print("ok ready is 200 again")
|
||||
|
||||
compose("pause", "minio")
|
||||
try:
|
||||
started = time.monotonic()
|
||||
c.timeout = 40
|
||||
c.call("POST", path, 503, actor=alice, raw=content, headers={"Content-Type": "image/png"})
|
||||
took = time.monotonic() - started
|
||||
check(took < 20, "upload to a hung S3 must fail fast, took %.1fs" % took)
|
||||
c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", 503, actor=bob)
|
||||
print("ok hung S3: upload answered 503 in %.1fs" % took)
|
||||
finally:
|
||||
compose("unpause", "minio")
|
||||
time.sleep(3)
|
||||
c.call("POST", path, 201, actor=alice, raw=content, headers={"Content-Type": "image/png"}, schema="Attachment")
|
||||
print("PASS: S3 outage behaviour")
|
||||
|
||||
|
||||
run(main)
|
||||
Reference in New Issue
Block a user