145 lines
5.4 KiB
Python
145 lines
5.4 KiB
Python
"""Негативные тесты для вложений (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
|
|
|
|
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 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("\nPASS: all negative attachment tests")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |