#!/usr/bin/env python3 """Wait for a stand, then prove that a short-TTL session expires. Run against a stand started with SESSION_TTL_SECONDS=2 (see check-expiry.sh). """ from __future__ import annotations import argparse import base64 import json import os import time import urllib.error import urllib.request def _call(base, method, path, token=None, body=None): headers = {"Accept": "application/json"} data = None if body is not None: data = json.dumps(body).encode("utf-8") headers["Content-Type"] = "application/json" if token: headers["Authorization"] = "Bearer " + token request = urllib.request.Request(base + path, data=data, headers=headers, method=method) try: with urllib.request.urlopen(request, timeout=10) as response: return response.status, json.loads(response.read() or b"null") except urllib.error.HTTPError as error: return error.code, json.loads(error.read() or b"null") def wait_ready(base, timeout=180.0): deadline = time.time() + timeout while time.time() < deadline: try: with urllib.request.urlopen(base + "/health/ready", timeout=3) as response: if response.status == 200: return except (urllib.error.URLError, TimeoutError, OSError): pass time.sleep(2) raise SystemExit("stand did not become ready") def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--base-url", default="http://localhost:8081") parser.add_argument("--ttl", type=int, default=2) args = parser.parse_args() base = args.base_url.rstrip("/") wait_ready(base) username = "expiry_" + os.urandom(4).hex() password = "T3st-" + os.urandom(8).hex() status, _ = _call(base, "POST", "/api/v1/users", body={"username": username, "display_name": "Expiry", "password": password}) assert status == 201, status credential = base64.b64encode(f"{username}:{password}".encode()).decode() request = urllib.request.Request( base + "/api/v1/auth/sessions", headers={"Authorization": "Basic " + credential, "Accept": "application/json"}, method="POST", ) with urllib.request.urlopen(request, timeout=10) as response: session = json.loads(response.read()) token = session["token"] me_before, _ = _call(base, "GET", "/api/v1/users/me", token=token) assert me_before == 200, me_before time.sleep(args.ttl + 1) me_after, _ = _call(base, "GET", "/api/v1/users/me", token=token) assert me_after == 401, f"expired token still accepted: {me_after}" print(f"PASS: session expired after ~{args.ttl}s (before=200, after=401)") if __name__ == "__main__": main()