lab6: observability — OTel Collector, Prometheus, Loki, Tempo, Grafana
This commit is contained in:
@@ -0,0 +1,292 @@
|
||||
"""Негативные тесты для вложений (lab4 grade 4).
|
||||
|
||||
Запуск:
|
||||
python3 test_attachments_negative.py --base-url http://localhost:8080
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
import time
|
||||
|
||||
BASE = (
|
||||
sys.argv[sys.argv.index("--base-url") + 1]
|
||||
if "--base-url" in sys.argv
|
||||
else "http://localhost:8080"
|
||||
)
|
||||
|
||||
|
||||
def call(method, path, headers=None, body=None, raw=None):
|
||||
data = None
|
||||
h = dict(headers or {})
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
h["Content-Type"] = "application/json"
|
||||
elif raw is not None:
|
||||
data = raw
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=30)
|
||||
payload = resp.read()
|
||||
return resp.status, json.loads(payload) if payload else None, dict(resp.headers)
|
||||
except urllib.error.HTTPError as e:
|
||||
payload = e.read()
|
||||
try:
|
||||
return e.code, json.loads(payload) if payload else None, dict(e.headers)
|
||||
except Exception:
|
||||
return e.code, None, dict(e.headers)
|
||||
|
||||
|
||||
def make_user(label):
|
||||
username = f"att_{label}_{uuid.uuid4().hex[:10]}"
|
||||
password = "negative-pass-1234567890"
|
||||
code, user, _ = call("POST", "/api/v1/users", body={
|
||||
"username": username, "display_name": f"Att {label}", "password": password,
|
||||
})
|
||||
assert code == 201, f"register {label} failed: {code} {user}"
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
code, session, _ = call("POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + cred})
|
||||
assert code == 201, f"login {label} failed: {code}"
|
||||
return {
|
||||
"id": user["id"],
|
||||
"token": session["token"],
|
||||
}
|
||||
|
||||
|
||||
def make_chat(owner, member_ids=None):
|
||||
if member_ids is None:
|
||||
member_ids = [owner["id"]]
|
||||
code, chat, _ = call("POST", "/api/v1/chats",
|
||||
headers={"Authorization": "Bearer " + owner["token"]},
|
||||
body={"title": "Negative", "member_ids": member_ids})
|
||||
assert code == 201, f"chat failed: {code} {chat}"
|
||||
return chat["id"]
|
||||
|
||||
|
||||
def upload(token, chat_id, filename, data, content_type):
|
||||
return call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat_id}/attachments?filename={filename}",
|
||||
headers={"Authorization": "Bearer " + token, "Content-Type": content_type},
|
||||
raw=data,
|
||||
)
|
||||
|
||||
|
||||
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")
|
||||
eve = make_user("eve")
|
||||
chat_ab = make_chat(alice, [alice["id"], bob["id"]])
|
||||
chat_alice = make_chat(alice)
|
||||
|
||||
# 1. Oversize: > 10 MiB
|
||||
big = b"\x89PNG\r\n\x1a\n" + b"\x00" * (10 * 1024 * 1024 + 1)
|
||||
code, _, _ = upload(alice["token"], chat_ab, "big.png", big, "image/png")
|
||||
assert code == 413, f"oversize: expected 413, got {code}"
|
||||
print("PASS: oversize -> 413")
|
||||
|
||||
# 2. Corrupted: валидная сигнатура, битые данные
|
||||
corrupted = b"\x89PNG\r\n\x1a\n" + b"\xff" * 100
|
||||
code, _, _ = upload(alice["token"], chat_ab, "corrupted.png", corrupted, "image/png")
|
||||
assert code == 415, f"corrupted: expected 415, got {code}"
|
||||
print("PASS: corrupted -> 415")
|
||||
|
||||
# 3. MIME-spoofing: image/png, но текст
|
||||
spoofed = b"this is definitely not an image"
|
||||
code, _, _ = upload(alice["token"], chat_ab, "spoof.png", spoofed, "image/png")
|
||||
assert code == 415, f"mime spoof: expected 415, got {code}"
|
||||
print("PASS: mime spoofing -> 415")
|
||||
|
||||
# 4. Чужой attachment_id: eve скачивает вложение из chat_ab
|
||||
# Сначала загрузим настоящий PNG (тестовый fixture)
|
||||
from pathlib import Path
|
||||
fixture = Path(__file__).resolve().parent.parent / "tests/fixtures/sample.png"
|
||||
if not fixture.exists():
|
||||
raise SystemExit(f"fixture not found: {fixture}")
|
||||
png = fixture.read_bytes()
|
||||
code, att, _ = upload(alice["token"], chat_ab, "sample.png", png, "image/png")
|
||||
assert code == 201, f"upload fixture failed: {code} {att}"
|
||||
att_id = att["id"]
|
||||
|
||||
code, _, _ = call("GET", f"/api/v1/attachments/{att_id}",
|
||||
headers={"Authorization": "Bearer " + eve["token"]})
|
||||
assert code == 404, f"outsider metadata: expected 404, got {code}"
|
||||
code, _, _ = call("GET", f"/api/v1/attachments/{att_id}/content",
|
||||
headers={"Authorization": "Bearer " + eve["token"]})
|
||||
assert code == 404, f"outsider content: expected 404, got {code}"
|
||||
print("PASS: outsider attachment -> 404")
|
||||
|
||||
# 5. Вложение из другого чата
|
||||
# Загружаем в chat_alice, прикрепляем к сообщению в chat_ab
|
||||
code, att2, _ = upload(alice["token"], chat_alice, "other.png", png, "image/png")
|
||||
assert code == 201, f"upload to chat_alice failed: {code} {att2}"
|
||||
other_id = att2["id"]
|
||||
|
||||
code, _, _ = call(
|
||||
"POST", f"/api/v1/chats/{chat_ab}/messages",
|
||||
headers={
|
||||
"Authorization": "Bearer " + alice["token"],
|
||||
"Idempotency-Key": uuid.uuid4().hex,
|
||||
},
|
||||
body={"text": "cross-chat", "attachment_ids": [other_id]},
|
||||
)
|
||||
assert code == 404, f"cross-chat attachment: expected 404, got {code}"
|
||||
print("PASS: cross-chat attachment -> 404")
|
||||
|
||||
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()
|
||||
Reference in New Issue
Block a user