160 lines
5.9 KiB
Python
160 lines
5.9 KiB
Python
"""Run from the root of the running lab7 Compose project."""
|
|
import base64
|
|
import hashlib
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import uuid
|
|
|
|
PASSWORD = "lab7-rehash-fixture-only"
|
|
LEGACY_HASH = "$argon2id$v=19$m=19456,t=2,p=1$bGFiN2ZpeHR1cmUtc2FsdA$npUjV+v4zK/zR82TCdOM9YcGKDqER/5Tsu7yE0LELtU"
|
|
CURRENT_PREFIX = "$argon2id$v=19$m=65536,t=3,p=2$"
|
|
|
|
DB_PROBE = """
|
|
import json
|
|
import sys
|
|
import pipeline as p
|
|
|
|
action, user_id, value = json.load(sys.stdin)
|
|
with p.db(p.settings()()) as conn:
|
|
if action == 'install_legacy':
|
|
result = conn.execute('UPDATE users SET password_hash=%s WHERE id=%s',
|
|
(value, user_id)).rowcount == 1
|
|
elif action == 'check_rehash':
|
|
row = conn.execute('SELECT password_hash FROM users WHERE id=%s', (user_id,)).fetchone()
|
|
result = bool(row and row['password_hash'].startswith(value))
|
|
elif action == 'shorten_ttl':
|
|
result = conn.execute(
|
|
"UPDATE sessions SET expires_at=now()+interval '2 seconds' "
|
|
"WHERE token_hash=%s AND user_id=%s AND revoked_at IS NULL",
|
|
(bytes.fromhex(value), user_id),
|
|
).rowcount == 1
|
|
elif action == 'check_expiry':
|
|
row = conn.execute(
|
|
'SELECT expires_at<=now() AND revoked_at IS NULL AS expired '
|
|
'FROM sessions WHERE token_hash=%s AND user_id=%s',
|
|
(bytes.fromhex(value), user_id),
|
|
).fetchone()
|
|
result = bool(row and row['expired'])
|
|
else:
|
|
raise AssertionError('unexpected action')
|
|
print(json.dumps(result))
|
|
"""
|
|
|
|
WATCHDOG_PROBE = """
|
|
from contextlib import nullcontext
|
|
import json
|
|
import signal
|
|
import time
|
|
import uuid
|
|
import pipeline as p
|
|
|
|
class FakeBroker:
|
|
def xgroup_create(self, *args, **kwargs):
|
|
pass
|
|
def xautoclaim(self, *args, **kwargs):
|
|
job = {'job_id': str(uuid.uuid4()), 'attempt': 1}
|
|
return ('0-0', [('1-0', {'job': json.dumps(job)})])
|
|
def xack(self, *args, **kwargs):
|
|
raise SystemExit('unexpected ACK')
|
|
|
|
def slow_job(*args):
|
|
print('watchdog-probe: entered slow job', flush=True)
|
|
time.sleep(5)
|
|
raise SystemExit('deadline did not stop the job')
|
|
|
|
assert p.TIMEOUT == 1
|
|
p.settings = lambda: lambda: {'S3_ACCESS_KEY': 'stub', 'S3_SECRET_KEY': 'stub'}
|
|
p.broker = FakeBroker
|
|
p.s3 = lambda _: object()
|
|
p.db = lambda _: nullcontext(object())
|
|
p.cleanup = lambda *_: None
|
|
p.process = slow_job
|
|
signal.signal(signal.SIGALRM, signal.SIG_DFL)
|
|
p.worker()
|
|
"""
|
|
|
|
|
|
def db_probe(action, user_id, value):
|
|
response = subprocess.run(
|
|
["docker", "compose", "exec", "-T", "worker", "python", "-c", DB_PROBE],
|
|
input=json.dumps([action, user_id, value]), text=True,
|
|
capture_output=True, timeout=20,
|
|
)
|
|
if response.returncode:
|
|
raise RuntimeError(f"database fixture failed at {action}, exit {response.returncode}")
|
|
if json.loads(response.stdout) is not True:
|
|
raise AssertionError(f"database fixture check failed at {action}")
|
|
|
|
|
|
def lab_client(root):
|
|
path = root / "tests/client.py"
|
|
spec = importlib.util.spec_from_file_location("lab7_test_client", path)
|
|
if spec is None or spec.loader is None:
|
|
raise ImportError(f"Cannot load lab test client from {path}")
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
return module.Client
|
|
|
|
|
|
def verify_auth(root):
|
|
client = lab_client(root)(
|
|
base_url=os.environ.get("BASE_URL", "https://localhost:8443"),
|
|
ca_file=str(root / "secrets/pki/ca.crt"),
|
|
)
|
|
username = "u_confirm_" + uuid.uuid4().hex[:12]
|
|
user = client.call("POST", "/api/v1/users", 201, body={
|
|
"username": username, "password": PASSWORD, "display_name": "Lab7 fixture",
|
|
}, schema="User")["json"]
|
|
db_probe("install_legacy", user["id"], LEGACY_HASH)
|
|
basic = base64.b64encode(f"{username}:{PASSWORD}".encode()).decode()
|
|
token = client.call("POST", "/api/v1/auth/sessions", 201,
|
|
headers={"Authorization": f"Basic {basic}"}, schema="Session")["json"]["token"]
|
|
db_probe("check_rehash", user["id"], CURRENT_PREFIX)
|
|
print("PASS: login upgraded a legacy Argon2id hash to current parameters", flush=True)
|
|
|
|
actor = {"token": token}
|
|
client.call("GET", "/api/v1/users/me", 200, actor=actor)
|
|
token_hash = hashlib.sha256(token.encode()).hexdigest()
|
|
db_probe("shorten_ttl", user["id"], token_hash)
|
|
time.sleep(2.2)
|
|
db_probe("check_expiry", user["id"], token_hash)
|
|
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
|
print("PASS: existing bearer rejected after session TTL elapsed without logout", flush=True)
|
|
|
|
|
|
def verify_watchdog():
|
|
probe = subprocess.run(
|
|
["docker", "compose", "run", "--rm", "--no-deps", "-T",
|
|
"-e", "JOB_TIMEOUT_SECONDS=1", "-e", "OTEL_EXPORTER_OTLP_ENDPOINT=",
|
|
"--entrypoint", "python", "worker", "-c", WATCHDOG_PROBE],
|
|
capture_output=True, text=True, timeout=30,
|
|
)
|
|
assert "watchdog-probe: entered slow job" in probe.stdout, (
|
|
f"isolated worker did not reach the simulated task, exit {probe.returncode}")
|
|
assert probe.returncode == 142, f"expected SIGALRM exit 142, got {probe.returncode}"
|
|
print("PASS: worker loop killed by SIGALRM at a 1 s deadline with stubbed dependencies")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
root = Path.cwd()
|
|
if not (root / "compose.yaml").is_file() or not (root / "tests/client.py").is_file():
|
|
sys.exit("Run this script from the lab7 repository root")
|
|
operations = [("rehash/session expiry", lambda: verify_auth(root)),
|
|
("worker deadline", verify_watchdog)]
|
|
success = True
|
|
for name, run in operations:
|
|
try:
|
|
run()
|
|
except AssertionError as error:
|
|
success = False
|
|
print(f"FAIL {name}: {error}", file=sys.stderr)
|
|
except Exception as error:
|
|
success = False
|
|
print(f"FAIL {name}: {type(error).__name__}", file=sys.stderr)
|
|
sys.exit(0 if success else 1)
|