From d6957b2f79ce0fb861c4b4e8bb67f1dc82ffade4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D1=81=D0=BB=D0=BE=D0=B2?= Date: Fri, 20 Nov 2026 19:19:20 +0300 Subject: [PATCH] test(security): automate lifecycle and login budget measurements --- compose.yaml | 4 +- scripts/operator_task.py | 2 +- scripts/research_security.py | 339 +++++++++++++++++++++++ scripts/stand.py | 33 +-- scripts/verify_clean.py | 149 ++++++++-- scripts/verify_cluster.py | 15 +- scripts/verify_login_budget.py | 227 +++++++++++++++ scripts/verify_pipeline.py | 5 + scripts/verify_security.py | 33 ++- src/operator_runtime.py | 29 ++ src/security_probe.py | 485 +++++++++++++++++---------------- 11 files changed, 1020 insertions(+), 301 deletions(-) create mode 100644 scripts/research_security.py create mode 100644 scripts/verify_login_budget.py create mode 100644 src/operator_runtime.py diff --git a/compose.yaml b/compose.yaml index 8fa8e65..ee9caec 100644 --- a/compose.yaml +++ b/compose.yaml @@ -44,7 +44,7 @@ services: image: valkey/valkey:8.1.12@sha256:5032c4dd7abe08d6fd9382054608183e2bf1f7e3895ef619b8784698454325f7 command: - valkey-server - - /run/secrets/valkey.conf + - /run/secrets/cache.conf secrets: - source: cache_config target: cache.conf @@ -1499,7 +1499,7 @@ services: entrypoint: - python - -m - - src.operator + - src.operator_runtime user: 10001:10001 environment: IDENTITY_ENABLED: '1' diff --git a/scripts/operator_task.py b/scripts/operator_task.py index baa69f8..0ef9120 100644 --- a/scripts/operator_task.py +++ b/scripts/operator_task.py @@ -22,7 +22,7 @@ def prepare(): values = { "DATABASE_URL": "postgresql://messenger:" + quote(raw["postgres_password"], safe="") - + "@postgres:5443/messenger?sslmode=verify-full&gssencmode=disable&sslrootcert=/trust/ca.pem&sslcert=/run/identity/current/cert.pem&sslkey=/run/identity/current/key.pem", + + "@postgres:5443/messenger?sslmode=verify-full&gssencmode=disable&sslrootcert=/trust/ca.pem&sslcert=/run/identity/current/cert.pem&sslkey=/tmp/operator-client.key", "BROKER_URL": "rediss://admin:" + raw["broker_admin"] + "@broker:6380/0", diff --git a/scripts/research_security.py b/scripts/research_security.py new file mode 100644 index 0000000..dbb04e2 --- /dev/null +++ b/scripts/research_security.py @@ -0,0 +1,339 @@ +"""Measured PKI lifecycle under bounded public HTTPS message/upload load.""" + +import argparse +import csv +import json +import socket +import ssl +import time +from collections import Counter +from datetime import UTC, datetime +from urllib.parse import urlsplit + +import httpx + +from scripts import pki +from scripts.bao_operator import Operator +from scripts.bootstrap_security import TRUST +from scripts.credentials import repair, rotate_s3 +from scripts.research_slo import Workload +from scripts.stand import BASE, ROOT, actor, auth, command, compose, ready +from scripts.tls_client import FreshTrustTransport + + +def images(): + ids = compose("ps", "-q").split() + return { + c["Name"]: c["Image"] + for c in json.loads(command(["docker", "inspect", *ids])) + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", default="evidence/pki-research-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, + "profile": { + "messages_per_second": 4, + "upload_every_seconds": 5, + "max_inflight": 16, + }, + "phases": [], + } + started = time.time() + load = None + lb_stopped = False + bao_sealed = False + with httpx.Client( + base_url=BASE, + transport=FreshTrustTransport(), + timeout=8, + trust_env=False, + ) as client: + + def save(): + report["elapsed_seconds"] = round(time.time() - started, 3) + output.write_text( + json.dumps(report, ensure_ascii=False, indent=2) + "\n" + ) + + def phase(name, action): + load.phase = name + entry = {"name": name, "started_at": time.time()} + report["phases"].append(entry) + save() + try: + entry["result"] = action() + finally: + entry["ended_at"] = time.time() + entry["seconds"] = round( + entry["ended_at"] - entry["started_at"], 3 + ) + save() + + try: + ready(timeout=90) + report["images_before"] = images() + user, _, session = actor(client) + headers = auth(session) + r = client.post( + "/api/v1/chats", + headers=headers, + json={"title": "PKI lifecycle", "member_ids": [user["id"]]}, + ) + assert r.status_code == 201 + chat = r.json()["id"] + load = Workload(client, headers, chat) + load.start() + + def renewal(): + before = pki.metadata() + time.sleep(100) + after = pki.metadata() + roles = set(before) - {"migrate"} + assert roles and all( + before[r]["serial"] != after[r]["serial"] for r in roles + ) + events = compose( + "logs", + "--no-color", + "--since", + datetime.fromtimestamp(started, UTC).isoformat(), + "identity-api", + ) + assert '"event":"identity.token_renewed"' in events + return { + "before": before, + "after": after, + "all_active_serials_changed": True, + "api_token_renewed": True, + } + + phase("automatic_renewal", renewal) + + def secret_rotation(): + operator = Operator() + try: + return rotate_s3(operator) + finally: + operator.close() + + phase("working_s3_key_rotation", secret_rotation) + + def revocation(): + operator = Operator() + try: + repair(operator, "lb") + old = pki.preserve_lb() + repair(operator, "lb") + pki.fixture_check("lb") + return pki.revoke(operator, old) + finally: + operator.close() + + phase("leaf_reissue_and_revocation", revocation) + + def expiry(): + nonlocal lb_stopped + compose("stop", "identity-lb") + lb_stopped = True + leaf = pki.metadata()["lb"] + wait_seconds = max(0, leaf["expires_at"] - time.time() + 3) + time.sleep(wait_seconds) + target = urlsplit(BASE) + context = ssl.create_default_context(cafile=TRUST / "ca.pem") + try: + with socket.create_connection( + (target.hostname, target.port), timeout=5 + ) as raw: + with context.wrap_socket( + raw, server_hostname=target.hostname + ): + pass + except ssl.SSLCertVerificationError as error: + assert error.verify_code == 10, ( + "Expected expired certificate" + ) + else: + raise AssertionError( + "Expired server certificate was accepted" + ) + recovery = time.monotonic() + operator = Operator() + try: + repair(operator, "lb") + finally: + operator.close() + compose("up", "-d", "--no-deps", "identity-lb") + lb_stopped = False + ready(timeout=60) + return { + "leaf": leaf, + "waited_seconds": round(wait_seconds, 3), + "expired_certificate_verified_denied": True, + "recovery_seconds": round(time.monotonic() - recovery, 3), + } + + phase("expiry_without_plaintext_fallback", expiry) + + def sealed(): + nonlocal bao_sealed + operator = Operator() + try: + operator.authorized("POST", "sys/seal", {}) + bao_sealed = True + finally: + operator.close() + time.sleep(70) + status, error_type = None, None + try: + status = client.get( + "/api/v1/users/me", headers=headers + ).status_code + assert status == 503, ( + "Expired secret snapshot must fail closed" + ) + except httpx.HTTPError as error: + error_type = type(error).__name__ + recovery = time.monotonic() + pki.recover_bao() + bao_sealed = False + ready(timeout=120) + return { + "sealed_seconds": 70, + "status_after_secret_expiry": status, + "tls_transport_failure": error_type, + "recovery_seconds": round(time.monotonic() - recovery, 3), + "explicit_operator_recovery": True, + } + + phase("sealed_openbao_bounded_cache", sealed) + phase("dual_trust_ca_rollover", pki.rollover) + phase("recovered_steady", lambda: time.sleep(30)) + load.close() + load.stop.set() + # Preserve every observed acknowledgement; ambiguous requests are + # counted separately and never presented as acknowledged writes. + messages = {row[5] for row in load.requests if row[2] == 201} + found, cursor = set(), None + while True: + r = client.get( + f"/api/v1/chats/{chat}/messages", + headers=headers, + params={ + "limit": 100, + **({"cursor": cursor} if cursor else {}), + }, + ) + assert r.status_code == 200 + page = r.json() + found.update(item["id"] for item in page["items"]) + cursor = page["next_cursor"] + if not cursor: + break + assert messages <= found + accepted = [row for row in load.uploads if row[2] == 202] + pending = {row[3] for row in accepted} + deadline = time.monotonic() + 120 + failed = set() + while pending and time.monotonic() < deadline: + for identity in list(pending): + r = client.get( + "/api/v1/attachments/" + identity, headers=headers + ) + assert r.status_code == 200 + state = r.json()["status"] + if state == "ready": + pending.remove(identity) + elif state == "failed": + failed.add(identity) + if failed: + # Replay is an explicit audited operator action after the + # seal experiment; never change DB job state directly. + from scripts.operator_task import run + + for identity in failed: + from scripts.stand import sql + + job = sql( + "SELECT id FROM jobs WHERE attachment_id='" + + identity + + "' ORDER BY pipeline_version DESC LIMIT 1" + ) + run( + "replay", + "--job-id", + job, + "--operator", + "synthetic-research", + "--reason", + "PKI research recovery after controlled seal", + ) + failed.clear() + time.sleep(1) + assert not pending, "Accepted upload not ready after recovery" + for row in accepted[:: max(1, len(accepted) // 5)]: + r = client.get( + "/api/v1/attachments/" + row[3] + "/content", + headers=headers, + ) + assert r.status_code == 200 and r.content == load.raw + report["preservation"] = { + "acknowledged_messages": len(messages), + "accepted_uploads": len(accepted), + "all_acknowledged_messages_present": True, + "all_accepted_uploads_ready": True, + "sampled_original_bytes_unchanged": True, + } + report["images_after"] = images() + assert report["images_before"] == report["images_after"], ( + "Lifecycle must not rebuild/replace images" + ) + report["complete"] = True + except BaseException as error: + report["failure_type"] = type(error).__name__ + raise + finally: + if load is not None: + load.close() + report["request_statuses"] = dict( + Counter(str(row[2]) for row in load.requests) + ) + report["upload_statuses"] = dict( + Counter(str(row[2]) for row in load.uploads) + ) + with output.with_name(output.stem + "-requests.csv").open( + "w" + ) as stream: + writer = csv.writer(stream) + writer.writerow( + [ + "started_at", + "phase", + "status", + "duration_seconds", + "trace_id", + "message_id", + ] + ) + writer.writerows(load.requests) + report["uploads"] = load.uploads + save() + if lb_stopped: + compose("up", "-d", "--no-deps", "identity-lb") + if bao_sealed: + pki.recover_bao() + print( + "PASS: measured renewal, working-key/leaf rotation, revocation, expiry, seal recovery and CA rollover" + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/stand.py b/scripts/stand.py index b7fe5f0..94fe8f7 100644 --- a/scripts/stand.py +++ b/scripts/stand.py @@ -87,8 +87,8 @@ def sql(query, *, database="messenger"): def cache(command_name, *args): script = ( - 'export REDISCLI_AUTH="$(cat /run/secrets/cache_password)"; ' - 'exec valkey-cli "$@"' + 'export REDISCLI_AUTH="$(cat /run/secrets/cache_admin)"; ' + 'exec valkey-cli --user admin "$@"' ) return compose( "exec", "-T", "cache", "sh", "-c", script, "sh", command_name, *args @@ -137,35 +137,6 @@ def auth(session): return {"Authorization": "Bearer " + session["token"]} -def extra_api(*, ttl=3600, pool_size=1): - name = "mtusi-lab6-test-" + uuid4().hex[:10] - compose( - "run", - "-d", - "--no-deps", - "--name", - name, - "-e", - "SESSION_TTL_SECONDS=" + str(ttl), - "-e", - "DB_POOL_SIZE=" + str(pool_size), - "-p", - "127.0.0.1::8080", - "api", - ) - try: - info = json.loads(command(["docker", "inspect", name]))[0] - base = ( - "http://127.0.0.1:" - + info["NetworkSettings"]["Ports"]["8080/tcp"][0]["HostPort"] - ) - ready(base) - return name, base - except Exception: - command(["docker", "rm", "-f", name]) - raise - - def instances(): data = {} for role in ["api", "postgres", "cache"]: diff --git a/scripts/verify_clean.py b/scripts/verify_clean.py index 14fcf45..21a62ec 100644 --- a/scripts/verify_clean.py +++ b/scripts/verify_clean.py @@ -37,23 +37,57 @@ def save_incomplete(): atexit.register(save_incomplete) +def redact(text, cwd): + def values(value): + if isinstance(value, dict): + for item in value.values(): + yield from values(item) + elif isinstance(value, list): + for item in value: + yield from values(item) + elif isinstance(value, str) and len(value) >= 12: + yield value + + for folder in [cwd / "secrets", cwd / "operator"]: + for path in folder.rglob("*"): + if not path.is_file(): + continue + try: + raw = path.read_text().strip() + except UnicodeDecodeError: + continue + if path.suffix == ".json": + try: + for value in values(json.loads(raw)): + text = text.replace(value, "") + except ValueError: + pass + if len(raw) >= 12: + text = text.replace(raw, "") + return ( + text.replace(str(cwd), "") + .replace(str(ROOT), "") + .replace(str(Path.home()), "") + ) + + def run(args, *, cwd, env, expected=0): + print("CHECK: " + redact(" ".join(args[:3]), cwd), flush=True) result = subprocess.run( args, cwd=cwd, env=env, capture_output=True, text=True ) - def redact(text): - return ( - text.replace(str(cwd), "") - .replace(str(ROOT), "") - .replace(str(Path.home()), "") - ) - if result.returncode != expected: if "receipt" in PROGRESS: - PROGRESS["receipt"]["failed_action"] = redact(" ".join(args)) - raise RuntimeError(redact(result.stdout + result.stderr)) - return redact(result.stdout.strip()) + PROGRESS["receipt"]["failed_action"] = redact(" ".join(args), cwd) + raise RuntimeError(redact(result.stdout + result.stderr, cwd)) + return redact(result.stdout.strip(), cwd) + + +def free_port(): + with socket.socket() as reservation: + reservation.bind(("127.0.0.1", 0)) + return reservation.getsockname()[1] def main(): @@ -70,7 +104,7 @@ def main(): ["git", "rev-parse", "HEAD"], cwd=ROOT, text=True ).strip() identity = uuid4().hex[:10] - project = "mtusi-lab6-clean-" + identity + project = "mtusi-lab7-clean-" + identity with socket.socket() as reservation: reservation.bind(("127.0.0.1", 0)) public_port = str(reservation.getsockname()[1]) @@ -80,9 +114,12 @@ def main(): env = { **os.environ, "COMPOSE_PROJECT_NAME": project, - "API_IMAGE": "mtusi-messenger:lab6-clean-" + identity, + "API_IMAGE": "mtusi-messenger:lab7-clean-" + identity, "PUBLIC_PORT": public_port, "GRAFANA_PORT": grafana_port, + "BASE_URL": "https://localhost:" + public_port, + "BAO_PORT": str(free_port()), + "S3_ADMIN_PORT": str(free_port()), "VCS_REF": sha, "COMPOSE_FILE": "compose.yaml:compose.test.yaml", "NO_PROXY": "localhost,127.0.0.1", @@ -96,8 +133,8 @@ def main(): "fixed_host_port_for_restart": int(public_port), } PROGRESS.update(receipt=receipt, output=output) - with tempfile.TemporaryDirectory(prefix="mtusi-lab6-clean-") as temporary: - clone = Path(temporary) / "lab6" + with tempfile.TemporaryDirectory(prefix="mtusi-lab7-clean-") as temporary: + clone = Path(temporary) / "lab7" run( [ "git", @@ -123,11 +160,12 @@ def main(): run(["make", "bootstrap"], cwd=clone, env=env) try: run( - ["docker", "compose", "up", "-d", "--build", "--wait"], + [".venv/bin/python", "-m", "scripts.up_security", "--build"], cwd=clone, env=env, ) - env["BASE_URL"] = "http://127.0.0.1:" + public_port + env["BASE_URL"] = "https://localhost:" + public_port + env["CA_FILE"] = str(clone / "trust/ca.pem") receipt["smoke"] = run( ["make", "test", "BASE_URL=" + env["BASE_URL"]], cwd=clone, @@ -136,18 +174,40 @@ def main(): receipt["http_tests"] = run( [".venv/bin/pytest", "student-tests", "-q"], cwd=clone, env=env ) + receipt["login_budget"] = run( + [ + ".venv/bin/python", + "-m", + "scripts.verify_login_budget", + "--output", + "evidence/clean-login-budget.json", + ], + cwd=clone, + env=env, + ) + receipt["public_security"] = run( + [ + "make", + "test-security", + "PYTHON=.venv/bin/python", + "BASE_URL=" + env["BASE_URL"], + ], + cwd=clone, + env=env, + ) for module, extra in [ + ("verify_security", []), ("verify_telemetry", []), ( "verify_observability_persistence", ["--causal-evidence", "evidence/clean-telemetry.json"], ), ]: - name = ( - "telemetry" - if module == "verify_telemetry" - else "observability-persistence" - ) + name = { + "verify_security": "security", + "verify_telemetry": "telemetry", + "verify_observability_persistence": "observability-persistence", + }[module] run( [ ".venv/bin/python", @@ -267,8 +327,53 @@ def main(): ["git", "fsck", "--full"], cwd=clone, env=env ) receipt["checks_completed"] = True + except BaseException: + receipt["partial_evidence"] = {} + for name in [ + "security", + "login-budget", + "telemetry", + "observability-persistence", + "cluster", + "pipeline", + "cleanup", + "gc-seed", + ]: + partial = clone / "evidence" / ("clean-" + name + ".json") + if partial.exists(): + receipt["partial_evidence"][name] = json.loads( + redact(partial.read_text(), clone) + ) + receipt["failure_diagnostics"] = {} + for label, arguments in [ + ("services", ["ps", "-a", "--format", "json"]), + ( + "logs", + [ + "logs", + "--no-color", + "--tail", + "60", + "api", + "s3", + "migrate", + "cache", + ], + ), + ]: + diagnostic = subprocess.run( + ["docker", "compose", *arguments], + cwd=clone, + env=env, + capture_output=True, + text=True, + ) + receipt["failure_diagnostics"][label] = redact( + diagnostic.stdout + diagnostic.stderr, clone + ) + raise finally: - assert project.startswith("mtusi-lab6-clean-") + assert project.startswith("mtusi-lab7-clean-") run( ["docker", "compose", "down", "--volumes", "--remove-orphans"], cwd=clone, diff --git a/scripts/verify_cluster.py b/scripts/verify_cluster.py index 19be419..4aedf0e 100644 --- a/scripts/verify_cluster.py +++ b/scripts/verify_cluster.py @@ -15,6 +15,7 @@ import httpx from scripts import cluster from scripts.stand import BASE, ROOT, actor, auth, command, compose, ready, sql +from scripts.tls_client import FreshTrustTransport def snapshot(): @@ -148,7 +149,12 @@ def main(): apis = [c for c in initial if c["role"] == "api"] assert len(apis) == 2 and len({c["pid"] for c in apis}) == 2 report["before"] = initial - with httpx.Client(base_url=BASE, trust_env=False, timeout=8) as client: + with httpx.Client( + base_url=BASE, + trust_env=False, + timeout=8, + transport=FreshTrustTransport(), + ) as client: user, _, session = actor(client) r = client.post( "/api/v1/chats", @@ -165,7 +171,10 @@ def main(): def repeat(_): with httpx.Client( - base_url=BASE, trust_env=False, timeout=8 + base_url=BASE, + trust_env=False, + timeout=8, + transport=FreshTrustTransport(), ) as c: r = c.post( path, @@ -321,6 +330,8 @@ def main(): hook, "--base-url", BASE, + "--ca-file", + str(ROOT / "trust/ca.pem"), ], cwd=ROOT, env=env, diff --git a/scripts/verify_login_budget.py b/scripts/verify_login_budget.py new file mode 100644 index 0000000..9d7de5a --- /dev/null +++ b/scripts/verify_login_budget.py @@ -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() diff --git a/scripts/verify_pipeline.py b/scripts/verify_pipeline.py index 57d9f1d..5b10d41 100644 --- a/scripts/verify_pipeline.py +++ b/scripts/verify_pipeline.py @@ -21,6 +21,8 @@ os.environ.setdefault("no_proxy", "localhost,127.0.0.1") from scripts.stand import BASE, ROOT, actor, auth, command, compose, ready PREFIX = """import io,json,hashlib,time,urllib.request +from src.operator_runtime import prepare_key +prepare_key() from uuid import UUID,uuid4 from psycopg.types.json import Jsonb from src.pipeline import database,broker,envelope,STREAM,GROUP @@ -32,6 +34,9 @@ db,store,queue=database(),ObjectStore(),broker() def inside(code): + from scripts.operator_task import prepare + + prepare() cid = compose("ps", "-q", "controller").split()[0] return json.loads( command( diff --git a/scripts/verify_security.py b/scripts/verify_security.py index ccd6024..dcb2e0f 100644 --- a/scripts/verify_security.py +++ b/scripts/verify_security.py @@ -2,9 +2,11 @@ import argparse import json +import subprocess from datetime import UTC, datetime from scripts.bootstrap_security import ( + OPERATOR, SECRET, key_bytes, make_root, @@ -12,7 +14,8 @@ from scripts.bootstrap_security import ( sign_leaf, write_private, ) -from scripts.stand import ROOT, command, compose +from scripts.stand import ROOT, command +from scripts.verify_clean import redact def main(): @@ -32,23 +35,43 @@ def main(): mode=0o644, ) write_private(fixture / "foreign/key.pem", key_bytes(key), mode=0o644) - result = json.loads( - compose( + for name in ["cert.pem", "key.pem"]: + write_private( + fixture / "operator" / name, + (OPERATOR / "client" / name).read_bytes(), + mode=0o644, + ) + process = subprocess.run( + [ + "docker", + "compose", "--profile", "operator", "run", "--rm", "--no-deps", "operator-probe", - ) + ], + cwd=ROOT, + capture_output=True, + text=True, ) + try: + result = json.loads(process.stdout) + except ValueError: + result = {"complete": False} + result["probe_exit_code"] = process.returncode + if process.returncode: + result["failure"] = redact(process.stderr, ROOT) result.update( date=datetime.now(UTC).isoformat(), source_commit=command(["git", "rev-parse", "HEAD"]), ) output.parent.mkdir(parents=True, exist_ok=True) output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n") - assert result["complete"] + assert process.returncode == 0 and result["complete"], ( + "Security probe failed; see saved receipt" + ) print( "PASS: real mTLS identities, server CA/hostname, closed plaintext boundaries and worker least privilege" ) diff --git a/src/operator_runtime.py b/src/operator_runtime.py new file mode 100644 index 0000000..8613a80 --- /dev/null +++ b/src/operator_runtime.py @@ -0,0 +1,29 @@ +"""Prepare an owner-only libpq key inside the explicit operator task tmpfs.""" + +import os +import runpy +from pathlib import Path + + +def prepare_key(): + # Docker Desktop bind ownership differs from the rootless container UID. + # The source stays beneath the host operator directory; only this explicit + # task mounts it. libpq receives an owned 0600 file in ephemeral tmpfs. + target = Path("/tmp/operator-client.key") + temporary = target.with_name(target.name + "." + str(os.getpid())) + fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + try: + with os.fdopen(fd, "wb") as stream: + stream.write(Path("/run/identity/current/key.pem").read_bytes()) + temporary.replace(target) + finally: + temporary.unlink(missing_ok=True) + + +def main(): + prepare_key() + runpy.run_module("src.operator", run_name="__main__") + + +if __name__ == "__main__": + main() diff --git a/src/security_probe.py b/src/security_probe.py index 3fd214f..0f03b1d 100644 --- a/src/security_probe.py +++ b/src/security_probe.py @@ -32,7 +32,7 @@ def context(role=None, *, foreign=False, wrong_ca=False): if foreign else ( Path("/probe-fixtures") / role - if role in {"revoked-lb", "retired-ca-lb"} + if role in {"revoked-lb", "retired-ca-lb", "operator"} else Path("/identities") / role / "current" ) ) @@ -77,255 +77,264 @@ def values(role): def main(): report = {"complete": False, "tls": [], "bypass": [], "database": {}} - request = ( - b"GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n" - ) - addresses = sorted( - { - x[4][0] - for x in socket.getaddrinfo( - "api", 8443, type=socket.SOCK_STREAM, family=socket.AF_INET - ) - } - ) - assert len(addresses) >= 2, "Both API replicas must be running" - endpoints = [ - ("api", 8443, "lb", "worker", request, ip) for ip in addresses - ] - body = b"{}" - otlp = ( - b"POST /v1/traces HTTP/1.1\r\nHost: otel\r\n" - b"Content-Type: application/json\r\nContent-Length: 2\r\n" - b"Connection: close\r\n\r\n" + body - ) - endpoints += [ - ("otel", 4438, "api", "lb", otlp, None), - ("broker", 6380, "worker", "api", b"*1\r\n$4\r\nPING\r\n", None), - ] - for host, port, good, wrong, payload, address in endpoints: - response = exchange(host, port, good, payload, address=address) - assert b" 200 " in response or response.startswith(b"-NOAUTH"), ( - host, - response[:80], + try: + request = ( + b"GET /health/live HTTP/1.1\r\nHost: api\r\n" + b"Connection: close\r\n\r\n" ) - result = { - "host": host, - "port": port, - "address": address, - "authorized": True, - } - for case, role, foreign in [ - ("no_certificate", None, False), - ("foreign_ca", good, True), - ("trusted_wrong_identity", wrong, False), - ]: - result[case + "_denied"] = denied( - partial( - exchange, - host, - port, - role, - payload, - address=address, - foreign=foreign, + addresses = sorted( + { + x[4][0] + for x in socket.getaddrinfo( + "api", 8443, type=socket.SOCK_STREAM, family=socket.AF_INET ) - ) - report["tls"].append(result) - report["tls_server_ca_denied"] = denied( - lambda: exchange("api", 8443, "lb", request, wrong_ca=True) - ) - report["tls_server_hostname_denied"] = denied( - lambda: exchange( - "api", 8443, "lb", request, hostname="unexpected.invalid" + } ) - ) - for host, port in [ - ("api", 8080), - ("postgres", 5432), - ("broker", 6379), - ("cache", 6379), - ("s3", 9000), - ("otel", 4318), - ("otel", 8889), - ("prometheus", 9090), - ("loki", 3100), - ("tempo", 3200), - ("grafana", 3000), - ("lb", 8404), - ]: - try: - with socket.create_connection((host, port), timeout=2): - raise AssertionError("Plaintext boundary bypass: " + host) - except ConnectionRefusedError: - report["bypass"].append( - {"host": host, "port": port, "closed": True} + assert len(addresses) >= 2, "Both API replicas must be running" + endpoints = [ + ("api", 8443, "lb", "worker", request, ip) for ip in addresses + ] + body = b"{}" + otlp = ( + b"POST /v1/traces HTTP/1.1\r\nHost: otel\r\n" + b"Content-Type: application/json\r\nContent-Length: 2\r\n" + b"Connection: close\r\n\r\n" + body + ) + endpoints += [ + ("otel", 4438, "api", "lb", otlp, None), + ("broker", 6380, "worker", "api", b"*1\r\n$4\r\nPING\r\n", None), + ] + for host, port, good, wrong, payload, address in endpoints: + response = exchange(host, port, good, payload, address=address) + assert b" 200 " in response or response.startswith(b"-NOAUTH"), ( + host, + response[:80], ) - worker = values("worker") - with psycopg.connect( - worker["DATABASE_URL"].replace( - "/run/identity/", "/identities/worker/" - ), - connect_timeout=3, - autocommit=True, - ) as connection: - assert connection.execute("SELECT 1").fetchone()[0] == 1 - for key, query in [ - ( - "user_passwords_denied", - "SELECT password_hash FROM users LIMIT 1", - ), - ( - "session_hashes_denied", - "SELECT token_digest FROM sessions LIMIT 1", - ), - ("create_role_denied", "CREATE ROLE unauthorized_probe LOGIN"), + result = { + "host": host, + "port": port, + "address": address, + "authorized": True, + } + for case, role, foreign in [ + ("no_certificate", None, False), + ("foreign_ca", good, True), + ("trusted_wrong_identity", wrong, False), + ]: + result[case + "_denied"] = denied( + partial( + exchange, + host, + port, + role, + payload, + address=address, + foreign=foreign, + ) + ) + report["tls"].append(result) + report["tls_server_ca_denied"] = denied( + lambda: exchange("api", 8443, "lb", request, wrong_ca=True) + ) + report["tls_server_hostname_denied"] = denied( + lambda: exchange( + "api", 8443, "lb", request, hostname="unexpected.invalid" + ) + ) + for host, port in [ + ("api", 8080), + ("postgres", 5432), + ("broker", 6379), + ("cache", 6379), + ("s3", 9000), + ("otel", 4318), + ("otel", 8889), + ("prometheus", 9090), + ("loki", 3100), + ("tempo", 3200), + ("grafana", 3000), + ("lb", 8404), ]: try: - connection.execute(query) - except InsufficientPrivilege: - report["database"][key] = True + with socket.create_connection((host, port), timeout=2): + raise AssertionError("Plaintext boundary bypass: " + host) + except ConnectionRefusedError: + report["bypass"].append( + {"host": host, "port": port, "closed": True} + ) + worker = values("worker") + with psycopg.connect( + worker["DATABASE_URL"].replace( + "/run/identity/", "/identities/worker/" + ), + connect_timeout=3, + autocommit=True, + ) as connection: + assert connection.execute("SELECT 1").fetchone()[0] == 1 + for key, query in [ + ( + "user_passwords_denied", + "SELECT password_hash FROM users LIMIT 1", + ), + ( + "session_hashes_denied", + "SELECT token_digest FROM sessions LIMIT 1", + ), + ("create_role_denied", "CREATE ROLE unauthorized_probe LOGIN"), + ]: + try: + connection.execute(query) + except InsufficientPrivilege: + report["database"][key] = True + else: + raise AssertionError( + "Worker SQL privilege was excessive: " + key + ) + url = worker["BROKER_URL"] + queue = redis.Redis.from_url( + url, + ssl_ca_certs="/trust/ca.pem", + ssl_certfile="/identities/worker/current/cert.pem", + ssl_keyfile="/identities/worker/current/key.pem", + ssl_cert_reqs="required", + ssl_check_hostname=True, + socket_timeout=3, + socket_connect_timeout=3, + ) + try: + assert queue.ping() + try: + queue.config_get("*") + except redis.exceptions.NoPermissionError: + report["broker_admin_denied"] = True else: raise AssertionError( - "Worker SQL privilege was excessive: " + key + "Worker received broker administration privileges" ) - url = worker["BROKER_URL"] - queue = redis.Redis.from_url( - url, - ssl_ca_certs="/trust/ca.pem", - ssl_certfile="/identities/worker/current/cert.pem", - ssl_keyfile="/identities/worker/current/key.pem", - ssl_cert_reqs="required", - ssl_check_hostname=True, - socket_timeout=3, - socket_connect_timeout=3, - ) - try: - assert queue.ping() - try: - queue.config_get("*") - except redis.exceptions.NoPermissionError: - report["broker_admin_denied"] = True - else: - raise AssertionError( - "Worker received broker administration privileges" - ) - finally: - queue.close() - - # Real service certificate authentication against persistent OpenBao. - def bao(method, path, payload=None, token=None): - headers = {"Content-Type": "application/json"} - if token: - headers["X-Vault-Token"] = token - request = urllib.request.Request( - "https://openbao:8200/v1/" + path, - data=json.dumps(payload).encode() if payload is not None else None, - method=method, - headers=headers, - ) - try: - with urllib.request.urlopen( - request, context=context("worker"), timeout=4 - ) as response: - return response.status, json.load( - response - ) if response.length != 0 else {} - except urllib.error.HTTPError as error: - return error.code, {} - - status, login = bao("POST", "auth/cert/login", {}) - assert status == 200 - token = login["auth"]["client_token"] - assert set(login["auth"]["policies"]) == {"messenger-worker"} - report["openbao"] = { - "service_policies": login["auth"]["policies"], - "token_ttl_seconds": login["auth"]["lease_duration"], - } - assert bao("GET", "secret/data/worker", token=token)[0] == 200 - for key, method, path, payload in [ - ("foreign_secret_denied", "GET", "secret/data/api", None), - ( - "policy_write_denied", - "PUT", - "sys/policies/acl/messenger-worker", - {"policy": 'path "*" { capabilities=["sudo"] }'}, - ), - ( - "foreign_pki_role_denied", - "POST", - "pki/issue/lb", - {"common_name": "lb"}, - ), - ]: - assert bao(method, path, payload, token)[0] == 403, key - report["openbao"][key] = True - clients = {} - pools = [] - for role in ["api", "worker", "reconciler"]: - credentials = values(role) - pool = urllib3.PoolManager( - ssl_context=context(role), - timeout=urllib3.Timeout(connect=2, read=4), - retries=False, - ) - pools.append(pool) - clients[role] = Minio( - "s3:9443", - credentials=StaticProvider( - credentials["S3_ACCESS_KEY"], credentials["S3_SECRET_KEY"] - ), - secure=True, - http_client=pool, - region="us-east-1", - ) - prefix = uuid4().hex - staging = "objects/staging/probe-" + prefix - derived = "objects/probe-" + prefix + "/v1/original" - - def put(role, key): - clients[role].put_object( - "messenger", key, io.BytesIO(b"Synthetic IAM probe"), 19 - ) - - def s3_denied(action): - try: - action() - except S3Error as error: - assert error.code == "AccessDenied", error.code - return True - raise AssertionError("S3 operation unexpectedly allowed") - - try: - put("api", staging) - received = clients["worker"].get_object("messenger", staging) - try: - assert received.read() == b"Synthetic IAM probe" finally: - received.close() - received.release_conn() - put("worker", derived) - report["s3"] = { - "api_staging_write": True, - "worker_source_read": True, - "worker_derived_write": True, - "api_derived_write_denied": s3_denied(lambda: put("api", derived)), - "worker_staging_write_denied": s3_denied( - lambda: put("worker", staging) - ), - "worker_list_all_buckets_denied": s3_denied( - lambda: clients["worker"].list_buckets() - ), - "worker_delete_denied": s3_denied( - lambda: clients["worker"].remove_object("messenger", derived) - ), + queue.close() + + # Real service certificate authentication against persistent OpenBao. + def bao(method, path, payload=None, token=None): + headers = {"Content-Type": "application/json"} + if token: + headers["X-Vault-Token"] = token + request = urllib.request.Request( + "https://openbao:8200/v1/" + path, + data=json.dumps(payload).encode() + if payload is not None + else None, + method=method, + headers=headers, + ) + try: + with urllib.request.urlopen( + request, context=context("worker"), timeout=4 + ) as response: + return response.status, json.load( + response + ) if response.length != 0 else {} + except urllib.error.HTTPError as error: + return error.code, {} + + status, login = bao("POST", "auth/cert/login", {}) + assert status == 200 + token = login["auth"]["client_token"] + assert set(login["auth"]["policies"]) == {"messenger-worker"} + report["openbao"] = { + "service_policies": login["auth"]["policies"], + "token_ttl_seconds": login["auth"]["lease_duration"], } + assert bao("GET", "secret/data/worker", token=token)[0] == 200 + for key, method, path, payload in [ + ("foreign_secret_denied", "GET", "secret/data/api", None), + ( + "policy_write_denied", + "PUT", + "sys/policies/acl/messenger-worker", + {"policy": 'path "*" { capabilities=["sudo"] }'}, + ), + ( + "foreign_pki_role_denied", + "POST", + "pki/issue/lb", + {"common_name": "lb"}, + ), + ]: + assert bao(method, path, payload, token)[0] == 403, key + report["openbao"][key] = True + clients = {} + pools = [] + for role in ["api", "worker", "reconciler"]: + credentials = values(role) + pool = urllib3.PoolManager( + ssl_context=context(role), + timeout=urllib3.Timeout(connect=2, read=4), + retries=False, + ) + pools.append(pool) + clients[role] = Minio( + "s3:9443", + credentials=StaticProvider( + credentials["S3_ACCESS_KEY"], credentials["S3_SECRET_KEY"] + ), + secure=True, + http_client=pool, + region="us-east-1", + ) + prefix = uuid4().hex + staging = "objects/staging/probe-" + prefix + derived = "objects/probe-" + prefix + "/v1/original" + + def put(role, key): + clients[role].put_object( + "messenger", key, io.BytesIO(b"Synthetic IAM probe"), 19 + ) + + def s3_denied(action): + try: + action() + except S3Error as error: + assert error.code == "AccessDenied", error.code + return True + raise AssertionError("S3 operation unexpectedly allowed") + + try: + put("api", staging) + received = clients["worker"].get_object("messenger", staging) + try: + assert received.read() == b"Synthetic IAM probe" + finally: + received.close() + received.release_conn() + put("worker", derived) + report["s3"] = { + "api_staging_write": True, + "worker_source_read": True, + "worker_derived_write": True, + "api_derived_write_denied": s3_denied( + lambda: put("api", derived) + ), + "worker_staging_write_denied": s3_denied( + lambda: put("worker", staging) + ), + "worker_list_all_buckets_denied": s3_denied( + lambda: clients["worker"].list_buckets() + ), + "worker_delete_denied": s3_denied( + lambda: clients["worker"].remove_object( + "messenger", derived + ) + ), + } + finally: + for key in [staging, derived]: + clients["reconciler"].remove_object("messenger", key) + for pool in pools: + pool.clear() + report["complete"] = True finally: - for key in [staging, derived]: - clients["reconciler"].remove_object("messenger", key) - for pool in pools: - pool.clear() - report["complete"] = True - print(json.dumps(report)) + print(json.dumps(report)) if __name__ == "__main__":