Files
mtusi2026lab7-fork/student-tests/security.py
T

321 lines
15 KiB
Python

"""Repeatable defensive checks against the local Lab7 Compose project."""
import argparse
import base64
import concurrent.futures
import hashlib
import json
import math
import os
from pathlib import Path
import re
import socket
import ssl
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
sys.path.insert(0, str(ROOT / "scripts"))
from bao import PRIVATE, compose, required, request, root_token, rotate_worker, unseal
from client import Client, check
from stack_action import inspect, stop_one
FIXTURE = ROOT / "tests/fixtures/sample.png"
def settings():
values = dict(line.split("=", 1) for line in (ROOT / ".env").read_text().splitlines()
if line and not line.lstrip().startswith("#") and "=" in line)
return values | os.environ
def api():
return Client(f"https://127.0.0.1:{int(settings().get('APP_PORT', 8443))}", str(PRIVATE / "ca.crt"), timeout=8)
def readiness(c):
try:
with c.opener.open(c.base + "/health/ready", timeout=3) as response:
return response.status
except urllib.error.HTTPError as response:
response.close()
return response.code
def wait_api(c, expected=200, timeout=65):
started = time.monotonic()
while time.monotonic() - started < timeout:
if readiness(c) == expected:
return time.monotonic() - started
time.sleep(0.4)
raise RuntimeError(f"API readiness did not reach HTTP {expected}")
def role_login(role, folder=None):
return required("auth/cert/login", method="POST", data={"name": role},
folder=folder or PRIVATE / "tls" / (role + "-client"))["auth"]
def bao_policy():
for role in ("api", "dispatcher", "worker", "jobs"):
folder = PRIVATE / "tls" / (role + "-client")
auth = role_login(role)
token = auth["client_token"]
check(auth["lease_duration"] == 45, "unexpected role lifetime")
own = required("lab/data/" + role, token=token, folder=folder)["data"]["data"]
check(not ({"root_token", "unseal_key", "s3_root_password"} & own.keys()), "operator secret in application KV")
for other in ("api", "dispatcher", "worker", "jobs"):
if other != role:
code, _ = request("lab/data/" + other, token=token, folder=folder)
check(code == 403, "cross-role KV read was not forbidden")
code, _ = request("sys/policies/acl/test", method="PUT", data={"policy": ""}, token=token, folder=folder)
check(code == 403, "service can write policy")
code, _ = request("auth/cert/login", method="POST", data={"name": role}, folder=PRIVATE / "tls/audit-client")
check(code in (400, 403), "same-CA audit identity obtained service token")
print("OpenBao: 4 scoped roles with 45s tokens; cross-role reads, policy writes and wrong same-CA identity denied")
def login_budget(c):
username = "audit_" + uuid.uuid4().hex[:12]
basic = base64.b64encode((username + ":synthetic-invalid-pass").encode()).decode()
replicas = set()
for _ in range(6):
resp = c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Basic " + basic})
replicas.add(resp["headers"]["X-Instance-Id"])
blocked = c.call("POST", "/api/v1/auth/sessions", 429, headers={"Authorization": "Basic " + basic})
replicas.add(blocked["headers"]["X-Instance-Id"])
check(len(replicas) >= 2, "rate test did not exercise multiple replicas")
check(1 <= int(blocked["headers"]["Retry-After"]) <= 31, "missing or incorrect Retry-After")
print(f"Login limit: 6 attempts across {len(replicas)} replicas; attempt 7 received 429 with Retry-After")
def enforce_http(c):
alice, bob, eve, chat = c.bootstrap()
attachment, _ = c.attachment(alice, chat)
path = "/api/v1/attachments/" + attachment["id"]
for suffix in ("", "/content"):
c.call("GET", path + suffix, 404, actor=eve, headers={"X-User-Id": alice["id"]})
private_chat = c.call("POST", "/api/v1/chats", 201, actor=eve,
body={"title": "ACL control", "member_ids": [eve["id"]]}, schema="Chat")["json"]
c.call("POST", f"/api/v1/chats/{private_chat['id']}/messages", 404, actor=eve,
body={"text": "", "attachment_ids": [attachment["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex})
c.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", 413, actor=alice,
raw=b"", headers={"Content-Type": "image/png", "Content-Length": str(10 * 1024 * 1024 + 1),
"Expect": "100-continue"})
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=bob)
c.call("GET", "/api/v1/users/me", 401, actor=bob)
print("HTTP ACL: forged identity, outsider metadata/content and cross-chat attachment denied; size limit and logout passed")
return alice
def grafana():
password = (PRIVATE / "grafana_password").read_text().strip()
credential = base64.b64encode(("admin:" + password).encode()).decode()
ctx = ssl.create_default_context(cafile=str(PRIVATE / "ca.crt"))
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), urllib.request.HTTPSHandler(context=ctx))
port = int(settings().get("GRAFANA_PORT", 3443))
def call(path, *, authenticated=True):
headers = {"Authorization": "Basic " + credential} if authenticated else {}
req = urllib.request.Request(f"https://127.0.0.1:{port}" + path, headers=headers)
with opener.open(req, timeout=8) as response:
data = response.read(2 * 1024 * 1024)
return json.loads(data)
return call
def telemetry(c, actor):
get = grafana()
try:
get("/api/datasources", authenticated=False)
except urllib.error.HTTPError as error:
check(error.code == 401, "Grafana did not require authentication")
else:
raise RuntimeError("anonymous Grafana access succeeded")
event = c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
request_id = event["headers"]["X-Request-Id"]
prom = "/api/datasources/proxy/uid/lab-prom/api/v1/query?" + urllib.parse.urlencode({
"query": 'sum(messenger_http_requests_total{service_name="messenger-api"})'})
logs = "/api/datasources/proxy/uid/lab-loki/loki/api/v1/query_range?" + urllib.parse.urlencode({
"query": '{service_name="messenger-api"} | request_id="' + request_id + '"',
"start": str(time.time_ns() - 60_000_000_000), "limit": "10"})
for _ in range(26):
time.sleep(0.5)
metrics = get(prom)
logdata = get(logs)
rows = logdata["data"]["result"]
if metrics["data"]["result"] and rows:
break
else:
raise RuntimeError("API metrics and request id did not arrive at telemetry storage")
serial = json.dumps(rows)
match = re.search(r'"trace_id"\s*:\s*"([0-9a-f]{32})"', serial)
check(match is not None, "Loki request lost its trace id")
for _ in range(16):
try:
trace = get("/api/datasources/proxy/uid/lab-tempo/api/traces/" + match[1])
break
except urllib.error.HTTPError as error:
if error.code != 404:
raise
time.sleep(0.5)
else:
raise RuntimeError("Loki trace was not found in Tempo")
logs_all = compose("logs", "--no-color", "--tail", "75", "api", "worker", "openbao", "lb")
material = serial + json.dumps(trace) + logs_all
for value in (actor["token"], actor["registration"]["password"], root_token()):
check(value not in material, "credential leaked to a sampled signal")
print("Telemetry: Grafana auth, mTLS data sources, API metrics, Loki request id and corresponding Tempo trace verified")
print("Sampled traces, logs and service output contain no synthetic session/password or OpenBao root token")
def security():
c = api()
wait_api(c)
with socket.create_connection(("127.0.0.1", int(settings().get("APP_PORT", 8443))), timeout=5) as conn:
context = ssl.create_default_context(cafile=str(PRIVATE / "ca.crt"))
try:
with context.wrap_socket(conn, server_hostname="wrong.lab7.invalid"):
raise RuntimeError("ingress accepted wrong server name")
except ssl.SSLCertVerificationError as error:
check(error.verify_code == 62, "ingress failed for a reason other than hostname mismatch")
print("Ingress: verified CA works; mismatched external hostname rejected")
print(compose("--profile", "audit", "run", "--rm", "--no-deps", "-T", "audit").strip())
bao_policy()
login_budget(c)
actor = enforce_http(c)
telemetry(c, actor)
def track(count):
c = api()
wait_api(c)
alice, bob, _, chat = c.bootstrap()
sample, _ = c.attachment(alice, chat)
c.wait_ready(bob, sample)
compose("stop", "worker")
stopped = time.monotonic()
def accept(_):
start = time.monotonic()
att, content = c.attachment(alice, chat)
message = c.message(alice, chat, "", attachments=[att["id"]])["json"]
return att, content, message["id"], (time.monotonic() - start) * 1000
begin_acceptance = time.monotonic()
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
accepted = list(pool.map(accept, range(count)))
acceptance_seconds = time.monotonic() - begin_acceptance
for att, _, _, _ in accepted:
response = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")
check(response["json"]["status"] == "queued", "queued fixture advanced without worker")
before = compose("run", "--rm", "--no-deps", "-T", "worker", "security-probe", "worker",
data=json.dumps({"attachment": sample["id"], "staging": accepted[0][0]["id"]}))
print(before.strip())
rotation = time.monotonic()
rotate_worker()
activated = time.monotonic()
for att, content, _, _ in accepted:
ready = c.wait_ready(bob, att, wait_seconds=65)
check(ready["status"] == "ready", "job not restored")
original = c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=bob)["bytes"]
check(hashlib.sha256(original).digest() == hashlib.sha256(content).digest(), "attachment bytes changed")
recovered = time.monotonic()
history = c.call("GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", actor=bob, schema="MessagePage")
by_id = {m["id"]: m["attachment_ids"] for m in history["json"]["items"]}
check(all(by_id.get(mid) == [att["id"]] for att, _, mid, _ in accepted), "message attachment link lost")
after = compose("exec", "-T", "worker", "/messenger", "security-probe", "worker",
data=json.dumps({"attachment": sample["id"]}))
check(all(line in before for line in after.splitlines()), "worker permissions changed after rotation")
times = sorted(item[3] for item in accepted)
summary = {"accepted": count, "ready": count, "lost": 0, "parallel_uploads": 2,
"accepted_per_second": round(count / acceptance_seconds, 2),
"accept_plus_message_ms": [round(item, 1) for item in times],
"p50_ms": round(times[math.ceil(count * 0.50) - 1], 1),
"p95_ms": round(times[math.ceil(count * 0.95) - 1], 1),
"p99_ms": round(times[math.ceil(count * 0.99) - 1], 1),
"rotation_s": round(activated - rotation, 2),
"activation_to_all_ready_s": round(recovered - activated, 2),
"worker_stop_to_all_ready_s": round(recovered - stopped, 2)}
print(json.dumps(summary, sort_keys=True))
def sealed():
c = api()
wait_api(c)
warm = time.monotonic()
required("sys/seal", token=root_token(), method="PUT", data={})
check(readiness(c) == 200, "existing cached credentials did not cover short seal")
try:
seconds = wait_api(c, 503, timeout=53)
print(f"Sealed OpenBao: last lease expired; verified HTTPS returned 503 after {seconds:.2f}s")
finally:
unseal()
recovery = wait_api(c, 200)
check(time.monotonic() - warm < 125, "seal recovery exceeded test deadline")
print(f"HTTPS readiness restored in {recovery:.2f}s after unseal")
def expiry():
env = os.environ.copy()
env["SESSION_TTL_SECONDS"] = "4"
args = ["docker", "compose", "up", "-d", "--no-build", "--no-deps", "--force-recreate", "api"]
c = api()
subprocess.run(args, env=env, cwd=ROOT, check=True, capture_output=True)
try:
wait_api(c)
actor = c.user("expiry")
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
time.sleep(4.2)
c.call("GET", "/api/v1/users/me", 401, actor=actor)
print("Session expiry: valid before configured TTL and rejected after expiry")
finally:
subprocess.run(args, cwd=ROOT, check=True, capture_output=True)
wait_api(c)
def failover_all():
c = api()
wait_api(c)
alice, bob, _, chat = c.bootstrap()
replicas = {node[0] for node in inspect(compose("ps", "-q", "api").split())}
check(len(replicas) == 2, "expected two active API containers")
confirmed = [c.message(alice, chat, "before sequential failover")["json"]]
for target in sorted(replicas):
try:
stop_one(target)
wait_api(c)
for step in range(5):
response = c.message(alice, chat, f"after stopping replica {len(confirmed)}-{step}")
check(response["headers"]["X-Instance-Id"] in replicas - {target}, "write bypassed survivor")
confirmed.append(response["json"])
history = c.call("GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", actor=bob, schema="MessagePage")
check(history["json"]["items"] == confirmed, "history changed after replica loss")
finally:
compose("start", "api")
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
response = c.call("GET", "/health/ready", schema="Health")
if response["headers"]["X-Instance-Id"] == target:
break
time.sleep(0.2)
else:
raise RuntimeError("stopped replica did not rejoin the load balancer")
print("Sequential failover: both explicit API targets stopped, 10 writes on the respective survivor, history and session preserved")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("scenario", choices=("security", "track", "sealed", "expiry", "failover-all"))
parser.add_argument("--count", type=int, default=10)
args = parser.parse_args()
if not 1 <= args.count <= 30:
parser.error("--count must be between 1 and 30")
{"security": security, "track": lambda: track(args.count), "sealed": sealed, "expiry": expiry,
"failover-all": failover_all}[args.scenario]()