Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/nix/host-modules/swarm-bao-agent-pki.nix
atlas 9b12532fc1 the log and metrics stores ask every request for a credential the gateway supplies
Each store runs with -httpAuth.* and a credential from the secret store, published to the namespace as a Secret by the host. The gateway's locations send it after auth_request has passed, and the collector's scrape and push take the same one, so a process on the node that bypasses the gateway is refused.
2026-11-28 09:59:25 +01:00

301 lines
13 KiB
Nix

# The store's agent PKI and agent SSH CA, set up by the granter: the PKI mount
# agents' client certificates are issued from, its root, its one role and the
# listener's trust in it, and the SSH CA mount agents get their user
# certificates from. Split out of ./swarm-bao.nix; the unit shape, the mount
# names and the listener bundle it shares with the host module are in
# ./lib/swarm-bao-shared.nix.
{
config,
lib,
pkgs,
...
}:
let
cfg = config.services.hyperhive.swarm.bao;
hyperhiveCfg = config.services.hyperhive;
deployCfg = hyperhiveCfg.deploy;
baoDeploy = deployCfg.bao;
shared = import ./lib/swarm-bao-shared.nix { inherit config lib pkgs; };
inherit (shared)
agentCaCachePath
agentPkiMountPath
agentPkiRoleName
baoCli
clientCaPath
composeListenerBundle
granterAfter
granterEnv
granterLogin
granterPolicyUnit
haveGranter
haveServerTls
listenerClientCaPath
openbaoStartSec
openbaoStopSec
refreshConsumer
servicesPkiRootLabel
sshAgent
sshAgentRoleName
sshAgentsMountPath
tlsDir
;
# Every common name the agent role issues for: `swarm_secret_client`'s
# `policy::AGENT_PREFIX`, which names each agent's cert-auth role too.
# Outside it the role refuses, so the controller cannot obtain
# a certificate for any other name.
agentCnGlob = "hive-agent-*";
# The anchor every agent's cert-auth role pins by value, so it is never
# replaced by a deploy. 262800h like `servicesPkiRootTtl`, and for the same
# reason: the mount is tuned to it before generation, or bao clamps it.
agentPkiRootTtl = "262800h";
# The agent leaf's window, pinned on the role. `swarm-controller` re-issues a
# live agent's leaf once it is past half of it (`agent_renewal.rs`).
agentPkiLeafTtl = "168h";
# What the role pins. `{{identity.entity.name}}` is the name of the entity the
# agent's cert login lands on, which swarm-controller sets to the agent's name
# (`swarm-controller/src/secrets/agent_entity.rs`); with `allowed_users_template` the
# engine checks every requested principal against it, and with
# `default_user_template` an unrequested one defaults to it, so a certificate
# names its holder's own agent and no other. `allowed_user_key_lengths` limits
# the keys it signs to ed25519, whatever the length. The only extension is
# `permit-pty`; `allow_host_certificates = false` keeps the CA from signing a
# host key. A certificate is valid for an hour and never longer than three, and
# `ssh-agent-ca.nix` derives the agent's renewal interval from the hour.
sshAgentRoleBody = builtins.toJSON {
key_type = "ca";
allow_user_certificates = true;
allow_host_certificates = false;
allowed_users = "{{identity.entity.name}}";
allowed_users_template = true;
default_user = "{{identity.entity.name}}";
default_user_template = true;
allow_user_key_ids = false;
allowed_user_key_lengths = {
"ssh-ed25519" = 0;
};
allowed_extensions = "permit-pty";
default_extensions = {
"permit-pty" = "";
};
ttl = "${toString sshAgent.certTtlMinutes}m";
max_ttl = "${toString sshAgent.certMaxTtlMinutes}m";
};
in
{
config = lib.mkIf (deployCfg.bao.enable && haveServerTls) {
# The SSH CA agents get their short-lived user certificates from: the
# mount, the CA key the engine generates inside itself, and the one role
# every agent signs through. The same idempotence as the agent PKI unit
# below, without its restart: nothing here changes what the listener trusts.
systemd.services.swarm-bao-agent-ssh-policy = granterPolicyUnit "set up the swarm SSH CA mount and the role agents sign their user certificates through" ''
mounts="$(bao secrets list -format=json)"
case "$mounts" in
*'"${sshAgentsMountPath}/"'*) ;;
*) bao secrets enable -path=${sshAgentsMountPath} ssh ;;
esac
# Generated once, ever: every target machine trusts this CA's public key
# by value, so a second `config/ca` write would replace the default
# issuer and lock every agent out of every target. There is no replace
# branch. The issuer list is the guard, and `{}` is the only answer that
# means "none".
if issuers="$(bao list -format=json ${lib.escapeShellArg "${sshAgentsMountPath}/issuers"})"; then
echo "the ${sshAgentsMountPath} mount already has a CA — leaving it alone"
elif [ "$issuers" = '{}' ]; then
echo "generating the swarm agent SSH CA into the ${sshAgentsMountPath} mount"
bao write -field=public_key ${lib.escapeShellArg "${sshAgentsMountPath}/config/ca"} \
generate_signing_key=true \
key_type=ssh-ed25519 >/dev/null
else
echo "could not list the ${sshAgentsMountPath} issuers — not generating a CA over one that may exist" >&2
exit 1
fi
# Upserted every run, so a change to the role applies on deploy.
printf '%s' ${lib.escapeShellArg sshAgentRoleBody} |
bao write ${lib.escapeShellArg "${sshAgentsMountPath}/roles/${sshAgentRoleName}"} -
'';
# The agent PKI mount: its root, its one role, the host's copy of the
# root's certificate, and the listener's trust in it.
#
# ⚠️ This unit RESTARTS openbao. openbao reads `tls_client_ca_file` only
# when a listener is built, at start: neither SIGHUP nor a reload re-reads
# it. So when the listener bundle changed after openbao last started,
# openbao is restarted here, which drops every client for the restart and
# the unseal. `swarm-bao-certs` composes the same bundle before every
# later start, so this happens when the agent CA first appears (or is
# replaced by a re-initialised store), not per boot. Under `shamir` a
# restart needs a human unseal, so there it prints the step instead.
#
# `after` the granting units so a restart does not cut their writes off.
systemd.services.swarm-bao-agent-pki = lib.mkIf haveGranter {
description = "set up the swarm agent PKI mount and make the store's listener trust it";
after = [
"container@${cfg.machine}.service"
"swarm-bao-controller-policy.service"
"swarm-bao-secret-publisher-policy.service"
"swarm-bao-matrix-ctl-policy.service"
"swarm-bao-grafana-oidc-policy.service"
"swarm-bao-otel-oidc-policy.service"
"swarm-bao-forwarder-oidc-policy.service"
"swarm-bao-services-issuer-policy.service"
"swarm-bao-nats-tls-policy.service"
"swarm-bao-hive-leaf-policy.service"
"swarm-bao-ci-runner-policy.service"
"swarm-bao-logs-auth-policy.service"
"swarm-bao-metrics-auth-policy.service"
"swarm-bao-store-auth-policy.service"
"swarm-bao-forge-publisher-policy.service"
]
++ granterAfter;
wants = [ "swarm-bao-pki.service" ];
wantedBy = [ "multi-user.target" ];
path = [
baoCli
pkgs.coreutils
pkgs.diffutils
pkgs.openssl
];
environment = granterEnv;
# Same unseal wait as its siblings above.
startLimitBurst = 2880;
startLimitIntervalSec = 90000;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
Restart = "on-failure";
RestartSec = 30;
# An attempt may generate a 4096-bit RSA root and then wait on a
# blocking restart of openbao: its stop (`openbaoStopSec`) and its
# start (`openbaoStartSec`), plus 120s for the key generation and
# the calls around it. 90 + 240 + 120 = 450s.
TimeoutStartSec = "${toString (openbaoStopSec + openbaoStartSec + 120)}s";
};
script = ''
set -euo pipefail
${granterLogin}
# Asked rather than attempted: `secrets enable` errors on a path
# already in use.
mounts="$(bao secrets list -format=json)"
case "$mounts" in
*'"${agentPkiMountPath}/"'*) ;;
*) bao secrets enable -path=${agentPkiMountPath} pki ;;
esac
# Before generation, on every run: an untuned mount silently clamps
# the root to 768h (see the services mount above).
bao secrets tune -max-lease-ttl=${agentPkiRootTtl} ${agentPkiMountPath}
# Generated once, ever. Every agent's cert-auth role pins this root
# by value, so a second one locks every agent out; there is no
# replace branch, and the granter holds no delete on the root. The
# mount's own issuer list is the guard, for the reason the services
# root gives: `{}` is the only answer that means "none".
if issuers="$(bao list -format=json ${lib.escapeShellArg "${agentPkiMountPath}/issuers"})"; then
echo "the ${agentPkiMountPath} mount already has an issuer — leaving it alone"
elif [ "$issuers" = '{}' ]; then
echo "generating the swarm agent CA into the ${agentPkiMountPath} mount"
# `max_path_length=0`: this CA signs leaves only.
bao write -field=issuing_ca ${lib.escapeShellArg "${agentPkiMountPath}/root/generate/internal"} \
common_name=${lib.escapeShellArg "swarm-bao-agent-ca ${servicesPkiRootLabel}"} \
issuer_name=swarm-agent-ca \
ttl=${agentPkiRootTtl} \
max_path_length=0 \
key_type=rsa \
key_bits=4096 >/dev/null
else
echo "could not list the ${agentPkiMountPath} issuers — not generating a root over one that may exist" >&2
exit 1
fi
# Upserted every run. The whole narrowing of what the controller can
# obtain: client certificates, named `hive-agent-*`, nothing else.
# `allow_localhost` and `server_flag` are on by default in bao, so
# they are turned off here, not left out. No `issuer_ref`: the mount
# holds one issuer, which is its default.
bao write ${lib.escapeShellArg "${agentPkiMountPath}/roles/${agentPkiRoleName}"} \
allowed_domains=${lib.escapeShellArg agentCnGlob} \
allow_glob_domains=true \
allow_bare_domains=false \
allow_subdomains=false \
allow_wildcard_certificates=false \
allow_localhost=false \
allow_any_name=false \
allow_ip_sans=false \
enforce_hostnames=true \
server_flag=false \
client_flag=true \
code_signing_flag=false \
email_protection_flag=false \
key_usage=DigitalSignature \
key_type=ec \
key_bits=256 \
ttl=${agentPkiLeafTtl} \
max_ttl=${agentPkiLeafTtl}
ca="$(bao read -field=certificate ${lib.escapeShellArg "${agentPkiMountPath}/cert/ca"})"
if ! openssl x509 -noout <<<"$ca" >/dev/null 2>&1; then
echo "the ${agentPkiMountPath} CA that bao returned does not parse — not caching it" >&2
exit 1
fi
tmp="$(mktemp -p ${tlsDir} .agent-ca.XXXXXX)"
printf '%s\n' "$ca" > "$tmp"
if cmp -s "$tmp" ${agentCaCachePath}; then
rm -f "$tmp"
else
chmod 0644 "$tmp"
mv -f "$tmp" ${agentCaCachePath}
echo "wrote ${agentCaCachePath}"
fi
${refreshConsumer}
${composeListenerBundle}
compose_listener_bundle
machine=${lib.escapeShellArg cfg.machine}
if ! systemctl --machine="$machine" is-active --quiet openbao.service; then
echo "openbao in $machine is not running; it reads ${listenerClientCaPath} when it starts"
exit 0
fi
newer=0
written_after_start openbao.service ${listenerClientCaPath} --machine="$machine" || newer=$?
if [ "$newer" = 1 ]; then
echo "openbao started after ${listenerClientCaPath} last changed; nothing to pick up"
fi
if [ "$newer" != 0 ]; then
exit 0
fi
# Fail closed: host logins go through this file too.
if [ ! -s ${listenerClientCaPath} ] \
|| ! cmp -s -n "$(stat -c %s ${clientCaPath})" ${clientCaPath} ${listenerClientCaPath} \
|| ! openssl x509 -noout -in ${listenerClientCaPath} >/dev/null 2>&1; then
echo "${listenerClientCaPath} is empty, unparseable or does not begin with ${clientCaPath}; not restarting openbao" >&2
exit 1
fi
''
+ (
if baoDeploy.seal == "pkcs11" then
''
echo "${listenerClientCaPath} changed after openbao started; restarting openbao in $machine (it unseals itself)"
systemctl --machine="$machine" restart openbao.service
''
else
''
echo "${listenerClientCaPath} changed after openbao started. A restart seals a ${baoDeploy.seal} store, so it is left to you, as root on this host:" >&2
echo " systemctl --machine=$machine restart openbao.service # then unseal" >&2
''
);
};
};
}