forked from mtusi2026/mtusi2026lab7
225 lines
10 KiB
Python
225 lines
10 KiB
Python
"""Isolated API qualification. Sends synthetic requests only to the grade-4 port."""
|
|
import argparse
|
|
import base64
|
|
from collections import Counter
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import http.client
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import ssl
|
|
import subprocess
|
|
from time import monotonic, sleep, time
|
|
from uuid import uuid4
|
|
|
|
from observability import Grafana, wait
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
WINDOW = int(os.getenv("LOGIN_WINDOW_SECONDS", "10"))
|
|
LIMIT = int(os.getenv("LOGIN_WINDOW_LIMIT", "40"))
|
|
|
|
|
|
def call(context, method, path, *, data=None, token=None, authorization=None):
|
|
connection = http.client.HTTPSConnection("localhost", 28443, context=context, timeout=5)
|
|
headers = {"Content-Type": "application/json"}
|
|
if token or authorization:
|
|
headers["Authorization"] = authorization or "Bearer " + token
|
|
try:
|
|
connection.request(method, path, None if data is None else json.dumps(data), headers)
|
|
reply = connection.getresponse()
|
|
return (reply.status, reply.getheader("X-Instance-Id"), reply.getheader("Retry-After"),
|
|
reply.read(), reply.getheader("X-Request-Id"))
|
|
finally:
|
|
connection.close()
|
|
|
|
|
|
def next_window():
|
|
sleep(WINDOW - time() % WINDOW + 0.15)
|
|
|
|
|
|
def login(context):
|
|
next_window()
|
|
start = monotonic()
|
|
path = "/api/v1/auth/sessions"
|
|
with ThreadPoolExecutor(max_workers=12) as executor:
|
|
replies = list(executor.map(lambda _: call(context, "POST", path), range(LIMIT * 2)))
|
|
assert monotonic() - start < WINDOW - 1
|
|
assert Counter(row[0] for row in replies) == {401: LIMIT, 429: LIMIT}
|
|
assert len({row[1] for row in replies if row[0] == 401 and row[1]}) == 2
|
|
assert all(row[2] and 1 <= int(row[2]) <= WINDOW for row in replies if row[0] == 429)
|
|
print(f"PASS: {LIMIT} shared admissions and {LIMIT} throttled across both API replicas")
|
|
|
|
next_window()
|
|
basic = base64.b64encode(b"absent_fixture_user:synthetic_password").decode()
|
|
start = monotonic()
|
|
with ThreadPoolExecutor(max_workers=12) as executor:
|
|
replies = list(executor.map(lambda _: call(context, "POST", path,
|
|
authorization="Basic " + basic), range(LIMIT * 2)))
|
|
elapsed = monotonic() - start
|
|
counts = Counter(row[0] for row in replies)
|
|
assert elapsed < WINDOW - 1 and counts.keys() == {401, 429}
|
|
assert counts[401] <= LIMIT and sum(counts.values()) == LIMIT * 2
|
|
assert call(context, "GET", "/health/ready")[0] == 200
|
|
print(f"PASS: wrong-password burst {elapsed:.3f}s: {counts[401]} rejected after hash, {counts[429]} throttled")
|
|
next_window()
|
|
assert call(context, "POST", path)[0] == 401
|
|
print("PASS: admissions resume in the next window")
|
|
|
|
|
|
def rehash(context):
|
|
username = "rehash_" + uuid4().hex[:12]
|
|
password = uuid4().hex
|
|
assert call(context, "POST", "/api/v1/users", data={
|
|
"username": username, "display_name": "Rehash fixture", "password": password
|
|
})[0] == 201
|
|
compose = ["sh", str(ROOT / "scripts/compose.sh"), "exec", "-T", "api-a", "python", "-c"]
|
|
code = """
|
|
import json, sys
|
|
from argon2 import PasswordHasher
|
|
import psycopg
|
|
from src.credentials import credentials
|
|
from src.auth import password_hasher
|
|
username, password, operation = json.load(sys.stdin)
|
|
credentials.start()
|
|
with psycopg.connect(credentials.get()["database_url"]) as conn:
|
|
old = PasswordHasher(memory_cost=19456, time_cost=2, parallelism=1)
|
|
if operation == "seed":
|
|
conn.execute("UPDATE users SET password_hash=%s WHERE username=%s", (old.hash(password), username))
|
|
else:
|
|
value = conn.execute("SELECT password_hash FROM users WHERE username=%s", (username,)).fetchone()[0]
|
|
assert password_hasher.verify(value, password) and not password_hasher.check_needs_rehash(value)
|
|
credentials.stop.set()
|
|
"""
|
|
subprocess.run([*compose, code], input=json.dumps([username, password, "seed"]), text=True, check=True)
|
|
basic = base64.b64encode(f"{username}:{password}".encode()).decode()
|
|
next_window()
|
|
assert call(context, "POST", "/api/v1/auth/sessions", authorization="Basic " + basic)[0] == 201
|
|
subprocess.run([*compose, code], input=json.dumps([username, password, "verify"]), text=True, check=True)
|
|
print("PASS: successful login rehashed an older Argon2id profile")
|
|
|
|
|
|
def rotation(context, kind):
|
|
username = "rotate_" + uuid4().hex[:12]
|
|
password = uuid4().hex
|
|
assert call(context, "POST", "/api/v1/users", data={
|
|
"username": username, "display_name": "Rotation fixture", "password": password
|
|
})[0] == 201
|
|
basic = base64.b64encode(f"{username}:{password}".encode()).decode()
|
|
result = call(context, "POST", "/api/v1/auth/sessions", authorization="Basic " + basic)
|
|
assert result[0] == 201
|
|
token = json.loads(result[3])["token"]
|
|
counts = Counter()
|
|
instances = set()
|
|
with subprocess.Popen(["python3", str(ROOT / "scripts" / f"rotate-{kind}.py")], cwd=ROOT) as process:
|
|
while process.poll() is None:
|
|
try:
|
|
status, instance, *_ = call(context, "GET", "/api/v1/users/me", token=token)
|
|
counts[status] += 1
|
|
if status == 200 and instance:
|
|
instances.add(instance)
|
|
except (OSError, http.client.HTTPException):
|
|
counts["transport_error"] += 1
|
|
sleep(0.1)
|
|
print(f"During {kind} rotation: {dict(counts)}, API replicas observed: {len(instances)}")
|
|
assert process.returncode == 0 and counts.keys() == {200} and len(instances) == 2
|
|
|
|
|
|
def log_hygiene(context):
|
|
username, password = "logs_" + uuid4().hex[:12], uuid4().hex
|
|
assert call(context, "POST", "/api/v1/users", data={
|
|
"username": username, "display_name": "Log fixture", "password": password
|
|
})[0] == 201
|
|
basic = base64.b64encode(f"{username}:{password}".encode()).decode()
|
|
next_window()
|
|
result = call(context, "POST", "/api/v1/auth/sessions", authorization="Basic " + basic)
|
|
assert result[0] == 201
|
|
token = json.loads(result[3])["token"]
|
|
authenticated = call(context, "GET", "/api/v1/users/me", token=token)
|
|
assert authenticated[0] == 200
|
|
logs = subprocess.check_output(
|
|
["sh", str(ROOT / "scripts/compose.sh"), "logs", "--no-color",
|
|
"api-a", "api-b", "worker", "recovery", "postgres", "otel-collector"], text=True
|
|
)
|
|
grafana = Grafana("https://localhost:23007")
|
|
secrets = (password, token, basic)
|
|
assert all(value not in logs for value in secrets)
|
|
for request_id in (result[4], authenticated[4]):
|
|
assert request_id
|
|
query = '{service_name="messenger-api"} | json | request_id="' + request_id + '"'
|
|
telemetry = wait(lambda: grafana.logs(query), timeout=45)
|
|
trace_id = next(log["trace_id"] for log in telemetry if log.get("trace_id"))
|
|
spans = wait(lambda: grafana.trace(trace_id), timeout=45)
|
|
sampled = json.dumps((telemetry, spans))
|
|
assert all(value not in sampled for value in secrets)
|
|
subprocess.run(
|
|
["sh", str(ROOT / "scripts/compose.sh"), "exec", "-T", "--user", "postgres", "postgres",
|
|
"psql", "-Xq", "-v", "ON_ERROR_STOP=1", "-d", "messenger"],
|
|
input=f"UPDATE sessions SET expires_at=now()-interval '1 second' WHERE user_id="
|
|
f"(SELECT id FROM users WHERE username='{username}');",
|
|
text=True, check=True,
|
|
)
|
|
assert call(context, "GET", "/api/v1/users/me", token=token)[0] == 401
|
|
print("PASS: container logs and correlated Loki/Tempo records exclude synthetic credentials")
|
|
print("PASS: the same bearer is denied after session expiry")
|
|
|
|
|
|
def await_ready(context, status, seconds):
|
|
deadline = monotonic() + seconds
|
|
while monotonic() < deadline:
|
|
try:
|
|
if call(context, "GET", "/health/ready")[0] == status:
|
|
return
|
|
except (OSError, http.client.HTTPException):
|
|
pass
|
|
sleep(0.5)
|
|
raise AssertionError(f"Readiness did not reach HTTP {status}")
|
|
|
|
|
|
def availability(context, kind):
|
|
compose = ["sh", str(ROOT / "scripts/compose.sh")]
|
|
if kind == "login-recovery":
|
|
subprocess.run([*compose, "stop", "postgres"], check=True)
|
|
try:
|
|
subprocess.run([*compose, "run", "--rm", "-T", "probe", "login-unavailable"], check=True)
|
|
finally:
|
|
subprocess.run([*compose, "start", "postgres"], check=True)
|
|
await_ready(context, 200, 45)
|
|
next_window()
|
|
assert call(context, "POST", "/api/v1/auth/sessions")[0] == 401
|
|
print("PASS: both login endpoints fail closed with PostgreSQL down and recover after restart")
|
|
else:
|
|
seal = "import bao; bao.request('sys/seal', token=bao.operator()['root_token'], method='PUT')"
|
|
subprocess.run(["python3", "-c", seal], env=dict(os.environ, PYTHONPATH=str(ROOT / "scripts")), check=True)
|
|
try:
|
|
await_ready(context, 503, 45)
|
|
finally:
|
|
subprocess.run(["python3", str(ROOT / "scripts/bao.py"), "unseal"], check=True)
|
|
await_ready(context, 200, 45)
|
|
print("PASS: sealed OpenBao drains bounded snapshots, fails closed, and recovers after unseal")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("test", choices=("login", "rehash", "db", "leaf", "login-recovery",
|
|
"sealed", "log-hygiene"))
|
|
args = parser.parse_args()
|
|
if (not os.environ.get("COMPOSE_PROJECT_NAME", "").startswith("lab7-grade4-")
|
|
or "grade4.compose.yaml" not in os.environ.get("COMPOSE_FILE", "")
|
|
or os.environ.get("LAB7_OPENBAO_URL") != "https://localhost:28200"):
|
|
parser.error("Use the isolated Compose override and OpenBao port documented in REPORT.md")
|
|
context = ssl.create_default_context(cafile=str(Path(os.environ["LAB7_STATE"]) / "trust/ca.crt"))
|
|
if args.test == "login":
|
|
login(context)
|
|
elif args.test == "rehash":
|
|
rehash(context)
|
|
elif args.test == "log-hygiene":
|
|
log_hygiene(context)
|
|
elif args.test in ("login-recovery", "sealed"):
|
|
availability(context, args.test)
|
|
else:
|
|
rotation(context, args.test)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|