#!/usr/bin/env python3 """Short-TTL session expiry and API-restart test for lab2. Operator contract: the API must be started with a short SESSION_TTL_SECONDS (the Makefile target test-expiry recreates only the API with 15 seconds). The script: 1. registers and logs in a synthetic user; 2. checks that /users/me works with the token; 3. optionally restarts ONLY the API container and checks the same token still works (sessions live in Valkey, not in API memory) while the process instance id changes; 4. waits for the original expiry deadline and checks the token now gets 401, so the TTL was not extended by the restart. No token is printed or written. """ import base64 import datetime as dt import json import subprocess import sys 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, arguments, check, timestamp # noqa: E402 def wait_ready(base_url, timeout=90): import urllib.request deadline = time.monotonic() + timeout last = None while time.monotonic() < deadline: try: with urllib.request.urlopen(base_url + '/health/ready', timeout=3) as response: if response.status == 200: return except Exception as exc: # noqa: BLE001 - readiness polling last = exc time.sleep(0.5) raise Failure('API did not become ready after restart (' + type(last).__name__ + ')') from None def main(): def configure(parser): parser.add_argument('--restart-api', action='store_true', help='restart only the API container through scripts/compose.sh') parser.add_argument('--expected-ttl', type=int, default=15, help='SESSION_TTL_SECONDS the API was started with') args = arguments('Short-TTL session expiry and API restart', configure) c = Client(args.base_url, args.ca_file) actor = c.user('expiry') registration = actor['registration'] credential = base64.b64encode( (registration['username'] + ':' + registration['password']).encode('utf-8')).decode('ascii') session = c.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': 'Basic ' + credential}, schema='Session')['json'] actor['token'] = session['token'] expires = timestamp(session['expires_at']) now = dt.datetime.now(dt.timezone.utc) remaining = (expires - now).total_seconds() check(remaining > 1, 'session expired before the test started') check(remaining <= args.expected_ttl + 2, 'session TTL is %.1fs, expected about %ds; start the API with the short TTL' % (remaining, args.expected_ttl)) me = c.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json'] check(me['id'] == actor['id'], 'fresh token does not resolve to its user') instance_before = c.call('GET', '/api/v1/users/me', actor=actor, schema='User')['headers']['X-Instance-Id'] check(bool(instance_before), 'missing X-Instance-Id') if args.restart_api: started = time.monotonic() subprocess.run([str(ROOT / 'scripts/compose.sh'), '--env-file', '.env', 'restart', 'api'], cwd=str(ROOT), check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) wait_ready(args.base_url) restart_seconds = time.monotonic() - started # The same token must still be valid: the session was not stored in the # API process and was not dropped by recreating it. same = c.call('GET', '/api/v1/users/me', actor=actor, schema='User') check(same['json']['id'] == actor['id'], 'token was lost when the API restarted') instance_after = same['headers']['X-Instance-Id'] check(instance_after != instance_before, 'API instance id did not change after restart') print('PASS: token survived an API-only restart in %.2fs; instance %s -> %s' % (restart_seconds, instance_before, instance_after)) else: restart_seconds = None instance_after = instance_before # Wait for the absolute deadline that was returned at login. Polling also # tolerates small clock differences between host and container. deadline = time.monotonic() + max(0.0, (expires - dt.datetime.now(dt.timezone.utc)).total_seconds()) + 2 status = None while time.monotonic() < deadline + 10: response = c.call('GET', '/api/v1/users/me', (200, 401), actor=actor) status = response['status'] if status == 401: break time.sleep(0.5) check(status == 401, 'expired token still authenticates (status %r)' % (status,)) challenge = c.call('GET', '/api/v1/users/me', 401, actor=actor)['headers'].get('WWW-Authenticate', '') check(challenge.lower().startswith('bearer'), 'expired token 401 has no Bearer challenge') # Revoked/expired sessions cannot be logged out a second time. c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=actor) summary = { 'checked_at': dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z'), 'configured_ttl_seconds': args.expected_ttl, 'observed_ttl_seconds': round(remaining, 3), 'api_restart': bool(args.restart_api), 'api_restart_seconds': None if restart_seconds is None else round(restart_seconds, 3), 'instance_before': instance_before, 'instance_after': instance_after, 'expired_status': status, } print(json.dumps(summary, ensure_ascii=False, sort_keys=True)) print('PASS: short-TTL expiry, absolute deadline, and API-restart session survival') if __name__ == '__main__': try: main() except AssertionError as exc: print('FAIL:', exc) raise SystemExit(1)