Files
mtusi2026lab4/student-tests/grade3.py
T

328 lines
15 KiB
Python

"""Black-box HTTP and real Docker fault checks for the local Lab 4 project."""
from concurrent.futures import ThreadPoolExecutor
import hashlib
from http.client import HTTPConnection
from io import BytesIO
import json
import os
from pathlib import Path
import re
import subprocess
import sys
from threading import Barrier
import time
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen
from uuid import UUID, uuid4
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run, shape
REPLICAS = {"api1", "api2"}
SERVICES = ("postgres", "s3", "api1", "api2")
def docker(*args):
return subprocess.check_output(
("docker", *args), text=True, timeout=30, stderr=subprocess.DEVNULL
).strip()
def container(service):
project = os.environ["LAB4_PROJECT"]
check(re.fullmatch(r"mtusi-lab4-grade3(?:-[a-z0-9-]+)?", project), "unexpected project")
ids = docker("ps", "-aq", "--filter", f"label=com.docker.compose.project={project}",
"--filter", f"label=com.docker.compose.service={service}",
"--filter", "label=com.docker.compose.oneoff=False").splitlines()
check(len(ids) == 1, "expected exactly one service container")
return ids[0]
def state(service):
row = docker("inspect", "--format",
"{{.Id}} {{.State.Running}} {{.State.StartedAt}} {{.State.FinishedAt}}",
container(service)).split()
return dict(zip(("id", "running", "started", "finished"), row))
def hook(name, **env):
subprocess.run(
[str(ROOT / "scripts" / name)], env={**os.environ, **env}, timeout=30,
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
def healthy(client, wanted, timeout=20):
deadline = time.monotonic() + timeout
instances = set()
while time.monotonic() < deadline:
try:
response = client.call("GET", "/health/ready", schema="Health")
instances.add(response["headers"]["X-Instance-Id"])
if instances == wanted:
return instances
except Failure:
pass
time.sleep(0.1)
raise Failure("expected instances not observed in readiness")
def image(fmt, size=(20, 12), mode="RGB"):
with Image.new(mode, size) as fixture, BytesIO() as stream:
fixture.save(stream, fmt)
return stream.getvalue()
def upload(client, actor, chat, data, mime="image/png", filename="фото.png", status=201):
path = f"/api/v1/chats/{chat['id']}/attachments?filename={quote(filename, safe='')}"
response = client.call("POST", path, status, actor=actor, raw=data,
headers={"Content-Type": mime}, schema="Attachment" if status == 201 else None)
if status == 201:
metadata = response["json"]
check(metadata["sha256"] == hashlib.sha256(data).hexdigest(), "metadata checksum")
check(metadata["size_bytes"] == len(data), "metadata size")
check(metadata["filename"] == filename, "metadata filename")
check(metadata["chat_id"] == chat["id"] and metadata["owner_id"] == actor["id"], "metadata ownership")
check(metadata["variants"] == [] and metadata["error_code"] is None, "ready metadata")
check(metadata["content_type"] == mime, "metadata MIME")
return response
def download(client, actor, metadata, data):
path = f"/api/v1/attachments/{metadata['id']}"
current = client.call("GET", path, actor=actor, schema="Attachment")
check(current["json"] == metadata, "metadata changed")
response = client.call("GET", path + "/content", actor=actor)
check(response["bytes"] == data, "original changed")
check(response["headers"].get_content_type() == metadata["content_type"], "download MIME")
check(hashlib.sha256(response["bytes"]).hexdigest() == metadata["sha256"], "download checksum")
return response
def chunked_limit(actor, chat):
path = f"/api/v1/chats/{chat['id']}/attachments?filename=chunked.png"
chunk = b"\x00" * (256 * 1024)
connection = HTTPConnection("lb", 8080, timeout=6)
try:
connection.putrequest("POST", path)
connection.putheader("Authorization", "Bearer " + actor["token"])
connection.putheader("Content-Type", "image/png")
connection.putheader("Transfer-Encoding", "chunked")
connection.endheaders()
for block in [chunk] * 40 + [b"\x00"]:
connection.send(f"{len(block):X}\r\n".encode() + block + b"\r\n")
connection.send(b"0\r\n\r\n")
response = connection.getresponse()
check(response.status == 413, "chunked upload exceeded limit")
shape(json.loads(response.read()), "Error")
finally:
connection.close()
def negatives(client, alice, eve, chat, metadata, png):
path = f"/api/v1/attachments/{metadata['id']}"
for suffix in ("", "/content"):
client.call("GET", path + suffix, 404, actor=eve)
client.call("GET", path + suffix, 401)
client.call("GET", path + "/content?variant=thumbnail", 404, actor=alice)
upload(client, eve, chat, png, status=404)
upload(client, None, chat, png, status=401)
for filename in ("", "a" * 256, "../photo.png", "sub\\photo.png", "nul\0.png", "ctl\x85.png"):
upload(client, alice, chat, png, filename=filename, status=400)
upload(client, alice, chat, b"not an image", status=415)
upload(client, alice, chat, png[:32], status=415)
upload(client, alice, chat, png[:-3], status=415)
upload(client, alice, chat, image("JPEG")[:-10], mime="image/jpeg", status=415)
upload(client, alice, chat, png, mime="image/jpeg", status=415)
upload(client, alice, chat, png, mime="multipart/form-data", status=415)
upload(client, alice, chat, b"\x00" * (10 * 1024 * 1024 + 1), status=413)
chunked_limit(alice, chat)
upload(client, alice, chat, image("PNG", (8001, 5000), "L"), status=413)
print("PASS ACL metadata/content/upload: outsider=404 missing Bearer=401; filenames=400; "
"damaged/false MIME=415; 10 MiB+1 with/without Content-Length=413; 40,005,000 pixels=413")
def metadata_sql(statement):
return docker("exec", container("postgres"), "psql", "-XAtq", "-v", "ON_ERROR_STOP=1",
"-U", "messenger", "-d", "messenger", "-c", statement)
def private_bucket(metadata):
attachment_id = UUID(metadata["id"])
key = metadata_sql(f"SELECT object_key FROM attachments WHERE id='{attachment_id}'")
check(re.fullmatch(r"originals/[0-9a-f]{32}", key), "unexpected object key")
check(not docker("port", container("s3")), "S3 is published")
bucket = os.environ["S3_BUCKET"]
try:
with urlopen(f"http://s3:9000/{quote(bucket)}/{quote(key)}", timeout=4):
raise Failure("anonymous direct S3 GET succeeded")
except HTTPError as exc:
with exc:
check(exc.code == 403, "anonymous direct object GET must be forbidden")
print("PASS anonymous internal GET of known existing object: 403; Docker publishes no S3 ports")
def idempotency(client, alice, bob, chat, first, second):
path = f"/api/v1/chats/{chat['id']}/messages"
other_chat = client.call("POST", "/api/v1/chats", 201, actor=alice,
body={"title": "Other chat", "member_ids": [alice["id"]]}, schema="Chat")["json"]
foreign = upload(client, alice, other_chat, image("PNG"))["json"]["id"]
for ids, code in (([foreign], 404), ([str(uuid4())], 404), ([first, first], 400),
([str(uuid4()) for _ in range(11)], 400)):
client.call("POST", path, code, actor=bob, body={"text": "", "attachment_ids": ids},
headers={"Idempotency-Key": uuid4().hex})
client.call("POST", path, 400, actor=bob, body={"text": " \t"},
headers={"Idempotency-Key": uuid4().hex})
try:
metadata_sql(f"UPDATE attachments SET status='failed',error_code='test' WHERE id='{UUID(first)}'")
client.call("POST", path, 409, actor=bob, body={"text": "", "attachment_ids": [first]},
headers={"Idempotency-Key": uuid4().hex})
finally:
metadata_sql(f"UPDATE attachments SET status='ready',error_code=NULL WHERE id='{UUID(first)}'")
headers = {"Idempotency-Key": uuid4().hex}
barrier = Barrier(2)
def send(replica, body):
endpoint = Client(f"http://{replica}:8080", timeout=5)
barrier.wait(timeout=5)
return endpoint.call("POST", path, 201, actor=bob, body=body,
headers=headers, schema="Message")
with ThreadPoolExecutor(max_workers=2) as executor:
left = executor.submit(send, "api1", {"text": " \t", "attachment_ids": [first, second]})
right = executor.submit(send, "api2", {"attachment_ids": [first, second], "text": " \t"})
results = [left.result(), right.result()]
check({r["headers"]["X-Instance-Id"] for r in results} == REPLICAS, "not cross-replica")
attached = results[0]["json"]
check(attached == results[1]["json"], "concurrent replay differed")
check(attached["attachment_ids"] == [first, second] and attached["sender_id"] == bob["id"],
"attachment order or sender incorrect")
client.call("POST", path, 409, actor=bob, body={"text": " \t", "attachment_ids": [second]},
headers=headers)
key = uuid4().hex
old = client.message(bob, chat, "ordinary text", key=key)["json"]
check(old == client.message(bob, chat, "ordinary text", key=key, attachments=[])["json"],
"omitted and empty attachments differed")
page1 = client.call("GET", path + "?limit=1", actor=alice, schema="MessagePage")["json"]
check(page1["items"] == [attached] and page1["next_cursor"], "first page lost attachments")
page2 = client.call("GET", path + "?limit=1&cursor=" + quote(page1["next_cursor"]),
actor=alice, schema="MessagePage")["json"]
check(page2 == {"items": [old], "next_cursor": None}, "second page duplicated or lost message")
print("PASS concurrent attached POST: api1/api2=201 same message; one history row; changed IDs=409; "
"omitted=[]; both cursor pages; foreign/unknown=404, failed=409, invalid lists=400")
def attachment_failover(client, alice, bob, chat, png):
for target in ("api1", "api2"):
healthy(client, REPLICAS)
for _ in range(6):
response = upload(client, alice, chat, png)
if response["headers"]["X-Instance-Id"] == target:
break
else:
raise Failure("upload did not reach target through HAProxy")
other = (REPLICAS - {target}).pop()
before = state(target)
survivor = state(other)
check(before["running"] == survivor["running"] == "true", "APIs not running before stop")
started = time.monotonic()
try:
hook("stop-one.sh", TARGET_INSTANCE_ID=target)
stopped = state(target)
check(stopped["running"] == "false" and stopped["id"] == before["id"],
"the upload-serving container was not stopped")
check(state(other) == survivor, "surviving container changed")
metadata = response["json"]
path = f"/api/v1/attachments/{metadata['id']}/content"
while True:
try:
after = client.call("GET", path, actor=bob)
break
except Failure:
check(time.monotonic() - started < 10, "download recovery exceeded ten seconds")
time.sleep(0.1)
elapsed = time.monotonic() - started
check(elapsed <= 10 and after["headers"]["X-Instance-Id"] == other, "wrong failover")
check(after["bytes"] == png and hashlib.sha256(after["bytes"]).hexdigest() == metadata["sha256"],
"failover changed original")
print(f"PASS failover upload={target} 201 stopped={stopped['id'][:12]} "
f"FinishedAt={stopped['finished']} download={other} 200 "
f"seconds={elapsed:.3f} sha256={metadata['sha256']}")
finally:
docker("start", before["id"])
healthy(client, REPLICAS)
def outage_and_restart(client, alice, bob, chat, metadata, png):
store = container("s3")
direct = Client("http://api1:8080", timeout=4)
try:
docker("stop", "--time", "4", store)
check(state("s3")["running"] == "false", "S3 did not stop")
upload(direct, alice, chat, png, status=503)
direct.call("GET", f"/api/v1/attachments/{metadata['id']}/content", 503, actor=bob)
direct.call("GET", "/health/ready", 503)
direct.call("GET", "/health/live", schema="Health")
for method, path in (
("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=outage.png"),
("GET", f"/api/v1/attachments/{metadata['id']}/content"),
):
headers = {"Authorization": "Bearer " + (alice if method == "POST" else bob)["token"]}
if method == "POST":
headers["Content-Type"] = "image/png"
request = Request(client.base + path, headers=headers, method=method,
data=png if method == "POST" else None)
try:
with urlopen(request, timeout=4):
raise Failure("HAProxy unexpectedly accepted the outage request")
except HTTPError as exc:
with exc:
check(exc.code == 503, "HAProxy did not return 503 during S3 outage")
print(f"PASS S3 stopped={store[:12]}: LB upload/download=503; API JSON upload/download/ready=503 live=200")
finally:
docker("start", store)
healthy(client, REPLICAS)
download(client, bob, metadata, png)
before = {name: state(name) for name in SERVICES}
hook("restart.sh")
healthy(client, REPLICAS)
for name in SERVICES:
after = state(name)
check(after["id"] == before[name]["id"] and after["running"] == "true", "container replaced")
check(after["started"] > before[name]["started"], "service did not restart")
print(f"restart {name} {after['id'][:12]} StartedAt={before[name]['started']} -> {after['started']}")
download(client, bob, metadata, png)
print(f"PASS original Bearer metadata/content=200 after restart sha256={metadata['sha256']}")
def main():
client = Client(timeout=3)
check(healthy(client, REPLICAS) == REPLICAS, "expected both APIs")
print("PASS HAProxy readiness: api1=200 api2=200")
alice, bob, eve, chat = client.bootstrap()
png = image("PNG")
jpeg = image("JPEG")
first = upload(client, alice, chat, png)["json"]
second = upload(client, alice, chat, jpeg, "image/jpeg", "photo.jpg")["json"]
for metadata, data in ((first, png), (second, jpeg)):
download(client, bob, metadata, data)
print(f"PASS {metadata['content_type']} upload=201 ready download=200 bytes={len(data)} "
f"sha256={metadata['sha256']}")
negatives(client, alice, eve, chat, first, png)
private_bucket(first)
idempotency(client, alice, bob, chat, first["id"], second["id"])
attachment_failover(client, alice, bob, chat, png)
outage_and_restart(client, alice, bob, chat, first, png)
if __name__ == "__main__":
run(main)