Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/nix/host-modules/lib/swarm-controller-tls-issue.nix

73 lines
2.7 KiB
Nix

# The script that issues the swarm-controller's TCP listener leaf from the
# store's `pki` mount, which the pod's init and renewal containers run
# (../k8s/render.nix). The directory is the pod's `emptyDir`, which exists and
# belongs to another user.
#
# Pure function of the evaluated configuration, NOT a NixOS module. `login`
# is the command that prints a store token on stdout, and `credential` names
# what it logs in with (for the error).
{ lib, config }:
let
deployCfg = config.services.hyperhive.deploy;
tcpCfg = config.services.hyperhive.swarm.controller.tcp;
tcpHost = deployCfg.swarm-controller.tcp;
in
{
script =
{
login,
credential,
}:
''
set -euo pipefail
d=${lib.escapeShellArg tcpHost.tlsDir}
name=${lib.escapeShellArg tcpCfg.domain}
# 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 (deployCfg.bao.servicesPkiLeafTtlHours * 3600 / 2)
} >/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 "controller listener leaf valid for $name — leaving it alone"
exit 0
fi
err="$(mktemp)"
resp="$(mktemp "$d/issue.json.XXXXXX")"
trap 'rm -f "$err" "$resp"' EXIT
if ! BAO_TOKEN="$(${login} 2>"$err")"; then
echo "could not log in to the swarm secret store with the controller's ${credential}." >&2
cat "$err" >&2
exit 1
fi
export BAO_TOKEN
echo "requesting the controller's listener leaf for $name from the store"
if ! bao write -format=json \
${lib.escapeShellArg "${deployCfg.bao.servicesPkiMountPath}/issue/${tcpCfg.serverPkiRole}"} \
common_name="$name" > "$resp" 2>"$err"; then
echo "the store refused to issue the controller's listener 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 0640 "$d/key.pem.new" "$d/cert.pem.new"
# Key first: the daemon pairs whatever it reads, and a new key beside
# the old certificate is a pair it refuses and retries.
mv -f "$d/key.pem.new" "$d/key.pem"
mv -f "$d/cert.pem.new" "$d/cert.pem"
'';
}