forked from mtusi2026/mtusi2026lab7
feat: complete lab 7 grade 4 security controls and report
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
"""Verify rehash in PostgreSQL and measure rejected concurrent login work."""
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client
|
||||
|
||||
|
||||
def main():
|
||||
ca = "secrets/tls/lab7-ingress-ca.crt"
|
||||
endpoint = "https://localhost:8443"
|
||||
api = Client(endpoint, ca)
|
||||
actor = api.user("rehash")
|
||||
registration = actor["registration"]
|
||||
user_id = actor["id"]
|
||||
|
||||
def sql(statement):
|
||||
return subprocess.check_output(["docker", "compose", "exec", "-T", "db", "sh", "-ec",
|
||||
'psql -X -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" "$POSTGRES_DB" -At'],
|
||||
text=True, input=statement, cwd=ROOT).strip()
|
||||
|
||||
# Derive a synthetic legacy hash with the same Go implementation in the test image.
|
||||
legacy = subprocess.check_output(["docker", "compose", "--profile", "test", "run", "--rm", "-T",
|
||||
"--no-deps", "-e", "LAB7_REHASH_FIXTURE", "backend-tests",
|
||||
"go", "test", "./backend/services", "-run", "^TestPrintLegacyFixture$", "-v"],
|
||||
cwd=ROOT, text=True, env=os.environ | {"LAB7_REHASH_FIXTURE": registration["password"]})
|
||||
old = next(line for line in legacy.splitlines() if line.startswith("$argon2id$"))
|
||||
sql(f"UPDATE users SET password_hash=convert_to('{old}','UTF8') WHERE id='{user_id}';")
|
||||
auth = "Basic " + base64.b64encode(
|
||||
f"{registration['username']}:{registration['password']}".encode()).decode()
|
||||
api.call("POST", "/api/v1/auth/sessions", 201, headers={"Authorization": auth}, schema="Session")
|
||||
assert sql(f"SELECT split_part(convert_from(password_hash,'UTF8'),'$',4) FROM users WHERE id='{user_id}';") == "m=65536,t=3,p=2"
|
||||
print("PASS: successful login upgraded the stored legacy Argon2id hash")
|
||||
context = ssl.create_default_context(cafile=ca)
|
||||
|
||||
def login(_):
|
||||
started = time.monotonic()
|
||||
req = Request(endpoint + "/api/v1/auth/sessions", data=b"", headers={"Authorization": auth})
|
||||
try:
|
||||
with urlopen(req, context=context, timeout=10) as response:
|
||||
return response.status, time.monotonic()-started
|
||||
except HTTPError as error:
|
||||
assert error.code == 429 and error.headers["Retry-After"]
|
||||
return error.code, time.monotonic()-started
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=24) as pool:
|
||||
result = list(pool.map(login, range(24)))
|
||||
status = {code: sum(c == code for c, _ in result) for code in (201, 429)}
|
||||
assert all(status.values()), status
|
||||
latencies = sorted(duration for _, duration in result)
|
||||
print(json.dumps({"requests": len(result), "status": status,
|
||||
"p50_ms": round(latencies[11]*1000), "max_ms": round(latencies[-1]*1000)}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user