forked from mtusi2026/mtusi2026lab6
Перенести рабочую реализацию lab5 в skeleton лабораторной 6.
API, worker, брокер и стенд остаются базой, контракт lab6 не менялся.
This commit is contained in:
@@ -0,0 +1,323 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Negative attachment cases. Prints statuses only, never tokens."""
|
||||
|
||||
import os
|
||||
import base64
|
||||
from urllib.parse import urlparse
|
||||
import hashlib
|
||||
import json
|
||||
import socket
|
||||
import struct
|
||||
import time
|
||||
import uuid
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
JPEG = base64.b64decode(
|
||||
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAIAAgDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD5soooroMD/9k="
|
||||
)
|
||||
|
||||
|
||||
def header_only_png(width: int, height: int) -> bytes:
|
||||
signature = b"\x89PNG\r\n\x1a\n"
|
||||
|
||||
def chunk(kind: bytes, data: bytes) -> bytes:
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||||
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return signature + chunk(b"IHDR", ihdr) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def png(width: int, height: int) -> bytes:
|
||||
signature = b"\x89PNG\r\n\x1a\n"
|
||||
|
||||
def chunk(kind: bytes, data: bytes) -> bytes:
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||||
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
raw = b"".join(b"\x00" + (b"\x10\x20\x30" * width) for _ in range(height))
|
||||
return signature + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
class Api:
|
||||
def __init__(self) -> None:
|
||||
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
|
||||
def call(self, method, path, body=None, token=None, headers=None, raw=None, content_type=None):
|
||||
hdrs = {}
|
||||
data = raw
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode("utf-8")
|
||||
hdrs["Content-Type"] = "application/json"
|
||||
if content_type:
|
||||
hdrs["Content-Type"] = content_type
|
||||
if token:
|
||||
hdrs["Authorization"] = "Bearer " + token
|
||||
if headers:
|
||||
hdrs.update(headers)
|
||||
request = urllib.request.Request(BASE + path, data=data, headers=hdrs, method=method)
|
||||
try:
|
||||
response = self.opener.open(request, timeout=30)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
payload = response.read()
|
||||
parsed = None
|
||||
if payload and response.headers.get_content_type() == "application/json":
|
||||
parsed = json.loads(payload)
|
||||
return response.status, response.headers, parsed, payload
|
||||
|
||||
|
||||
def wait_ready(api: Api, attachment_id: str, token: str):
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
status, _, body, _ = api.call("GET", "/api/v1/attachments/" + attachment_id, token=token)
|
||||
expect(200, status, "poll attachment")
|
||||
if body["status"] == "failed":
|
||||
raise SystemExit("FAIL attachment failed")
|
||||
if body["status"] == "ready":
|
||||
return body
|
||||
time.sleep(0.3)
|
||||
raise SystemExit("FAIL attachment did not become ready")
|
||||
|
||||
|
||||
def expect(status, got, label):
|
||||
if got == 500:
|
||||
raise SystemExit("FAIL %s returned 500" % label)
|
||||
if got != status:
|
||||
raise SystemExit("FAIL %s expected %s got %s" % (label, status, got))
|
||||
print("PASS", label, got)
|
||||
|
||||
|
||||
def user(api: Api, label: str):
|
||||
username = "g4_" + label + "_" + uuid.uuid4().hex[:10]
|
||||
password = "T3st-" + uuid.uuid4().hex
|
||||
status, _, body, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": username, "display_name": "Grade " + label, "password": password},
|
||||
)
|
||||
expect(201, status, "register " + label)
|
||||
basic = base64.b64encode((username + ":" + password).encode()).decode()
|
||||
status, _, session, _ = api.call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic})
|
||||
expect(201, status, "login " + label)
|
||||
return body["id"], session["token"]
|
||||
|
||||
|
||||
def declared_length(token, chat_id):
|
||||
parsed = urlparse(BASE)
|
||||
host = parsed.netloc or "127.0.0.1:8080"
|
||||
request = (
|
||||
"POST /api/v1/chats/%s/attachments?filename=big.png HTTP/1.1\r\n"
|
||||
"Host: %s\r\n"
|
||||
"Authorization: Bearer %s\r\n"
|
||||
"Content-Type: image/png\r\n"
|
||||
"Content-Length: 10485761\r\n"
|
||||
"Connection: close\r\n\r\n" % (chat_id, host, token)
|
||||
).encode() + b"\x89PNG"
|
||||
sock = socket.create_connection((parsed.hostname or "127.0.0.1", parsed.port or 80), timeout=5)
|
||||
try:
|
||||
sock.sendall(request)
|
||||
data = b""
|
||||
while b"\r\n" not in data:
|
||||
chunk = sock.recv(256)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
finally:
|
||||
sock.close()
|
||||
line = data.split(b"\r\n", 1)[0].decode("latin1", "replace")
|
||||
code = int(line.split()[1])
|
||||
expect(413, code, "content-length above 10MiB before body is read")
|
||||
|
||||
|
||||
def main():
|
||||
api = Api()
|
||||
alice, alice_token = user(api, "alice")
|
||||
bob, bob_token = user(api, "bob")
|
||||
eve, eve_token = user(api, "eve")
|
||||
status, _, chat, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{"title": "grade4", "member_ids": [alice, bob]},
|
||||
token=alice_token,
|
||||
)
|
||||
expect(201, status, "create chat")
|
||||
chat_id = chat["id"]
|
||||
status, _, other, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{"title": "other", "member_ids": [alice, eve]},
|
||||
token=alice_token,
|
||||
)
|
||||
expect(201, status, "create other chat")
|
||||
|
||||
status, _, message, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/messages" % chat_id,
|
||||
{"text": "только текст"},
|
||||
token=alice_token,
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
expect(201, status, "text message")
|
||||
if message["attachment_ids"] != []:
|
||||
raise SystemExit("FAIL text message lost empty attachment_ids")
|
||||
|
||||
good = png(32, 32)
|
||||
status, _, attachment, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=ok.png" % chat_id,
|
||||
token=alice_token,
|
||||
raw=good,
|
||||
content_type="image/png",
|
||||
)
|
||||
expect(202, status, "png upload")
|
||||
if attachment["sha256"] != hashlib.sha256(good).hexdigest() or attachment["status"] != "queued":
|
||||
raise SystemExit("FAIL png metadata")
|
||||
attachment = wait_ready(api, attachment["id"], bob_token)
|
||||
status, headers, _, downloaded = api.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/%s/content" % attachment["id"],
|
||||
token=bob_token,
|
||||
)
|
||||
expect(200, status, "member download")
|
||||
if downloaded != good or headers.get_content_type() != "image/png":
|
||||
raise SystemExit("FAIL download bytes")
|
||||
if headers.get("Location"):
|
||||
raise SystemExit("FAIL download redirected")
|
||||
|
||||
status, _, jpeg_meta, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=ok.jpg" % chat_id,
|
||||
token=alice_token,
|
||||
raw=JPEG,
|
||||
content_type="image/jpeg",
|
||||
)
|
||||
expect(202, status, "jpeg upload")
|
||||
if jpeg_meta["content_type"] != "image/jpeg" or jpeg_meta["sha256"] != hashlib.sha256(JPEG).hexdigest():
|
||||
raise SystemExit("FAIL jpeg metadata")
|
||||
|
||||
status, _, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=a/b.png" % chat_id,
|
||||
token=alice_token,
|
||||
raw=good,
|
||||
content_type="image/png",
|
||||
)
|
||||
expect(400, status, "filename with slash")
|
||||
status, _, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=%s" % (chat_id, "bad%0Aname.png"),
|
||||
token=alice_token,
|
||||
raw=good,
|
||||
content_type="image/png",
|
||||
)
|
||||
expect(400, status, "filename with control character")
|
||||
|
||||
status, _, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=lie.png" % chat_id,
|
||||
token=alice_token,
|
||||
raw=good,
|
||||
content_type="image/jpeg",
|
||||
)
|
||||
expect(415, status, "png bytes declared as jpeg")
|
||||
status, _, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=cut.png" % chat_id,
|
||||
token=alice_token,
|
||||
raw=b"\x89PNG\r\n\x1a\ntruncated",
|
||||
content_type="image/png",
|
||||
)
|
||||
expect(415, status, "truncated png")
|
||||
status, _, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=cut.jpg" % chat_id,
|
||||
token=alice_token,
|
||||
raw=JPEG[:-40],
|
||||
content_type="image/jpeg",
|
||||
)
|
||||
expect(415, status, "truncated jpeg")
|
||||
status, _, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=huge.png" % chat_id,
|
||||
token=alice_token,
|
||||
raw=header_only_png(10000, 5000),
|
||||
content_type="image/png",
|
||||
)
|
||||
expect(413, status, "pixel limit")
|
||||
declared_length(alice_token, chat_id)
|
||||
status, _, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=big.png" % chat_id,
|
||||
token=alice_token,
|
||||
raw=b"\x89PNG" + b"\x00" * (10_485_760),
|
||||
content_type="image/png",
|
||||
)
|
||||
expect(413, status, "body above 10MiB")
|
||||
|
||||
status, _, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=nope.png" % chat_id,
|
||||
token=eve_token,
|
||||
raw=good,
|
||||
content_type="image/png",
|
||||
)
|
||||
expect(404, status, "outsider upload")
|
||||
for suffix in ("", "/content"):
|
||||
status, _, _, _ = api.call("GET", "/api/v1/attachments/%s%s" % (attachment["id"], suffix), token=eve_token)
|
||||
expect(404, status, "outsider get " + (suffix or "metadata"))
|
||||
|
||||
missing = str(uuid.uuid4())
|
||||
status, _, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/messages" % chat_id,
|
||||
{"text": "", "attachment_ids": [missing]},
|
||||
token=alice_token,
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
expect(404, status, "unknown attachment id")
|
||||
status, _, foreign, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=other.png" % other["id"],
|
||||
token=alice_token,
|
||||
raw=good,
|
||||
content_type="image/png",
|
||||
)
|
||||
expect(202, status, "upload into other chat")
|
||||
status, _, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/messages" % chat_id,
|
||||
{"text": "", "attachment_ids": [foreign["id"]]},
|
||||
token=alice_token,
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
expect(404, status, "attachment from another chat")
|
||||
ids = [str(uuid.uuid4()) for _ in range(11)]
|
||||
status, _, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/messages" % chat_id,
|
||||
{"text": "x", "attachment_ids": ids},
|
||||
token=alice_token,
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
expect(400, status, "more than 10 attachment ids")
|
||||
status, _, linked, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/messages" % chat_id,
|
||||
{"text": "", "attachment_ids": [attachment["id"]]},
|
||||
token=bob_token,
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
expect(201, status, "message with attachment")
|
||||
if linked["attachment_ids"] != [attachment["id"]] or linked["text"] != "":
|
||||
raise SystemExit("FAIL linked message")
|
||||
print("PASS grade4 api checks")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,232 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Private bucket, orphan grace, and a bounded concurrent-upload memory sample."""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / "evidence" / "grade4-infra.json"
|
||||
|
||||
|
||||
def compose(*args, input_text=None):
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=ROOT,
|
||||
input=input_text,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise SystemExit(result.stderr[-500:] or result.stdout[-500:] or "compose failed")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def anonymous_status():
|
||||
script = r"""
|
||||
code=$(wget -S -O /dev/null http://127.0.0.1:9000/messenger-attachments/ 2>&1 | awk 'BEGIN{c=""} /^[[:space:]]*HTTP\//{c=$2} END{print c}')
|
||||
printf '%s' "$code"
|
||||
"""
|
||||
output = compose("exec", "-T", "s3", "sh", "-c", script).strip()
|
||||
if output != "403":
|
||||
raise SystemExit("anonymous bucket status %s" % output)
|
||||
return output
|
||||
|
||||
|
||||
def other_bucket_denied():
|
||||
code = r"""
|
||||
import os
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
from botocore.exceptions import ClientError
|
||||
client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=os.environ["S3_ENDPOINT"],
|
||||
aws_access_key_id=os.environ["S3_ACCESS_KEY_ID"],
|
||||
aws_secret_access_key=os.environ["S3_SECRET_ACCESS_KEY"],
|
||||
region_name=os.environ.get("S3_REGION", "us-east-1"),
|
||||
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
|
||||
)
|
||||
try:
|
||||
client.create_bucket(Bucket="not-the-messenger-bucket")
|
||||
print("allowed")
|
||||
except ClientError as exc:
|
||||
print(exc.response.get("Error", {}).get("Code", "denied"))
|
||||
"""
|
||||
output = compose("exec", "-T", "api", "python", "-c", code).strip()
|
||||
if output == "allowed":
|
||||
raise SystemExit("app credentials created a second bucket")
|
||||
return output
|
||||
|
||||
|
||||
def plant_and_sweep():
|
||||
code = r"""
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from app import config, db, s3
|
||||
|
||||
async def main():
|
||||
await db.connect()
|
||||
old_key = "originals/orphan-evidence"
|
||||
fresh_key = "originals/fresh-evidence"
|
||||
payload = b"not-a-real-image"
|
||||
await s3.put_bytes(old_key, payload, "application/octet-stream")
|
||||
await s3.put_bytes(fresh_key, payload, "application/octet-stream")
|
||||
old = datetime.now(timezone.utc) - timedelta(seconds=config.ORPHAN_GRACE_SECONDS + 60)
|
||||
fresh = datetime.now(timezone.utc)
|
||||
async with db.require().acquire() as conn:
|
||||
await conn.execute("DELETE FROM blob_writes WHERE object_key = ANY($1::text[])", [old_key, fresh_key])
|
||||
await conn.execute(
|
||||
"INSERT INTO blob_writes (object_key, committed, created_at) VALUES ($1, FALSE, $2), ($3, FALSE, $4)",
|
||||
old_key, old, fresh_key, fresh,
|
||||
)
|
||||
from app.attachments import sweep_orphans
|
||||
deleted = await sweep_orphans()
|
||||
async def exists(key):
|
||||
try:
|
||||
await s3.get_bytes(key)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
print("%s %s %s" % (deleted, int(await exists(old_key)), int(await exists(fresh_key))))
|
||||
await s3.delete_key(fresh_key)
|
||||
async with db.require().acquire() as conn:
|
||||
await conn.execute("DELETE FROM blob_writes WHERE object_key = $1 AND NOT committed", fresh_key)
|
||||
await db.close()
|
||||
|
||||
asyncio.run(main())
|
||||
"""
|
||||
output = compose("exec", "-T", "api", "python", "-c", code).strip().split()
|
||||
deleted, old_exists, fresh_exists = int(output[0]), int(output[1]), int(output[2])
|
||||
if deleted < 1 or old_exists != 0 or fresh_exists != 1:
|
||||
raise SystemExit("sweep result deleted=%s old=%s fresh=%s" % (deleted, old_exists, fresh_exists))
|
||||
return {"deleted": deleted, "old_removed": True, "fresh_kept": True}
|
||||
|
||||
|
||||
def memory_sample():
|
||||
import base64
|
||||
|
||||
username = "mem_" + uuid.uuid4().hex[:10]
|
||||
password = "T3st-" + uuid.uuid4().hex
|
||||
body = json.dumps({"username": username, "display_name": "Mem", "password": password}).encode()
|
||||
|
||||
def call(method, path, data=None, headers=None):
|
||||
request = urllib.request.Request("http://127.0.0.1:8080" + path, data=data, headers=headers or {}, method=method)
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=60)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
return response.status, response.read()
|
||||
|
||||
status, raw = call("POST", "/api/v1/users", body, {"Content-Type": "application/json"})
|
||||
if status != 201:
|
||||
raise SystemExit("memory user %s" % status)
|
||||
user = json.loads(raw)
|
||||
basic = base64.b64encode((username + ":" + password).encode()).decode()
|
||||
status, raw = call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic})
|
||||
if status != 201:
|
||||
raise SystemExit("memory login %s" % status)
|
||||
token = json.loads(raw)["token"]
|
||||
status, raw = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
json.dumps({"title": "mem", "member_ids": [user["id"]]}).encode(),
|
||||
{"Content-Type": "application/json", "Authorization": "Bearer " + token},
|
||||
)
|
||||
if status != 201:
|
||||
raise SystemExit("memory chat %s" % status)
|
||||
chat_id = json.loads(raw)["id"]
|
||||
import os
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
def png():
|
||||
signature = b"\x89PNG\r\n\x1a\n"
|
||||
|
||||
def chunk(kind, data):
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||||
|
||||
width, height = 320, 240
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
raw_rows = b"".join(b"\x00" + os.urandom(width * 3) for _ in range(height))
|
||||
return signature + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw_rows, 1)) + chunk(b"IEND", b"")
|
||||
|
||||
blob = png()
|
||||
codes = []
|
||||
|
||||
def upload():
|
||||
status, _ = call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=m.png" % chat_id,
|
||||
blob,
|
||||
{"Content-Type": "image/png", "Authorization": "Bearer " + token},
|
||||
)
|
||||
codes.append(status)
|
||||
|
||||
samples = []
|
||||
|
||||
def watch():
|
||||
end = time.monotonic() + 8
|
||||
while time.monotonic() < end:
|
||||
stats = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{.Name}} {{.MemUsage}}"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
for line in stats.stdout.splitlines():
|
||||
if "mtusi2026lab6-api-" in line:
|
||||
samples.append(line.strip())
|
||||
time.sleep(0.4)
|
||||
|
||||
watcher = threading.Thread(target=watch)
|
||||
watcher.start()
|
||||
threads = [threading.Thread(target=upload) for _ in range(10)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
watcher.join()
|
||||
if codes.count(202) != 10:
|
||||
raise SystemExit("concurrent uploads %s" % codes)
|
||||
|
||||
def mib(line):
|
||||
value = line.split()[1]
|
||||
number = float(value[:-3]) if value.lower().endswith("mib") else float(value[:-3]) / 1024
|
||||
return number
|
||||
|
||||
peak = max(mib(line) for line in samples) if samples else 0
|
||||
return {"uploads": 10, "bytes_each": len(blob), "success": 10, "peak_api_mib": round(peak, 1), "samples": len(samples)}
|
||||
|
||||
|
||||
def main():
|
||||
published = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", "port", "s3", "9000"],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
binding = published.stdout.strip()
|
||||
if published.returncode == 0 and binding and not binding.startswith("127.0.0.1:"):
|
||||
raise SystemExit("s3 port is published outside loopback: " + binding)
|
||||
summary = {
|
||||
"anonymous_bucket_status": anonymous_status(),
|
||||
"second_bucket": other_bucket_denied(),
|
||||
"sweep": plant_and_sweep(),
|
||||
"s3_port_published": binding or False,
|
||||
"memory": memory_sample(),
|
||||
}
|
||||
OUT.parent.mkdir(exist_ok=True)
|
||||
OUT.write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps(summary, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import urllib.error
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab5 fault checks: worker down, content 409, then the same upload reaches ready.
|
||||
|
||||
Prints statuses and ids only. Does not print tokens.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
|
||||
FIXTURE = ROOT / "tests" / "fixtures" / "sample.png"
|
||||
|
||||
|
||||
def compose(*args: str) -> None:
|
||||
command = ["docker", "compose", "--env-file", ".env"]
|
||||
extra = os.environ.get("LAB5_COMPOSE_FILES", "")
|
||||
if extra:
|
||||
for name in extra.split(os.pathsep):
|
||||
if name:
|
||||
command.extend(["-f", name])
|
||||
subprocess.run([*command, *args], cwd=ROOT, check=True)
|
||||
|
||||
|
||||
class Api:
|
||||
def __init__(self) -> None:
|
||||
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
|
||||
def call(self, method, path, body=None, token=None, raw=None, content_type=None, headers=None):
|
||||
hdrs = dict(headers or {})
|
||||
data = raw
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode("utf-8")
|
||||
hdrs["Content-Type"] = "application/json"
|
||||
if content_type:
|
||||
hdrs["Content-Type"] = content_type
|
||||
if token:
|
||||
hdrs["Authorization"] = "Bearer " + token
|
||||
request = urllib.request.Request(BASE + path, data=data, headers=hdrs, method=method)
|
||||
try:
|
||||
response = self.opener.open(request, timeout=30)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
payload = response.read()
|
||||
parsed = json.loads(payload) if payload and response.headers.get_content_type() == "application/json" else None
|
||||
return response.status, parsed, payload
|
||||
|
||||
|
||||
def expect(status, got, label):
|
||||
if got != status:
|
||||
raise SystemExit("FAIL %s expected %s got %s" % (label, status, got))
|
||||
print("PASS", label, got)
|
||||
|
||||
|
||||
def user(api: Api):
|
||||
username = "l5_" + uuid.uuid4().hex[:10]
|
||||
password = "T3st-" + uuid.uuid4().hex
|
||||
status, body, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": username, "display_name": "Lab5", "password": password},
|
||||
)
|
||||
expect(201, status, "register")
|
||||
basic = base64.b64encode((username + ":" + password).encode()).decode()
|
||||
status, session, _ = api.call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic})
|
||||
expect(201, status, "login")
|
||||
return body["id"], session["token"]
|
||||
|
||||
|
||||
def wait_ready(api: Api, attachment_id: str, token: str):
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
status, body, _ = api.call("GET", "/api/v1/attachments/" + attachment_id, token=token)
|
||||
expect(200, status, "poll")
|
||||
if body["status"] == "failed":
|
||||
raise SystemExit("FAIL attachment failed " + str(body.get("error_code")))
|
||||
if body["status"] == "ready":
|
||||
return body
|
||||
time.sleep(0.4)
|
||||
raise SystemExit("FAIL not ready")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
api = Api()
|
||||
alice, alice_token = user(api)
|
||||
bob, bob_token = user(api)
|
||||
status, chat, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{"title": "lab5", "member_ids": [alice, bob]},
|
||||
token=alice_token,
|
||||
)
|
||||
expect(201, status, "chat")
|
||||
chat_id = chat["id"]
|
||||
print("chat", chat_id)
|
||||
|
||||
compose("stop", "worker")
|
||||
content = FIXTURE.read_bytes()
|
||||
status, attachment, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=sample.png" % chat_id,
|
||||
token=alice_token,
|
||||
raw=content,
|
||||
content_type="image/png",
|
||||
)
|
||||
expect(202, status, "upload while worker is stopped")
|
||||
if attachment["status"] != "queued" or attachment["sha256"] != hashlib.sha256(content).hexdigest():
|
||||
raise SystemExit("FAIL queued metadata")
|
||||
print("attachment", attachment["id"])
|
||||
status, _, _ = api.call("GET", "/api/v1/attachments/%s/content" % attachment["id"], token=bob_token)
|
||||
expect(409, status, "content before ready")
|
||||
status, message, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/messages" % chat_id,
|
||||
{"text": "очередь не блокирует чат", "attachment_ids": [attachment["id"]]},
|
||||
token=alice_token,
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
expect(201, status, "message while queued")
|
||||
if message["attachment_ids"] != [attachment["id"]]:
|
||||
raise SystemExit("FAIL queued attachment was not linkable")
|
||||
|
||||
compose("start", "worker")
|
||||
ready = wait_ready(api, attachment["id"], bob_token)
|
||||
thumbs = [item for item in ready["variants"] if item["name"] == "thumbnail"]
|
||||
if len(thumbs) != 1 or (thumbs[0]["width"], thumbs[0]["height"]) != (256, 160):
|
||||
raise SystemExit("FAIL thumbnail metadata %s" % thumbs)
|
||||
names = sorted(item["name"] for item in ready["variants"])
|
||||
if names != ["crop", "optimized", "thumbnail"]:
|
||||
raise SystemExit("FAIL variants %s" % names)
|
||||
status, _, payload = api.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/%s/content?variant=thumbnail" % attachment["id"],
|
||||
token=bob_token,
|
||||
)
|
||||
expect(200, status, "thumbnail bytes")
|
||||
if hashlib.sha256(payload).hexdigest() != thumbs[0]["sha256"]:
|
||||
raise SystemExit("FAIL thumbnail checksum")
|
||||
print("PASS lab5 worker-down upload became ready", attachment["id"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
# Restart API replicas and every store they use. Volumes are kept.
|
||||
set -eu
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
if [ -f .env ]; then
|
||||
docker compose --env-file .env restart postgres redis s3 rabbitmq api worker
|
||||
else
|
||||
docker compose restart postgres redis s3 rabbitmq api worker
|
||||
fi
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/bin/sh
|
||||
# Replace API replicas one at a time. The other replica keeps serving.
|
||||
set -eu
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
|
||||
compose() {
|
||||
if [ -f .env ]; then
|
||||
docker compose --env-file .env "$@"
|
||||
else
|
||||
docker compose "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
if command -v python3 >/dev/null 2>&1; then
|
||||
PY=python3
|
||||
else
|
||||
PY=python
|
||||
fi
|
||||
|
||||
ids=$(compose ps -q api)
|
||||
count=0
|
||||
for id in $ids; do
|
||||
count=$((count + 1))
|
||||
done
|
||||
if [ "$count" -lt 2 ]; then
|
||||
echo "rolling update needs at least 2 running API replicas" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for id in $ids; do
|
||||
echo "replacing $(docker inspect -f '{{.Config.Hostname}}' "$id")"
|
||||
docker stop -t 8 "$id" >/dev/null
|
||||
docker rm "$id" >/dev/null
|
||||
compose up -d --scale "api=$count" --no-deps --no-recreate api >/dev/null
|
||||
ready=0
|
||||
i=0
|
||||
while [ "$i" -lt 40 ]; do
|
||||
running=0
|
||||
for cid in $(compose ps -q api); do
|
||||
running=$((running + 1))
|
||||
done
|
||||
if [ "$running" -ge "$count" ] && "$PY" -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2)" >/dev/null 2>&1; then
|
||||
ready=1
|
||||
break
|
||||
fi
|
||||
i=$((i + 1))
|
||||
sleep 1
|
||||
done
|
||||
if [ "$ready" -ne 1 ]; then
|
||||
echo "replacement did not become ready" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
echo "rolling update finished; replicas=$count"
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/bin/sh
|
||||
# Stop the single API replica whose X-Instance-Id is TARGET_INSTANCE_ID.
|
||||
# Leaves it stopped. Does not touch the database, Redis, the load balancer, or volumes.
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
|
||||
compose() {
|
||||
if [ -f .env ]; then
|
||||
docker compose --env-file .env "$@"
|
||||
else
|
||||
docker compose "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
found=0
|
||||
for id in $(compose ps -q api); do
|
||||
iid=$(docker exec "$id" cat /tmp/instance-id 2>/dev/null | tr -d '\r\n' || true)
|
||||
host=$(docker inspect -f '{{.Config.Hostname}}' "$id")
|
||||
if [ "$iid" = "$TARGET_INSTANCE_ID" ] || [ "$host" = "$TARGET_INSTANCE_ID" ]; then
|
||||
docker stop -t 5 "$id" >/dev/null
|
||||
found=1
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$found" -ne 1 ]; then
|
||||
echo "no running API replica matched TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
# Stop the worker and leave it stopped. The broker, API and volumes keep running.
|
||||
set -eu
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
if [ -f .env ]; then
|
||||
docker compose --env-file .env stop worker
|
||||
else
|
||||
docker compose stop worker
|
||||
fi
|
||||
@@ -0,0 +1,394 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Track 1: presigned upload, negative cases, API traffic and RAM at two sizes.
|
||||
|
||||
The signed URL is never written to the evidence file.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
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
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / "evidence" / "track1.json"
|
||||
BASE = "http://127.0.0.1:8080"
|
||||
|
||||
|
||||
def expect(status, got, label):
|
||||
if got == 500:
|
||||
raise SystemExit("FAIL %s returned 500" % label)
|
||||
if got != status:
|
||||
raise SystemExit("FAIL %s expected %s got %s" % (label, status, got))
|
||||
|
||||
|
||||
def wait_ready(api, attachment_id, token):
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
status, body, _ = api.call("GET", "/api/v1/attachments/" + attachment_id, token=token)
|
||||
expect(200, status, "poll attachment")
|
||||
if body["status"] == "failed":
|
||||
raise SystemExit("FAIL attachment failed")
|
||||
if body["status"] == "ready":
|
||||
return body
|
||||
time.sleep(0.3)
|
||||
raise SystemExit("FAIL attachment did not become ready")
|
||||
print("PASS", label, got)
|
||||
|
||||
|
||||
class Api:
|
||||
def __init__(self) -> None:
|
||||
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
|
||||
def call(self, method, path, body=None, token=None, raw=None, content_type=None):
|
||||
headers = {}
|
||||
data = raw
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode("utf-8")
|
||||
headers["Content-Type"] = "application/json"
|
||||
if content_type:
|
||||
headers["Content-Type"] = content_type
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
request = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
|
||||
try:
|
||||
response = self.opener.open(request, timeout=60)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
payload = response.read()
|
||||
parsed = None
|
||||
if payload and response.headers.get_content_type() == "application/json":
|
||||
parsed = json.loads(payload)
|
||||
return response.status, parsed, payload
|
||||
|
||||
|
||||
def png(width: int, height: int) -> bytes:
|
||||
signature = b"\x89PNG\r\n\x1a\n"
|
||||
|
||||
def chunk(kind: bytes, data: bytes) -> bytes:
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||||
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
raw = b"".join(b"\x00" + os.urandom(width * 3) for _ in range(height))
|
||||
return signature + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw, 1)) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def put_signed(url: str, data: bytes, content_type: str) -> int:
|
||||
request = urllib.request.Request(url, data=data, method="PUT", headers={"Content-Type": content_type})
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=60)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
response.read()
|
||||
return response.status
|
||||
|
||||
|
||||
def api_rx() -> int:
|
||||
ids = subprocess.check_output(
|
||||
["docker", "compose", "--env-file", ".env", "ps", "-q", "api"],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
).split()
|
||||
total = 0
|
||||
for container_id in ids:
|
||||
raw = subprocess.check_output(["docker", "exec", container_id, "cat", "/proc/net/dev"], text=True)
|
||||
for line in raw.splitlines():
|
||||
if "eth0" not in line:
|
||||
continue
|
||||
total += int(line.split()[1])
|
||||
return total
|
||||
|
||||
|
||||
def peak_during(action):
|
||||
peaks = []
|
||||
stop = threading.Event()
|
||||
|
||||
def watch():
|
||||
while not stop.is_set():
|
||||
stats = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{.Name}} {{.MemUsage}}"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
for line in stats.stdout.splitlines():
|
||||
if "mtusi2026lab6-api-" not in line:
|
||||
continue
|
||||
value = line.split()[1]
|
||||
number = float(value[:-3])
|
||||
if not value.lower().endswith("mib"):
|
||||
number = number / 1024
|
||||
peaks.append(number)
|
||||
time.sleep(0.25)
|
||||
|
||||
thread = threading.Thread(target=watch)
|
||||
thread.start()
|
||||
before = api_rx()
|
||||
result = action()
|
||||
after = api_rx()
|
||||
time.sleep(0.3)
|
||||
stop.set()
|
||||
thread.join()
|
||||
return {"rx_bytes": after - before, "peak_api_mib": round(max(peaks) if peaks else 0, 1), "result": result}
|
||||
|
||||
|
||||
def compose_psql(sql: str) -> None:
|
||||
subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-c", sql],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
def negatives(api, alice_token, bob_token, eve_token, chat_id):
|
||||
small = png(16, 16)
|
||||
status, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/uploads" % chat_id,
|
||||
{"filename": "a/b.png", "content_type": "image/png", "size_bytes": len(small)},
|
||||
token=alice_token,
|
||||
)
|
||||
expect(400, status, "direct filename")
|
||||
status, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/uploads" % chat_id,
|
||||
{"filename": "big.png", "content_type": "image/png", "size_bytes": 10485761},
|
||||
token=alice_token,
|
||||
)
|
||||
expect(413, status, "direct declared size")
|
||||
status, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/uploads" % chat_id,
|
||||
{"filename": "x.png", "content_type": "image/png", "size_bytes": len(small)},
|
||||
token=eve_token,
|
||||
)
|
||||
expect(404, status, "outsider presign")
|
||||
|
||||
status, started, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/uploads" % chat_id,
|
||||
{"filename": "wait.png", "content_type": "image/png", "size_bytes": len(small)},
|
||||
token=alice_token,
|
||||
)
|
||||
expect(201, status, "presign for incomplete")
|
||||
status, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/uploads/%s/complete" % started["upload_id"],
|
||||
{"sha256": hashlib.sha256(small).hexdigest()},
|
||||
token=alice_token,
|
||||
)
|
||||
expect(409, status, "complete before PUT")
|
||||
status, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/uploads/%s/complete" % started["upload_id"],
|
||||
{"sha256": hashlib.sha256(small).hexdigest()},
|
||||
token=bob_token,
|
||||
)
|
||||
expect(404, status, "complete by another member")
|
||||
|
||||
tampered = put_signed(started["url"] + "x", small, "image/png")
|
||||
if tampered == 200:
|
||||
raise SystemExit("FAIL tampered signature was accepted")
|
||||
print("PASS tampered signature", tampered)
|
||||
|
||||
status, started, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/uploads" % chat_id,
|
||||
{"filename": "badsum.png", "content_type": "image/png", "size_bytes": len(small)},
|
||||
token=alice_token,
|
||||
)
|
||||
expect(201, status, "presign for bad checksum")
|
||||
if put_signed(started["url"], small, "image/png") != 200:
|
||||
raise SystemExit("FAIL signed PUT")
|
||||
status, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/uploads/%s/complete" % started["upload_id"],
|
||||
{"sha256": "0" * 64},
|
||||
token=alice_token,
|
||||
)
|
||||
expect(400, status, "wrong checksum")
|
||||
status, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/uploads/%s/complete" % started["upload_id"],
|
||||
{"sha256": hashlib.sha256(small).hexdigest()},
|
||||
token=alice_token,
|
||||
)
|
||||
expect(409, status, "complete after rejected checksum")
|
||||
|
||||
status, started, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/uploads" % chat_id,
|
||||
{"filename": "late.png", "content_type": "image/png", "size_bytes": len(small)},
|
||||
token=alice_token,
|
||||
)
|
||||
expect(201, status, "presign for expiry")
|
||||
compose_psql(
|
||||
"UPDATE direct_uploads SET expires_at = now() - interval '5 minutes' WHERE id = '%s'"
|
||||
% started["upload_id"]
|
||||
)
|
||||
status, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/uploads/%s/complete" % started["upload_id"],
|
||||
{"sha256": hashlib.sha256(small).hexdigest()},
|
||||
token=alice_token,
|
||||
)
|
||||
expect(409, status, "expired upload")
|
||||
|
||||
digest = hashlib.sha256(small).hexdigest()
|
||||
status, started, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/uploads" % chat_id,
|
||||
{"filename": "ok.png", "content_type": "image/png", "size_bytes": len(small)},
|
||||
token=alice_token,
|
||||
)
|
||||
expect(201, status, "presign happy path")
|
||||
if "originals/" in json.dumps({k: v for k, v in started.items() if k != "url"}):
|
||||
raise SystemExit("FAIL object key leaked outside the signed URL")
|
||||
if put_signed(started["url"], small, "image/png") != 200:
|
||||
raise SystemExit("FAIL happy PUT")
|
||||
status, attachment, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/uploads/%s/complete" % started["upload_id"],
|
||||
{"sha256": digest},
|
||||
token=alice_token,
|
||||
)
|
||||
expect(202, status, "complete happy path")
|
||||
if attachment["sha256"] != digest or attachment["status"] != "queued":
|
||||
raise SystemExit("FAIL complete metadata")
|
||||
attachment = wait_ready(api, attachment["id"], bob_token)
|
||||
status, _, downloaded = api.call("GET", "/api/v1/attachments/%s/content" % attachment["id"], token=bob_token)
|
||||
expect(200, status, "member downloads direct upload")
|
||||
if downloaded != small:
|
||||
raise SystemExit("FAIL direct bytes")
|
||||
status, _, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/uploads/%s/complete" % started["upload_id"],
|
||||
{"sha256": digest},
|
||||
token=alice_token,
|
||||
)
|
||||
expect(409, status, "second complete")
|
||||
status, proxy, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=proxy.png" % chat_id,
|
||||
token=alice_token,
|
||||
raw=small,
|
||||
content_type="image/png",
|
||||
)
|
||||
expect(202, status, "proxy endpoint still works")
|
||||
return proxy["id"]
|
||||
|
||||
|
||||
def compare(api, token, chat_id):
|
||||
rows = []
|
||||
for label, image in (("small", png(200, 150)), ("large", png(900, 700))):
|
||||
digest = hashlib.sha256(image).hexdigest()
|
||||
proxy = peak_during(
|
||||
lambda image=image: api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=%s.png" % (chat_id, label),
|
||||
token=token,
|
||||
raw=image,
|
||||
content_type="image/png",
|
||||
)
|
||||
)
|
||||
if proxy["result"][0] != 202:
|
||||
raise SystemExit("FAIL proxy %s %s" % (label, proxy["result"][0]))
|
||||
status, started, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/uploads" % chat_id,
|
||||
{"filename": label + "-direct.png", "content_type": "image/png", "size_bytes": len(image)},
|
||||
token=token,
|
||||
)
|
||||
expect(201, status, "presign " + label)
|
||||
direct_put = peak_during(lambda image=image, url=started["url"]: put_signed(url, image, "image/png"))
|
||||
if direct_put["result"] != 200:
|
||||
raise SystemExit("FAIL direct PUT %s %s" % (label, direct_put["result"]))
|
||||
direct_complete = peak_during(
|
||||
lambda digest=digest, upload_id=started["upload_id"]: api.call(
|
||||
"POST",
|
||||
"/api/v1/uploads/%s/complete" % upload_id,
|
||||
{"sha256": digest},
|
||||
token=token,
|
||||
)
|
||||
)
|
||||
if direct_complete["result"][0] != 202:
|
||||
raise SystemExit("FAIL complete %s %s" % (label, direct_complete["result"][0]))
|
||||
rows.append(
|
||||
{
|
||||
"label": label,
|
||||
"bytes": len(image),
|
||||
"proxy_rx_bytes": proxy["rx_bytes"],
|
||||
"proxy_peak_api_mib": proxy["peak_api_mib"],
|
||||
"direct_put_rx_bytes": direct_put["rx_bytes"],
|
||||
"direct_put_peak_api_mib": direct_put["peak_api_mib"],
|
||||
"complete_rx_bytes": direct_complete["rx_bytes"],
|
||||
"complete_peak_api_mib": direct_complete["peak_api_mib"],
|
||||
}
|
||||
)
|
||||
print("MEASURED", rows[-1])
|
||||
return rows
|
||||
|
||||
|
||||
def main():
|
||||
api = Api()
|
||||
|
||||
def register(label):
|
||||
username = "t1_" + label + "_" + uuid.uuid4().hex[:10]
|
||||
password = "T3st-" + uuid.uuid4().hex
|
||||
status, body, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": username, "display_name": "Track " + label, "password": password},
|
||||
)
|
||||
expect(201, status, "register " + label)
|
||||
return username, password, body
|
||||
|
||||
def login(username, password):
|
||||
basic = base64.b64encode((username + ":" + password).encode()).decode()
|
||||
request = urllib.request.Request(
|
||||
BASE + "/api/v1/auth/sessions",
|
||||
method="POST",
|
||||
headers={"Authorization": "Basic " + basic},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
return json.loads(response.read())["token"]
|
||||
|
||||
alice_name, alice_password, alice = register("alice")
|
||||
bob_name, bob_password, bob = register("bob")
|
||||
eve_name, eve_password, eve = register("eve")
|
||||
alice_token = login(alice_name, alice_password)
|
||||
bob_token = login(bob_name, bob_password)
|
||||
eve_token = login(eve_name, eve_password)
|
||||
status, chat, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{"title": "track1", "member_ids": [alice["id"], bob["id"]]},
|
||||
token=alice_token,
|
||||
)
|
||||
expect(201, status, "chat")
|
||||
negatives(api, alice_token, bob_token, eve_token, chat["id"])
|
||||
rows = compare(api, alice_token, chat["id"])
|
||||
summary = {
|
||||
"hypothesis": "A presigned PUT does not enter the API, so API RX stays near zero at both sizes. complete reads the object once to check the checksum, and the proxy endpoint still receives the whole body.",
|
||||
"presign_ttl_seconds": 60,
|
||||
"sizes": rows,
|
||||
}
|
||||
OUT.parent.mkdir(exist_ok=True)
|
||||
OUT.write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps(summary, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,251 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Track 2: versioned pipeline under duplicate, reorder, crash and a stale job.
|
||||
|
||||
Prints statuses and attachment ids only. Tokens stay in memory.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / "evidence" / "track2.json"
|
||||
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
|
||||
FIXTURE = ROOT / "tests" / "fixtures" / "sample.png"
|
||||
|
||||
|
||||
def compose(*args: str) -> None:
|
||||
command = ["docker", "compose", "--env-file", ".env"]
|
||||
extra = os.environ.get("LAB5_COMPOSE_FILES", "")
|
||||
for name in extra.split(os.pathsep):
|
||||
if name:
|
||||
command.extend(["-f", name])
|
||||
subprocess.run([*command, *args], cwd=ROOT, check=True)
|
||||
|
||||
|
||||
class Api:
|
||||
def __init__(self) -> None:
|
||||
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
|
||||
def call(self, method, path, body=None, token=None, raw=None, content_type=None, headers=None):
|
||||
hdrs = dict(headers or {})
|
||||
data = raw
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode("utf-8")
|
||||
hdrs["Content-Type"] = "application/json"
|
||||
if content_type:
|
||||
hdrs["Content-Type"] = content_type
|
||||
if token:
|
||||
hdrs["Authorization"] = "Bearer " + token
|
||||
request = urllib.request.Request(BASE + path, data=data, headers=hdrs, method=method)
|
||||
try:
|
||||
response = self.opener.open(request, timeout=30)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
payload = response.read()
|
||||
parsed = json.loads(payload) if payload and response.headers.get_content_type() == "application/json" else None
|
||||
return response.status, parsed, payload
|
||||
|
||||
|
||||
def expect(status, got, label):
|
||||
if got != status:
|
||||
raise SystemExit("FAIL %s expected %s got %s" % (label, status, got))
|
||||
|
||||
|
||||
def wait_applied(api: Api, attachment_id: str, token: str, version: int, seconds: int = 150, allow_failed: bool = False):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
status, body, _ = api.call("GET", "/api/v1/attachments/" + attachment_id, token=token)
|
||||
expect(200, status, "poll")
|
||||
state = jobs(api, attachment_id)
|
||||
if body["status"] == "failed" and allow_failed:
|
||||
return body
|
||||
if (
|
||||
body["status"] == "ready"
|
||||
and state["applied_pipeline_version"] == version
|
||||
and any(item["name"] == "thumbnail" for item in body["variants"])
|
||||
):
|
||||
return body
|
||||
time.sleep(0.4)
|
||||
raise SystemExit("FAIL timeout waiting for pipeline %s" % version)
|
||||
deadline = time.monotonic() + seconds
|
||||
last = None
|
||||
while time.monotonic() < deadline:
|
||||
status, body, _ = api.call("GET", "/api/v1/attachments/" + attachment_id, token=token)
|
||||
expect(200, status, "poll")
|
||||
last = body
|
||||
if body["status"] == "ready" and any(item["name"] == "thumbnail" for item in body["variants"]):
|
||||
return body
|
||||
if body["status"] == "failed":
|
||||
return body
|
||||
time.sleep(0.4)
|
||||
raise SystemExit("FAIL timeout last=%s" % (last or {}).get("status"))
|
||||
|
||||
|
||||
def jobs(api: Api, attachment_id: str):
|
||||
status, body, _ = api.call("GET", "/api/v1/_lab/attachments/%s/jobs" % attachment_id)
|
||||
expect(200, status, "jobs")
|
||||
return body
|
||||
|
||||
|
||||
def thumb(body):
|
||||
found = [item for item in body["variants"] if item["name"] == "thumbnail"]
|
||||
if len(found) != 1:
|
||||
raise SystemExit("FAIL thumbnail count %s" % len(found))
|
||||
return found[0]["sha256"]
|
||||
|
||||
|
||||
def user(api: Api):
|
||||
username = "t2_" + uuid.uuid4().hex[:10]
|
||||
password = "T3st-" + uuid.uuid4().hex
|
||||
status, body, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": username, "display_name": "Track2", "password": password},
|
||||
)
|
||||
expect(201, status, "register")
|
||||
basic = base64.b64encode((username + ":" + password).encode()).decode()
|
||||
status, session, _ = api.call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic})
|
||||
expect(201, status, "login")
|
||||
return body["id"], session["token"]
|
||||
|
||||
|
||||
def upload(api: Api, chat_id: str, token: str, filename: str):
|
||||
status, body, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=%s" % (chat_id, filename),
|
||||
token=token,
|
||||
raw=FIXTURE.read_bytes(),
|
||||
content_type="image/png",
|
||||
)
|
||||
expect(202, status, "upload " + filename)
|
||||
return body
|
||||
|
||||
|
||||
def main() -> None:
|
||||
api = Api()
|
||||
content = FIXTURE.read_bytes()
|
||||
original = hashlib.sha256(content).hexdigest()
|
||||
alice, token = user(api)
|
||||
status, chat, _ = api.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{"title": "track2", "member_ids": [alice]},
|
||||
token=token,
|
||||
)
|
||||
expect(201, status, "chat")
|
||||
chat_id = chat["id"]
|
||||
report = {"hypothesis": "at-least-once plus a versioned effect key keeps the newest committed pipeline", "cases": []}
|
||||
|
||||
first = upload(api, chat_id, token, "v1.png")
|
||||
ready = wait_applied(api, first["id"], token, 1)
|
||||
sha_v1 = thumb(ready)
|
||||
state = jobs(api, first["id"])
|
||||
v1_job = state["jobs"][0]["job_id"]
|
||||
expect(202, api.call("POST", "/api/v1/_lab/jobs/%s/redeliver" % v1_job)[0], "duplicate 1")
|
||||
expect(202, api.call("POST", "/api/v1/_lab/jobs/%s/redeliver" % v1_job)[0], "duplicate 2")
|
||||
time.sleep(2)
|
||||
again = wait_applied(api, first["id"], token, 1)
|
||||
state = jobs(api, first["id"])
|
||||
v1_rows = [item for item in state["variants"] if item["pipeline_version"] == 1]
|
||||
if thumb(again) != sha_v1 or len(v1_rows) != 3:
|
||||
raise SystemExit("FAIL duplicate changed the effect")
|
||||
report["cases"].append({"name": "duplicate", "attachment_id": first["id"], "thumbnail_sha256": sha_v1, "variant_rows": len(v1_rows)})
|
||||
|
||||
expect(202, api.call("POST", "/api/v1/_lab/attachments/%s/pipelines" % first["id"])[0], "bump")
|
||||
bumped = wait_applied(api, first["id"], token, 2)
|
||||
sha_v2 = thumb(bumped)
|
||||
state = jobs(api, first["id"])
|
||||
if sha_v2 == sha_v1 or state["applied_pipeline_version"] != 2:
|
||||
raise SystemExit("FAIL version 2 did not replace the served bytes")
|
||||
v1_job = [item["job_id"] for item in state["jobs"] if item["pipeline_version"] == 1][0]
|
||||
expect(202, api.call("POST", "/api/v1/_lab/jobs/%s/redeliver" % v1_job)[0], "stale redelivery")
|
||||
time.sleep(2)
|
||||
after_stale = wait_applied(api, first["id"], token, 2)
|
||||
state = jobs(api, first["id"])
|
||||
if thumb(after_stale) != sha_v2 or state["applied_pipeline_version"] != 2:
|
||||
raise SystemExit("FAIL stale job overwrote version 2")
|
||||
report["cases"].append(
|
||||
{
|
||||
"name": "reorder_and_stale_version",
|
||||
"attachment_id": first["id"],
|
||||
"version1_sha256": sha_v1,
|
||||
"version2_sha256": sha_v2,
|
||||
"applied_pipeline_version": state["applied_pipeline_version"],
|
||||
"variant_rows": len(state["variants"]),
|
||||
}
|
||||
)
|
||||
|
||||
def crashed(mode: str):
|
||||
expect(200, api.call("POST", "/api/v1/_lab/faults", {"mode": mode, "remaining": 1})[0], mode)
|
||||
created = upload(api, chat_id, token, mode + ".png")
|
||||
# The worker process exits. Docker restarts it; the lease must expire before retry.
|
||||
body = wait_applied(api, created["id"], token, 1, seconds=180)
|
||||
if body["status"] != "ready":
|
||||
raise SystemExit("FAIL %s ended %s" % (mode, body["status"]))
|
||||
status_code, _, payload = api.call("GET", "/api/v1/attachments/%s/content" % created["id"], token=token)
|
||||
expect(200, status_code, mode + " original")
|
||||
if hashlib.sha256(payload).hexdigest() != original:
|
||||
raise SystemExit("FAIL %s lost the original" % mode)
|
||||
state_now = jobs(api, created["id"])
|
||||
rows = [item for item in state_now["variants"] if item["pipeline_version"] == 1]
|
||||
if len(rows) != 3:
|
||||
raise SystemExit("FAIL %s variant rows %s" % (mode, len(rows)))
|
||||
report["cases"].append(
|
||||
{
|
||||
"name": mode,
|
||||
"attachment_id": created["id"],
|
||||
"original_sha256": original,
|
||||
"variant_rows": len(rows),
|
||||
"thumbnail_sha256": thumb(body),
|
||||
}
|
||||
)
|
||||
|
||||
crashed("crash_before_s3")
|
||||
crashed("crash_after_s3")
|
||||
|
||||
expect(200, api.call("POST", "/api/v1/_lab/faults", {"mode": "fail_once", "remaining": 1})[0], "fail_once")
|
||||
failed = upload(api, chat_id, token, "fail.png")
|
||||
failed_body = wait_applied(api, failed["id"], token, 1, allow_failed=True)
|
||||
if failed_body["status"] != "failed" or failed_body["error_code"] != "processing_failed":
|
||||
raise SystemExit("FAIL expected a terminal processing_failed")
|
||||
expect(200, api.call("POST", "/api/v1/_lab/attachments/%s/replay" % failed["id"])[0], "replay")
|
||||
restored = wait_applied(api, failed["id"], token, 1)
|
||||
if restored["status"] != "ready":
|
||||
raise SystemExit("FAIL replay did not reach ready")
|
||||
state = jobs(api, failed["id"])
|
||||
replay_job = state["jobs"][0]["job_id"]
|
||||
expect(202, api.call("POST", "/api/v1/_lab/jobs/%s/redeliver" % replay_job)[0], "replay duplicate")
|
||||
time.sleep(2)
|
||||
state = jobs(api, failed["id"])
|
||||
if len(state["variants"]) != 3 or state["jobs"][0]["status"] != "ready":
|
||||
raise SystemExit("FAIL replay produced another effect")
|
||||
report["cases"].append(
|
||||
{
|
||||
"name": "replay_then_duplicate",
|
||||
"attachment_id": failed["id"],
|
||||
"variant_rows": len(state["variants"]),
|
||||
"job_status": state["jobs"][0]["status"],
|
||||
}
|
||||
)
|
||||
|
||||
report["not_exactly_once"] = (
|
||||
"The broker delivers a message more than once. A crash after the object PUT and before ack "
|
||||
"runs the S3 write again. The database commit of a pipeline version happens once, and an older "
|
||||
"version cannot replace the applied one. That is idempotent effect, not exactly-once delivery."
|
||||
)
|
||||
OUT.parent.mkdir(exist_ok=True)
|
||||
OUT.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("PASS track2", OUT)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user