52 lines
2.0 KiB
Python
52 lines
2.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Check the shared login rate limit (429 + Retry-After) over HTTPS."""
|
|
import base64
|
|
import json
|
|
import ssl
|
|
import sys
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
CA = str(ROOT / "pki" / "ca.crt")
|
|
BASE = "https://localhost:8443"
|
|
|
|
|
|
def call(method, path, body=None, headers=None):
|
|
ctx = ssl.create_default_context(cafile=CA)
|
|
data = json.dumps(body).encode() if body is not None else None
|
|
request = urllib.request.Request(BASE + path, data=data, method=method,
|
|
headers={"Content-Type": "application/json", **(headers or {})})
|
|
try:
|
|
with urllib.request.urlopen(request, context=ctx, timeout=10) as response:
|
|
return response.status, dict(response.headers), response.read()
|
|
except urllib.error.HTTPError as error:
|
|
return error.code, dict(error.headers), error.read()
|
|
|
|
|
|
def main():
|
|
username = "rl_" + uuid.uuid4().hex[:10]
|
|
password = "T3st-" + uuid.uuid4().hex
|
|
status, _, _ = call("POST", "/api/v1/users",
|
|
{"username": username, "display_name": "Rate limit", "password": password})
|
|
assert status == 201, status
|
|
bad = base64.b64encode((username + ":wrong-password-123").encode()).decode()
|
|
results = []
|
|
for _ in range(6):
|
|
status, headers, body = call("POST", "/api/v1/auth/sessions",
|
|
headers={"Authorization": "Basic " + bad})
|
|
retry_after = headers.get("Retry-After") or headers.get("retry-after")
|
|
results.append((status, retry_after))
|
|
print("attempts:", results)
|
|
limited = results[-1][0] == 429 and results[-1][1] is not None
|
|
earlier = all(code == 401 for code, _ in results[:5])
|
|
if not (limited and earlier):
|
|
raise SystemExit("login rate limit did not behave as expected")
|
|
print("PASS: login rate limit returns 429 with Retry-After after repeated failures")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|