Files
mtusi2026lab7/tests/test_login_budget.py
T

49 lines
1.8 KiB
Python

"""Verify the shared login rate limit with synthetic credentials on the local stand."""
import base64
import json
from pathlib import Path
import time
import uuid
from client import Client, arguments, check, run
ROOT = Path(__file__).resolve().parents[1]
def main():
args = arguments('Local shared login limit')
client = Client(args.base_url, args.ca_file)
credential = 'budget_probe_' + uuid.uuid4().hex[:12] + ':synthetic-password'
basic = base64.b64encode(credential.encode()).decode()
challenge = {'Authorization': 'Basic ' + basic}
limited_instances = set()
rejected = 0
throttled = 0
started = time.monotonic()
for _ in range(250):
response = client.call('POST', '/api/v1/auth/sessions', (401, 429), headers=challenge)
check(basic not in response['bytes'].decode() and credential not in response['bytes'].decode(),
'Error included synthetic credentials')
if response['status'] == 401:
rejected += 1
continue
throttled += 1
check(response['headers'].get('Retry-After') == '60', 'Missing Retry-After')
limited_instances.add(response['headers']['X-Instance-Id'])
if len(limited_instances) == 2:
break
check(len(limited_instances) == 2, 'The same login budget did not block both replicas')
(ROOT / 'evidence/login-budget.json').write_text(json.dumps({
'invalid_credentials_responses': rejected,
'rate_limited_responses': throttled,
'limited_replicas': len(limited_instances),
'retry_after_seconds': 60,
'elapsed_seconds': round(time.monotonic() - started, 3),
}, indent=2) + '\n', encoding='utf-8')
print('PASS: shared login budget, HTTP 429 on both replicas and no credentials in errors')
if __name__ == '__main__':
run(main)