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
This commit is contained in:
parent
e95d97869f
commit
422eb3bc6e
8 changed files with 359 additions and 79 deletions
|
|
@ -8,6 +8,7 @@
|
|||
./garage.nix
|
||||
./postgres.nix
|
||||
./traefik.nix
|
||||
./xmpp-cert-sync.nix
|
||||
];
|
||||
|
||||
networking.hostName = lib.mkDefault "asxpio-ops";
|
||||
|
|
|
|||
40
nixos/hosts/asxpio-ops/xmpp-cert-sync.nix
Normal file
40
nixos/hosts/asxpio-ops/xmpp-cert-sync.nix
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
# XMPP certificates come from Traefik here (router xmpp-cert requests
|
||||
# xmpp.asxp.io + conference.; asxp.io is the site's own certificate) and
|
||||
# are pushed to ejabberd on asxpio-services on every renewal.
|
||||
{ config, pkgs, ... }:
|
||||
let
|
||||
sync = pkgs.writers.writePython3 "xmpp-cert-sync" {
|
||||
flakeIgnore = [ "E501" ];
|
||||
} (builtins.readFile ./xmpp-cert-sync.py);
|
||||
in
|
||||
{
|
||||
sops.secrets."xmpp_cert_sync/ssh_key" = { };
|
||||
|
||||
systemd.services.xmpp-cert-sync = {
|
||||
description = "Push the XMPP certificate from Traefik to ejabberd";
|
||||
path = [
|
||||
pkgs.openssh
|
||||
pkgs.openssl
|
||||
pkgs.coreutils
|
||||
];
|
||||
environment.XMPP_CERT_KEY = config.sops.secrets."xmpp_cert_sync/ssh_key".path;
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
ExecStart = sync;
|
||||
StateDirectory = "xmpp-cert-sync";
|
||||
};
|
||||
};
|
||||
systemd.paths.xmpp-cert-sync = {
|
||||
description = "Watch Traefik's acme.json for a renewed XMPP certificate";
|
||||
wantedBy = [ "paths.target" ];
|
||||
pathConfig.PathChanged = "/var/lib/traefik/acme.json";
|
||||
};
|
||||
systemd.timers.xmpp-cert-sync = {
|
||||
description = "Daily XMPP certificate check (fallback for the path unit)";
|
||||
wantedBy = [ "timers.target" ];
|
||||
timerConfig = {
|
||||
OnCalendar = "*-*-* 05:40:00";
|
||||
Persistent = true;
|
||||
};
|
||||
};
|
||||
}
|
||||
80
nixos/hosts/asxpio-ops/xmpp-cert-sync.py
Normal file
80
nixos/hosts/asxpio-ops/xmpp-cert-sync.py
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
# 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)
|
||||
|
|
@ -6,9 +6,11 @@
|
|||
imports = [
|
||||
./acme-forward.nix
|
||||
./minecraft.nix
|
||||
./replica.nix
|
||||
./runner.nix
|
||||
./sillytavern.nix
|
||||
./xmpp.nix
|
||||
./xmpp-cert-install.nix
|
||||
./xray.nix
|
||||
];
|
||||
|
||||
|
|
|
|||
86
nixos/hosts/asxpio-services/replica.nix
Normal file
86
nixos/hosts/asxpio-services/replica.nix
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
# Daily one-way replica of the hel1 buckets into their fsn1 twins.
|
||||
# restic/ is left out: restic writes its own, independent fsn1 repository.
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
let
|
||||
pairs = [
|
||||
{
|
||||
src = "asxpio-backups-main";
|
||||
dst = "asxpio-backups-repl";
|
||||
exclude = [ "restic/**" ];
|
||||
}
|
||||
{
|
||||
src = "asxpio-terraform-main";
|
||||
dst = "asxpio-terraform-repl";
|
||||
}
|
||||
{
|
||||
src = "k8s-asxpio-main";
|
||||
dst = "k8s-asxpio-repl";
|
||||
}
|
||||
];
|
||||
# A run that would delete more than this stops and fails (and mails):
|
||||
# a mistake on the hel1 side must not empty the replica the next morning
|
||||
maxDelete = 1000;
|
||||
textfileDir = "/var/lib/node_exporter/textfile";
|
||||
in
|
||||
{
|
||||
sops.templates."s3-replicate.env".content =
|
||||
let
|
||||
remote = name: region: ''
|
||||
RCLONE_CONFIG_${name}_TYPE=s3
|
||||
RCLONE_CONFIG_${name}_PROVIDER=Other
|
||||
RCLONE_CONFIG_${name}_ENDPOINT=https://${region}.your-objectstorage.com
|
||||
RCLONE_CONFIG_${name}_REGION=${region}
|
||||
RCLONE_CONFIG_${name}_ACCESS_KEY_ID=${config.sops.placeholder."s3/access_key"}
|
||||
RCLONE_CONFIG_${name}_SECRET_ACCESS_KEY=${config.sops.placeholder."s3/secret_key"}
|
||||
'';
|
||||
in
|
||||
remote "HEL1" "hel1"
|
||||
+ remote "FSN1" "fsn1"
|
||||
+ ''
|
||||
RCLONE_CONFIG_FSN1_NO_CHECK_BUCKET=true
|
||||
'';
|
||||
|
||||
systemd.services.s3-replicate = {
|
||||
description = "Replicate the hel1 buckets to fsn1";
|
||||
wants = [ "network-online.target" ];
|
||||
after = [ "network-online.target" ];
|
||||
onFailure = [ "alert-mail@%n.service" ];
|
||||
path = [ pkgs.rclone ];
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
EnvironmentFile = config.sops.templates."s3-replicate.env".path;
|
||||
TimeoutStartSec = "12h";
|
||||
};
|
||||
# One bucket at a time; a failing pair does not stop the others, but
|
||||
# fails the run
|
||||
script = ''
|
||||
failed=0
|
||||
${lib.concatMapStrings (p: ''
|
||||
echo "s3-replicate: ${p.src} -> ${p.dst}"
|
||||
rclone sync hel1:${p.src} fsn1:${p.dst} \
|
||||
--fast-list --checkers 16 --transfers 8 --max-delete ${toString maxDelete} \
|
||||
${lib.concatMapStringsSep " " (e: "--exclude ${lib.escapeShellArg e}") (p.exclude or [ ])} \
|
||||
--stats-one-line -v || failed=1
|
||||
'') pairs}
|
||||
if [ $failed = 0 ] && [ -d ${textfileDir} ]; then
|
||||
f=${textfileDir}/s3_replicate.prom
|
||||
printf '# HELP s3_replicate_last_success_timestamp_seconds Last fully successful hel1 to fsn1 replica.\n# TYPE s3_replicate_last_success_timestamp_seconds gauge\ns3_replicate_last_success_timestamp_seconds %s\n' "$(date +%s)" > "$f.tmp" && mv "$f.tmp" "$f"
|
||||
fi
|
||||
exit $failed
|
||||
'';
|
||||
};
|
||||
systemd.timers.s3-replicate = {
|
||||
description = "Daily hel1 -> fsn1 bucket replica";
|
||||
wantedBy = [ "timers.target" ];
|
||||
timerConfig = {
|
||||
OnCalendar = "*-*-* 06:00:00";
|
||||
RandomizedDelaySec = "15m";
|
||||
Persistent = true;
|
||||
};
|
||||
};
|
||||
}
|
||||
32
nixos/hosts/asxpio-services/xmpp-cert-install.nix
Normal file
32
nixos/hosts/asxpio-services/xmpp-cert-install.nix
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
# Receiving end of xmpp-cert-sync on asxpio-ops (see its file there): the
|
||||
# key below may run exactly one command, from ops only.
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
let
|
||||
install = pkgs.writeShellApplication {
|
||||
name = "xmpp-cert-install";
|
||||
runtimeInputs = [
|
||||
pkgs.coreutils
|
||||
pkgs.openssl
|
||||
pkgs.gnugrep
|
||||
pkgs.util-linux
|
||||
config.virtualisation.podman.package
|
||||
];
|
||||
text = builtins.readFile ./xmpp-cert-install.sh;
|
||||
};
|
||||
in
|
||||
{
|
||||
options.asxpio.xmppCertSyncKey = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAKd1FvOgmxeNCHUJzRQxNA3IBRz59A1VDdsnOwxhybl";
|
||||
description = "Public half of xmpp_cert_sync/ssh_key in the ops secrets.";
|
||||
};
|
||||
|
||||
config.users.users.root.openssh.authorizedKeys.keys = [
|
||||
''restrict,from="10.10.0.10",command="${lib.getExe install}" ${config.asxpio.xmppCertSyncKey} xmpp-cert-sync''
|
||||
];
|
||||
}
|
||||
31
nixos/hosts/asxpio-services/xmpp-cert-install.sh
Normal file
31
nixos/hosts/asxpio-services/xmpp-cert-install.sh
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
# Forced command of the xmpp-cert-sync key from asxpio-ops: read a
|
||||
# certificate chain + key on stdin, check it, install it as
|
||||
# certs/<name>.pem for ejabberd (which picks the matching file per
|
||||
# domain) and reload.
|
||||
set -eu
|
||||
umask 022
|
||||
name=${SSH_ORIGINAL_COMMAND:-}
|
||||
case "$name" in
|
||||
asxp.io|*.asxp.io) ;;
|
||||
*) echo "refusing certificate name '$name'" >&2; exit 1 ;;
|
||||
esac
|
||||
case "$name" in *[!a-z0-9.-]*) echo "bad name" >&2; exit 1 ;; esac
|
||||
dir=/opt/xmpp/state/certs
|
||||
tmp=$(mktemp "$dir/.incoming.XXXXXX")
|
||||
trap 'rm -f "$tmp"' EXIT
|
||||
head -c 65536 > "$tmp"
|
||||
# Valid for at least another day, for this name, with its matching key
|
||||
openssl x509 -in "$tmp" -noout -checkend 86400 >/dev/null
|
||||
openssl x509 -in "$tmp" -noout -checkhost "$name" | grep -q "does match"
|
||||
cert_pub=$(openssl x509 -in "$tmp" -noout -pubkey | sha256sum)
|
||||
key_pub=$(openssl pkey -in "$tmp" -pubout | sha256sum)
|
||||
[ "$cert_pub" = "$key_pub" ] || { echo "key does not match certificate" >&2; exit 1; }
|
||||
chmod 0644 "$tmp"
|
||||
mv "$tmp" "$dir/$name.pem"
|
||||
trap - EXIT
|
||||
# Not running during a restore or on a rehearsal host: ejabberd reads the
|
||||
# file at its next start
|
||||
if podman container exists xmpp-ejabberd; then
|
||||
podman exec xmpp-ejabberd ejabberdctl reload_config
|
||||
fi
|
||||
logger -t xmpp-cert-install "installed $name.pem, $(openssl x509 -in "$dir/$name.pem" -noout -enddate)"
|
||||
|
|
@ -13,6 +13,7 @@
|
|||
systemd.network.networks."10-public".address = lib.mkForce [ "2a01:4f9:c01d:6f9::1/64" ];
|
||||
|
||||
asxpio.publicIPv4 = "2.29.197.9";
|
||||
asxpio.xmppCertSyncKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHXhvaO3Dhkw3QuMUHycoPU12Vx8bKWk2PCFoULvnTAf";
|
||||
|
||||
# A 4 GB server
|
||||
services.minecraft-server.jvmOpts = lib.mkForce "-Xmx2G -Xms1G";
|
||||
|
|
@ -37,6 +38,9 @@
|
|||
autoStart = false;
|
||||
});
|
||||
|
||||
# Dummy keys; and nothing here may write to the production buckets
|
||||
systemd.timers.s3-replicate.enable = false;
|
||||
|
||||
# This runner would take real jobs of another project
|
||||
systemd.services.forgejo-runner-interop.wantedBy = lib.mkForce [ ];
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue