#!/usr/bin/env python3 """Revoke the worker AppRole SecretID and recover a queued attachment with a replacement.""" import json import os from pathlib import Path import ssl import subprocess import urllib.error import urllib.request from client import Client, arguments, check, run ROOT = Path(__file__).resolve().parents[1] SECRET_DIR = ROOT / "secrets" / "openbao" class BaoClient: def __init__(self, ca_file: str, root_token_file: str): self.address = "https://localhost:8200" self.context = ssl.create_default_context(cafile=ca_file) self.root_token = Path(root_token_file).read_text(encoding="utf-8").strip() check(bool(self.root_token), "operator root-token file is empty") def request(self, method: str, path: str, payload=None, token=None): body = json.dumps(payload).encode("utf-8") if payload is not None else None headers = {"Content-Type": "application/json"} if token is not None: if token: headers["X-Vault-Token"] = token elif self.root_token: headers["X-Vault-Token"] = self.root_token request = urllib.request.Request( self.address + "/v1/" + path, data=body, headers=headers, method=method, ) try: with urllib.request.urlopen(request, context=self.context, timeout=8) as response: data = response.read(1024 * 1024) return response.status, json.loads(data) if data else {} except urllib.error.HTTPError as error: return error.code, {} except (urllib.error.URLError, TimeoutError, OSError, ValueError) as error: raise RuntimeError(f"OpenBao request failed ({type(error).__name__})") from None def compose(*args) -> None: subprocess.run( ["docker", "compose", *args], cwd=ROOT, check=True, capture_output=True, text=True, ) def save_secret_id(value: str) -> None: path = SECRET_DIR / "worker_secret_id" temporary = path.with_suffix(".tmp") descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(descriptor, "w", encoding="utf-8") as output: output.write(value + "\n") os.replace(temporary, path) def rotate_worker_secret(bao: BaoClient) -> None: role_id = (SECRET_DIR / "worker_role_id").read_text(encoding="utf-8").strip() old_secret_id = (SECRET_DIR / "worker_secret_id").read_text(encoding="utf-8").strip() check(bool(role_id) and bool(old_secret_id), "worker AppRole credential files are empty") status, created = bao.request( "POST", "auth/approle/role/worker/secret-id", {}, ) new_secret_id = created.get("data", {}).get("secret_id") check(status == 200 and isinstance(new_secret_id, str), "OpenBao did not issue a replacement SecretID") save_secret_id(new_secret_id) status, login = bao.request( "POST", "auth/approle/login", {"role_id": role_id, "secret_id": new_secret_id}, token="", ) token = login.get("auth", {}).get("client_token") check(status == 200 and isinstance(token, str), "replacement worker SecretID did not authenticate") status, _ = bao.request( "GET", "secret/data/messenger/worker", token=token, ) check(status == 200, "replacement worker identity cannot read its own secret path") status, _ = bao.request( "POST", "auth/approle/role/worker/secret-id/destroy", {"secret_id": old_secret_id}, ) check(status == 204, "OpenBao did not revoke the previous worker SecretID") status, _ = bao.request( "POST", "auth/approle/login", {"role_id": role_id, "secret_id": old_secret_id}, token="", ) check(status == 400, "revoked worker SecretID still authenticates") def main() -> None: def configure(parser): parser.add_argument("--root-token-file", required=True) args = arguments("Verify queued attachment recovery after worker SecretID rotation", configure) ca_file = args.ca_file or str(ROOT / "secrets" / "pki" / "ca.crt") client = Client(args.base_url, ca_file) bao = BaoClient(ca_file, args.root_token_file) alice, bob, _, chat = client.bootstrap() worker_stopped = False try: compose("stop", "worker") worker_stopped = True attachment, original = client.attachment(alice, chat) check(attachment["status"] == "queued", "upload was not queued while the worker was stopped") message = client.message(alice, chat, "", attachments=[attachment["id"]])["json"] check(message["attachment_ids"] == [attachment["id"]], "queued attachment was not linked to its message") rotate_worker_secret(bao) compose("up", "-d", "--no-deps", "--force-recreate", "worker") worker_stopped = False ready = client.wait_ready(bob, attachment) original_bytes = client.call( "GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob, )["bytes"] check(original_bytes == original, "rotated worker changed the original attachment bytes") page = client.call( "GET", f"/api/v1/chats/{chat['id']}/messages", actor=bob, schema="MessagePage", )["json"] recovered = next(item for item in page["items"] if item["id"] == message["id"]) check(recovered["attachment_ids"] == [attachment["id"]], "message lost its attachment link") print( json.dumps( { "result": "PASS", "old_worker_secret_id_revoked": True, "replacement_worker_secret_id_authenticated": True, "attachment_state": [attachment["status"], ready["status"]], "original_sha256_preserved": True, "message_attachment_link_preserved": True, }, sort_keys=True, ) ) finally: if worker_stopped: compose("up", "-d", "--no-deps", "--force-recreate", "worker") if __name__ == "__main__": run(main)