Complete Lab 4 attachment service

This commit is contained in:
2026-11-14 02:11:47 +03:00
parent ec540a1a72
commit 1c10525136
36 changed files with 2740 additions and 73 deletions
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""Grade-4 attachment rejection checks; uses only the public HTTP contract."""
import uuid
import json
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, arguments, check, run
def main():
args = arguments("Lab 4 grade-4 negative attachment checks")
client = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = client.bootstrap()
base_path = "/api/v1/chats/" + chat["id"] + "/attachments"
valid_png = (Path(__file__).resolve().parents[1] / "tests/fixtures/sample.png").read_bytes()
too_large = b"\x00" * (10 * 1024 * 1024 + 1)
oversized = client.call(
"POST", base_path + "?filename=large.png", 413,
actor=alice, raw=too_large, headers={"Content-Type": "image/png"},
)
corrupt = client.call(
"POST", base_path + "?filename=broken.png", 415,
actor=alice, raw=b"not a PNG", headers={"Content-Type": "image/png"},
)
spoofed = client.call(
"POST", base_path + "?filename=spoofed.jpg", 415,
actor=alice, raw=valid_png, headers={"Content-Type": "image/jpeg"},
)
unsafe_name = client.call(
"POST", base_path + "?filename=..%2Foutside.png", 400,
actor=alice, raw=valid_png, headers={"Content-Type": "image/png"},
)
client.attachment(alice, chat)
second_chat = client.call(
"POST", "/api/v1/chats", 201, actor=bob,
body={"title": "Другой чат", "member_ids": [bob["id"], eve["id"]]}, schema="Chat",
)["json"]
foreign_attachment, _ = client.attachment(bob, second_chat)
foreign = client.call(
"POST", "/api/v1/chats/" + chat["id"] + "/messages", 404,
actor=alice,
body={"text": "чужое вложение", "attachment_ids": [foreign_attachment["id"]]},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
unknown = client.call(
"POST", "/api/v1/chats/" + chat["id"] + "/messages", 404,
actor=alice,
body={"text": "неизвестное вложение", "attachment_ids": [str(uuid.uuid4())]},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
summary = {
"oversized_upload": oversized["status"],
"corrupt_image": corrupt["status"],
"mime_spoof": spoofed["status"],
"unsafe_filename": unsafe_name["status"],
"foreign_chat_attachment": foreign["status"],
"unknown_attachment": unknown["status"],
"result": "PASS",
}
evidence = Path(__file__).resolve().parents[1] / "evidence/grade4-attachments.json"
evidence.parent.mkdir(parents=True, exist_ok=True)
evidence.write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
print(json.dumps(summary, separators=(",", ":")))
if __name__ == "__main__":
run(main)
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Prove shared message idempotency across concurrent API replicas."""
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import sys
import threading
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, arguments, check, run
def main():
def configure(parser):
parser.add_argument("--workers", type=int, default=12)
parser.add_argument("--requests", type=int, default=24)
args = arguments("Concurrent duplicate message POST across API replicas", configure)
check(args.workers >= 2 and args.requests >= args.workers, "requests must be >= workers >= 2")
setup = Client(args.base_url, args.ca_file, timeout=10)
alice, bob, _eve, chat = setup.bootstrap()
key = uuid.uuid4().hex
body = "parallel-idempotency-" + uuid.uuid4().hex
barrier = threading.Barrier(args.workers)
def send(index):
client = Client(args.base_url, args.ca_file, timeout=10)
if index < args.workers:
barrier.wait(timeout=10)
result = client.message(alice, chat, body, key=key)
return result["json"], result["headers"]["X-Instance-Id"]
with ThreadPoolExecutor(max_workers=args.workers) as pool:
results = list(pool.map(send, range(args.requests)))
messages = [item[0] for item in results]
instances = {item[1] for item in results}
check(all(message == messages[0] for message in messages), "same key/body returned different messages")
check(len(instances) >= 2, "concurrent requests did not reach two API replicas")
history = setup.call(
"GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100",
actor=bob, schema="MessagePage",
)["json"]["items"]
stored = [item for item in history if item["text"] == body]
check(len(stored) == 1, "concurrent duplicate created zero or multiple stored messages")
print(json.dumps({
"parallel_requests": args.requests,
"workers": args.workers,
"replicas_observed": len(instances),
"unique_message_ids": len({item["id"] for item in messages}),
"stored_copies": len(stored),
"result": "PASS",
}, ensure_ascii=False))
if __name__ == "__main__":
run(main)
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env python3
"""Stop RustFS briefly and confirm the API fails closed, then restore it."""
import subprocess
import sys
import time
import json
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, Failure, arguments, check, run
def compose(*args):
return subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=30,
)
def main():
args = arguments("Bounded S3 outage check; stops and restores only the local RustFS service")
client = Client(args.base_url, args.ca_file, timeout=12)
alice, _bob, _eve, chat = client.bootstrap()
stopped = False
results = {}
try:
compose("stop", "s3")
stopped = True
live = client.call("GET", "/health/live", schema="Health")
check(live["json"]["status"] == "ok", "liveness failed during S3 outage")
results["liveness"] = live["status"]
results["readiness_during_outage"] = client.call("GET", "/health/ready", 503)["status"]
image = (Path(__file__).resolve().parents[1] / "tests/fixtures/sample.png").read_bytes()
upload = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments?filename=s3-outage.png",
503,
actor=alice,
raw=image,
headers={"Content-Type": "image/png"},
)
# urllib response headers are an HTTPMessage, not JSON serializable.
# Record only the safe scalar evidence needed for this outage check.
results["upload_during_outage"] = {
"status": upload["status"],
"error_code": upload["json"]["error"]["code"],
"elapsed_seconds": round(upload["elapsed"], 3),
}
finally:
if stopped:
compose("start", "s3")
deadline = time.monotonic() + 90
while True:
try:
client.call("GET", "/health/ready", schema="Health")
break
except Failure:
if time.monotonic() >= deadline:
raise
time.sleep(1)
print("PASS: RustFS is ready again.")
results["readiness_after_restore"] = 200
results["result"] = "PASS"
evidence = Path(__file__).resolve().parents[1] / "evidence/s3-outage.json"
evidence.parent.mkdir(parents=True, exist_ok=True)
evidence.write_text(json.dumps(results, indent=2) + "\n", encoding="utf-8")
print(json.dumps(results, separators=(",", ":")))
if __name__ == "__main__":
run(main)
+129
View File
@@ -0,0 +1,129 @@
#!/usr/bin/env python3
"""Upload ten decoded 3000x3000 PNGs concurrently and sample Docker API memory."""
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
import json
from pathlib import Path
import re
import struct
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
import zlib
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, check
def png_chunk(kind: bytes, payload: bytes) -> bytes:
return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", zlib.crc32(kind + payload) & 0xFFFFFFFF)
def large_decode_png(width=3000, height=3000) -> bytes:
row = b"\x00" + (b"\x28\x80\xc0" * width)
compressor = zlib.compressobj(level=6)
compressed = bytearray()
for _ in range(height):
compressed.extend(compressor.compress(row))
compressed.extend(compressor.flush())
header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", header) + png_chunk(b"IDAT", bytes(compressed)) + png_chunk(b"IEND", b"")
def memory_mib(containers):
result = subprocess.run(
["docker", "stats", "--no-stream", "--format", "{{.ID}}|{{.MemUsage}}", *containers],
check=True, capture_output=True, text=True, timeout=10,
)
samples = {}
for line in result.stdout.splitlines():
fields = line.split("|", 1)
if len(fields) != 2:
continue
number = fields[1].split("/", 1)[0].strip().split()[0]
match = re.fullmatch(r"([0-9.]+)(B|KiB|MiB|GiB)", number)
if not match:
continue
value = float(match.group(1))
value_mib = value * {"GiB": 1024, "MiB": 1, "KiB": 1 / 1024, "B": 1 / (1024 * 1024)}[match.group(2)]
samples[fields[0]] = value_mib
return samples
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default=None)
parser.add_argument("--ca-file", default=None)
parser.add_argument("--concurrency", type=int, default=10)
parser.add_argument("--output", default="evidence/upload-memory.json")
args = parser.parse_args()
check(args.concurrency >= 10, "grade 4 memory run requires at least 10 concurrent clients")
client = Client(args.base_url, args.ca_file, timeout=90)
alice, _bob, _eve, chat = client.bootstrap()
image = large_decode_png()
containers = subprocess.check_output(
["docker", "compose", "--env-file", ".env", "ps", "-q", "api"], text=True, timeout=10,
).split()
check(len(containers) >= 2, "start at least two API replicas behind the load balancer")
before = memory_mib(containers)
peak = dict(before)
stop = threading.Event()
def sample():
while not stop.is_set():
try:
for container, value in memory_mib(containers).items():
peak[container] = max(peak.get(container, 0), value)
except (subprocess.SubprocessError, OSError):
pass
stop.wait(0.25)
monitor = threading.Thread(target=sample, daemon=True)
monitor.start()
path = f"/api/v1/chats/{chat['id']}/attachments?filename=memory-probe.png"
def upload(_index):
request = urllib.request.Request(
client.base + path,
data=image,
headers={"Authorization": "Bearer " + alice["token"], "Content-Type": "image/png"},
method="POST",
)
try:
with client.opener.open(request, timeout=90) as response:
response.read(1024 * 1024)
check(response.status == 201, "upload did not return 201")
return response.headers.get("X-Instance-Id", "")
except urllib.error.HTTPError as exc:
raise AssertionError(f"upload returned HTTP {exc.code}") from None
started = time.monotonic()
successes = []
try:
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
futures = [pool.submit(upload, i) for i in range(args.concurrency)]
for future in as_completed(futures):
successes.append(future.result())
finally:
stop.set()
monitor.join(timeout=3)
report = {
"concurrent_clients": args.concurrency,
"successful_uploads": len(successes),
"decoded_dimensions": [3000, 3000],
"input_bytes": len(image),
"container_memory_mib_before": before,
"container_memory_mib_peak": peak,
"elapsed_seconds": round(time.monotonic() - started, 3),
"observed_instances": sorted({item for item in successes if item}),
}
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
Path(args.output).write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
print(json.dumps(report, separators=(",", ":")))
if __name__ == "__main__":
main()