Files
mtusi2026lab7/research/auth_budget.py
T

116 lines
3.6 KiB
Python

#!/usr/bin/env python3
"""Shared-replica login window and real weak-hash rehash regression."""
import base64
import json
import subprocess
import sys
import time
from pathlib import Path
from argon2 import PasswordHasher
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, check # noqa: E402
def sql(query):
result = subprocess.run(
[
"docker",
"compose",
"exec",
"-T",
"postgres",
"psql",
"-U",
"messenger",
"-d",
"messenger",
"-At",
"-v",
"ON_ERROR_STOP=1",
],
cwd=ROOT,
input=query,
text=True,
capture_output=True,
check=True,
)
return result.stdout.strip()
def main():
c = Client("https://localhost:8447", str(ROOT / "secrets/ca.pem"))
actor = c.user("rehash")
password = actor["registration"]["password"]
weak = PasswordHasher(time_cost=1, memory_cost=8192, parallelism=1).hash(password)
sql("UPDATE users SET password_hash='" + weak + "' WHERE id='" + actor["id"] + "';")
authorization = (
"Basic "
+ base64.b64encode((actor["registration"]["username"] + ":" + password).encode()).decode()
)
c.call(
"POST",
"/api/v1/auth/sessions",
201,
headers={"Authorization": authorization},
schema="Session",
)
upgraded = sql("SELECT password_hash FROM users WHERE id='" + actor["id"] + "';")
check(
upgraded != weak and "$m=65536,t=2,p=1$" in upgraded,
"successful login did not upgrade hash",
)
time.sleep(10.2)
wrong = (
"Basic "
+ base64.b64encode((actor["registration"]["username"] + ":incorrect").encode()).decode()
)
rows = []
for _ in range(12):
response = c.call(
"POST", "/api/v1/auth/sessions", expected=[401, 429], headers={"Authorization": wrong}
)
rows.append(
{
"status": response["status"],
"instance": response["headers"]["X-Instance-Id"],
"retry_after": response["headers"].get("Retry-After"),
"milliseconds": round(response["elapsed"] * 1000, 3),
}
)
sql(
"UPDATE sessions SET expires_at=now()-interval '1 second' WHERE user_id='"
+ actor["id"]
+ "';"
)
expiry_rows = []
for _ in range(4):
expired = c.call("GET", "/api/v1/users/me", expected=401, actor=actor)
expiry_rows.append(
{"status": expired["status"], "instance": expired["headers"]["X-Instance-Id"]}
)
result = {
"weak_hash_upgraded": True,
"expired_session_requests": expiry_rows,
"expired_session_denied_both_replicas": len({r["instance"] for r in expiry_rows}) >= 2,
"configured_memory_kib": 65536,
"time_cost": 2,
"parallelism": 1,
"requests": rows,
"distinct_api_instances": len({r["instance"] for r in rows}),
"passed": len({r["instance"] for r in expiry_rows}) >= 2
and sum(r["status"] == 401 for r in rows) == 10
and all(r["status"] == 429 and r["retry_after"] == "10" for r in rows[10:])
and len({r["instance"] for r in rows}) >= 2,
}
(ROOT / "evidence/auth-budget.json").write_text(json.dumps(result, indent=2) + "\n")
check(result["passed"], "shared login window failed")
print(json.dumps({k: v for k, v in result.items() if k != "requests"}))
if __name__ == "__main__":
main()