iac/nixos/hosts/asxpio-ops/xmpp-cert-sync.py
Sergei Poljanski 422eb3bc6e
nixos: bucket replica and XMPP certificate sync
s3-replicate is the same rclone sync with the same delete limit, run by
the rclone package instead of its image.

The certificate push keeps its shape: ops reads Traefik's acme.json and
sends each certificate over SSH with a key that may run one command on
services, from ops only. The key is now a sops secret with its public
half in the config, instead of being generated on the host, so a
rebuilt pair works without a manual step. Tried on the rehearsal pair
with a throwaway certificate; any other command is refused.

Assisted-by: Claude:fable-5-2
2026-11-16 23:27:47 +04:00

80 lines
3.3 KiB
Python

# Push the XMPP certificates from Traefik's acme.json to ejabberd on
# asxpio-services whenever they change (xmpp-cert-sync.path), and daily
# as a fallback. The SSH key may only run xmpp-cert-install there.
import base64
import hashlib
import json
import os
import subprocess
import sys
import tempfile
import time
ACME = os.environ.get("XMPP_CERT_ACME", "/var/lib/traefik/acme.json")
CERTS = ["asxp.io", "xmpp.asxp.io"]
TARGET = "root@10.10.0.20"
KEY = os.environ["XMPP_CERT_KEY"]
STATE = "/var/lib/xmpp-cert-sync"
KNOWN = STATE + "/known_hosts"
PROM_DIR = "/var/lib/node_exporter/textfile"
PROM = PROM_DIR + "/xmpp_cert.prom"
def not_after(pem):
with tempfile.NamedTemporaryFile() as t:
t.write(pem)
t.flush()
end = subprocess.run(["openssl", "x509", "-in", t.name, "-noout", "-enddate"],
capture_output=True, text=True, check=True).stdout
end = end.split("=", 1)[1].strip()
return end, subprocess.run(["date", "-d", end, "+%s"], capture_output=True,
text=True, check=True).stdout.strip()
try:
acme = json.load(open(ACME))["letsencrypt"]["Certificates"] or []
except (OSError, KeyError, ValueError):
acme = []
os.makedirs(STATE, exist_ok=True)
expiry, missing = {}, []
for name in CERTS:
entry = next((c for c in acme if c["domain"]["main"] == name), None)
if not entry:
print(f"no certificate for {name} in {ACME} yet")
missing.append(name)
continue
pem = base64.b64decode(entry["certificate"]) + base64.b64decode(entry["key"])
end, expiry[name] = not_after(pem)
digest = hashlib.sha256(pem).hexdigest()
state = os.path.join(STATE, name + ".sha256")
try:
pushed = open(state).read().strip()
except OSError:
pushed = ""
if pushed == digest and "--force" not in sys.argv:
print(f"{name}: ejabberd already has it (valid until {end})")
continue
subprocess.run(["ssh", "-i", KEY, "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes",
"-o", f"UserKnownHostsFile={KNOWN}", "-o", "StrictHostKeyChecking=accept-new",
TARGET, name], input=pem, check=True, timeout=120)
with open(state, "w") as f:
f.write(digest + "\n")
print(f"{name}: pushed (valid until {end})")
if os.path.isdir(PROM_DIR):
lines = ["# HELP xmpp_cert_source_not_after_timestamp_seconds Expiry of each XMPP certificate in Traefik's acme.json.",
"# TYPE xmpp_cert_source_not_after_timestamp_seconds gauge"]
lines += [f'xmpp_cert_source_not_after_timestamp_seconds{{cert="{n}"}} {t}' for n, t in expiry.items()]
if not missing:
lines += ["# HELP xmpp_cert_sync_last_success_timestamp_seconds Last run that left ejabberd with all of Traefik's current certificates.",
"# TYPE xmpp_cert_sync_last_success_timestamp_seconds gauge",
f"xmpp_cert_sync_last_success_timestamp_seconds {int(time.time())}"]
else:
try: # keep the last success, so the stale alert still counts from it
lines += [ln.rstrip("\n") for ln in open(PROM)
if ln.startswith(("# HELP xmpp_cert_sync", "# TYPE xmpp_cert_sync", "xmpp_cert_sync"))]
except OSError:
pass
with open(PROM + ".tmp", "w") as f:
f.write("\n".join(lines) + "\n")
os.replace(PROM + ".tmp", PROM)