yurtaev - lab4

This commit is contained in:
yurtaev.va
2026-11-06 15:43:25 +03:00
parent ec540a1a72
commit 2a88f717f3
22 changed files with 1627 additions and 42 deletions
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""Acceptance checks for the level-5 presigned upload track."""
import hashlib
import json
from pathlib import Path
import urllib.error
import urllib.request
from urllib.parse import urlsplit, urlunsplit
from client import Client, arguments, check, run
def presign(client, actor, chat, content, digest=None):
response = client.call(
"POST", "/api/v1/chats/" + chat["id"] + "/attachments/presign", 201,
actor=actor,
body={
"filename": "direct.png",
"content_type": "image/png",
"size_bytes": len(content),
"sha256": digest or hashlib.sha256(content).hexdigest(),
},
)
return json.loads(response["bytes"])
def put(ticket, content):
request = urllib.request.Request(
ticket["upload_url"], data=content, method="PUT",
headers=ticket["required_headers"],
)
with urllib.request.urlopen(request, timeout=15) as response:
check(response.status == 200, "presigned PUT failed")
def main():
args = arguments("Lab4 direct upload track")
client = Client(args.base_url, args.ca_file)
alice, bob, _, chat = client.bootstrap()
content = (Path(__file__).parent / "fixtures/sample.png").read_bytes()
unfinished = presign(client, alice, chat, content)
client.call(
"POST", "/api/v1/attachments/" + unfinished["attachment_id"] + "/complete", 409,
actor=alice, body={},
)
client.call(
"POST", "/api/v1/attachments/" + unfinished["attachment_id"] + "/complete", 404,
actor=bob, body={},
)
wrong = presign(client, alice, chat, content, "0" * 64)
put(wrong, content)
client.call(
"POST", "/api/v1/attachments/" + wrong["attachment_id"] + "/complete", 409,
actor=alice, body={},
)
ticket = presign(client, alice, chat, content)
put(ticket, content)
ready = client.call(
"POST", "/api/v1/attachments/" + ticket["attachment_id"] + "/complete", 200,
actor=alice, body={}, schema="Attachment",
)["json"]
check(ready["sha256"] == hashlib.sha256(content).hexdigest(), "checksum changed")
downloaded = client.call(
"GET", "/api/v1/attachments/" + ready["id"] + "/content", actor=bob,
)["bytes"]
check(downloaded == content, "direct-uploaded object changed")
parts = urlsplit(ticket["upload_url"])
private_url = urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))
try:
urllib.request.urlopen(private_url, timeout=5)
except urllib.error.HTTPError as error:
check(error.code in (401, 403), "private bucket returned unexpected status")
else:
check(False, "private bucket allowed anonymous GET")
print("PASS: presign, ownership, checksum, completion and private bucket")
if __name__ == "__main__":
run(main)
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Negative and isolation checks required by level 4."""
from pathlib import Path
from urllib.parse import quote
from client import Client, arguments, run
def main():
args = arguments("Lab4 negative upload scenarios")
client = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = client.bootstrap()
base = "/api/v1/chats/" + chat["id"] + "/attachments?filename="
client.call(
"POST", base + "large.png", 413, actor=alice,
raw=b"x" * (10 * 1024 * 1024 + 1), headers={"Content-Type": "image/png"},
)
client.call(
"POST", base + "broken.png", 415, actor=alice,
raw=b"not-an-image", headers={"Content-Type": "image/png"},
)
content = (Path(__file__).parent / "fixtures/sample.png").read_bytes()
client.call(
"POST", base + "spoofed.jpg", 415, actor=alice,
raw=content, headers={"Content-Type": "image/jpeg"},
)
client.call(
"POST", base + quote("../unsafe.png", safe=""), 400, actor=alice,
raw=content, headers={"Content-Type": "image/png"},
)
attachment, _ = client.attachment(alice, chat)
for suffix in ("", "/content"):
client.call("GET", "/api/v1/attachments/" + attachment["id"] + suffix, 404, actor=eve)
other = client.call(
"POST", "/api/v1/chats", 201, actor=alice,
body={"title": "Другой чат", "member_ids": [alice["id"], eve["id"]]}, schema="Chat",
)["json"]
alien, _ = client.attachment(alice, other)
client.call(
"POST", "/api/v1/chats/" + chat["id"] + "/messages", 404, actor=bob,
body={"text": "", "attachment_ids": [alien["id"]]},
headers={"Idempotency-Key": "cross-chat-attachment"},
)
print("PASS: lab4 level-4 negative and authorization scenarios")
if __name__ == "__main__":
run(main)
+143
View File
@@ -0,0 +1,143 @@
#!/usr/bin/env python3
"""Compare API traffic and memory for proxy and presigned uploads."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
from pathlib import Path
import re
import struct
import subprocess
import threading
import time
import urllib.request
import uuid
import zlib
from client import Client, check
def chunk(kind, payload):
return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", zlib.crc32(kind + payload))
def png(width, height):
compressor = zlib.compressobj(level=0)
encoded = bytearray()
row = b"\0" + bytes(range(256)) * ((width * 3 + 255) // 256)
for _ in range(height):
encoded.extend(compressor.compress(row[:width * 3 + 1]))
encoded.extend(compressor.flush())
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + chunk(b"IDAT", bytes(encoded)) + chunk(b"IEND", b"")
def memory_mib():
ids = subprocess.run(
["docker", "compose", "--env-file", ".env", "ps", "-q", "api"],
check=True, capture_output=True, text=True,
).stdout.split()
if not ids:
return 0.0
values = subprocess.run(
["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", *ids],
check=True, capture_output=True, text=True,
).stdout.splitlines()
total = 0.0
for value in values:
match = re.fullmatch(r"([0-9.]+)(KiB|MiB|GiB)", value.split("/")[0].strip())
if match is None:
raise ValueError("unexpected docker stats memory format")
number, unit = match.groups()
factor = {"KiB": 1 / 1024, "MiB": 1, "GiB": 1024}[unit]
total += float(number) * factor
return total
def sample_memory(stop, samples):
while not stop.is_set():
try:
samples.append(memory_mib())
except (OSError, subprocess.SubprocessError, ValueError, KeyError):
pass
stop.wait(0.1)
def proxy(client, actor, chat, content):
client.call(
"POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=bench.png", 201,
actor=actor, raw=content, headers={"Content-Type": "image/png"}, schema="Attachment",
)
def direct(client, actor, chat, content):
ticket = json.loads(client.call(
"POST", "/api/v1/chats/" + chat["id"] + "/attachments/presign", 201,
actor=actor,
body={
"filename": "bench.png", "content_type": "image/png",
"size_bytes": len(content), "sha256": hashlib.sha256(content).hexdigest(),
},
)["bytes"])
request = urllib.request.Request(
ticket["upload_url"], data=content, method="PUT", headers=ticket["required_headers"],
)
with urllib.request.urlopen(request, timeout=60) as response:
check(response.status == 200, "presigned PUT failed")
client.call(
"POST", "/api/v1/attachments/" + ticket["attachment_id"] + "/complete", 200,
actor=actor, body={}, schema="Attachment",
)
def measure(client, actor, chat, content, concurrency, mode):
stop = threading.Event()
samples = []
sampler = threading.Thread(target=sample_memory, args=(stop, samples), daemon=True)
sampler.start()
started = time.monotonic()
with ThreadPoolExecutor(max_workers=concurrency) as pool:
futures = [pool.submit(proxy if mode == "proxy" else direct, client, actor, chat, content)
for _ in range(concurrency)]
for future in futures:
future.result()
elapsed = time.monotonic() - started
stop.set()
sampler.join()
return {
"mode": mode,
"file_bytes": len(content),
"concurrency": concurrency,
"elapsed_seconds": round(elapsed, 3),
"api_upload_body_bytes": len(content) * concurrency if mode == "proxy" else 0,
"api_storage_body_bytes": len(content) * concurrency,
"api_total_binary_bytes": len(content) * concurrency * (2 if mode == "proxy" else 1),
"s3_upload_body_bytes": len(content) * concurrency,
"api_replicas_peak_memory_mib": round(max(samples), 3) if samples else None,
"sample_count": len(samples),
}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--concurrency", type=int, default=10)
parser.add_argument("--output", default="evidence/upload_benchmark.json")
args = parser.parse_args()
client = Client(args.base_url, timeout=90)
alice, _, _, chat = client.bootstrap()
results = []
for content in (png(600, 600), png(1600, 1600)):
for mode in ("proxy", "direct"):
results.append(measure(client, alice, chat, content, args.concurrency, mode))
output = {
"run_id": uuid.uuid4().hex,
"method": "closed-loop, same valid PNG shared by 10 client threads; 100 ms docker-stats sampling",
"results": results,
}
Path(args.output).write_text(json.dumps(output, indent=2) + "\n", encoding="utf-8")
print(json.dumps(output, indent=2))
if __name__ == "__main__":
main()