lab4: address reviewer feedback — pixel limit before decode, cursor validation, C1 filename, S3 readiness, honest RAM limits

This commit is contained in:
2026-10-23 15:53:27 +03:00
parent 652dfda832
commit f31bd358df
8 changed files with 313 additions and 55 deletions
+148 -1
View File
@@ -12,6 +12,7 @@ import sys
import urllib.error
import urllib.request
import uuid
import time
BASE = (
sys.argv[sys.argv.index("--base-url") + 1]
@@ -77,6 +78,147 @@ def upload(token, chat_id, filename, data, content_type):
)
def test_decompression_bomb():
"""PNG 8200x5000 (41M пикселей) — маленький по размеру, но огромный по пикселям."""
from PIL import Image
import io as _io
alice = make_user("bomb")
chat = make_chat(alice)
img = Image.new("RGB", (8200, 5000), color=(255, 0, 0))
buf = _io.BytesIO()
img.save(buf, format="PNG", compress_level=9)
data = buf.getvalue()
assert len(data) < 500 * 1024, f"expected small compressed, got {len(data)}"
started = time.monotonic()
code, _, _ = upload(alice["token"], chat, "bomb.png", data, "image/png")
elapsed = time.monotonic() - started
assert code == 413, f"expected 413, got {code}"
assert elapsed < 2.0, f"expected fast rejection (<2s), got {elapsed:.2f}s"
print(f"PASS: decompression bomb -> 413 ({len(data)} bytes, {elapsed:.2f}s)")
def test_invalid_cursor():
"""Cursor с невалидным timestamp или UUID -> 400."""
import base64 as _b64
alice = make_user("cursor")
chat = make_chat(alice)
chat_id = chat
# Невалидный timestamp
bad_t = _b64.urlsafe_b64encode(
json.dumps({
"s": f"chat:{chat_id}",
"t": "not-a-time",
"i": "00000000-0000-4000-8000-000000000000",
}).encode()
).decode().rstrip("=")
code, _, _ = call(
"GET", f"/api/v1/chats/{chat_id}/messages?cursor={bad_t}",
headers={"Authorization": "Bearer " + alice["token"]},
)
assert code == 400, f"invalid timestamp: expected 400, got {code}"
# Невалидный UUID
bad_i = _b64.urlsafe_b64encode(
json.dumps({
"s": f"chat:{chat_id}",
"t": "2026-01-01T00:00:00.000000Z",
"i": "not-a-uuid",
}).encode()
).decode().rstrip("=")
code, _, _ = call(
"GET", f"/api/v1/chats/{chat_id}/messages?cursor={bad_i}",
headers={"Authorization": "Bearer " + alice["token"]},
)
assert code == 400, f"invalid uuid: expected 400, got {code}"
print("PASS: invalid cursor -> 400 (timestamp and uuid)")
def test_filename_c1():
"""Filename с C1 control (U+0085) -> 400."""
from pathlib import Path
fixture = Path(__file__).resolve().parent.parent / "tests/fixtures/sample.png"
png = fixture.read_bytes()
alice = make_user("c1")
chat = make_chat(alice)
# filename = "c1\u0085.png" — C1 control U+0085
code, _, _ = call(
"POST",
f"/api/v1/chats/{chat}/attachments?filename=c1%C2%85.png",
headers={
"Authorization": "Bearer " + alice["token"],
"Content-Type": "image/png",
},
raw=png,
)
assert code == 400, f"expected 400 for C1 filename, got {code}"
print("PASS: C1 filename -> 400")
def test_s3_unavailable():
"""S3 down: readiness 503, upload 503."""
import subprocess
from pathlib import Path
alice = make_user("s3down")
chat = make_chat(alice)
# 1. Baseline: readiness 200
code, _, _ = call("GET", "/health/ready")
assert code == 200, f"readiness should be 200 before stop, got {code}"
# 2. Останавливаем S3
try:
subprocess.run(
["docker", "compose", "--env-file", ".env", "stop", "s3"],
check=True, capture_output=True, text=True,
cwd=str(Path(__file__).resolve().parent.parent),
timeout=30,
)
except subprocess.CalledProcessError as e:
raise SystemExit(f"failed to stop s3: {e.stderr}")
import time as _t
_t.sleep(3)
try:
# 3. Readiness должен быть 503
code, body, _ = call("GET", "/health/ready")
assert code == 503, f"readiness should be 503 with S3 down, got {code}"
assert body and body["error"]["code"] == "unavailable", \
f"expected unavailable, got {body}"
# 4. Upload должен быть 503
fixture = Path(__file__).resolve().parent.parent / "tests/fixtures/sample.png"
png = fixture.read_bytes()
code, body, _ = upload(alice["token"], chat, "s3down.png", png, "image/png")
assert code == 503, f"upload should be 503 with S3 down, got {code}"
assert body and body["error"]["code"] == "unavailable", \
f"expected unavailable, got {body}"
print("PASS: S3 down -> readiness 503, upload 503")
finally:
# 5. Возвращаем S3
subprocess.run(
["docker", "compose", "--env-file", ".env", "start", "s3"],
check=False, capture_output=True, text=True,
cwd=str(Path(__file__).resolve().parent.parent),
timeout=30,
)
# Ждём готовности
deadline = _t.monotonic() + 30
while _t.monotonic() < deadline:
code, _, _ = call("GET", "/health/ready")
if code == 200:
break
_t.sleep(1)
def main():
alice = make_user("alice")
bob = make_user("bob")
@@ -138,8 +280,13 @@ def main():
assert code == 404, f"cross-chat attachment: expected 404, got {code}"
print("PASS: cross-chat attachment -> 404")
print("\nPASS: all negative attachment tests")
print("\nNew tests from reviewer feedback")
test_decompression_bomb()
test_invalid_cursor()
test_filename_c1()
print("\nS3 unavailable")
test_s3_unavailable()
if __name__ == "__main__":
main()