Files
mtusi2026lab4/scripts/attachment_demo.py

24 lines
2.0 KiB
Python
Executable File

#!/usr/bin/env python3
"""Сценарий защиты: файл, сообщение, чужой пользователь, прямой доступ к S3. Запускать из корня репозитория."""
import hashlib
import subprocess
import sys
from pathlib import Path
sys.path.insert(0, "student-tests")
from api import call, new_chat, new_user, request_bytes, send
data = Path("tests/fixtures/sample.png").read_bytes()
alice, bob, eve = new_user("alice"), new_user("bob"), new_user("eve")
chat = new_chat(alice, bob)
_, att, _ = call("POST", "/api/v1/chats/%s/attachments?filename=sample.png" % chat["id"], raw=data, user=alice, headers={"Content-Type": "image/png"})
print("загрузка:", att["status"], att["size_bytes"], "байт, sha256", att["sha256"][:16])
status, msg, _ = send(alice, chat, "смотри файл", attachment_ids=[att["id"]])
print("сообщение:", status, "attachment_ids =", len(msg["attachment_ids"]))
status, body, headers = request_bytes("GET", "/api/v1/attachments/%s/content" % att["id"], user=bob)
print("второй участник скачал:", status, headers.get_content_type(), "sha256 совпал:", hashlib.sha256(body).hexdigest() == hashlib.sha256(data).hexdigest())
print("посторонний, метаданные:", call("GET", "/api/v1/attachments/" + att["id"], user=eve)[0], " байты:", request_bytes("GET", "/api/v1/attachments/%s/content" % att["id"], user=eve)[0])
code = "import urllib.request,urllib.error\ntry:\n print(urllib.request.urlopen('http://s3:9000/messenger-attachments/originals/%s',timeout=3).status)\nexcept urllib.error.HTTPError as e:\n print(e.code)" % att["id"]
cid = subprocess.run(["docker","compose","--env-file",".env","ps","-q","api"],capture_output=True,text=True).stdout.split()[0]
out = subprocess.run(["docker","exec",cid,"python","-c",code],capture_output=True,text=True).stdout.strip()
print("прямой GET в S3 без подписи изнутри сети:", out)