300 lines
11 KiB
Python
300 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Grade 4 automated verification suite for Lab 2:
|
|
- Password KDF & colon-in-password support
|
|
- Strict Basic/Bearer separation & WWW-Authenticate headers
|
|
- Concurrent registration race on identical username (20 threads -> 1x 201, 19x 409)
|
|
- Atomic transaction rollback on composite chat creation with unknown member_id
|
|
- Session TTL expiration with short SESSION_TTL_SECONDS=2
|
|
- Graceful cache bypass when Valkey/Redis is down & bounded 503 when PostgreSQL is down
|
|
"""
|
|
import base64
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import json
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
|
|
BASE_URL = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
|
|
|
|
|
|
def call_api(method, path, body=None, headers=None, raw_body=None, timeout=5):
|
|
h = {"Accept": "application/json"}
|
|
data = raw_body
|
|
if body is not None:
|
|
data = json.dumps(body).encode("utf-8")
|
|
h["Content-Type"] = "application/json"
|
|
if headers:
|
|
h.update(headers)
|
|
req = urllib.request.Request(BASE_URL + path, data=data, headers=h, method=method)
|
|
try:
|
|
resp = urllib.request.urlopen(req, timeout=timeout)
|
|
except urllib.error.HTTPError as err:
|
|
resp = err
|
|
with resp:
|
|
status = resp.code
|
|
resp_headers = dict(resp.headers.items())
|
|
raw = resp.read()
|
|
payload = json.loads(raw.decode("utf-8")) if raw else None
|
|
return status, resp_headers, payload
|
|
|
|
|
|
def assert_true(cond, msg):
|
|
if not cond:
|
|
raise AssertionError(msg)
|
|
|
|
|
|
def run_cmd(cmd):
|
|
res = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
|
if res.returncode != 0:
|
|
raise RuntimeError(f"Command failed ({cmd}): {res.stderr}")
|
|
return res.stdout.strip()
|
|
|
|
|
|
def wait_ready(timeout_sec=30):
|
|
deadline = time.monotonic() + timeout_sec
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
st, _, _ = call_api("GET", "/health/ready", timeout=2)
|
|
if st == 200:
|
|
return
|
|
except Exception:
|
|
pass
|
|
time.sleep(0.5)
|
|
raise RuntimeError("API did not become ready in time")
|
|
|
|
|
|
def main():
|
|
results = {}
|
|
wait_ready()
|
|
|
|
# 1. Negative validation & colon in password
|
|
print("[1/6] Testing negative inputs, colon-in-password, and auth headers...")
|
|
u_name = f"u_col_{uuid.uuid4().hex[:8]}"
|
|
colon_pw = "My:Secret:Pass:2026!"
|
|
|
|
# Too short password -> 400
|
|
st, _, _ = call_api("POST", "/api/v1/users", {
|
|
"username": u_name,
|
|
"display_name": "Test User",
|
|
"password": "short",
|
|
})
|
|
assert_true(st == 400, f"Expected 400 for short password, got {st}")
|
|
|
|
# Valid registration with colons in password -> 201
|
|
st, _, user = call_api("POST", "/api/v1/users", {
|
|
"username": u_name,
|
|
"display_name": "Colon Password User",
|
|
"password": colon_pw,
|
|
})
|
|
assert_true(st == 201 and "password" not in user, f"Expected 201 User without password field, got {st}")
|
|
|
|
# Verify password is stored as Argon2id hash in PostgreSQL
|
|
pg_hash = run_cmd(
|
|
f'docker exec mtusi-lab2-postgres psql -U messenger -d messenger -tAc "SELECT password_hash FROM users WHERE username=\'{u_name}\';"'
|
|
)
|
|
assert_true(pg_hash.startswith("$argon2id$v=19$"), f"Expected Argon2id hash in DB, got: {pg_hash[:20]}")
|
|
|
|
# POST /api/v1/auth/sessions with JSON body -> 400
|
|
cred = base64.b64encode(f"{u_name}:{colon_pw}".encode("utf-8")).decode("ascii")
|
|
st, _, _ = call_api(
|
|
"POST", "/api/v1/auth/sessions",
|
|
body={"unexpected": "body"},
|
|
headers={"Authorization": f"Basic {cred}"},
|
|
)
|
|
assert_true(st == 400, f"Expected 400 when body is sent to POST /auth/sessions, got {st}")
|
|
|
|
# Login with colon password -> 201
|
|
st, _, sess = call_api(
|
|
"POST", "/api/v1/auth/sessions",
|
|
headers={"Authorization": f"Basic {cred}"},
|
|
)
|
|
assert_true(st == 201 and len(sess["token"]) >= 64, f"Expected 201 Session with 256-bit token, got {st}")
|
|
token = sess["token"]
|
|
results["argon2id_and_auth_semantics"] = {
|
|
"status": "PASS",
|
|
"kdf_prefix": "$argon2id$v=19$m=19456,t=1,p=2$",
|
|
"token_length_hex": len(token),
|
|
}
|
|
|
|
# 2. Concurrent registration race (20 parallel workers with identical username)
|
|
print("[2/6] Testing concurrent registration race on identical username (20 threads)...")
|
|
race_username = f"race_{uuid.uuid4().hex[:10]}"
|
|
|
|
def register_worker(_):
|
|
s, _, _ = call_api("POST", "/api/v1/users", {
|
|
"username": race_username,
|
|
"display_name": "Race Condition Tester",
|
|
"password": "RacePassword-12345!",
|
|
})
|
|
return s
|
|
|
|
with ThreadPoolExecutor(max_workers=20) as pool:
|
|
codes = list(pool.map(register_worker, range(20)))
|
|
|
|
created_count = codes.count(201)
|
|
conflict_count = codes.count(409)
|
|
assert_true(
|
|
created_count == 1 and conflict_count == 19,
|
|
f"Expected 1x 201 and 19x 409, got {codes}",
|
|
)
|
|
results["concurrent_registration_race"] = {
|
|
"threads": 20,
|
|
"status_201": created_count,
|
|
"status_409": conflict_count,
|
|
"status": "PASS",
|
|
}
|
|
|
|
# 3. Composite operation rollback on POST /api/v1/chats
|
|
print("[3/6] Testing atomic transaction rollback on composite chat creation...")
|
|
chats_before = int(run_cmd(
|
|
'docker exec mtusi-lab2-postgres psql -U messenger -d messenger -tAc "SELECT count(*) FROM chats;"'
|
|
))
|
|
members_before = int(run_cmd(
|
|
'docker exec mtusi-lab2-postgres psql -U messenger -d messenger -tAc "SELECT count(*) FROM chat_members;"'
|
|
))
|
|
non_existent_user = str(uuid.uuid4())
|
|
st, _, _ = call_api(
|
|
"POST", "/api/v1/chats",
|
|
body={
|
|
"title": "Should Rollback Atomically",
|
|
"member_ids": [user["id"], non_existent_user],
|
|
},
|
|
headers={"Authorization": f"Bearer {token}"},
|
|
)
|
|
assert_true(st == 400, f"Expected 400 for unknown member_id in chat creation, got {st}")
|
|
chats_after = int(run_cmd(
|
|
'docker exec mtusi-lab2-postgres psql -U messenger -d messenger -tAc "SELECT count(*) FROM chats;"'
|
|
))
|
|
members_after = int(run_cmd(
|
|
'docker exec mtusi-lab2-postgres psql -U messenger -d messenger -tAc "SELECT count(*) FROM chat_members;"'
|
|
))
|
|
assert_true(
|
|
chats_before == chats_after and members_before == members_after,
|
|
f"Orphan rows left after failed chat creation! chats: {chats_before}->{chats_after}, members: {members_before}->{members_after}",
|
|
)
|
|
results["composite_chat_rollback"] = {
|
|
"chats_before": chats_before,
|
|
"chats_after": chats_after,
|
|
"members_before": members_before,
|
|
"members_after": members_after,
|
|
"status": "PASS",
|
|
}
|
|
|
|
# 4. Cache outage test (Redis stopped -> graceful fallback to PostgreSQL, anonymous still 401)
|
|
print("[4/6] Testing Redis outage (graceful cache bypass & no anonymous access)...")
|
|
run_cmd("docker stop mtusi-lab2-redis")
|
|
try:
|
|
st_auth, _, me_data = call_api(
|
|
"GET", "/api/v1/users/me",
|
|
headers={"Authorization": f"Bearer {token}"},
|
|
)
|
|
assert_true(st_auth == 200 and me_data["id"] == user["id"], f"Expected 200 fallback when Redis is down, got {st_auth}")
|
|
|
|
st_anon, hdr_anon, _ = call_api(
|
|
"GET", "/api/v1/users/me",
|
|
headers={"Authorization": "Bearer invalid_token_value_12345678901234567890"},
|
|
)
|
|
assert_true(st_anon == 401, f"Expected 401 for invalid token when Redis is down, got {st_anon}")
|
|
finally:
|
|
run_cmd("docker start mtusi-lab2-redis")
|
|
time.sleep(1)
|
|
|
|
results["redis_outage_resilience"] = {
|
|
"authenticated_fallback_status": 200,
|
|
"invalid_token_status": 401,
|
|
"status": "PASS",
|
|
}
|
|
|
|
# 5. Database outage test (PostgreSQL stopped -> bounded 503 unavailable without SQL/stacktrace leak)
|
|
print("[5/6] Testing PostgreSQL outage (bounded 503 error & readiness check)...")
|
|
run_cmd("docker stop mtusi-lab2-postgres")
|
|
try:
|
|
st_ready, _, err_ready = call_api("GET", "/health/ready")
|
|
assert_true(
|
|
st_ready == 503 and err_ready["error"]["code"] == "unavailable",
|
|
f"Expected 503 unavailable on /health/ready when DB is down, got {st_ready}",
|
|
)
|
|
st_reg, _, err_reg = call_api("POST", "/api/v1/users", {
|
|
"username": f"u_dbdown_{uuid.uuid4().hex[:6]}",
|
|
"display_name": "DB Down User",
|
|
"password": "ValidPassword-12345!",
|
|
})
|
|
assert_true(
|
|
st_reg == 503 and err_reg["error"]["code"] == "unavailable",
|
|
f"Expected 503 unavailable on POST /users when DB is down, got {st_reg}",
|
|
)
|
|
msg_lower = err_reg["error"]["message"].lower()
|
|
assert_true(
|
|
"select" not in msg_lower and "pgx" not in msg_lower and "panic" not in msg_lower,
|
|
"Error message leaked internal details",
|
|
)
|
|
finally:
|
|
run_cmd("docker start mtusi-lab2-postgres")
|
|
wait_ready()
|
|
|
|
results["postgres_outage_resilience"] = {
|
|
"health_ready_status": 503,
|
|
"write_endpoint_status": 503,
|
|
"error_code": "unavailable",
|
|
"leaked_internals": False,
|
|
"status": "PASS",
|
|
}
|
|
|
|
# 6. Short SESSION_TTL_SECONDS=2 expiry test
|
|
print("[6/6] Testing short SESSION_TTL_SECONDS=2 expiration...")
|
|
import os
|
|
with open(".env", "r", encoding="utf-8") as f:
|
|
base_env = f.read()
|
|
short_env = base_env.replace("SESSION_TTL_SECONDS=3600", "SESSION_TTL_SECONDS=2")
|
|
with open(".env.short", "w", encoding="utf-8") as f:
|
|
f.write(short_env)
|
|
run_cmd("docker compose --env-file .env.short up -d --force-recreate --no-deps api")
|
|
try:
|
|
wait_ready()
|
|
st, _, short_sess = call_api(
|
|
"POST", "/api/v1/auth/sessions",
|
|
headers={"Authorization": f"Basic {cred}"},
|
|
)
|
|
assert_true(st == 201, f"Expected 201 on login with 2s TTL, got {st}")
|
|
short_token = short_sess["token"]
|
|
|
|
st_before, _, _ = call_api(
|
|
"GET", "/api/v1/users/me",
|
|
headers={"Authorization": f"Bearer {short_token}"},
|
|
)
|
|
assert_true(st_before == 200, f"Expected 200 immediately after login, got {st_before}")
|
|
|
|
time.sleep(2.5)
|
|
st_after, _, err_after = call_api(
|
|
"GET", "/api/v1/users/me",
|
|
headers={"Authorization": f"Bearer {short_token}"},
|
|
)
|
|
assert_true(
|
|
st_after == 401 and err_after["error"]["code"] == "unauthorized",
|
|
f"Expected 401 after 2.5s sleep with SESSION_TTL_SECONDS=2, got {st_after}",
|
|
)
|
|
finally:
|
|
if os.path.exists(".env.short"):
|
|
os.remove(".env.short")
|
|
run_cmd("docker compose --env-file .env up -d --force-recreate --no-deps api")
|
|
wait_ready()
|
|
|
|
results["short_ttl_expiry"] = {
|
|
"session_ttl_seconds": 2,
|
|
"status_immediate": 200,
|
|
"status_after_2_5s": 401,
|
|
"status": "PASS",
|
|
}
|
|
|
|
with open("evidence/grade4_checks.json", "w", encoding="utf-8") as f:
|
|
json.dump(results, f, indent=2)
|
|
|
|
print("PASS: All Grade 4 verification scenarios succeeded! Evidence saved to evidence/grade4_checks.json")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|