#!/usr/bin/env python3 """Rotate exactly one explicitly selected LEAF key. Never prints API bodies/keys. Run on sensor: sudo python3 .../rotate-vyos-key.py --old-id Other applications' credentials are preserved. Retrying after retirement/save failure requires inspecting router key IDs first; no blind mass-delete mode. """ import argparse import os from pathlib import Path import re import secrets import string import subprocess import sys import time sys.path.insert(0, '/opt/leaf-controller/controller') from leaf_controller.config import load_config, read_key_env from leaf_controller.vyos_client import VyosClient, VyosApiError ENV_PATH = '/etc/leaf-controller/env' CFG_PATH = '/etc/leaf-controller/config.yaml' SERVICE = 'leaf-controller.service' KEYS_PATH = ['service', 'https', 'api', 'keys', 'id'] def atomic_env(text): tmp=ENV_PATH+'.new' fd=os.open(tmp, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, 0o600) os.fchmod(fd, 0o600) with os.fdopen(fd, 'w') as f: f.write(text); f.flush(); os.fsync(f.fileno()) os.replace(tmp, ENV_PATH) fd=os.open(str(Path(ENV_PATH).parent), os.O_DIRECTORY) try: os.fsync(fd) finally: os.close(fd) def restart_service(): subprocess.run(['systemctl','restart',SERVICE], check=True, capture_output=True) subprocess.run(['systemctl','is-active','--quiet',SERVICE], check=True, capture_output=True) def wait_auth(client, group, accepted=True, attempts=24): for i in range(attempts): try: client.group_members(group) if accepted: return except VyosApiError as exc: if not accepted and exc.status in (401,403): return except Exception: pass if i+1