"""Сравнивает права worker и проверяет сохранность задания при отзыве доступа.""" import hashlib import json import os from pathlib import Path import re import secrets import shutil import socket import subprocess import sys from tempfile import TemporaryDirectory import time from uuid import UUID, uuid4 from scripts.bootstrap_bao import Bao, TLS, bootstrap, operator_token from scripts.check_lifecycle import deny from scripts.deployment import ROOT, ComposeProject, inventory from scripts.init_local import main as initialize from scripts.init_tls import issue from scripts.rotate_worker import change_db_password, rotate from tests.client import Client PREFIX = "messenger-worker-lab-" PROBE = "scripts/worker_probe.py" RESULT = Path("evidence/worker-compromise.json") S3_OPERATOR = """ import os from pathlib import Path import sys from bootstrap import operator access = Path("/run/credentials/worker_access_key_id").read_text().strip() bucket = os.environ["S3_BUCKET"] with operator() as (mc, config): phase = sys.argv[1] if phase == "broad": fixture = config / "fixture" fixture.write_bytes(b"synthetic worker experiment") for key in ("staging/experiment/fixture", "private/experiment/fixture", "staging/experiment/delete-broad", "staging/experiment/delete-limited"): mc("cp", str(fixture), f"storage/{bucket}/{key}") mc("admin", "policy", "attach", "storage", "readwrite", "--user", access) elif phase == "limited": mc("admin", "policy", "detach", "storage", "readwrite", "--user", access) elif phase == "revoke": mc("admin", "user", "disable", "storage", access) else: raise ValueError("Неизвестная фаза проверки") """ LIMITED_DENIALS = { "postgresql": {"read_users", "update_users", "read_messages"}, "rabbitmq": {"configure_private", "read_private", "publish_private"}, "s3": {"write_staging", "read_private", "write_private"}, } def wait_for(operation, description, timeout=60): deadline = time.monotonic() + timeout while time.monotonic() < deadline: value = operation() if value: return value time.sleep(0.5) raise RuntimeError(description) def database(project, sql): return project.run( "exec", "-T", "postgres", "sh", "-ec", 'psql -XAt -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"', input_text=sql, ) def broker(project, *args): return project.run("exec", "-T", "broker", "rabbitmqctl", *args, timeout=30) def minio(project, phase): project.run("run", "--rm", "--no-deps", "-T", "--entrypoint", "python", "minio-bootstrap", "-c", S3_OPERATOR, phase) def probe(project, phase, payload=None): output = project.run( "run", "--rm", "--no-deps", "-T", "--volume", f"{ROOT / PROBE}:/app/worker_probe.py:ro", "--entrypoint", "python", "worker", "-m", "worker_probe", phase, input_text=json.dumps(payload) if payload else None, ) return json.loads(output) def job_state(project, attachment_id): attachment_id = UUID(attachment_id) output = database(project, f""" SELECT json_build_object('id', j.id, 'attempt', j.attempt, 'published_attempt', j.published_attempt, 'status', a.status) FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id WHERE j.attachment_id = '{attachment_id}'::uuid; """) rows = output.splitlines() assert len(rows) == 1, "У вложения должно быть ровно одно задание" return json.loads(rows[0]) def queue_ready(project, queue): rows = json.loads(broker(project, "list_queues", "--formatter=json", "name", "messages_ready", "messages_unacknowledged", "durable")) state = next(row for row in rows if row["name"] == queue) assert state["durable"] return state["messages_ready"] if state["messages_unacknowledged"] == 0 else None def assert_profiles(broad, limited): assert set(broad) == set(limited) == set(LIMITED_DENIALS) for service, denials in LIMITED_DENIALS.items(): assert broad[service].keys() == limited[service].keys() assert all(broad[service].values()), service assert {key for key, value in limited[service].items() if not value} == denials, service def recover_service_identities(project, definitions, permission): # Новые CN оставляют старые сертификаты пригодными только для проверки отказа. issue(TLS, "attachment-worker-recovered", "DNS:attachment-worker-recovered", "clientAuth", "broker-client-ca") issue(TLS, "otel-worker-recovered", "DNS:otel-worker-recovered", "clientAuth", "otel-ingest-ca") original = next(user for user in definitions["users"] if user["name"] == "attachment-worker") identity = "attachment-worker-recovered" replacement = { "users": [{**original, "name": identity}], "permissions": [{**permission, "user": identity}], } project.run( "exec", "-T", "broker", "sh", "-ec", 'file=$(mktemp); trap \'rm -f "$file"\' EXIT; cat >"$file"; rabbitmqctl import_definitions "$file"', input_text=json.dumps(replacement), ) collector = ROOT / "infra/otel/collector-scrape.conf" collector.write_text(collector.read_text().replace( "CN=otel-worker 0;", "CN=otel-worker-recovered 1;" )) project.run("exec", "-T", "collector-scrape", "nginx", "-s", "reload") for file in ("worker_s3_access_key_id", "worker_s3_secret_access_key"): target = ROOT / "secrets" / file temporary = target.with_suffix(".new") temporary.write_text(secrets.token_urlsafe(24)) temporary.chmod(0o444) temporary.replace(target) project.run("run", "--rm", "--no-deps", "-T", "minio-bootstrap") compose = ROOT / "compose.yaml" config = compose.read_text() for name in ("attachment-worker", "otel-worker"): config = config.replace(f"./secrets/tls/{name}.", f"./secrets/tls/{name}-recovered.") compose.write_text(config) def experiment(port, ingress): project_name = os.environ.get("COMPOSE_PROJECT_NAME", "") if (Path.cwd() != ROOT or ROOT.parent != Path("/tmp") or not ROOT.name.startswith(PREFIX) or not re.fullmatch(r"messenger-worker-lab-[0-9a-f]{12}", project_name)): raise RuntimeError("Эксперимент выполняется только во временной копии") if (ROOT / ".env").exists() or any(inventory([project_name]).values()): raise RuntimeError("Для эксперимента нужны новые локальные настройки и тома") initialize() lifecycle = ComposeProject() try: lifecycle.run("up", "-d", "openbao", timeout=90) bootstrap(port) lifecycle.run("up", "-d", "--build", "--wait", "--wait-timeout", "180", timeout=600) lifecycle.run("stop", "worker") definitions = json.loads((ROOT / "secrets/broker_definitions.json").read_text()) permission = next(item for item in definitions["permissions"] if item["user"] == "attachment-worker") queue = lifecycle.config["services"]["worker"]["environment"]["BROKER_QUEUE"] def set_permissions(configure, read, write): broker(lifecycle, "set_permissions", "-p", permission["vhost"], "attachment-worker", configure, write, read) database(lifecycle, "GRANT SELECT, UPDATE ON users TO worker; GRANT SELECT ON messages TO worker;") set_permissions(".*", ".*", ".*") minio(lifecycle, "broad") broad = probe(lifecycle, "broad") database(lifecycle, "REVOKE SELECT, UPDATE ON users FROM worker; REVOKE SELECT ON messages FROM worker;") set_permissions(permission["configure"], permission["read"], permission["write"]) minio(lifecycle, "limited") limited = probe(lifecycle, "limited") assert_profiles(broad, limited) print("PASS: проверены широкая и ограниченная роли", flush=True) client = Client(f"https://localhost:{ingress}", str(TLS / "ca.crt")) actor, _, _, chat = client.bootstrap() attachment, content = client.attachment(actor, chat) message = client.message(actor, chat, "", attachments=[attachment["id"]])["json"] before = wait_for( lambda: job_state(lifecycle, attachment["id"]) if queue_ready(lifecycle, queue) == 1 else None, "Задание не попало в RabbitMQ", ) assert before["status"] == "queued" and before["published_attempt"] == 1 assert before["attempt"] == 0 operator, root_token = Bao(port), operator_token(port) old_identity = Bao(port, TLS / "worker-bao.crt", TLS / "worker-bao.key") old_token = old_identity.call("auth/cert/login", {"name": "worker"})["auth"] secret_path = "messenger/data/worker" password = old_identity.call(secret_path, token=old_token["client_token"])["data"]["data"]["db_password"] started = time.monotonic() operator.call("auth/cert/certs/worker", token=root_token, method="DELETE") operator.call("auth/token/revoke-accessor", {"accessor": old_token["accessor"]}, token=root_token) broker(lifecycle, "delete_user", "attachment-worker") minio(lifecycle, "revoke") change_db_password(lifecycle, secrets.token_urlsafe(24)) revoked_db = probe(lifecycle, "old-db", {"old_db_password": password})["old_db"] assert not revoked_db collector = ROOT / "infra/otel/collector-scrape.conf" collector.write_text(collector.read_text().replace("CN=otel-worker 1;", "CN=otel-worker 0;")) lifecycle.run("exec", "-T", "collector-scrape", "nginx", "-s", "reload") deny(lambda: old_identity.call("auth/cert/login", {"name": "worker"})) deny(lambda: old_identity.call(secret_path, token=old_token["client_token"])) revoked = probe(lifecycle, "revoked") assert revoked == {"rabbitmq": {"connect": False}, "collector": False, "s3": {"read_staging": False}}, revoked assert queue_ready(lifecycle, queue) == 1 assert job_state(lifecycle, attachment["id"]) == before print("PASS: прежние учётные данные недействительны, задание сохранено", flush=True) image = lifecycle.run("images", "-q", "worker") recover_service_identities(lifecycle, definitions, permission) rotate(ComposeProject(), port) assert lifecycle.run("images", "-q", "worker") == image deny(lambda: old_identity.call("auth/cert/login", {"name": "worker"})) recovered = probe(ComposeProject(), "recovered", {"old_db_password": password}) assert recovered == {"rabbitmq": {"connect": True}, "collector": True, "old_db": False} ready = client.wait_ready(actor, attachment, wait_seconds=60) elapsed = round(time.monotonic() - started, 2) after = job_state(lifecycle, attachment["id"]) assert before["id"] == after["id"] and after["status"] == "ready" and after["attempt"] == 1 assert {variant["name"] for variant in ready["variants"]} == {"thumbnail", "crop", "optimized"} downloaded = client.call("GET", f"/api/v1/attachments/{ready['id']}/content", actor=actor)["bytes"] assert downloaded == content history = client.call("GET", f"/api/v1/chats/{chat['id']}/messages", actor=actor, schema="MessagePage")["json"]["items"] assert sum(item == message for item in history) == 1 wait_for(lambda: queue_ready(lifecycle, queue) == 0, "Задание не подтверждено брокеру") result = { "result": "PASS", "broad": broad, "least_privilege": limited, "revoked_access": {**revoked, "postgresql": revoked_db, "openbao": False}, "job": {"before": before, "after": after, "queued_during_revocation": 1, "queue_after_ack": 0, "recovery_seconds": elapsed, "original_sha256": hashlib.sha256(downloaded).hexdigest(), "variants": sorted(variant["name"] for variant in ready["variants"]), "message_occurrences": 1, "worker_image_preserved": True}, } print("PASS: то же задание обработано за одну попытку без повторной загрузки", flush=True) finally: lifecycle.run("down", "--volumes", "--remove-orphans", timeout=120) if any(inventory([project_name]).values()): raise RuntimeError("Не все ресурсы экспериментального проекта удалены") images = [f"{project_name}-{component}:local" for component in ("app", "minio", "bootstrap")] for image_tag in images: if lifecycle.docker("image", "ls", "-q", image_tag): lifecycle.docker("image", "rm", image_tag) result["stand_removed"] = True (ROOT / RESULT).write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n") def free_ports(): with socket.socket() as first, socket.socket() as second, socket.socket() as third: for listener in (first, second, third): listener.bind(("127.0.0.1", 0)) return [listener.getsockname()[1] for listener in (first, second, third)] def main(): if len(sys.argv) == 4 and sys.argv[1] == "--isolated": experiment(int(sys.argv[2]), int(sys.argv[3])) return with TemporaryDirectory(prefix=PREFIX, dir="/tmp") as directory: target = Path(directory) for name in ("app", "infra", "migrations", "scripts", "tests", "contracts"): shutil.copytree(ROOT / name, target / name, ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) for name in (".env.example", ".dockerignore", "Dockerfile", "alembic.ini", "requirements.txt", "compose.yaml", "lab.json"): shutil.copy2(ROOT / name, target / name) (target / "evidence").mkdir() project = PREFIX + uuid4().hex[:12] compose = target / "compose.yaml" compose.write_text(compose.read_text() .replace("messenger-lab7-minio:local", f"{project}-minio:local") .replace("messenger-lab7-minio-bootstrap:local", f"{project}-bootstrap:local")) ingress, bao, grafana = free_ports() settings = { line.partition("=")[0].strip() for line in (target / ".env.example").read_text().splitlines() if "=" in line and not line.lstrip().startswith("#") } env = {key: value for key, value in os.environ.items() if key not in settings and not key.startswith("COMPOSE_")} env.update(COMPOSE_PROJECT_NAME=project, API_IMAGE=f"{project}-app:local", LB_HOST_PORT=str(ingress), BAO_HOST_PORT=str(bao), GRAFANA_HOST_PORT=str(grafana)) subprocess.run([sys.executable, "-m", "scripts.worker_experiment", "--isolated", str(bao), str(ingress)], cwd=target, env=env, check=True) shutil.copy2(target / RESULT, ROOT / RESULT) if __name__ == "__main__": main()