forked from mtusi2026/mtusi2026lab2
189 lines
5.7 KiB
Python
189 lines
5.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Integration checks for the lab2 level-4 rubric; requires the local Compose stack."""
|
|
import base64
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import hashlib
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
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, check # noqa: E402
|
|
|
|
|
|
def compose(*args):
|
|
result = subprocess.run(
|
|
["docker", "compose", "--env-file", ".env", *args],
|
|
cwd=ROOT,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
text=True,
|
|
check=False,
|
|
)
|
|
if result.returncode:
|
|
raise Failure("Docker Compose operation failed: " + args[0])
|
|
return result.stdout.strip()
|
|
|
|
|
|
def psql_scalar(sql):
|
|
result = subprocess.run(
|
|
[
|
|
"docker",
|
|
"compose",
|
|
"--env-file",
|
|
".env",
|
|
"exec",
|
|
"-T",
|
|
"postgres",
|
|
"sh",
|
|
"-c",
|
|
'psql -X -qAt -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "$1"',
|
|
"level4-test",
|
|
sql,
|
|
],
|
|
cwd=ROOT,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
text=True,
|
|
check=False,
|
|
)
|
|
if result.returncode:
|
|
raise Failure("PostgreSQL verification query failed")
|
|
return result.stdout.strip()
|
|
|
|
|
|
def assert_ready(client, expected=200, deadline_seconds=45):
|
|
deadline = time.monotonic() + deadline_seconds
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
client.call("GET", "/health/ready", expected, schema="Health" if expected == 200 else None)
|
|
return
|
|
except Failure:
|
|
if expected != 200:
|
|
raise
|
|
time.sleep(0.5)
|
|
raise Failure("API did not become ready")
|
|
|
|
|
|
def expire_only(args):
|
|
client = Client(args.base_url)
|
|
actor = client.user("level4expiry")
|
|
time.sleep(args.ttl_seconds + 1)
|
|
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
|
print("PASS: expired session rejected")
|
|
|
|
|
|
def main():
|
|
import argparse
|
|
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--base-url", default="http://127.0.0.1:8080")
|
|
parser.add_argument("--expiry-only", action="store_true")
|
|
parser.add_argument("--ttl-seconds", type=int, default=2)
|
|
args = parser.parse_args()
|
|
if args.expiry_only:
|
|
check(args.ttl_seconds >= 1, "TTL must be positive")
|
|
expire_only(args)
|
|
return
|
|
|
|
client = Client(args.base_url)
|
|
user = client.user("level4")
|
|
username = user["registration"]["username"]
|
|
wrong = base64.b64encode((username + ":not-the-correct-password").encode()).decode()
|
|
client.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Basic " + wrong})
|
|
|
|
client.call("GET", "/api/v1/users/me", actor=user, schema="User")
|
|
token_hash = hashlib.sha256(user["token"].encode("utf-8")).hexdigest()
|
|
redis_key = "messenger:session:" + token_hash
|
|
ttl_ms = int(
|
|
compose(
|
|
"exec",
|
|
"-T",
|
|
"redis",
|
|
"redis-cli",
|
|
"--raw",
|
|
"PTTL",
|
|
redis_key,
|
|
)
|
|
)
|
|
check(ttl_ms > 0, "session cache entry must have a positive Redis TTL")
|
|
|
|
unique_name = "race_" + uuid.uuid4().hex[:20]
|
|
registration = {
|
|
"username": unique_name,
|
|
"display_name": "Concurrent registration",
|
|
"password": "Concurrent-test-password-42",
|
|
}
|
|
barrier = threading.Barrier(4)
|
|
|
|
def register_once(_):
|
|
barrier.wait(timeout=10)
|
|
return Client(args.base_url).call(
|
|
"POST", "/api/v1/users", expected=[201, 409], body=registration
|
|
)["status"]
|
|
|
|
with ThreadPoolExecutor(max_workers=4) as executor:
|
|
statuses = list(executor.map(register_once, range(4)))
|
|
check(statuses.count(201) == 1 and statuses.count(409) == 3, "username race was not serialized")
|
|
check(
|
|
psql_scalar("SELECT count(*) FROM users WHERE username = '" + unique_name + "'") == "1",
|
|
"username race persisted other than one user",
|
|
)
|
|
|
|
chat_title = "rollback_" + uuid.uuid4().hex
|
|
missing_user_id = str(uuid.uuid4())
|
|
client.call(
|
|
"POST",
|
|
"/api/v1/chats",
|
|
400,
|
|
actor=user,
|
|
body={"title": chat_title, "member_ids": [user["id"], missing_user_id]},
|
|
)
|
|
check(
|
|
psql_scalar("SELECT count(*) FROM chats WHERE title = '" + chat_title + "'") == "0",
|
|
"failed chat creation left a partial chat row",
|
|
)
|
|
|
|
compose("stop", "redis")
|
|
try:
|
|
client.call("GET", "/api/v1/users/me", actor=user, schema="User")
|
|
finally:
|
|
compose("start", "redis")
|
|
deadline = time.monotonic() + 30
|
|
while True:
|
|
try:
|
|
if compose("exec", "-T", "redis", "redis-cli", "ping") == "PONG":
|
|
break
|
|
except Failure:
|
|
if time.monotonic() >= deadline:
|
|
raise Failure("Redis did not recover")
|
|
time.sleep(0.5)
|
|
client.call("GET", "/api/v1/users/me", actor=user, schema="User")
|
|
|
|
compose("stop", "postgres")
|
|
try:
|
|
client.call("GET", "/health/ready", 503)
|
|
client.call("GET", "/api/v1/chats?limit=10", 503, actor=user)
|
|
finally:
|
|
compose("start", "postgres")
|
|
assert_ready(client)
|
|
client.call("GET", "/api/v1/users/me", actor=user, schema="User")
|
|
print(
|
|
"PASS: level-4 checks (password failure, username race, atomic rollback, "
|
|
"Redis TTL/fallback, bounded PostgreSQL outage)"
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except (Failure, OSError, subprocess.SubprocessError) as exc:
|
|
print("FAIL:", str(exc))
|
|
raise SystemExit(1)
|