Files
mtusi2026lab7/student-tests/login_rate_limit.py
T
imenno_on d15d78efdf
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Добавил TLS и защиту мессенджера для лабораторной 7
2026-11-29 13:06:06 +03:00

41 lines
1.6 KiB
Python

#!/usr/bin/env python3
"""Проверяет 401 на ошибочные попытки и 429/Retry-After после лимита."""
import base64
import ssl
import sys
import urllib.error
import urllib.request
import uuid
from pathlib import Path
root = Path(__file__).resolve().parents[1]
base = sys.argv[1] if len(sys.argv) > 1 else "https://localhost:8443"
ca = sys.argv[2] if len(sys.argv) > 2 else str(root / "secrets/pki/ca.crt")
username = "rate_" + uuid.uuid4().hex[:20]
password = "synthetic-invalid-password"
request = urllib.request.Request(
base.rstrip("/") + "/api/v1/auth/sessions",
data=b"",
headers={"Authorization": "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()},
method="POST",
)
opener = urllib.request.build_opener(urllib.request.HTTPSHandler(
context=ssl.create_default_context(cafile=ca)))
for _ in range(10):
try:
opener.open(request, timeout=5)
except urllib.error.HTTPError as exc:
if exc.code != 401:
raise SystemExit("FAIL: invalid login did not return 401 before the limit")
else:
raise SystemExit("FAIL: invalid credentials were accepted")
try:
opener.open(request, timeout=5)
except urllib.error.HTTPError as exc:
retry = exc.headers.get("Retry-After", "")
if exc.code != 429 or not retry.isdigit() or int(retry) < 1:
raise SystemExit("FAIL: limiter did not return 429 with Retry-After")
else:
raise SystemExit("FAIL: limiter accepted attempt 11")
print("PASS: ten invalid logins returned 401; next login returned 429 with Retry-After")