#!/usr/bin/env python3 """Install the fleet CI repository secrets from a decrypted spindle bundle. The bundle is produced by the operator decrypting secrets/nix-cache-spindle.age. It is JSON: {"version": 1, "repoDid": "did:plc:...", "secrets": {"NAME": "value", ...}} Values are read from the bundle and sent only in request bodies. Nothing secret is printed, written to argv, or persisted; a PDS session is held in memory. Authentication uses AT Protocol service auth: the human operator's PDS session mints a short-lived token with audience did:web: and lxm bound to each secret NSID. The repository DID is only the target repository; it is never used to discover the human operator's PDS. """ from __future__ import annotations import argparse import getpass import json import os import re import stat import sys import time import urllib.error import urllib.parse import urllib.request from pathlib import Path KEY_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$") DID_RE = re.compile(r"^did:[a-z0-9]+:[A-Za-z0-9._:%-]+$") MAX_VALUE_LEN = 4096 MAX_KEY_LEN = 50 SERVICE_AUTH_SECONDS = 300 ADD = "org.tangled.secret.addSecret" LIST = "org.tangled.secret.listSecrets" REMOVE = "org.tangled.secret.removeSecret" USER_AGENT = "spindle-bootstrap/1" class BootstrapError(Exception): pass def http_json( method: str, url: str, *, token: str | None = None, body: dict | None = None, timeout: float = 30.0, ) -> dict: data = None headers = {"Accept": "application/json", "User-Agent": USER_AGENT} if token is not None: headers["Authorization"] = f"Bearer {token}" if body is not None: data = json.dumps(body, separators=(",", ":")).encode() headers["Content-Type"] = "application/json" req = urllib.request.Request(url, data=data, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=timeout) as resp: payload = resp.read() return json.loads(payload) if payload else {} except urllib.error.HTTPError as exc: detail = "" try: raw = exc.read(8192) parsed = json.loads(raw) if isinstance(parsed, dict): detail = str(parsed.get("error") or parsed.get("message") or "") except Exception: pass detail = " ".join(detail.split())[:200] suffix = f": {detail}" if detail else "" raise BootstrapError(f"{method} {redact_url(url)} returned HTTP {exc.code}{suffix}") from None except urllib.error.URLError as exc: raise BootstrapError(f"{method} {redact_url(url)} failed: {exc.reason}") from None def redact_url(url: str) -> str: """URLs here never contain credentials, but avoid query values in errors.""" parts = urllib.parse.urlsplit(url) return urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path, "", "")) def require_https(url: str, what: str) -> str: parts = urllib.parse.urlsplit(url) if parts.scheme not in {"http", "https"} or not parts.hostname: raise BootstrapError(f"{what} must be an http(s) URL") local = parts.hostname in {"localhost", "127.0.0.1", "::1"} if parts.scheme != "https" and not local: raise BootstrapError(f"{what} must use https") if parts.query or parts.fragment: raise BootstrapError(f"{what} must not contain a query or fragment") return url.rstrip("/") def load_bundle(path: str) -> tuple[str, dict[str, str]]: if path == "-": raw = sys.stdin.buffer.read() else: p = Path(path) if p.suffix == ".age": raise BootstrapError( "bundle is still encrypted; decrypt it first, then pass the plaintext JSON" ) if not p.is_file(): raise BootstrapError(f"bundle not found: {path}") mode = stat.S_IMODE(p.stat().st_mode) if mode & 0o077: print( f"warning: {path} is readable by group/others (mode {mode:04o})", file=sys.stderr, ) raw = p.read_bytes() try: bundle = json.loads(raw) except json.JSONDecodeError as exc: raise BootstrapError(f"bundle is not valid JSON: {exc}") from None if not isinstance(bundle, dict): raise BootstrapError("bundle must be a JSON object") if bundle.get("version") != 1: raise BootstrapError("bundle version must be 1") repo_did = bundle.get("repoDid") if not isinstance(repo_did, str) or not DID_RE.match(repo_did): raise BootstrapError("bundle repoDid is not a valid DID") secrets = bundle.get("secrets") if not isinstance(secrets, dict) or not secrets: raise BootstrapError("bundle secrets must be a non-empty object") clean: dict[str, str] = {} for key, value in secrets.items(): if not isinstance(key, str) or not KEY_RE.match(key): raise BootstrapError(f"invalid secret key in bundle: {key!r}") if len(key) > MAX_KEY_LEN: raise BootstrapError(f"secret key is longer than {MAX_KEY_LEN}: {key}") if not isinstance(value, str) or not value: raise BootstrapError(f"secret {key} must be a non-empty string") if len(value) > MAX_VALUE_LEN: raise BootstrapError(f"secret {key} is longer than {MAX_VALUE_LEN} characters") clean[key] = value return repo_did, clean def read_session_file(path: str) -> dict: try: session = json.loads(Path(path).read_text()) except FileNotFoundError: raise BootstrapError(f"session file not found: {path}") from None except (OSError, json.JSONDecodeError) as exc: raise BootstrapError(f"cannot read session file {path}: {exc}") from None return normalize_session(session) def normalize_session(session: object) -> dict: if not isinstance(session, dict): raise BootstrapError("PDS session must be a JSON object") access = session.get("accessJwt") or session.get("access_token") or session.get("accessJWT") refresh = session.get("refreshJwt") or session.get("refresh_token") or session.get("refreshJWT") if not isinstance(access, str) or not access: raise BootstrapError("PDS session has no access token") return { "access": access, "refresh": refresh if isinstance(refresh, str) and refresh else None, "did": session.get("did"), } def resolve_handle(handle: str, pds_url: str | None) -> str: queries = ["https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle"] if pds_url: queries.append(f"{pds_url}/xrpc/com.atproto.identity.resolveHandle") last: BootstrapError | None = None for base in queries: url = f"{base}?{urllib.parse.urlencode({'handle': handle})}" try: doc = http_json("GET", url) except BootstrapError as exc: last = exc continue did = doc.get("did") if isinstance(did, str) and did.startswith("did:"): return did raise BootstrapError(f"cannot resolve handle {handle!r}") from last def did_document_url(did: str) -> str: if did.startswith("did:plc:"): return f"https://plc.directory/{urllib.parse.quote(did, safe=':')}" if did.startswith("did:web:"): rest = did[len("did:web:") :] host, *segments = rest.split(":") host = urllib.parse.unquote(host) if not host: raise BootstrapError(f"invalid did:web: {did}") path = "/".join(segments) base = f"https://{host}/.well-known/did.json" if not path else f"https://{host}/{path}/did.json" return base raise BootstrapError(f"cannot resolve PDS for DID method in {did}") def resolve_pds(identifier: str) -> tuple[str, str]: if identifier.startswith("did:"): did = identifier else: did = resolve_handle(identifier, None) doc = http_json("GET", did_document_url(did)) services = doc.get("service") if not isinstance(services, list): raise BootstrapError(f"DID document for {did} has no services") for service in services: if not isinstance(service, dict): continue sid = service.get("id", "") if isinstance(sid, str) and sid.endswith("#atproto_pds"): endpoint = service.get("serviceEndpoint") if isinstance(endpoint, str) and endpoint: return did, require_https(endpoint, "PDS endpoint") raise BootstrapError(f"DID document for {did} has no #atproto_pds service") def create_session(pds_url: str, identifier: str) -> dict: if not sys.stdin.isatty(): raise BootstrapError( "no PDS session supplied and stdin is not a terminal; pass --session-file " "or NIX_CACHE_PDS_SESSION JSON instead of prompting" ) password = getpass.getpass(f"App password for {identifier} (not logged): ") if not password: raise BootstrapError("empty app password") session = http_json( "POST", f"{pds_url}/xrpc/com.atproto.server.createSession", body={"identifier": identifier, "password": password}, ) del password return normalize_session(session) def refresh_session(pds_url: str, session: dict) -> dict: refresh = session.get("refresh") if not refresh: raise BootstrapError("PDS access token was rejected and no refresh token is available") refreshed = http_json( "POST", f"{pds_url}/xrpc/com.atproto.server.refreshSession", token=refresh, ) return normalize_session(refreshed) def service_token(pds_url: str, session: dict, audience: str, lxm: str) -> str: url = ( f"{pds_url}/xrpc/com.atproto.server.getServiceAuth?" + urllib.parse.urlencode({"aud": audience, "lxm": lxm, "exp": int(time.time()) + SERVICE_AUTH_SECONDS}) ) try: doc = http_json("GET", url, token=session["access"]) except BootstrapError as exc: if "HTTP 401" not in str(exc): raise session.update(refresh_session(pds_url, session)) doc = http_json("GET", url, token=session["access"]) token = doc.get("token") if not isinstance(token, str) or not token: raise BootstrapError(f"PDS returned no service token for {lxm}") return token def spindle_did(spindle_url: str) -> str: host = urllib.parse.urlsplit(spindle_url).netloc if not host: raise BootstrapError("--spindle-url has no host") return "did:web:" + host.replace(":", "%3A") def install_secret(spindle_url: str, token: str, repo_did: str, key: str, value: str) -> None: http_json( "POST", f"{spindle_url}/xrpc/{ADD}", token=token, body={"repo": repo_did, "key": key, "value": value}, ) def remove_secret(spindle_url: str, token: str, repo_did: str, key: str) -> None: http_json( "POST", f"{spindle_url}/xrpc/{REMOVE}", token=token, body={"repo": repo_did, "key": key}, ) def list_secrets(spindle_url: str, token: str, repo_did: str) -> list[str]: url = f"{spindle_url}/xrpc/{LIST}?" + urllib.parse.urlencode({"repo": repo_did}) doc = http_json("GET", url, token=token) entries = doc.get("secrets") or [] keys: list[str] = [] if isinstance(entries, list): for entry in entries: if isinstance(entry, dict) and isinstance(entry.get("key"), str): keys.append(entry["key"]) return keys def main() -> int: parser = argparse.ArgumentParser( description="Install fleet CI secrets into a self-hosted Tangled spindle.", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument("--bundle", required=True, help="decrypted bundle JSON, or - for stdin") parser.add_argument("--spindle-url", required=True, help="public base URL of the spindle") parser.add_argument("--spindle-did", help="override the derived did:web spindle audience") parser.add_argument( "--pds-url", default="https://sharkgirl.pet", help="PDS base URL; override when the operator account lives elsewhere", ) parser.add_argument( "--identifier", default="callie.on-her.computer", help="human owner/collaborator handle or DID", ) parser.add_argument("--session-file", help="JSON file containing an existing PDS session") parser.add_argument("--replace", action="store_true", help="replace secrets that already exist") parser.add_argument("--check", action="store_true", help="only list which bundle keys are installed") parser.add_argument("--keys", help="comma-separated subset of bundle keys to install") args = parser.parse_args() try: spindle_url = require_https(args.spindle_url, "--spindle-url") audience = args.spindle_did or spindle_did(spindle_url) if not audience.startswith("did:web:"): raise BootstrapError("--spindle-did must be a did:web DID") repo_did, secrets = load_bundle(args.bundle) if args.keys: wanted = [key.strip() for key in args.keys.split(",") if key.strip()] missing = [key for key in wanted if key not in secrets] if missing: raise BootstrapError("bundle has no such secret(s): " + ", ".join(missing)) secrets = {key: secrets[key] for key in wanted} session: dict | None = None if args.session_file: session = read_session_file(args.session_file) else: env_session = os.environ.get("NIX_CACHE_PDS_SESSION") or os.environ.get("ATP_SESSION_JSON") if env_session: try: session = normalize_session(json.loads(env_session)) except json.JSONDecodeError as exc: raise BootstrapError(f"NIX_CACHE_PDS_SESSION is not JSON: {exc}") from None identifier = args.identifier pds_url = require_https(args.pds_url, "--pds-url") if args.pds_url else None if session is None: if not identifier: raise BootstrapError( "no PDS session supplied: pass --identifier (handle or DID) to log in, " "or --session-file/NIX_CACHE_PDS_SESSION for an existing session" ) if pds_url is None: resolved_did, pds_url = resolve_pds(identifier) identifier = resolved_did session = create_session(pds_url, identifier) elif pds_url is None: if identifier: _, pds_url = resolve_pds(identifier) elif session.get("did"): _, pds_url = resolve_pds(session["did"]) else: raise BootstrapError("--pds-url is required when the supplied session has no DID") if args.check: token = service_token(pds_url, session, audience, LIST) installed = set(list_secrets(spindle_url, token, repo_did)) for key in sorted(secrets): print(f"{'installed' if key in installed else 'missing'} {key}") return 0 add_token = None remove_token = None for key in sorted(secrets): if add_token is None: add_token = service_token(pds_url, session, audience, ADD) try: install_secret(spindle_url, add_token, repo_did, key, secrets[key]) print(f"installed {key}") except BootstrapError as exc: if "HTTP 409" not in str(exc) or not args.replace: if "HTTP 409" in str(exc): print(f"exists {key} (rerun with --replace to update)", file=sys.stderr) continue raise if remove_token is None: remove_token = service_token(pds_url, session, audience, REMOVE) remove_secret(spindle_url, remove_token, repo_did, key) install_secret(spindle_url, add_token, repo_did, key, secrets[key]) print(f"replaced {key}") try: list_token = service_token(pds_url, session, audience, LIST) installed = set(list_secrets(spindle_url, list_token, repo_did)) except BootstrapError as exc: print(f"warning: could not verify installed keys: {exc}", file=sys.stderr) else: missing = sorted(set(secrets) - installed) if missing: raise BootstrapError("spindle does not list these keys after install: " + ", ".join(missing)) print(f"verified {len(secrets)} secret(s) on {repo_did}") return 0 except BootstrapError as exc: print(f"error: {exc}", file=sys.stderr) return 1 except KeyboardInterrupt: print("interrupted", file=sys.stderr) return 130 if __name__ == "__main__": raise SystemExit(main())