Files
mtusi2026lab7/scripts/check_api_security.py
T

72 lines
3.3 KiB
Python

"""Verify HTTPS permission, size, rate and session controls on synthetic users."""
import sys
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, Failure, arguments, check, run
def main():
args = arguments(__doc__, lambda parser: parser.add_argument("--expiry-only", action="store_true"))
client = Client(args.base_url, args.ca_file)
if args.expiry_only:
deadline = time.monotonic() + 40
replicas = set()
while len(replicas) < 2 and time.monotonic() < deadline:
try:
response = client.call("GET", "/health/ready", schema="Health")
replicas.add(response["headers"]["X-Instance-Id"])
except Failure:
pass
time.sleep(0.3)
check(len(replicas) >= 2, "Both API replicas must be ready for the expiry check")
actor = client.user("shortttl")
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
time.sleep(6)
client.call("GET", "/api/v1/users/me", 401, actor=actor)
print("PASS: HTTPS session expired on the stand configured with SESSION_TTL_SECONDS=5")
return
alice, bob, eve, chat = client.bootstrap()
attachment, _ = client.attachment(alice, chat)
attachment = client.wait_ready(alice, attachment)
base = "/api/v1/attachments/" + attachment["id"]
for suffix in ("", "/content"):
client.call("GET", base + suffix, 404, actor=eve, headers={"X-User-Id": alice["id"]})
other = client.call("POST", "/api/v1/chats", 201, actor=bob, body={
"title": "Separate chat", "member_ids": [bob["id"]],
}, schema="Chat")["json"]
client.call("POST", f"/api/v1/chats/{other['id']}/messages", 404, actor=bob, body={
"text": "", "attachment_ids": [attachment["id"]],
}, headers={"Idempotency-Key": uuid.uuid4().hex})
client.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": alice["id"]})
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
client.call("GET", "/api/v1/users/me", 401, actor=alice)
print("PASS: private attachment metadata/content, cross-chat reference, Bearer precedence and logout")
oversized = b'{"test":"' + b"x" * (1024 * 1024) + b'"}'
client.call("POST", "/api/v1/users", 413, raw=oversized,
headers={"Content-Type": "application/json"})
print("PASS: oversized JSON returned 413")
path = "/api/v1/auth/sessions"
client.call("POST", path, 401, headers={"X-Lab7-Login-Limited": "1"})
with ThreadPoolExecutor(max_workers=8) as pool:
burst = list(pool.map(lambda _: client.call("POST", path, [401, 429]), range(32)))
limited = [reply for reply in burst if reply["status"] == 429]
check(bool(limited), "Login limit did not activate during a burst")
for result in limited:
check(result["headers"].get("Retry-After") == "10", "missing or invalid Retry-After")
check(result["json"]["error"]["code"] == "rate_limited", "wrong error code for 429")
print("PASS: login rate limited with 429 and Retry-After=10; client flag stripped")
time.sleep(10)
client.call("POST", path, 401)
if __name__ == "__main__":
run(main)