Files
mtusi2026lab7/student-tests/security_lifecycle.py

237 lines
8.3 KiB
Python

import hashlib
import json
import secrets
import shutil
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
import bootstrap
from bootstrap import PRIVATE, ROOT, write
from provision import bao, compose, initialize_bao, initialize_db, initialize_s3, prepare
from client import Client, check
from cryptography import x509
def sql(statement):
return compose(
"exec",
"-T",
"db",
"psql",
"-U",
"operator",
"-d",
"messenger",
"-v",
"ON_ERROR_STOP=1",
"-At",
stdin=statement,
).strip()
def wait(predicate, timeout=90):
started = time.monotonic()
while time.monotonic() - started < timeout:
if predicate():
return round(time.monotonic() - started, 3)
time.sleep(1)
raise AssertionError("Recovery deadline exceeded")
def ready(client):
try:
return client.call("GET", "/health/ready")["status"] == 200
except Exception:
return False
def identity_images():
result = {}
for role in ("api", "worker", "dispatcher"):
ids = compose("ps", "-a", "-q", role).splitlines()
result[role] = sorted(
{
json.loads(__import__("subprocess").check_output(["docker", "inspect", value]))[0][
"Image"
]
for value in ids
}
)
return result
def minio_disable(identity):
operator = json.loads((PRIVATE / "operator/credentials.json").read_text())
script = f"set -eu\nmc alias set local https://minio:9000 {operator['minio_root_user']} {operator['minio_root_password']} >/dev/null\nmc admin user disable local {identity} >/dev/null\n"
compose("run", "--rm", "--no-deps", "-T", "s3-admin", stdin=script)
def revoke_and_rotate():
path = PRIVATE / "operator/credentials.json"
data = json.loads(path.read_text())
old = data["roles"]["worker"].copy()
write(PRIVATE / "operator/worker-before.json", json.dumps(old))
shutil.copytree(PRIVATE / "worker", PRIVATE / "revoked-worker", dirs_exist_ok=True)
old_cert = x509.load_pem_x509_certificate((PRIVATE / "worker/service.crt").read_bytes())
root = json.loads((PRIVATE / "operator/bao-init.json").read_text())["root_token"]
bao("auth/cert/certs/worker", token=root, method="DELETE")
minio_disable(old["s3_access_key_id"])
values = data["roles"]["worker"]
values.update(
postgres_password=secrets.token_hex(24),
s3_access_key_id="worker-" + secrets.token_hex(4),
s3_secret_access_key=secrets.token_hex(24),
broker_user="worker-" + secrets.token_hex(4),
broker_password=secrets.token_hex(24),
)
write(path, json.dumps(data))
initialize_db()
sql(
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename='worker' AND pid<>pg_backend_pid();"
)
key, ca = bootstrap.authority()
old_crl = x509.load_pem_x509_crl((PRIVATE / "public/ca.crl").read_bytes())
serials = {entry.serial_number for entry in old_crl} | {old_cert.serial_number}
bootstrap.crl(key, ca, serials)
bootstrap.leaf("worker", key, ca)
prepare()
initialize_s3()
bao("auth/cert/crls/lab7", {"crl": (PRIVATE / "public/ca.crl").read_text()}, root)
initialize_bao()
compose("exec", "-T", "gateway", "nginx", "-s", "reload")
compose("restart", "broker")
output = compose("run", "--rm", "--no-deps", "-T", "audit", "/checks/revocation_probe.py")
result = json.loads(output)
check(result["status"] == "PASS", "Old credentials still work")
return result
def expiry_probe():
key, ca = bootstrap.authority()
original = bootstrap.PRIVATE
try:
bootstrap.PRIVATE = PRIVATE / "operator/expiry"
bootstrap.leaf("worker", key, ca, minutes=0)
finally:
bootstrap.PRIVATE = original
shutil.copytree(
PRIVATE / "operator/expiry/worker", PRIVATE / "expired-worker", dirs_exist_ok=True
)
time.sleep(1)
command = "import sys;sys.path.insert(0,'/checks');from tls_matrix import deny_http;assert deny_http('otel-collector',4318,'/v1/traces','expired-worker','POST',b'{}') in (400,'tls_rejected');print('PASS expired allowed-role certificate rejected')"
return compose("run", "--rm", "--no-deps", "-T", "audit", "-c", command).strip()
def sealed_bao(client, actor):
init = json.loads((PRIVATE / "operator/bao-init.json").read_text())
started = time.monotonic()
bao("sys/seal", {}, init["root_token"])
try:
elapsed = wait(lambda: not ready(client), 50)
client.call("GET", "/health/live")
response = client.call("GET", "/api/v1/users/me", 503, actor=actor)
check(
response["json"]["error"]["code"] == "unavailable",
"Expiry must be bounded and explicit",
)
finally:
bao("sys/unseal", {"key": init["keys"][0]})
recovery = wait(lambda: ready(client), 30)
client.call("GET", "/api/v1/users/me", actor=actor)
return dict(
readiness_fail_closed_seconds=elapsed,
recovery_seconds=recovery,
liveness=200,
existing_session_survives=True,
total_seconds=round(time.monotonic() - started, 3),
)
def main():
client = Client(base_url="https://127.0.0.1:8443", ca_file=str(PRIVATE / "public/ca.crt"))
wait(lambda: ready(client), 120)
actor, _, _, chat = client.bootstrap()
before = identity_images()
compose("stop", "worker")
png = (ROOT / "tests/fixtures/sample.png").read_bytes()
attachments = []
for _ in range(10):
value = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments?filename=security.png",
202,
actor=actor,
raw=png,
headers={"Content-Type": "image/png"},
schema="Attachment",
)["json"]
check(value["status"] == "queued", "Expected durable queued snapshot")
attachments.append(value)
print("Accepted ten durable jobs before revocation", flush=True)
started = time.monotonic()
revoked = revoke_and_rotate()
expected = json.loads((PRIVATE / "operator/credentials.json").read_text())["roles"]["worker"][
"s3_access_key_id"
]
def refreshed():
code = (
"import json;assert json.load(open('/runtime/secrets.json'))['s3_access_key_id']=='"
+ expected
+ "'"
)
try:
compose("exec", "-T", "worker-agent", "python", "-c", code)
return True
except RuntimeError:
return False
wait(refreshed, 30)
compose("start", "worker")
for attachment in attachments:
final = client.wait_ready(actor, attachment)
check(len(final["variants"]) == 3, "Variant set not complete")
content = client.call(
"GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=actor
)["bytes"]
check(
hashlib.sha256(content).digest() == hashlib.sha256(png).digest(),
"Confirmed original corrupted",
)
recovery = round(time.monotonic() - started, 3)
check(before == identity_images(), "Rotation rebuilt workload images")
ids = ",".join("'" + item["id"] + "'" for item in attachments)
rows = sql(
"SELECT count(*),count(DISTINCT attachment_id) FROM attachment_variants WHERE attachment_id IN ("
+ ids
+ ");"
)
check(rows == "30|10", "Duplicate or missing published effects")
expiry = expiry_probe()
sealed = sealed_bao(client, actor)
result = dict(
status="PASS",
track=1,
confirmed_jobs=10,
ready_after_revoke=10,
originals_sha256_verified=10,
manifest_rows=30,
distinct_attachments=10,
revocation=revoked,
recovery_seconds=recovery,
images_unchanged=True,
expiry=expiry,
sealed_bao=sealed,
limitations="single host; in-flight requests finish within their existing operation budgets; static KV credentials require explicit downstream revocation",
)
write(ROOT / "evidence/security-lifecycle.json", json.dumps(result, indent=2) + "\n")
print(json.dumps(result, indent=2))
if __name__ == "__main__":
main()