forked from mtusi2026/mtusi2026lab7
test(security): automate lifecycle and login budget measurements
This commit is contained in:
@@ -0,0 +1,227 @@
|
||||
"""Real old-hash migration and shared login admission/resource measurement."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import statistics
|
||||
import threading
|
||||
import time
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
from argon2 import PasswordHasher
|
||||
|
||||
from scripts.stand import BASE, ROOT, command, compose, ready, sql
|
||||
from scripts.tls_client import FreshTrustTransport
|
||||
|
||||
|
||||
def resources():
|
||||
ids = compose("ps", "-q", "api").split()
|
||||
result = []
|
||||
for cid in ids:
|
||||
raw = command(
|
||||
[
|
||||
"docker",
|
||||
"exec",
|
||||
cid,
|
||||
"python",
|
||||
"-c",
|
||||
"import json,pathlib;p=pathlib.Path('/sys/fs/cgroup');print(json.dumps({'memory_current':int((p/'memory.current').read_text()),'cpu_stat':dict(line.split() for line in (p/'cpu.stat').read_text().splitlines())}))",
|
||||
]
|
||||
)
|
||||
info = json.loads(command(["docker", "inspect", cid]))[0]
|
||||
result.append(
|
||||
{
|
||||
"container": cid[:12],
|
||||
"cpu_nano": info["HostConfig"]["NanoCpus"],
|
||||
"memory_limit": info["HostConfig"]["Memory"],
|
||||
**json.loads(raw),
|
||||
}
|
||||
)
|
||||
assert len(result) == 2
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output", default="evidence/login-budget-first.json")
|
||||
args = parser.parse_args()
|
||||
output = ROOT / args.output
|
||||
assert not output.exists(), "Choose a new receipt path"
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
report = {
|
||||
"date": datetime.now(UTC).isoformat(),
|
||||
"source_commit": command(["git", "rev-parse", "HEAD"]),
|
||||
"complete": False,
|
||||
"measurements": [],
|
||||
}
|
||||
with httpx.Client(
|
||||
base_url=BASE,
|
||||
transport=FreshTrustTransport(),
|
||||
trust_env=False,
|
||||
timeout=12,
|
||||
) as client:
|
||||
try:
|
||||
ready(timeout=90)
|
||||
username = "legacy_" + uuid4().hex[:20]
|
||||
password = "Synthetic-password-" + uuid4().hex
|
||||
r = client.post(
|
||||
"/api/v1/users",
|
||||
json={
|
||||
"username": username,
|
||||
"display_name": "Synthetic migration",
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
assert r.status_code == 201
|
||||
uid = r.json()["id"]
|
||||
previous = PasswordHasher(
|
||||
time_cost=2, memory_cost=19456, parallelism=1
|
||||
).hash(password)
|
||||
sql(
|
||||
"UPDATE users SET password_hash='"
|
||||
+ previous
|
||||
+ "' WHERE id='"
|
||||
+ uid
|
||||
+ "'"
|
||||
)
|
||||
r = client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
auth=httpx.BasicAuth(username, password + "-wrong"),
|
||||
)
|
||||
assert r.status_code == 401
|
||||
assert (
|
||||
sql("SELECT password_hash FROM users WHERE id='" + uid + "'")
|
||||
== previous
|
||||
)
|
||||
began = time.monotonic()
|
||||
r = client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
auth=httpx.BasicAuth(username, password),
|
||||
)
|
||||
assert r.status_code == 201
|
||||
elapsed = time.monotonic() - began
|
||||
current = sql(
|
||||
"SELECT password_hash FROM users WHERE id='" + uid + "'"
|
||||
)
|
||||
assert current != previous and "$m=65536,t=3,p=4$" in current
|
||||
assert PasswordHasher().verify(current, password)
|
||||
report["rehash"] = {
|
||||
"old_parameters": "argon2id m=19456KiB,t=2,p=1",
|
||||
"new_parameters": "argon2id m=65536KiB,t=3,p=4",
|
||||
"wrong_password_kept_old_hash": True,
|
||||
"valid_login_updated_hash": True,
|
||||
"valid_login_seconds_including_rehash": round(elapsed, 6),
|
||||
}
|
||||
# Operator resets only synthetic limiter state to define a known
|
||||
# initial burst. No API/rate configuration is changed for the test.
|
||||
sql("TRUNCATE login_buckets")
|
||||
report["before"] = resources()
|
||||
stop = threading.Event()
|
||||
health = []
|
||||
|
||||
def healthy():
|
||||
while not stop.is_set():
|
||||
t = time.monotonic()
|
||||
response = client.get("/health/ready")
|
||||
health.append(
|
||||
{
|
||||
"status": response.status_code,
|
||||
"seconds": time.monotonic() - t,
|
||||
}
|
||||
)
|
||||
stop.wait(0.25)
|
||||
|
||||
observer = threading.Thread(target=healthy)
|
||||
observer.start()
|
||||
started = time.monotonic()
|
||||
|
||||
def login(i):
|
||||
name = (
|
||||
"absent_"
|
||||
+ hashlib.sha256((username + str(i)).encode()).hexdigest()[
|
||||
:20
|
||||
]
|
||||
)
|
||||
t = time.monotonic()
|
||||
r = client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
auth=httpx.BasicAuth(name, password),
|
||||
)
|
||||
result = {
|
||||
"status": r.status_code,
|
||||
"seconds": time.monotonic() - t,
|
||||
"instance": r.headers.get("x-instance-id"),
|
||||
"retry_after": r.headers.get("retry-after"),
|
||||
}
|
||||
assert r.status_code in {401, 429}
|
||||
if r.status_code == 429:
|
||||
assert int(r.headers["retry-after"]) >= 1
|
||||
return result
|
||||
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=12) as pool:
|
||||
report["measurements"] = list(pool.map(login, range(72)))
|
||||
finally:
|
||||
stop.set()
|
||||
observer.join(15)
|
||||
duration = time.monotonic() - started
|
||||
report["after"] = resources()
|
||||
admitted = [
|
||||
x for x in report["measurements"] if x["status"] == 401
|
||||
]
|
||||
limited = [x for x in report["measurements"] if x["status"] == 429]
|
||||
assert limited and admitted
|
||||
assert len(admitted) <= 8 + int(2 * duration) + 1
|
||||
assert len({x["instance"] for x in report["measurements"]}) == 2
|
||||
assert health and all(x["status"] == 200 for x in health)
|
||||
buckets = int(
|
||||
sql(
|
||||
"SELECT count(*) FROM login_buckets WHERE bucket<>'global'"
|
||||
)
|
||||
)
|
||||
assert buckets == len(admitted), (
|
||||
"Rejected random accounts must not allocate buckets"
|
||||
)
|
||||
report["flood"] = {
|
||||
"requests": 72,
|
||||
"concurrency": 12,
|
||||
"seconds": round(duration, 6),
|
||||
"statuses": dict(
|
||||
Counter(str(x["status"]) for x in report["measurements"])
|
||||
),
|
||||
"both_replicas_observed": True,
|
||||
"new_account_buckets": buckets,
|
||||
"shared_admission_bound": 8 + int(2 * duration) + 1,
|
||||
"limited_median_seconds": statistics.median(
|
||||
x["seconds"] for x in limited
|
||||
),
|
||||
"admitted_median_seconds": statistics.median(
|
||||
x["seconds"] for x in admitted
|
||||
),
|
||||
"health": health,
|
||||
"cpu_usage_seconds": sum(
|
||||
int(a["cpu_stat"]["usage_usec"])
|
||||
- int(b["cpu_stat"]["usage_usec"])
|
||||
for a, b in zip(
|
||||
report["after"], report["before"], strict=True
|
||||
)
|
||||
)
|
||||
/ 1e6,
|
||||
"memory_measurement": "cgroup current before/after, not a peak measurement",
|
||||
}
|
||||
report["complete"] = True
|
||||
finally:
|
||||
output.write_text(
|
||||
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
||||
)
|
||||
print(
|
||||
"PASS: old-hash upgrade, shared pre-KDF rate limit and measured login resource budget"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user