# 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)