Files
mtusi2026lab4/student-tests/run_files.py
T

231 lines
8.4 KiB
Python

"""Негативные случаи вложений, память десяти загрузок и закрытый bucket.
Сервер уже должен слушать http://127.0.0.1:8080. Секреты скрипт не печатает.
"""
import base64
import json
import os
import struct
import subprocess
import threading
import time
import urllib.error
import urllib.request
import uuid
import zlib
from pathlib import Path
BASE = "http://127.0.0.1:8080"
ROOT = Path(__file__).resolve().parents[1]
MAX_BYTES = 10 * 1024 * 1024
def call(method, path, body=None, token=None, raw=None, content_type=None, status=None, headers=None):
data = raw
sent = dict(headers or {})
if body is not None:
data = json.dumps(body).encode("utf-8")
sent["Content-Type"] = "application/json"
if content_type:
sent["Content-Type"] = content_type
if token:
sent["Authorization"] = "Bearer " + token
request = urllib.request.Request(BASE + path, data=data, headers=sent, method=method)
try:
with urllib.request.urlopen(request, timeout=60) as response:
payload = response.read()
code = response.status
response_headers = response.headers
except urllib.error.HTTPError as exc:
payload = exc.read()
code = exc.status
response_headers = exc.headers
if status is not None and code != status:
raise SystemExit("{} {} -> {} expected {}\n{}".format(method, path, code, status, payload[:300]))
parsed = None
if response_headers.get_content_type() == "application/json" and payload:
parsed = json.loads(payload.decode("utf-8"))
return {"status": code, "json": parsed, "bytes": payload, "headers": response_headers}
def user(prefix):
name = prefix + uuid.uuid4().hex[:10]
password = "password-" + uuid.uuid4().hex
created = call("POST", "/api/v1/users", {"username": name, "password": password, "display_name": name}, status=201)["json"]
basic = base64.b64encode((name + ":" + password).encode()).decode("ascii")
session = call("POST", "/api/v1/auth/sessions", token=None, headers={"Authorization": "Basic " + basic}, status=201)["json"]
created["token"] = session["token"]
return created
def chat(owner, *members):
return call(
"POST",
"/api/v1/chats",
{"title": "files", "member_ids": [owner["id"], *[item["id"] for item in members]]},
token=owner["token"],
status=201,
)["json"]
def png_chunk(tag, data):
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
def tiny_png():
raw = b"\x00\xff\x00\x00"
return (
b"\x89PNG\r\n\x1a\n"
+ png_chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0))
+ png_chunk(b"IDAT", zlib.compress(raw))
+ png_chunk(b"IEND", b"")
)
def noisy_png(width, height):
rows = bytearray()
for _ in range(height):
rows.append(0)
rows.extend(os.urandom(width * 3))
return (
b"\x89PNG\r\n\x1a\n"
+ png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ png_chunk(b"IDAT", zlib.compress(bytes(rows), 1))
+ png_chunk(b"IEND", b"")
)
def huge_header():
return (
b"\x89PNG\r\n\x1a\n"
+ png_chunk(b"IHDR", struct.pack(">IIBBBBB", 8000, 8000, 8, 2, 0, 0, 0))
+ png_chunk(b"IEND", b"")
)
def upload(token, chat_id, data, filename="a.png", content_type="image/png", status=201):
return call(
"POST",
"/api/v1/chats/{}/attachments?filename={}".format(chat_id, urllib.request.quote(filename)),
token=token,
raw=data,
content_type=content_type,
status=status,
)
def message(token, chat_id, text, attachments, status=201, key=None):
headers = {"Idempotency-Key": key or uuid.uuid4().hex}
return call(
"POST",
"/api/v1/chats/" + chat_id + "/messages",
{"text": text, "attachment_ids": attachments},
token=token,
status=status,
headers=headers,
)
def main():
picture = tiny_png()
alice = user("fa")
bob = user("fb")
eve = user("fe")
room = chat(alice, bob)
other = chat(alice, bob)
saved = upload(alice["token"], room["id"], picture)["json"]
if saved["status"] != "ready" or saved["sha256"] != __import__("hashlib").sha256(picture).hexdigest():
raise SystemExit("checksum")
if saved["filename"] != "a.png" or "object_key" in saved or saved["content_type"] != "image/png":
raise SystemExit("filename leaked into key fields")
linked = message(alice["token"], room["id"], "", [saved["id"]])["json"]
if linked["attachment_ids"] != [saved["id"]]:
raise SystemExit("link")
downloaded = call("GET", "/api/v1/attachments/" + saved["id"] + "/content", token=bob["token"])
if downloaded["bytes"] != picture or downloaded["headers"].get_content_type() != "image/png":
raise SystemExit("download")
if downloaded["headers"].get("Location"):
raise SystemExit("redirect")
call("GET", "/api/v1/attachments/" + saved["id"], token=eve["token"], status=404)
call("GET", "/api/v1/attachments/" + saved["id"] + "/content", token=eve["token"], status=404)
call("GET", "/api/v1/attachments/" + saved["id"] + "/content?variant=thumbnail", token=bob["token"], status=404)
upload(eve["token"], room["id"], picture, status=404)
upload(alice["token"], room["id"], picture, filename="../x.png", status=400)
upload(alice["token"], room["id"], picture, filename="a\\b.png", status=400)
upload(alice["token"], room["id"], picture, filename="bad\nname.png", status=400)
upload(alice["token"], room["id"], b"\x89PNG\r\n\x1a\nbroken", status=415)
upload(alice["token"], room["id"], picture, content_type="image/jpeg", status=415)
upload(alice["token"], room["id"], picture, content_type="text/plain", status=415)
upload(alice["token"], room["id"], huge_header(), status=413)
upload(alice["token"], room["id"], b"x" * (MAX_BYTES + 1), status=413)
foreign = upload(alice["token"], other["id"], picture)["json"]
message(alice["token"], room["id"], "x", [foreign["id"]], status=404)
message(alice["token"], room["id"], "x", [str(uuid.uuid4())], status=404)
message(alice["token"], room["id"], " ", [], status=400)
message(alice["token"], room["id"], "", [], status=400)
call("POST", "/api/v1/chats/" + room["id"] + "/attachments?filename=a.png", raw=picture, content_type="image/png", status=401)
same = uuid.uuid4().hex
first = message(alice["token"], room["id"], "same", [saved["id"]], key=same)["json"]
replay = message(alice["token"], room["id"], "same", [saved["id"]], key=same)["json"]
if replay != first:
raise SystemExit("replay")
message(alice["token"], room["id"], "other", [saved["id"]], key=same, status=409)
peaks = {}
stop = threading.Event()
def sample():
while not stop.is_set():
result = subprocess.run(
["docker", "stats", "--no-stream", "--format", "{{.Name}} {{.MemUsage}}"],
capture_output=True,
text=True,
check=False,
)
for line in result.stdout.splitlines():
if "mtusi-lab4-api" not in line:
continue
name, usage = line.split()[:2]
number = usage.replace("MiB", "").replace("GiB", "")
try:
value = float(number)
except ValueError:
continue
if usage.endswith("GiB"):
value *= 1024
peaks[name] = max(peaks.get(name, 0), value)
time.sleep(0.2)
thread = threading.Thread(target=sample)
thread.start()
errors = []
wide = noisy_png(640, 480)
def once():
try:
upload(alice["token"], room["id"], wide, filename="batch.png")
except SystemExit as exc:
errors.append(str(exc))
workers = [threading.Thread(target=once) for _ in range(10)]
for worker in workers:
worker.start()
for worker in workers:
worker.join()
stop.set()
thread.join()
if errors:
raise SystemExit("concurrent " + errors[0])
print(json.dumps({
"concurrent_uploads": 10,
"upload_bytes": len(wide),
"peak_mib": peaks,
"limit_mib": 256,
}, ensure_ascii=False))
print("PASS files")
if __name__ == "__main__":
main()