Files
mtusi2026lab7/scripts/rotate_identity.py
T

130 lines
4.7 KiB
Python

#!/usr/bin/env python3
"""Operator-driven worker revoke/cert renewal and DB credential rotation, no rebuild."""
import importlib.util
import json
import secrets
import ssl
import subprocess
import time
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def main():
spec = importlib.util.spec_from_file_location("bootstrap", ROOT / "scripts/bootstrap.py")
bootstrap = importlib.util.module_from_spec(spec)
spec.loader.exec_module(bootstrap)
old = ROOT / "secrets/pki/worker"
cert = ssl._ssl._test_decode_cert(str(old / "cert.pem"))
snapshot = ROOT / "operator-private/revoked-worker"
snapshot.mkdir(exist_ok=True, mode=0o700)
for name in ("cert.pem", "key.pem"):
(snapshot / name).write_bytes((old / name).read_bytes())
(snapshot / name).chmod(0o600)
context = ssl.create_default_context(cafile=str(ROOT / "secrets/ca.pem"))
context.load_cert_chain(snapshot / "cert.pem", snapshot / "key.pem")
auth_request = urllib.request.Request(
"https://localhost:18207/v1/auth/cert/login",
data=b'{"name":"worker"}',
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(auth_request, context=context, timeout=5) as response:
old_auth = json.load(response)["auth"]
old_token = old_auth["client_token"]
old_token_expiry = time.time() + old_auth["lease_duration"]
seed_before = json.loads((ROOT / "secrets/bao_seed.json").read_text())
material = seed_before["worker"]
material["REVOKED_BAO_TOKEN"] = old_token
material["REVOKED_BAO_TOKEN_EXPIRES_AT"] = old_token_expiry
(snapshot / "material.json").write_text(json.dumps(material))
(snapshot / "material.json").chmod(0o644)
# The containing operator-private directory stays 0700 on the host. This
# disposable old-material mount is used only by the explicit negative probe.
for name in ("cert.pem", "key.pem"):
(snapshot / name).chmod(0o644)
snapshot.chmod(0o755)
revoked = ROOT / "secrets/revoked.json"
serials = json.loads(revoked.read_text())
serials.append(cert["serialNumber"].lstrip("0").lower())
revoked.write_text(json.dumps(sorted(set(serials))))
subprocess.run(
["docker", "compose", "stop", "worker"], cwd=ROOT, check=True, capture_output=True
)
# Close OLD certificate authentication before enumerating/revoking tokens;
# otherwise an attacker could mint another token during the rotation gap.
subprocess.run(
["python3", "scripts/bao_operator.py", "disable-worker-auth"],
cwd=ROOT,
check=True,
capture_output=True,
)
try:
with urllib.request.urlopen(auth_request, context=context, timeout=5):
raise RuntimeError("Old worker certificate authentication remained enabled")
except urllib.error.HTTPError as exc:
if exc.code not in {400, 403}:
raise
subprocess.run(
["python3", "scripts/bao_operator.py", "revoke-worker-tokens"],
cwd=ROOT,
check=True,
capture_output=True,
)
bootstrap.certificate("worker", replace=True)
password = secrets.token_urlsafe(32)
# psql receives SQL through stdin, never a process argument/output containing
# credentials. The operator/admin role is confined to this explicit command.
sql = f"ALTER ROLE worker PASSWORD '{password}'; SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename='worker' AND pid<>pg_backend_pid();"
subprocess.run(
[
"docker",
"compose",
"exec",
"-T",
"postgres",
"psql",
"-U",
"messenger",
"-d",
"messenger",
"-v",
"ON_ERROR_STOP=1",
],
cwd=ROOT,
input=sql,
text=True,
check=True,
capture_output=True,
)
path = ROOT / "secrets/worker_db_password"
path.write_text(password)
bootstrap.write_roles()
seed_path = ROOT / "secrets/bao_seed.json"
seed = json.loads(seed_path.read_text())
seed["worker"]["DATABASE_URL"] = (
"postgresql://worker:"
+ password
+ "@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/tls/ca.pem"
)
seed_path.write_text(json.dumps(seed))
subprocess.run(
["python3", "scripts/bao_operator.py", "configure"],
cwd=ROOT,
check=True,
capture_output=True,
)
subprocess.run(
["docker", "compose", "start", "worker"], cwd=ROOT, check=True, capture_output=True
)
print(
"Worker identity revoked and replaced; database credential rotated; worker resumed without image rebuild."
)
if __name__ == "__main__":
main()