import base64 import os import sys import urllib.error import urllib.request import uuid BASE_URL = os.getenv("BASE_URL", "https://localhost:8443").rstrip("/") CA_FILE = os.getenv("CA_FILE") if not CA_FILE: sys.exit("ERROR: CA_FILE must point to a trusted CA certificate") import ssl SSL_CONTEXT = ssl.create_default_context(cafile=CA_FILE) username = "rl_" + uuid.uuid4().hex[:16] password = "Wrong-Password-For-Rate-Limit-2026" def login(): credentials = base64.b64encode( f"{username}:{password}".encode() ).decode() request = urllib.request.Request( BASE_URL + "/api/v1/auth/sessions", data=b"", method="POST", headers={"Authorization": "Basic " + credentials}, ) try: with urllib.request.urlopen( request, context=SSL_CONTEXT, timeout=10, ) as response: return response.status, response.headers except urllib.error.HTTPError as exc: return exc.code, exc.headers print("Testing rate limit with username:", username) statuses = [] for attempt in range(1, 7): status, headers = login() statuses.append(status) print( f"Attempt {attempt}: HTTP {status}, " f"Retry-After={headers.get('Retry-After')}" ) if attempt <= 5: assert status == 401, ( f"Expected HTTP 401 for attempt {attempt}, got {status}" ) else: assert status == 429, ( f"Expected HTTP 429 for attempt {attempt}, got {status}" ) retry_after = headers.get("Retry-After") assert retry_after and retry_after.isdigit(), ( "Missing or invalid Retry-After" ) assert int(retry_after) > 0 print("PASS: shared login rate limit and Retry-After")