Files
mtusi2026lab2/student-tests/deps.py
T
2026-10-23 16:31:42 +03:00

74 lines
2.4 KiB
Python

#!/usr/bin/env python3
"""Stop Redis, then Postgres, and check the API does not trust an anonymous caller."""
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, arguments, check, run
def compose(*args):
completed = subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
text=True,
capture_output=True,
)
check(completed.returncode == 0, "compose " + " ".join(args) + " failed")
def wait_ready(client, timeout):
deadline = time.monotonic() + timeout
while True:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
check(time.monotonic() < deadline, "API did not become ready")
time.sleep(0.5)
def main():
args = arguments("Dependency failure checks")
client = Client(args.base_url, args.ca_file, timeout=8)
wait_ready(client, 30)
actor = client.user("deps")
try:
compose("stop", "redis")
time.sleep(1)
ready = client.call("GET", "/health/ready", 503)
check(ready["json"]["error"]["code"] == "unavailable", "ready code")
anon = client.call("GET", "/api/v1/users/me", 401)
check(anon["json"]["error"]["code"] == "unauthorized", "anonymous became trusted while redis was down")
authed = client.call("GET", "/api/v1/users/me", 503, actor=actor)
check(authed["json"]["error"]["code"] == "unavailable", "bearer during redis outage")
check("labredispass" not in authed["json"]["error"]["message"], "secret leaked")
finally:
compose("start", "redis")
wait_ready(client, 40)
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
try:
compose("stop", "postgres")
time.sleep(1)
client.call("GET", "/health/ready", 503)
client.call("GET", "/api/v1/users/me", 401)
client.call(
"POST",
"/api/v1/users",
503,
body={"username": "down_" + uuid.uuid4().hex[:8], "display_name": "Down", "password": "long-enough-password"},
)
finally:
compose("start", "postgres")
wait_ready(client, 40)
print("PASS: dependency failures stay untrusted")
if __name__ == "__main__":
run(main)