Files
mtusi2026lab3/student-tests/grade3.py
T

277 lines
14 KiB
Python

"""Additional grade-3 checks. Run only on the isolated synthetic Compose stack."""
from concurrent.futures import ThreadPoolExecutor
from http.client import HTTPConnection
import json
import os
from pathlib import Path
import subprocess
import sys
from threading import Barrier
import time
from urllib.parse import urlsplit
from uuid import uuid4
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, Failure, check, run
from resilience import history
BASE = os.environ.get("BASE_URL", "http://localhost:8080")
REPLICAS = {"api1", "api2"}
COMPOSE = ["docker", "compose", "-p", os.environ.get("LAB3_PROJECT", "mtusi-lab3-grade3")]
PSQL = [*COMPOSE, "exec", "-T", "postgres", "psql", "-XAtq", "-v", "ON_ERROR_STOP=1",
"-U", "messenger", "-d", "messenger"]
def instance(response):
return response["headers"]["X-Instance-Id"]
def wait_for_both(client, actor=None):
observed = set()
path, schema = ("/api/v1/users/me", "User") if actor else ("/health/ready", "Health")
deadline = time.monotonic() + 40
while time.monotonic() < deadline:
try:
response = client.call("GET", path, actor=actor, schema=schema)
if actor:
check(response["json"] == actor["user"], "same Bearer changed identity")
observed.add(instance(response))
if observed == REPLICAS:
return
except Failure:
pass
time.sleep(0.2)
raise Failure("both real replicas did not respond through the LB")
def pair(left, right):
barrier = Barrier(2)
def send(operation):
barrier.wait(timeout=5)
return operation()
with ThreadPoolExecutor(max_workers=2) as executor:
futures = [executor.submit(send, operation) for operation in (left, right)]
results = [future.result() for future in futures]
check({instance(result) for result in results} == REPLICAS, "parallel requests did not hit two replicas")
return results
def database(sql):
return subprocess.check_output(PSQL, input=sql + "\n", text=True, timeout=12).strip()
def core(client):
wait_for_both(client)
alice, bob, eve, chat = client.bootstrap()
wait_for_both(client, alice)
print("PASS: one Bearer accepted by api1 and api2")
path = "/api/v1/chats/" + chat["id"] + "/messages"
key = "grade3.same." + uuid4().hex
headers = {"Idempotency-Key": key, "Content-Type": "application/json"}
def post(raw, expected=201, actor=alice, request_headers=headers):
return Client(BASE, timeout=5).call(
"POST", path, expected, actor=actor, raw=raw,
headers=request_headers, schema="Message",
)
first, second = pair(lambda: post(b'{"text":"parallel same"}'),
lambda: post(b'{ "text" : "parallel \\u0073ame" }'))
original = first["json"]
check(original == second["json"] and history(client, bob, chat) == [original],
"same-key race did not produce one identical Message")
print(json.dumps({"same_key_race": [
{"instance": instance(r), "status": r["status"], "message_id": r["json"]["id"]}
for r in (first, second)], "history_count": 1}))
rival_key = "grade3.conflict." + uuid4().hex
rival_headers = dict(headers, **{"Idempotency-Key": rival_key})
left, right = pair(lambda: post(b'{"text":"left"}', [201, 409], request_headers=rival_headers),
lambda: post(b'{"text":"right"}', [201, 409], request_headers=rival_headers))
check(sorted([left["status"], right["status"]]) == [201, 409], "different body race must conflict")
check(len(history(client, bob, chat)) == 2, "different body race added a duplicate")
print(json.dumps({"different_body_race": {instance(r): r["status"] for r in (left, right)}}))
distinct = pair(lambda: client.message(alice, chat, "same text, independent keys"),
lambda: client.message(alice, chat, "same text, independent keys"))
check(len({r["json"]["id"] for r in distinct}) == 2, "different keys were deduplicated")
other_chat = client.call("POST", "/api/v1/chats", 201, actor=alice,
body={"title": "Scope", "member_ids": [alice["id"]]}, schema="Chat")["json"]
check(client.message(bob, chat, original["text"], key=key)["json"]["id"] != original["id"],
"users must have independent key spaces")
check(client.message(alice, other_chat, original["text"], key=key)["json"]["id"] != original["id"],
"chats must have independent key spaces")
for invalid_key in (None, "", "a" * 129, "with space", "comma,key", "é"):
bad = {"Content-Type": "application/json"}
if invalid_key is not None:
bad["Idempotency-Key"] = invalid_key
post(b'{"text":"parallel same"}', 400, request_headers=bad)
for bad_body in (b"{", b"{}", b'{"text":4}', b'{"text":" "}', b'{"text":"x","sender_id":"x"}'):
post(bad_body, 400)
post(b'{"text":"parallel same"}', 404, actor=eve)
post(b'{"text":"parallel same"}', 401, actor=None)
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
post(b'{"text":"parallel same"}', 401)
print("PASS: independent keys/users/chats, invalid key/body, authorization and revocation on replay")
check(database(f"SELECT password_hash LIKE '$argon2id$%' FROM users WHERE id='{bob['id']}';") == "t",
"password is not stored using Argon2id")
check(database(f"""SELECT extract(epoch FROM expires_at - created_at) BETWEEN 3590 AND 3600
FROM sessions WHERE user_id='{bob['id']}';""") == "t", "unexpected default session TTL")
database(f"UPDATE sessions SET created_at=clock_timestamp()-interval '1 hour', expires_at=clock_timestamp()-interval '1 second' WHERE user_id='{eve['id']}';")
client.call("GET", "/api/v1/users/me", 401, actor=eve)
check(database(f"""SELECT extract(epoch FROM i.expires_at - m.created_at) BETWEEN 86390 AND 86400
FROM message_idempotency i JOIN messages m ON m.id=i.message_id
WHERE m.id='{original['id']}';""") == "t", "unexpected idempotency TTL")
previous = next(m for m in history(client, bob, chat) if m["sender_id"] == bob["id"])
database(f"""UPDATE message_idempotency SET expires_at=clock_timestamp()-interval '1 second'
WHERE message_id='{previous['id']}';""")
after = pair(lambda: client.message(bob, chat, "after expiry", key=key),
lambda: client.message(bob, chat, "after expiry", key=key))
check(after[0]["json"] == after[1]["json"] and after[0]["json"]["id"] != previous["id"],
"expired key was not reclaimed exactly once")
check(sum(m["text"] == "after expiry" for m in history(client, bob, chat)) == 1, "expired-key race duplicated")
print("PASS: Argon2id, session TTL and expiry, 24h key TTL and concurrent key reuse after expiry")
unknown_key = "uncertain." + uuid4().hex
url = urlsplit(BASE)
connection = HTTPConnection(url.hostname, url.port, timeout=5)
connection.request("POST", path, body=b'{"text":"unread response"}', headers={
"Authorization": "Bearer " + bob["token"], "Idempotency-Key": unknown_key,
"Content-Type": "application/json",
})
try:
# Observe the committed write through another connection without reading its response.
deadline = time.monotonic() + 5
while True:
observed = [m for m in history(client, bob, chat) if m["text"] == "unread response"]
if observed:
break
check(time.monotonic() < deadline, "unacknowledged write did not reach history")
time.sleep(0.05)
finally:
connection.close()
replay = client.message(bob, chat, "unread response", key=unknown_key)["json"]
check(observed == [replay] and history(client, bob, chat).count(replay) == 1, "unconfirmed POST duplicated")
print(f"PASS: retry of committed POST with unread response returned {replay['id']}")
blocked_key = "transient." + uuid4().hex
with subprocess.Popen(PSQL, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) as lock:
lock.stdin.write("BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT 'locked';\n")
lock.stdin.flush()
try:
check(lock.stdout.readline().strip() == "locked", "could not acquire test lock")
post(b'{"text":"retry after 503"}', 503, actor=bob,
request_headers=dict(headers, **{"Idempotency-Key": blocked_key}))
finally:
lock.stdin.write("ROLLBACK;\n")
lock.stdin.close()
lock.wait(timeout=10)
check(database(f"SELECT count(*) FROM message_idempotency WHERE key='{blocked_key}';") == "0",
"lock timeout left a committed key reservation")
recovered = client.message(bob, chat, "retry after 503", key=blocked_key)["json"]
check(history(client, bob, chat).count(recovered) == 1, "503 poisoned key or duplicated history")
print("PASS: message insert lock timeout produced 503 and rolled back reservation, same key then committed once")
def container_state(service):
container = subprocess.check_output([*COMPOSE, "ps", "-a", "-q", service], text=True, timeout=10).strip()
template = "{{.Id}} {{.State.Status}} {{.State.StartedAt}}"
return subprocess.check_output(["docker", "inspect", "--format", template, container],
text=True, timeout=10).strip()
def persistence(client):
wait_for_both(client)
alice, bob, _, chat = client.bootstrap()
key = uuid4().hex
original = client.message(alice, chat, "replay across restart", key=key)["json"]
expiry_query = f"SELECT expires_at FROM sessions WHERE user_id='{alice['id']}';"
expiry = database(expiry_query)
check(bool(expiry), "expected a stored session before restart")
services = ("postgres", "api1", "api2")
before = {service: container_state(service) for service in services}
subprocess.run(["make", "test-persistence", "ACTION_SCRIPT=scripts/restart.sh"], check=True, timeout=120)
for service in services:
after = container_state(service)
check(before[service].split()[0] == after.split()[0] and before[service] != after,
"hook did not restart existing " + service)
print(f"{service} before {before[service]} after {after}")
wait_for_both(client, alice)
check(client.message(alice, chat, original["text"], key=key)["json"] == original
and history(client, bob, chat) == [original], "idempotency did not survive restart")
check(database(expiry_query) == expiry, "restart changed the session expiry")
print(f"PASS: old Bearer on both replicas after PostgreSQL restart, unchanged expiry, replay {original['id']}, history count 1")
def run_public_failover(client, actor, chat, original, target, survivor):
command = ["make", "test-failover", "ACTION_SCRIPT=scripts/stop-one.sh"]
recovery = None
with subprocess.Popen(command, stdout=subprocess.PIPE, text=True) as process:
for line in process.stdout:
print(line, end="")
if not line.startswith("Executing explicit failover hook"):
continue
started = time.monotonic()
while time.monotonic() - started <= 10:
if container_state(target).split()[1] == "exited":
try:
path = "/api/v1/chats/" + chat["id"] + "/messages"
response = client.call("GET", path, actor=actor, schema="MessagePage")
if instance(response) == survivor and original in response["json"]["items"]:
recovery = time.monotonic() - started
break
except Failure:
pass
time.sleep(0.1)
check(process.wait(timeout=5) == 0, "public failover scenario failed")
check(recovery is not None and recovery <= 10, "history did not recover within 10 seconds")
print(f"PASS: {survivor} read confirmed history after {target} stopped in {recovery:.3f}s")
def failover(client):
wait_for_both(client)
alice, bob, _, chat = client.bootstrap()
migration = container_state("migrate")
for target in sorted(REPLICAS):
survivor = (REPLICAS - {target}).pop()
key = uuid4().hex
original = client.message(alice, chat, "keep " + target, key=key)["json"]
before = {service: container_state(service) for service in sorted(REPLICAS)}
check(all(state.split()[1] == "running" for state in before.values()), "expected two running containers")
# Public setup sends ten requests through round robin before choosing its target
# from request number ten. Prime the last response to select that replica.
for _ in range(4):
if instance(client.call("GET", "/api/v1/users/me", actor=alice, schema="User")) == target:
break
else:
raise Failure("could not prime failover target")
try:
run_public_failover(client, bob, chat, original, target, survivor)
after = {service: container_state(service) for service in sorted(REPLICAS)}
print(json.dumps({"target": target, "before": before, "after": after}))
check(after[target].split()[1] == "exited" and after[survivor] == before[survivor],
"public hook did not stop exactly the selected container")
replay = client.message(alice, chat, original["text"], key=key)
check(instance(replay) == survivor and replay["json"] == original
and history(client, bob, chat).count(original) == 1, "surviving replica replay failed")
print(f"PASS: {survivor} replayed {original['id']} while {target} was stopped, history count 1")
finally:
subprocess.run(["docker", "start", before[target].split()[0]], check=True, timeout=25)
wait_for_both(client, alice)
check(container_state("migrate") == migration, "replica recovery restarted the migrator")
print(f"PASS: {target} rejoined the LB with the same Bearer; migrator was not restarted")
def main():
scenario = {"ready": wait_for_both, "core": core, "persistence": persistence, "failover": failover}
check(len(sys.argv) == 2 and sys.argv[1] in scenario, "choose ready, core, persistence or failover")
scenario[sys.argv[1]](Client(BASE, timeout=5))
if __name__ == "__main__":
run(main)