Files
mtusi2026lab7/scripts/check-login-limit.py
T
ejur22 d995f98446
Skeleton contracts / contracts (pull_request) Canceled after 0s
Lab 7
2026-11-27 20:47:58 +03:00

59 lines
2.1 KiB
Python

#!/usr/bin/env python3
"""Login rate limit check (lab7): 429 + Retry-After after the shared budget.
Hits /api/v1/auth/sessions with wrong credentials for one synthetic username
until the per-(ip,user) budget is exhausted. The limiter runs before the
expensive Argon2 verification, so this also bounds password-spray CPU cost.
Run: python scripts/check-login-limit.py
"""
from __future__ import annotations
import base64
import json
import os
import ssl
import sys
import urllib.error
import urllib.request
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE = os.environ.get("BASE_URL", "https://localhost:8443")
CA = os.environ.get("CA_FILE", os.path.join(ROOT, "secrets", "pki", "ca.crt"))
LIMIT = int(os.environ.get("LOGIN_RATE_LIMIT", "10"))
def main() -> int:
context = ssl.create_default_context(cafile=CA)
username = "ratelimit_probe_%d" % os.getpid()
credentials = base64.b64encode((username + ":wrong-password").encode()).decode()
print("probing %s (limit=%d)" % (BASE, LIMIT))
limited = False
retry_after = None
for attempt in range(1, LIMIT + 4):
request = urllib.request.Request(
BASE + "/api/v1/auth/sessions", method="POST",
headers={"Authorization": "Basic " + credentials,
"Content-Type": "application/json"},
)
try:
urllib.request.urlopen(request, timeout=5, context=context).read()
status = 200
except urllib.error.HTTPError as error:
status = error.code
if status == 429:
limited = True
retry_after = error.headers.get("Retry-After")
print(" attempt %2d -> %d%s" % (attempt, status,
" Retry-After=" + str(retry_after) if status == 429 else ""))
if limited:
break
ok = limited and retry_after is not None and int(retry_after) > 0
print("PASS: login limited with 429 and Retry-After" if ok
else "FAIL: no 429/Retry-After observed")
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())