Files
mtusi2026lab7/tests/session_expiry.py

43 lines
1.7 KiB
Python

#!/usr/bin/env python3
"""Verify that a bearer session is rejected after its configured Redis TTL."""
from __future__ import annotations
from pathlib import Path
import time
from client import Client, arguments, check, run
ROOT = Path(__file__).resolve().parents[1]
def configured_ttl() -> int:
env_file = ROOT / '.env'
check(env_file.is_file(), '.env is missing')
for raw in env_file.read_text(encoding='utf-8').splitlines():
line = raw.strip()
if line.startswith('SESSION_TTL_SECONDS='):
return int(line.split('=', 1)[1].strip().strip('"\''))
raise SystemExit('SESSION_TTL_SECONDS is missing from .env')
def main() -> None:
def configure(parser):
parser.add_argument('--wait-seconds', type=int, default=5,
help='expected SESSION_TTL_SECONDS configured on the running API')
args = arguments('Session expiry check; run against an isolated short-TTL test configuration', configure)
check(args.wait_seconds >= 1, '--wait-seconds must be positive')
check(configured_ttl() == args.wait_seconds,
'set SESSION_TTL_SECONDS in .env to --wait-seconds and recreate both API replicas first')
client = Client(args.base_url, args.ca_file)
actor = client.user('expiry')
fresh = client.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json']
check(fresh == actor['user'], 'fresh session was not accepted')
# Add a small scheduling margin without exposing or storing the bearer token.
time.sleep(args.wait_seconds + 1)
client.call('GET', '/api/v1/users/me', expected=401, actor=actor)
print('PASS: bearer session was accepted before expiry and rejected after the configured TTL.')
if __name__ == '__main__':
run(main)