diff --git a/nix/host-modules/default.nix b/nix/host-modules/default.nix index 9d34cc4d4..7dfa9682f 100644 --- a/nix/host-modules/default.nix +++ b/nix/host-modules/default.nix @@ -76,6 +76,7 @@ ./swarm-bao.nix ./swarm-bao-operator-viewer.nix ./swarm-bao-readers.nix + ./swarm-bao-agent-pki.nix ./swarm-builder.nix ./swarm-claude-login.nix ./swarm-notify-router.nix diff --git a/nix/host-modules/lib/swarm-bao-shared.nix b/nix/host-modules/lib/swarm-bao-shared.nix index 19a0a7f71..f1dd8adcc 100644 --- a/nix/host-modules/lib/swarm-bao-shared.nix +++ b/nix/host-modules/lib/swarm-bao-shared.nix @@ -378,9 +378,99 @@ let } ''; + # OpenBao's start job limit inside the container, and the container's own, + # which is the same plus a margin: the container is `Type=notify`, so its + # start job spans OpenBao's and must outlast it, or the container's limit + # kills a start the unit would still finish. + openbaoStartSec = 240; + containerStartSec = openbaoStartSec + 60; + + # systemd's default stop limit, which bounds the stop half of a restart. + openbaoStopSec = 90; + + # Subject of the root generated into that mount. A label for a human reading + # a chain, not an identity anything authenticates against. Falls through so + # a hive that has set neither a swarm name nor a domain still evaluates. + servicesPkiRootLabel = + if hyperhiveCfg.swarm.name != null then + hyperhiveCfg.swarm.name + else if hyperhiveCfg.domain != null then + hyperhiveCfg.domain + else + "hyperhive"; + + # The PKI mount agent client certificates are issued from. Its root is + # generated inside the store, so the agent CA's key never exists outside it. + # A mount of its own because the services mount holds exactly one issuer; a + # root apart from ../glue-bao-tls.nix's CA because that is what keeps an + # agent's certificate from satisfying any host role. + agentPkiMountPath = baoDeploy.agentPkiMountPath; + agentPkiRoleName = baoDeploy.agentPkiRoleName; + + # The SSH secrets engine mount whose CA signs the agents' user certificates, + # and the one role they sign through, spelled once for this file and + # ../../agent-modules/ssh.nix in ./ssh-agent-ca.nix. + sshAgent = import ./ssh-agent-ca.nix { }; + sshAgentsMountPath = sshAgent.mountPath; + sshAgentRoleName = sshAgent.roleName; + + # The agent CA's certificate, cached on this host by `swarm-bao-agent-pki`, + # so `swarm-bao-certs` can compose the listener's bundle before the store + # is up. Public material. + agentCaCachePath = "${tlsDir}/agent-ca.pem"; + + # What the listener verifies client certificates against: `client-ca.pem` + # first, then the agent CA. A file of its own because every host cert-auth + # role pins `client-ca.pem`: with the agent CA in that file, every leaf the + # controller can request would satisfy every host role. + listenerClientCaPath = "${tlsDir}/listener-client-ca.pem"; + + # Writes `listenerClientCaPath` from `clientCaPath` and, when it parses, the + # cached agent CA. The file is replaced only when its bytes change, so its + # mtime says when the listener's trust last changed; `swarm-bao-agent-pki` + # restarts openbao on exactly that. Refuses, leaving the current file, when + # the result would not begin with `client-ca.pem`: host logins depend on it. + composeListenerBundle = '' + compose_listener_bundle() { + if [ ! -s ${clientCaPath} ]; then + echo "${clientCaPath} is missing or empty; not composing the listener bundle" >&2 + return 1 + fi + local tmp + tmp="$(mktemp -p ${tlsDir} .listener-client-ca.XXXXXX)" + cat ${clientCaPath} > "$tmp" + if [ -s ${agentCaCachePath} ]; then + if openssl x509 -noout -in ${agentCaCachePath} >/dev/null 2>&1; then + printf '\n' >> "$tmp" + cat ${agentCaCachePath} >> "$tmp" + else + echo "${agentCaCachePath} does not parse; the listener will not trust agent certificates" >&2 + fi + fi + if ! cmp -s -n "$(stat -c %s ${clientCaPath})" ${clientCaPath} "$tmp"; then + rm -f "$tmp" + echo "the composed listener bundle does not begin with ${clientCaPath}; leaving the current one" >&2 + return 1 + fi + if cmp -s "$tmp" ${listenerClientCaPath}; then + rm -f "$tmp" + else + chmod 0644 "$tmp" + mv -f "$tmp" ${listenerClientCaPath} + echo "wrote ${listenerClientCaPath}" + fi + } + ''; + + clientCaPath = "${tlsDir}/client-ca.pem"; + + refreshConsumer = import ./refresh-consumer.nix { }; in { inherit + agentCaCachePath + agentPkiMountPath + agentPkiRoleName atticCacheLeaf atticFactLeaves atticJwtLeaf @@ -401,6 +491,9 @@ in classifierAcpKeyLeaf classifierApiKeyLeaf classifierForgeTokenLeaf + clientCaPath + composeListenerBundle + containerStartSec controllerClientLeaf controllerForgeTokenLeaf controllerGrafanaTokenLeaf @@ -422,8 +515,16 @@ in haveServerTls issuerPublicLeaf issuerSeedLeaf + listenerClientCaPath listStanza + openbaoStartSec + openbaoStopSec readStanza + refreshConsumer + servicesPkiRootLabel + sshAgent + sshAgentRoleName + sshAgentsMountPath swarmAppserviceRegistrationLeaf swarmAppserviceTokenLeaf tlsDir diff --git a/nix/host-modules/swarm-bao-agent-pki.nix b/nix/host-modules/swarm-bao-agent-pki.nix new file mode 100644 index 000000000..4cd2fa626 --- /dev/null +++ b/nix/host-modules/swarm-bao-agent-pki.nix @@ -0,0 +1,300 @@ +# 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/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-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 + '' + ); + }; + + }; +} diff --git a/nix/host-modules/swarm-bao.nix b/nix/host-modules/swarm-bao.nix index 9ad05ce64..3307b50e3 100644 --- a/nix/host-modules/swarm-bao.nix +++ b/nix/host-modules/swarm-bao.nix @@ -43,6 +43,8 @@ let shared = import ./lib/swarm-bao-shared.nix { inherit config lib pkgs; }; inherit (shared) + agentPkiMountPath + agentPkiRoleName atticFactLeaves atticJwtLeaf atticPublicKeyLeaf @@ -60,6 +62,8 @@ let classifierAcpKeyLeaf classifierApiKeyLeaf classifierForgeTokenLeaf + composeListenerBundle + containerStartSec controllerClientLeaf controllerForgeTokenLeaf controllerGrafanaTokenLeaf @@ -79,8 +83,13 @@ let haveGranter haveServerTls issuerSeedLeaf + listenerClientCaPath listStanza + openbaoStartSec readStanza + refreshConsumer + servicesPkiRootLabel + sshAgentsMountPath swarmAppserviceRegistrationLeaf swarmAppserviceTokenLeaf tlsDir @@ -99,16 +108,6 @@ let # `nix/module-eval/grafana.nix` pins it against the shipped dashboard file. collectorServiceName = "bao"; - # OpenBao's start job limit inside the container, and the container's own, - # which is the same plus a margin: the container is `Type=notify`, so its - # start job spans OpenBao's and must outlast it, or the container's limit - # kills a start the unit would still finish. - openbaoStartSec = 240; - containerStartSec = openbaoStartSec + 60; - - # systemd's default stop limit, which bounds the stop half of a restart. - openbaoStopSec = 90; - # Upstream's own default, kept so its documentation matches. The raft data # lives INSIDE the container on `ephemeral = false`, the same way # ./swarm-grafana.nix keeps its sqlite database — no sibling service binds @@ -784,17 +783,6 @@ let # its two principals are granted the matching issue paths below. tcpCfg = hyperhiveCfg.swarm.controller.tcp; - # Subject of the root generated into that mount. A label for a human reading - # a chain, not an identity anything authenticates against. Falls through so - # a hive that has set neither a swarm name nor a domain still evaluates. - servicesPkiRootLabel = - if hyperhiveCfg.swarm.name != null then - hyperhiveCfg.swarm.name - else if hyperhiveCfg.domain != null then - hyperhiveCfg.domain - else - "hyperhive"; - # Where the store's host publishes that root's PUBLIC certificate. Its own # directory rather than ./glue-bao-tls.nix's `/var/lib/swarm-bao-pki`: that # one holds the CA key that opens the store, is 0700 for exactly that @@ -946,114 +934,6 @@ let + readStanza "${credentialMountPath}/data/swarm/hives/${obj.hiveName}/archive/*" + listStanza "${credentialMountPath}/metadata/swarm/hives/${obj.hiveName}/archive/"; - # The PKI mount agent client certificates are issued from. Its root is - # generated inside the store, so the agent CA's key never exists outside it. - # A mount of its own because the services mount holds exactly one issuer; a - # root apart from ./glue-bao-tls.nix's CA because that is what keeps an - # agent's certificate from satisfying any host role. - agentPkiMountPath = baoDeploy.agentPkiMountPath; - agentPkiRoleName = baoDeploy.agentPkiRoleName; - - # 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"; - - # The SSH secrets engine mount whose CA signs the agents' user certificates, - # and the one role they sign through, spelled once for this file and - # ../agent-modules/ssh.nix in ./lib/ssh-agent-ca.nix. - sshAgent = import ./lib/ssh-agent-ca.nix { }; - sshAgentsMountPath = sshAgent.mountPath; - sshAgentRoleName = sshAgent.roleName; - - # 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/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"; - }; - - # The agent CA's certificate, cached on this host by `swarm-bao-agent-pki`, - # so `swarm-bao-certs` can compose the listener's bundle before the store - # is up. Public material. - agentCaCachePath = "${tlsDir}/agent-ca.pem"; - - # What the listener verifies client certificates against: `client-ca.pem` - # first, then the agent CA. A file of its own because every host cert-auth - # role pins `client-ca.pem`: with the agent CA in that file, every leaf the - # controller can request would satisfy every host role. - listenerClientCaPath = "${tlsDir}/listener-client-ca.pem"; - - # Writes `listenerClientCaPath` from `clientCaPath` and, when it parses, the - # cached agent CA. The file is replaced only when its bytes change, so its - # mtime says when the listener's trust last changed; `swarm-bao-agent-pki` - # restarts openbao on exactly that. Refuses, leaving the current file, when - # the result would not begin with `client-ca.pem`: host logins depend on it. - composeListenerBundle = '' - compose_listener_bundle() { - if [ ! -s ${clientCaPath} ]; then - echo "${clientCaPath} is missing or empty; not composing the listener bundle" >&2 - return 1 - fi - local tmp - tmp="$(mktemp -p ${tlsDir} .listener-client-ca.XXXXXX)" - cat ${clientCaPath} > "$tmp" - if [ -s ${agentCaCachePath} ]; then - if openssl x509 -noout -in ${agentCaCachePath} >/dev/null 2>&1; then - printf '\n' >> "$tmp" - cat ${agentCaCachePath} >> "$tmp" - else - echo "${agentCaCachePath} does not parse; the listener will not trust agent certificates" >&2 - fi - fi - if ! cmp -s -n "$(stat -c %s ${clientCaPath})" ${clientCaPath} "$tmp"; then - rm -f "$tmp" - echo "the composed listener bundle does not begin with ${clientCaPath}; leaving the current one" >&2 - return 1 - fi - if cmp -s "$tmp" ${listenerClientCaPath}; then - rm -f "$tmp" - else - chmod 0644 "$tmp" - mv -f "$tmp" ${listenerClientCaPath} - echo "wrote ${listenerClientCaPath}" - fi - } - ''; - # Every listener serves the same identity: they differ in which address # they answer on, not in who they are. Client verification is separate and # optional — a store with no `clientCaFile` still serves TLS, it just does @@ -1068,8 +948,6 @@ let tls_require_and_verify_client_cert = true; }; - clientCaPath = "${tlsDir}/client-ca.pem"; - extraListeners = lib.listToAttrs ( lib.imap1 ( i: addr: @@ -1250,7 +1128,6 @@ let forwarderLegacyHostSecretPath = "/var/lib/nixos-containers/${cfg.machine}/var/lib/swarm-bao-otel-oidc/${cfg.otel.clientId}.secret"; atomicWriteSecret = import ./lib/atomic-write-secret.nix { }; - refreshConsumer = import ./lib/refresh-consumer.nix { }; # The collector runs under `DynamicUser` and opens `client_secret_file` # itself, so there is no uid to hand a 0400 file to. `LoadCredential` reads # it as root before the sandbox exists and re-exposes it under a path that @@ -3545,214 +3422,6 @@ in '') hiveLeafIssuers ); - # 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-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 - '' - ); - }; - # The CA bind source is written at runtime by a host unit, so the # container has to start after it — otherwise nspawn sets up a mount # over a file that does not exist yet.