#!/usr/bin/env python3 import argparse import base64 import json import subprocess import threading import time import urllib.error import urllib.request import uuid class Failure(AssertionError): pass def check(condition, message): if not condition: raise Failure(message) def call(base, method, path, body=None, token=None, basic=None, headers=None): h = {"Accept": "application/json"} if token: h["Authorization"] = "Bearer " + token if basic: h["Authorization"] = "Basic " + base64.b64encode(basic.encode("utf-8")).decode("ascii") data = None if body is not None: data = json.dumps(body, ensure_ascii=False).encode("utf-8") h["Content-Type"] = "application/json" h.update(headers or {}) request = urllib.request.Request(base + path, data=data, headers=h, method=method) try: response = urllib.request.urlopen(request, timeout=10) except urllib.error.HTTPError as error: response = error with response: raw = response.read() return response.code, response.headers, raw def register(base, username, password): return call(base, "POST", "/api/v1/users", body={ "username": username, "display_name": "Студент " + username, "password": password}) def main(): parser = argparse.ArgumentParser() parser.add_argument("--base-url", default="http://localhost:8080") parser.add_argument("--expiry", action="store_true", help="expect a short SESSION_TTL_SECONDS") parser.add_argument("--cache-check", action="store_true", help="stop Valkey via docker compose") parser.add_argument("--compose-dir", default=".") args = parser.parse_args() base = args.base_url.rstrip("/") tag = uuid.uuid4().hex[:10] password = "T3st-" + uuid.uuid4().hex status, _, raw = register(base, "u_neg_" + tag, password) check(status == 201, "registration failed: %d" % status) user = json.loads(raw) status, headers, _ = call(base, "POST", "/api/v1/auth/sessions", basic="u_neg_%s:%s" % (tag, "wrong-password-123")) check(status == 401, "wrong password must be 401, got %d" % status) check(headers.get("WWW-Authenticate", "").lower().startswith("basic"), "missing Basic challenge") print("PASS: wrong password -> 401 with Basic challenge") status, _, raw = call(base, "POST", "/api/v1/auth/sessions", basic="u_neg_%s:%s" % (tag, password)) check(status == 201, "login failed: %d" % status) token = json.loads(raw)["token"] status, _, _ = call(base, "GET", "/api/v1/users/me", headers={"X-User-Id": user["id"]}) check(status == 401, "X-User-Id must not authenticate, got %d" % status) other = json.loads(register(base, "u_neg2_" + tag, password)[2]) status, _, raw = call(base, "GET", "/api/v1/users/me", token=token, headers={"X-User-Id": other["id"]}) check(status == 200 and json.loads(raw)["id"] == user["id"], "X-User-Id overrode bearer identity") print("PASS: X-User-Id ignored for authentication") status, _, raw = call(base, "DELETE", "/api/v1/auth/sessions/current", token=token) check(status == 204 and not raw, "logout must be 204 without body, got %d" % status) status, headers, _ = call(base, "GET", "/api/v1/users/me", token=token) check(status == 401, "revoked token must be 401, got %d" % status) check(headers.get("WWW-Authenticate", "").lower().startswith("bearer"), "missing Bearer challenge") print("PASS: logout revokes the session") race_username = "u_race_" + tag results = [] lock = threading.Lock() barrier = threading.Barrier(8) def attempt(): barrier.wait() code, _, _ = register(base, race_username, password) with lock: results.append(code) threads = [threading.Thread(target=attempt) for _ in range(8)] for thread in threads: thread.start() for thread in threads: thread.join() check(results.count(201) == 1, "exactly one registration must succeed: %s" % sorted(results)) check(results.count(409) == 7, "losers must get 409: %s" % sorted(results)) print("PASS: concurrent registration -> one 201 and seven 409") if args.expiry: status, _, raw = call(base, "POST", "/api/v1/auth/sessions", basic="u_neg_%s:%s" % (tag, password)) check(status == 201, "login failed: %d" % status) short = json.loads(raw) expires = short["expires_at"] from datetime import datetime, timezone ttl = (datetime.fromisoformat(expires.replace("Z", "+00:00")) - datetime.now(timezone.utc)).total_seconds() check(ttl < 60, "run this with a short SESSION_TTL_SECONDS (ttl=%.1fs)" % ttl) time.sleep(max(0.0, ttl) + 1.5) status, _, _ = call(base, "GET", "/api/v1/users/me", token=short["token"]) check(status == 401, "expired session must be 401, got %d" % status) print("PASS: session expired after %.0fs TTL" % ttl) if args.cache_check: status, _, raw = call(base, "POST", "/api/v1/auth/sessions", basic="u_neg_%s:%s" % (tag, password)) token = json.loads(raw)["token"] subprocess.run(["docker", "compose", "stop", "valkey"], cwd=args.compose_dir, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) try: status, _, _ = call(base, "GET", "/api/v1/users/me", token=token) check(status == 200, "auth must keep working without the cache, got %d" % status) print("PASS: authentication survives a cache outage") finally: subprocess.run(["docker", "compose", "start", "valkey"], cwd=args.compose_dir, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) print("PASS: student lab2 checks completed") if __name__ == "__main__": try: main() except Failure as error: print("FAIL:", error) raise SystemExit(1)