forked from mtusi2026/mtusi2026lab2
124 lines
5.2 KiB
Python
124 lines
5.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Own lab2 checks: authentication, logout, atomic chat creation and registration race."""
|
|
import argparse
|
|
import base64
|
|
import sys
|
|
import subprocess
|
|
import time
|
|
import uuid
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "tests"))
|
|
from client import Client, check
|
|
|
|
|
|
def basic(username, password):
|
|
value = base64.b64encode((username + ":" + password).encode()).decode()
|
|
return {"Authorization": "Basic " + value}
|
|
|
|
|
|
def wait_ready(client):
|
|
for _ in range(40):
|
|
try:
|
|
client.call("GET", "/health/ready", schema="Health")
|
|
return
|
|
except Exception:
|
|
time.sleep(0.25)
|
|
raise AssertionError("dependencies did not become ready")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--base-url", default="http://localhost:8080")
|
|
parser.add_argument("--check-expiry", action="store_true")
|
|
parser.add_argument("--check-redis", action="store_true")
|
|
parser.add_argument("--check-postgres", action="store_true")
|
|
args = parser.parse_args()
|
|
c = Client(args.base_url)
|
|
|
|
alice = c.user("grade4_alice")
|
|
bob = c.user("grade4_bob")
|
|
|
|
# Basic is only for login; business endpoints require the returned Bearer token.
|
|
c.call("POST", "/api/v1/users", 400, body={
|
|
"username": "spaces_" + uuid.uuid4().hex[:16],
|
|
"display_name": "Whitespace",
|
|
"password": "\u0085" * 12,
|
|
})
|
|
c.call("POST", "/api/v1/auth/sessions", 400,
|
|
headers={**basic(alice["registration"]["username"], alice["registration"]["password"]),
|
|
"Content-Type": "application/json"}, raw=b"{}")
|
|
wrong = c.call("POST", "/api/v1/auth/sessions", 401,
|
|
headers=basic(alice["registration"]["username"], "wrong-password-123"))
|
|
check(wrong["headers"].get("WWW-Authenticate", "").startswith("Basic"),
|
|
"wrong password must challenge with Basic")
|
|
c.call("GET", "/api/v1/users/me", 401,
|
|
headers=basic(alice["registration"]["username"], alice["registration"]["password"]))
|
|
me = c.call("GET", "/api/v1/users/me", actor=alice,
|
|
headers={"X-User-Id": bob["id"]}, schema="User")["json"]
|
|
check(me["id"] == alice["id"], "X-User-Id changed Bearer identity")
|
|
|
|
if args.check_redis:
|
|
subprocess.run(["docker", "compose", "--env-file", ".env", "stop", "redis"], check=True,
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
try:
|
|
time.sleep(1)
|
|
c.call("GET", "/api/v1/users/me", 503, actor=bob)
|
|
finally:
|
|
subprocess.run(["docker", "compose", "--env-file", ".env", "start", "redis"], check=True,
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
wait_ready(c)
|
|
print("PASS: Redis outage returns 503")
|
|
|
|
if args.check_postgres:
|
|
subprocess.run(["docker", "compose", "--env-file", ".env", "stop", "postgres"], check=True,
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
try:
|
|
time.sleep(1)
|
|
c.call("GET", "/api/v1/users/me", 503, actor=bob)
|
|
finally:
|
|
subprocess.run(["docker", "compose", "--env-file", ".env", "start", "postgres"], check=True,
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
wait_ready(c)
|
|
print("PASS: PostgreSQL outage returns 503")
|
|
|
|
# Creating a chat with an unknown member must leave no half-created chat.
|
|
title = "rollback-check-" + uuid.uuid4().hex
|
|
c.call("POST", "/api/v1/chats", 400, actor=alice,
|
|
body={"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]})
|
|
chats = c.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]["items"]
|
|
check(all(chat["title"] != title for chat in chats), "failed chat creation was not rolled back")
|
|
|
|
# Database UNIQUE(username) must decide a concurrent registration race.
|
|
username = "race_" + uuid.uuid4().hex[:20]
|
|
body = {"username": username, "display_name": "Race", "password": "race-password-123"}
|
|
def register_once():
|
|
return Client(args.base_url).call("POST", "/api/v1/users", [201, 409], body=body)["status"]
|
|
with ThreadPoolExecutor(max_workers=10) as pool:
|
|
statuses = list(pool.map(lambda _: register_once(), range(10)))
|
|
check(statuses.count(201) == 1 and statuses.count(409) == 9,
|
|
"concurrent username registration must produce one 201 and nine 409")
|
|
|
|
# Logout revokes the exact token; a second logout is unauthorized.
|
|
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
|
c.call("GET", "/api/v1/users/me", 401, actor=alice)
|
|
c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=alice)
|
|
|
|
if args.check_expiry:
|
|
short = c.user("grade4_expiry")
|
|
time.sleep(3)
|
|
c.call("GET", "/api/v1/users/me", 401, actor=short)
|
|
print("PASS: expiry with short SESSION_TTL_SECONDS")
|
|
|
|
print("PASS: wrong password, Basic/Bearer separation, X-User-Id isolation, rollback, race and logout")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except Exception as error:
|
|
print("FAIL:", error)
|
|
raise SystemExit(1)
|