forked from mtusi2026/mtusi2026lab2
Implement Lab 2 grade 4 messenger service
This commit is contained in:
+205
@@ -0,0 +1,205 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Manual integration checks for Lab 2 grade 4; uses a disposable local Compose stack."""
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args: str) -> None:
|
||||
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True, capture_output=True, text=True)
|
||||
|
||||
|
||||
def compose_output(*args: str) -> str:
|
||||
result = subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True, capture_output=True, text=True)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def get_status(base_url: str, path: str, actor=None) -> tuple[int, dict, object, float]:
|
||||
headers = {"Accept": "application/json"}
|
||||
if actor:
|
||||
headers["Authorization"] = "Bearer " + actor["token"]
|
||||
request = urllib.request.Request(base_url.rstrip("/") + path, headers=headers)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=10)
|
||||
except urllib.error.HTTPError as exc:
|
||||
response = exc
|
||||
with response:
|
||||
headers = {name.lower(): value for name, value in response.headers.items()}
|
||||
body = json.loads(response.read())
|
||||
return response.status, headers, body, time.monotonic() - started
|
||||
|
||||
|
||||
def register_once(base_url: str, username: str, password: str) -> int:
|
||||
body = json.dumps({"username": username, "display_name": "Race test", "password": password}).encode()
|
||||
request = urllib.request.Request(
|
||||
base_url.rstrip("/") + "/api/v1/users",
|
||||
data=body,
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=10)
|
||||
except urllib.error.HTTPError as exc:
|
||||
response = exc
|
||||
with response:
|
||||
return response.status
|
||||
|
||||
|
||||
def fresh_actor(client: Client, registration: dict) -> dict:
|
||||
credential = base64.b64encode(
|
||||
(registration["username"] + ":" + registration["password"]).encode()
|
||||
).decode()
|
||||
session = client.call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
201,
|
||||
headers={"Authorization": "Basic " + credential},
|
||||
schema="Session",
|
||||
)["json"]
|
||||
return {
|
||||
"id": session["user"]["id"],
|
||||
"user": session["user"],
|
||||
"registration": registration,
|
||||
"token": session["token"],
|
||||
}
|
||||
|
||||
|
||||
def wait_ready(base_url: str, timeout: int = 45) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
status, _headers, _body, _elapsed = get_status(base_url, "/health/ready")
|
||||
if status == 200:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise Failure("API did not become ready after restoring a dependency")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = arguments("Lab 2 grade-4 checks; dependency-outage checks restart Compose services")
|
||||
client = Client(args.base_url)
|
||||
|
||||
config = subprocess.run(
|
||||
["docker", "compose", "config", "--format", "json"],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
ttl = int(json.loads(config.stdout)["services"]["api"]["environment"]["SESSION_TTL_SECONDS"])
|
||||
check(ttl <= 10, "Run this check with SESSION_TTL_SECONDS=10 to verify expiry.")
|
||||
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
registration = alice["registration"]
|
||||
|
||||
bad = base64.b64encode((registration["username"] + ":wrong-password").encode()).decode()
|
||||
client.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Basic " + bad})
|
||||
print("PASS: invalid password returns the same Basic 401 challenge")
|
||||
|
||||
alice = fresh_actor(client, registration)
|
||||
chat_count_before = len(client.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]["items"])
|
||||
unknown_id = str(uuid.uuid4())
|
||||
failed_title = "must_roll_back_" + uuid.uuid4().hex[:12]
|
||||
client.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
400,
|
||||
actor=alice,
|
||||
body={"title": failed_title, "member_ids": [alice["id"], unknown_id]},
|
||||
)
|
||||
chat_count_after = len(client.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]["items"])
|
||||
check(chat_count_after == chat_count_before, "invalid chat creation left visible partial state")
|
||||
stored_failed_chats = compose_output(
|
||||
"exec", "-T", "db", "psql", "-U", "messenger", "-d", "messenger", "-Atc",
|
||||
f"SELECT count(*) FROM chats WHERE title = '{failed_title}'",
|
||||
)
|
||||
check(stored_failed_chats == "0", "database kept a chat row after the member foreign-key rollback")
|
||||
print("PASS: invalid composite chat creation leaves no chat")
|
||||
|
||||
race_name = "race_" + uuid.uuid4().hex[:20]
|
||||
race_password = "T3st-" + uuid.uuid4().hex
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
|
||||
statuses = list(executor.map(lambda _i: register_once(client.base, race_name, race_password), range(2)))
|
||||
check(statuses.count(201) == 1 and statuses.count(409) == 1, "username race was not resolved by the unique constraint")
|
||||
print("PASS: concurrent duplicate registration produced one 201 and one 409 response")
|
||||
|
||||
expiring = client.call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
201,
|
||||
headers={"Authorization": "Basic " + base64.b64encode(
|
||||
(registration["username"] + ":" + registration["password"]).encode()
|
||||
).decode()},
|
||||
schema="Session",
|
||||
)["json"]
|
||||
time.sleep(ttl + 1)
|
||||
status, headers, body, _elapsed = get_status(client.base, "/api/v1/users/me", {"token": expiring["token"]})
|
||||
check(
|
||||
status == 401 and headers.get("www-authenticate", "").lower().startswith("bearer"),
|
||||
"expired session was not rejected with a Bearer challenge",
|
||||
)
|
||||
check(body["error"]["code"] == "unauthorized", "expired session returned the wrong error")
|
||||
print("PASS: session expiry with short TTL")
|
||||
|
||||
# A protected request fails closed when Redis is unavailable; the stack is restored in finally.
|
||||
alice = fresh_actor(client, registration)
|
||||
compose("stop", "redis")
|
||||
try:
|
||||
try:
|
||||
status, _headers, body, elapsed = get_status(client.base, "/api/v1/users/me", alice)
|
||||
except OSError as exc:
|
||||
raise Failure("Redis outage request timed out before the API returned 503") from exc
|
||||
check(
|
||||
status == 503 and body["error"]["code"] == "unavailable" and elapsed <= 8,
|
||||
f"Redis outage did not return a bounded 503 (status={status}, elapsed={elapsed:.2f}s)",
|
||||
)
|
||||
print("PASS: Redis outage returns bounded 503")
|
||||
finally:
|
||||
compose("start", "redis")
|
||||
wait_ready(client.base)
|
||||
|
||||
# Database loss has the same bounded behavior and does not trust a cached identity.
|
||||
bob = fresh_actor(client, bob["registration"])
|
||||
compose("stop", "db")
|
||||
try:
|
||||
try:
|
||||
status, _headers, body, elapsed = get_status(client.base, "/api/v1/users/me", bob)
|
||||
except OSError as exc:
|
||||
raise Failure("Postgres outage request timed out before the API returned 503") from exc
|
||||
check(
|
||||
status == 503 and body["error"]["code"] == "unavailable" and elapsed <= 8,
|
||||
f"Postgres outage did not return a bounded 503 (status={status}, elapsed={elapsed:.2f}s)",
|
||||
)
|
||||
print("PASS: Postgres outage returns bounded 503")
|
||||
finally:
|
||||
compose("start", "db")
|
||||
wait_ready(client.base)
|
||||
|
||||
# Explicitly verify logout too; the public smoke covers this but grade 4 records it separately.
|
||||
bob = fresh_actor(client, bob["registration"])
|
||||
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=bob)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=bob)
|
||||
print("PASS: logout revokes the bearer session")
|
||||
|
||||
# A harmless read confirms the restored stack and the same persistent conversation still work.
|
||||
alice = fresh_actor(client, registration)
|
||||
client.call("GET", "/api/v1/chats/" + chat["id"], 200, actor=alice, schema="Chat")
|
||||
print("PASS: API and persistent stores are ready after dependency restarts")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user