forked from mtusi2026/mtusi2026lab4
82 lines
3.5 KiB
Python
82 lines
3.5 KiB
Python
"""Negative binary-upload scenarios and concurrent-upload measurement."""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from pathlib import Path
|
|
from urllib.parse import quote
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "tests"))
|
|
from client import Client, check # noqa: E402
|
|
|
|
|
|
def stats(stop, snapshots):
|
|
ids = subprocess.check_output(["docker", "compose", "ps", "-q", "api"], cwd=ROOT, text=True).split()
|
|
while not stop.is_set():
|
|
raw = subprocess.check_output(["docker", "stats", "--no-stream", "--format",
|
|
"{{.Name}} {{.MemUsage}}", *ids], cwd=ROOT, text=True, timeout=12)
|
|
snapshots.append(raw.splitlines())
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--base-url", default="http://localhost:8080")
|
|
parser.add_argument("--docker-stats", action="store_true")
|
|
parser.add_argument("--output", type=Path, default=ROOT / "evidence/uploads.json")
|
|
args = parser.parse_args()
|
|
client = Client(args.base_url, timeout=25)
|
|
actor, peer, outsider, chat = client.bootstrap()
|
|
image = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
|
endpoint = f"/api/v1/chats/{chat['id']}/attachments?filename="
|
|
png = {"Content-Type": "image/png"}
|
|
client.call("POST", endpoint + "bad.png", 415, actor=actor, raw=b"not png", headers=png)
|
|
client.call("POST", endpoint + "wrong.jpg", 415, actor=actor, raw=image,
|
|
headers={"Content-Type": "image/jpeg"})
|
|
client.call("POST", endpoint + quote("../bad.png", safe=""), 400, actor=actor, raw=image, headers=png)
|
|
client.call("POST", endpoint + "too-big.png", 413, actor=actor,
|
|
raw=b"x" * (10 * 1024 * 1024 + 1), headers=png)
|
|
original, _ = client.attachment(actor, chat)
|
|
other = client.call("POST", "/api/v1/chats", 201, actor=outsider,
|
|
body={"title": "Private", "member_ids": [outsider["id"]]}, schema="Chat")["json"]
|
|
path = f"/api/v1/chats/{other['id']}/messages"
|
|
client.call("POST", path, 404, actor=outsider, headers={"Idempotency-Key": "foreign-file"},
|
|
body={"text": "", "attachment_ids": [original["id"]]})
|
|
client.call("GET", f"/api/v1/attachments/{original['id']}", 404, actor=outsider)
|
|
snapshots = []
|
|
stop = threading.Event()
|
|
polling = threading.Thread(target=stats, args=(stop, snapshots)) if args.docker_stats else None
|
|
if polling:
|
|
polling.start()
|
|
barrier = threading.Barrier(10)
|
|
|
|
def send(index):
|
|
local = Client(args.base_url, timeout=25)
|
|
barrier.wait()
|
|
return local.call("POST", endpoint + f"concurrent-{index}.png", 201, actor=actor,
|
|
raw=image, headers=png, schema="Attachment")["elapsed"]
|
|
|
|
started = time.monotonic()
|
|
try:
|
|
with ThreadPoolExecutor(10) as pool:
|
|
observations = list(pool.map(send, range(10)))
|
|
finally:
|
|
stop.set()
|
|
if polling:
|
|
polling.join(timeout=15)
|
|
result = {"uploads": 10, "source_bytes": len(image), "elapsed_s": time.monotonic() - started,
|
|
"request_seconds": observations, "container_memory_samples": snapshots}
|
|
if args.docker_stats:
|
|
check(bool(snapshots), "docker stats did not return any data")
|
|
args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
|
|
print("PASS: upload validation, foreign attachment denied, ten concurrent uploads")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|