# The script that issues the queue's TLS leaf from the store's `pki` mount, and # the two places that run it: the host's `swarm-bao-nats-tls.service` # (../swarm-nats.nix) and the pod's init container (the same file's `pod`). # One script, so the leaf's checks (name, half-life, the role it is issued # through) cannot differ between them. # # Pure function of the evaluated configuration, NOT a NixOS module. `dir` is # where the leaf lands, `login` the command that prints a store token on # stdout, and `credential` what it logs in with (for the error). `createDir` is # false where the directory exists and belongs to another user, as an # `emptyDir` does in a pod. `preLogin` is shell run before the login, once the # leaf is known to need issuing. { lib, config }: let cfg = config.services.hyperhive.swarm.nats; baoDeploy = config.services.hyperhive.deploy.bao; # Re-issue once the leaf is past half of the 720h `pki/roles/swarm-nats` # grants it (./swarm-bao.nix), so the daily check has two weeks of retries # before it lapses. leafRenewSeconds = 360 * 3600; in { inherit leafRenewSeconds; script = { dir, login, credential, createDir ? true, preLogin ? "", }: lib.removeSuffix "\n" '' set -euo pipefail d=${lib.escapeShellArg dir} name=${lib.escapeShellArg cfg.domain} ${lib.optionalString createDir ''install -d -m 0755 "$d"''} # Missing, past half its window, or naming something other than the # configured domain. reissue=0 { [ -s "$d/cert.pem" ] && [ -s "$d/key.pem" ]; } || reissue=1 openssl x509 -in "$d/cert.pem" -noout -checkend ${toString leafRenewSeconds} >/dev/null 2>&1 || reissue=1 openssl x509 -in "$d/cert.pem" -noout -checkhost "$name" 2>/dev/null | grep -q ' does match ' || reissue=1 if [ "$reissue" = 0 ]; then echo "queue leaf valid for $name — leaving it alone" exit 0 fi ${preLogin} err="$(mktemp)" trap 'rm -f "$err"' EXIT if ! BAO_TOKEN="$(${login} 2>"$err")"; then echo "could not log in to the swarm secret store with the queue's ${credential}." >&2 cat "$err" >&2 exit 1 fi export BAO_TOKEN echo "requesting the queue's TLS leaf for $name from the store" resp="$(mktemp "$d/issue.json.XXXXXX")" trap 'rm -f "$err" "$resp"' EXIT if ! bao write -format=json \ ${lib.escapeShellArg "${baoDeploy.servicesPkiMountPath}/issue/${baoDeploy.natsPkiRoleName}"} \ common_name="$name" > "$resp" 2>"$err"; then echo "the store refused to issue the queue's certificate." >&2 cat "$err" >&2 exit 1 fi jq -r '.data.private_key // empty' < "$resp" > "$d/key.pem.new" jq -r '.data.certificate // empty' < "$resp" > "$d/cert.pem.new" for f in "$d/key.pem.new" "$d/cert.pem.new"; do if [ ! -s "$f" ]; then echo "the store's response was missing a field: $f is empty" >&2 exit 1 fi done chmod 0600 "$d/key.pem.new" chmod 0644 "$d/cert.pem.new" mv -f "$d/key.pem.new" "$d/key.pem" mv -f "$d/cert.pem.new" "$d/cert.pem" ''; }