From 0dd05b4308d39877857ec385006226c5a6a03efe Mon Sep 17 00:00:00 2001 From: atlas Date: Sun, 22 Nov 2026 17:31:51 +0100 Subject: [PATCH] nats: runtime k8s runs the queue and its auth callout as one pod --- nix/host-modules/k8s/render.nix | 111 +- nix/host-modules/lib/swarm-nats-raw-rules.nix | 41 + nix/host-modules/lib/swarm-nats-tls-issue.nix | 89 + nix/host-modules/swarm-nats.nix | 2118 ++++++++++------- 4 files changed, 1502 insertions(+), 857 deletions(-) create mode 100644 nix/host-modules/lib/swarm-nats-raw-rules.nix create mode 100644 nix/host-modules/lib/swarm-nats-tls-issue.nix diff --git a/nix/host-modules/k8s/render.nix b/nix/host-modules/k8s/render.nix index e8e1354d0..00617d480 100644 --- a/nix/host-modules/k8s/render.nix +++ b/nix/host-modules/k8s/render.nix @@ -45,6 +45,7 @@ let controllerCfg = deployCfg.swarm-controller; controllerOnCluster = controllerCfg.enable && controllerCfg.runtime == "k8s"; controllerTcp = hyperhiveCfg.swarm.controller.tcp; + natsCfg = deployCfg.nats; servicesRootPath = "${deployCfg.hive-controller.tls.stateDir}/${servicesRootKey}"; caSources = { ${trustBundleKey} = if caTrust.useSelfSigned then caTrust.caHostPath else null; @@ -142,6 +143,13 @@ let # `"own"` and keeps the route its unit names, because the hive collector # stamps the `hive` label on what it forwards and a swarm-level series must # not carry one (../swarm-otel.nix, the swarm tier's own pipeline). + # `daemon` is the unit's binary and systemd name where the service's own name + # differs, `baoRole` the store role the daemon logs in with, and `pod`, where + # a pod holds more than the daemon, a function of the daemon's container + # (its environment, mounts and security context) giving the rest: further + # containers, init containers, volumes, host aliases, pod settings, objects and + # images. An `otlp` of `"none"` is a daemon that pushes no telemetry of its + # own. services = { swarm-controller = { inherit (controllerCfg) enable package unit; @@ -168,6 +176,25 @@ let hostUnit = "swarm-controller.service"; }; }; + # The queue and its auth-callout responder are one pod: the responder is the + # daemon below, and the server (with its exporter) is `pod`'s. + swarm-nats = { + inherit (natsCfg) enable; + inherit (natsCfg) pod; + package = natsCfg.authPackage; + daemon = "swarm-nats-auth"; + baoRole = "swarm-nats-auth"; + unit = natsCfg.unit; + kind = "Deployment"; + healthEnv = "SWARM_NATS_AUTH_HEALTH_ADDR"; + etcFiles = [ ]; + publicCredentials."bao-ca.pem" = baoServerCaKey; + otlp = "none"; + switch = { + inherit (natsCfg) runtime; + hostUnit = "container@swarm-nats.service"; + }; + }; swarm-notify-router = { inherit (deployCfg.notify-router) enable package; unit = deployCfg.notify-router.unit; @@ -264,6 +291,41 @@ let fail = name: msg: throw "services.hyperhive.k8s: ${name}: ${msg}"; + # A unit's `ExecStart` as argv, split as systemd splits it: on spaces, with + # single quotes grouping a word (`lib.escapeShellArg` writes them) and `$$` + # standing for `$`. A pod's arguments are not expanded by a shell. + splitExec = + name: line: + let + quotes = w: lib.length (lib.splitString "'" w) - 1; + step = + st: w: + let + text = if st.open == null then w else "${st.open} ${w}"; + in + if lib.mod (quotes text) 2 == 1 then + st // { open = text; } + else + { + open = null; + words = st.words ++ [ text ]; + }; + split = lib.foldl' step { + open = null; + words = [ ]; + } (lib.filter (w: w != "") (lib.splitString " " line)); + unquote = + w: + if lib.hasInfix "'\\''" w then + fail name "ExecStart has an argument with a single quote in it" + else + builtins.replaceStrings [ "'" "$$" ] [ "" "$" ] w; + in + if split.open != null then + fail name "ExecStart has an unterminated quote" + else + map unquote split.words; + labelsFor = name: { "app.kubernetes.io/name" = name; "app.kubernetes.io/part-of" = "hyperhive"; @@ -349,8 +411,10 @@ let listener = svc.listener or { }; publicFiles = svc.publicFiles or { }; + daemon = svc.daemon or name; + baoRole = svc.baoRole or name; - credDir = "/run/credentials/${name}.service"; + credDir = "/run/credentials/${daemon}.service"; # `LoadCredential` entries are `id:source` on the host and a bare `id` # inside a container. Only the id is rendered. unitCredIds = map (e: lib.head (lib.splitString ":" e)) (lib.toList (sc.LoadCredential or [ ])); @@ -369,7 +433,7 @@ let # logs in with its pod's ServiceAccount token: the pod holds no client # certificate. It reaches the store on the listener that asks for none # (`deploy.bao.podListenerPort`), by the name every reader dials. - baoLogin = lib.elem name baoDeployCfg.k8sPrincipals && unitEnv ? BAO_CLIENT_CERT; + baoLogin = lib.elem baoRole baoDeployCfg.k8sPrincipals && unitEnv ? BAO_CLIENT_CERT; baoClientCredIds = map ( @@ -391,7 +455,7 @@ let BAO_ADDR = "https://${hyperhiveCfg.swarm.bao.domain}:${toString baoDeployCfg.podListenerPort}"; BAO_AUTH = "jwt"; BAO_JWT_FILE = podAuth.tokenFile; - BAO_JWT_ROLE = name; + BAO_JWT_ROLE = baoRole; BAO_JWT_MOUNT = podAuth.mount; }; @@ -443,13 +507,14 @@ let image = mkServiceImage { inherit name; inherit (svc) package; + bin = daemon; extraContents = lib.optional (storeValues != [ ]) ( pkgs.writeTextDir "share/hyperhive/${name}.env-refs" (lib.concatLines storeValues) ); }; - execWords = lib.filter (w: w != "") (lib.splitString " " (toString sc.ExecStart)); - entrypoint = "${svc.package}/bin/${name}"; + execWords = splitExec name (toString sc.ExecStart); + entrypoint = "${svc.package}/bin/${daemon}"; # The credentials that are public CA files come from the CA ConfigMap, the # rest from the service's Secret. A volume holding both is a projected @@ -683,6 +748,23 @@ let package = leafImagePackage; bin = leafIssueBin; }; + # What the service adds to the daemon's pod. + extra = { + containers = [ ]; + initContainers = [ ]; + volumes = [ ]; + hostAliases = [ ]; + podSpec = { }; + objects = { }; + images = [ ]; + } + // lib.optionalAttrs (svc ? pod) ( + svc.pod { + inherit env volumeMounts metaFor; + inherit (container) securityContext; + } + ); + leafContainer = { name = "tls-issue"; image = "${leafImage.imageName}:${leafImage.imageTag}"; @@ -718,7 +800,8 @@ let }; podSpec = { - inherit terminationGracePeriodSeconds volumes; + inherit terminationGracePeriodSeconds; + volumes = volumes ++ extra.volumes; containers = [ container ] @@ -728,7 +811,8 @@ let name = "tls-renew"; command = [ "/bin/${leafRenewBin}" ]; } - ); + ) + ++ extra.containers; # The API token is never mounted; a pod that logs in to the store gets # a token of its own, projected for the store's audience. automountServiceAccountToken = false; @@ -741,7 +825,11 @@ let }; } // lib.optionalAttrs baoLogin { serviceAccountName = name; } - // lib.optionalAttrs (listener != { }) { initContainers = [ leafContainer ]; }; + // lib.optionalAttrs (listener != { } || extra.initContainers != [ ]) { + initContainers = lib.optional (listener != { }) leafContainer ++ extra.initContainers; + } + // lib.optionalAttrs (extra.hostAliases != [ ]) { inherit (extra) hostAliases; } + // extra.podSpec; # What the `-etc` ConfigMap holds. A file mounted from it by `subPath` # never sees a later change, so the pod template carries a hash of the @@ -810,6 +898,7 @@ let objects = { "${name}/${lib.toLower svc.kind}" = main; } + // extra.objects // lib.optionalAttrs baoLogin { # Named after the service: the store's jwt role binds this account. "${name}/serviceaccount" = { @@ -847,8 +936,8 @@ let fail name "the unit already sets ${svc.healthEnv}" else if lib.head execWords != entrypoint then fail name "ExecStart is not ${entrypoint} with plain arguments" - else if lib.any (w: lib.hasInfix "\"" w || lib.hasInfix "'" w) execWords then - fail name "ExecStart has quoted arguments, which the split on spaces would break" + else if lib.any (w: lib.hasInfix "\"" w) execWords then + fail name "ExecStart has double-quoted arguments, which the split on spaces would break" else if unmounted != { } then fail name "the pod mounts nothing at the path ${lib.concatStringsSep ", " (lib.attrNames unmounted)} names" else if missingCreds != { } then @@ -857,7 +946,7 @@ let { inherit objects image; # What the pod's other containers run. - extraImages = lib.optional (listener != { }) leafImage; + extraImages = lib.optional (listener != { }) leafImage ++ extra.images; }; enabled = lib.mapAttrs workload (lib.filterAttrs (_: svc: svc.enable) services); diff --git a/nix/host-modules/lib/swarm-nats-raw-rules.nix b/nix/host-modules/lib/swarm-nats-raw-rules.nix new file mode 100644 index 000000000..ec413675e --- /dev/null +++ b/nix/host-modules/lib/swarm-nats-raw-rules.nix @@ -0,0 +1,41 @@ +# The iptables rules that give the queue pod's `hostPort`s the reach the +# queue's container has. A `hostPort` is a DNAT rule, and what a DNAT rule +# rewrites is forwarded, never delivered to the host: the INPUT rules (the +# firewall's `allowedTCPPorts` and per-interface rules) never see it, and the +# cluster's own forwarding rules accept it. The raw table is read before the +# DNAT and before any of those, so a rule there reads the original +# destination, as INPUT does for the container's listener. +# +# The client port is dropped for a packet addressed to the host unless it +# arrives on one of `trusted` (the host's loopback, the hive bridge and the +# pods' interfaces), or `openClient` is set, which is +# `deploy.nats.openFirewall`. The exporter's port answers with every client's +# name, so it is dropped for all but the host's own loopback. +# +# Pure function — NOT a NixOS module. Returns the text for the firewall's +# `extraCommands`. +{ lib }: +{ + chain, + clientPort, + metricsPort, + trusted, + openClient, +}: +let + rule = "iptables -t raw -A ${chain}"; + local = "-m addrtype --dst-type LOCAL -j DROP"; +in +'' + iptables -t raw -N ${chain} 2>/dev/null || iptables -t raw -F ${chain} + ${rule} -p tcp --dport ${toString metricsPort} -i lo -j RETURN + ${rule} -p tcp --dport ${toString metricsPort} ${local} + ${lib.optionalString (!openClient) '' + ${lib.concatMapStrings (i: '' + ${rule} -p tcp --dport ${toString clientPort} -i ${i} -j RETURN + '') trusted} + ${rule} -p tcp --dport ${toString clientPort} ${local} + ''} + iptables -t raw -D PREROUTING -j ${chain} 2>/dev/null || true + iptables -t raw -I PREROUTING -j ${chain} +'' diff --git a/nix/host-modules/lib/swarm-nats-tls-issue.nix b/nix/host-modules/lib/swarm-nats-tls-issue.nix new file mode 100644 index 000000000..4f761b59a --- /dev/null +++ b/nix/host-modules/lib/swarm-nats-tls-issue.nix @@ -0,0 +1,89 @@ +# 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" + ''; +} diff --git a/nix/host-modules/swarm-nats.nix b/nix/host-modules/swarm-nats.nix index e7b66b49f..1fbfabe1b 100644 --- a/nix/host-modules/swarm-nats.nix +++ b/nix/host-modules/swarm-nats.nix @@ -90,9 +90,7 @@ let # `ExecStart` names a runtime path, so that reference is what keeps the store # file in the closure and stops it being garbage-collected out from under a # running server. - renderedSettings = natsFormat.generate "nats.conf" ( - config.containers.${machine}.config.services.nats.settings - ); + renderedSettings = natsFormat.generate "nats.conf" natsSystem.services.nats.settings; # Defined once, rendered twice: into `settings` with no keys, and into the # runtime fragment with placeholders for the three public keys, filled in @@ -328,10 +326,39 @@ let refreshConsumer = import ./lib/refresh-consumer.nix { }; storeRetry = import ./lib/store-retry.nix { }; - # Re-issue once the leaf is past half of the 720h `pki/roles/swarm-nats` - # grants it (./swarm-bao.nix), so the daily timer below has two weeks of - # retries before it lapses. - leafRenewSeconds = 360 * 3600; + # The script that issues the queue's leaf, which the host unit below and the + # pod's init container both run. + tlsIssue = import ./lib/swarm-nats-tls-issue.nix { inherit lib config; }; + leafScript = tlsIssue.script { + dir = tlsDir; + login = "bao login -method=cert -token-only"; + credential = "certificate"; + preLogin = + if deployCfg.nats.baoClientCertFile == null || deployCfg.nats.baoClientKeyFile == null then + '' + echo "no bao client certificate configured for the queue, so its TLS leaf" >&2 + echo "cannot be requested from the store." >&2 + echo "Set services.hyperhive.deploy.nats.baoClient{Cert,Key}File" >&2 + echo "to a leaf the store's CA signed with CN=${baoDeploy.natsCommonName}." >&2 + echo "They default to the leaf the store mints only where" >&2 + echo "services.hyperhive.deploy.bao.enable is set on this host." >&2 + exit 1'' + else + ""; + }; + + # Where the queue runs: in its container on this host, or as a pod in this + # host's cluster, which ./k8s/render.nix renders from the units below. + onK8s = deployCfg.nats.runtime == "k8s"; + + # The server's monitoring endpoint, which the exporter reads, and the + # collectors it serves. + monitorUrl = "http://127.0.0.1:${toString deployCfg.nats.monitorPort}"; + exporterFlags = [ + "-varz" + "-connz" + "-jsz=all" + ]; # Shared host netns, like every sibling swarm container. # @@ -353,6 +380,689 @@ let rearmResponder = '' systemctl --machine=${lib.escapeShellArg machine} reset-failed swarm-nats-auth.service systemctl --machine=${lib.escapeShellArg machine} start --no-block swarm-nats-auth.service''; + + # The module the queue's container runs: its own NixOS system sharing the host's + # network namespace, or, with the queue in the cluster, only the source of the + # units the pod is rendered from (`deploy.nats.unit`, `deploy.nats.pod`). + containerConfig = + { ... }@container: + { + imports = [ + ../container-modules/swarm-container.nix + ../container-modules/swarm-journal-forwarder.nix + (import ../container-modules/swarm-container-resolver.nix { + inherit (networkCfg) bridgeIp; + # The responder introspects authelia BY NAME on every auth + # request, and a responder that cannot resolve it denies + # every client — so it must not start before the resolver + # file exists. + # + # The forwarder and its secret fetch dial the swarm collector, + # authelia and the store by name too. + dnsConsumers = [ + "swarm-nats-auth.service" + "opentelemetry-collector.service" + "swarm-journal-forwarder-oidc.service" + ]; + }) + caBundleModule + ]; + + services.hyperhive.swarmContainer = { inherit privateNetwork; }; + + # Authenticated as the queue's own OIDC client, whose secret the + # responder's store identity already reads: one identity for the + # whole container. + services.hyperhive.swarmJournalForwarder = { + enable = true; + # The scrape job's name, so the queue's logs and metrics carry one + # `service.name`. + serviceName = "nats"; + endpoint = forwarderEndpoint; + inherit (cfg) clientId; + tokenUrl = "${toString autheliaUrl}/api/oidc/token"; + telemetryPort = deployCfg.nats.otel.telemetryPort; + store = { + package = baoDeploy.package; + addr = "https://${baoCfg.domain}:${toString baoCfg.port}"; + secretPath = "secret/swarm/services/${cfg.clientId}/oidc/client"; + clientCertFile = inContainer "bao-client.pem"; + clientKeyFile = inContainer "bao-client-key.pem"; + caFile = if authStoreFiles ? "bao-ca.pem" then inContainer "bao-ca.pem" else null; + }; + }; + + services.nats = { + enable = true; + + # Retention, so a reader can ask "what did this hive last + # say?" without anyone keeping a second copy. The upstream + # option also wires `settings.jetstream.store_dir = dataDir`; + # the container is `ephemeral = false`, so that survives a + # restart with no bind mount. + # + # ⚠️ Losing the store is not a correctness problem here: a + # reader then sees nothing for every hive, which is the true + # answer until each one publishes again. It degrades to + # honesty rather than to a stale "healthy". + jetstream = true; + + serverName = "swarm-nats"; + port = cfg.port; + # Off. The `tls` block below names a leaf that exists only at + # runtime, and `nats-server -t` loads it, so the build-time check + # fails on every hive; so do the callout keys, empty in + # `settings`. Upstream's own description names the case: disable + # it when the config includes other files. The check moves to + # server start. + validateConfig = false; + + settings = + calloutBlocks { + userKey = ""; + issuerKey = ""; + } + // { + # The most a single publish may be, in bytes, before the + # server answers `-ERR 'Maximum Payload Violation'` and + # closes the connection — not a truncation, a dropped row + # and a reconnect. This queue carries agent terminal rows + # published whole rather than split, so upstream's own + # default is sized to lose one of those rather than merely + # shorten it. Bounded from above by + # `max_pending`: nats-server refuses to start once this + # exceeds it, and widening that ceiling instead costs + # memory per connection, so this stays comfortably under it. + max_payload = 8388608; + + # The monitoring endpoint, which is what the exporter below + # reads. `//` adds a key `calloutBlocks` does not produce + # (`accounts`, `authorization`) — checked, because a shallow + # merge that collided here would drop the auth config while + # rendering a config the server starts on. + # + # ⚠️ Loopback: unauthenticated, and `/connz` lists every + # connected client. + http = "127.0.0.1:${toString deployCfg.nats.monitorPort}"; + + # TLS required on the client port: a server with a `tls` + # block advertises `tls_required` and refuses a client that + # does not upgrade. No `allow_non_tls`, which would keep the + # plaintext path open on the network. The 2s timeout is for + # a handshake that crosses the network; upstream's 0.5s is sized + # for a LAN. + tls = { + cert_file = tlsCertPath; + # The pod has no credential directory: its leaf and key are + # files of one volume. + key_file = if onK8s then tlsKeyPath else tlsKeyCredentialPath; + timeout = 2; + }; + }; + }; + + # The key as the `nats` user can read it; see `tlsDir`. Resolved at + # unit start only, which is why a renewed leaf restarts the server + # rather than reloading it. + systemd.services.nats.serviceConfig.LoadCredential = [ + "${tlsKeyCredential}:${tlsKeyPath}" + ]; + + # The translation layer. NATS has no Prometheus format of its + # own, so this reads the JSON monitoring endpoint above and + # re-serves it in the format the collector scrapes. + # + # Upstream's exporter module rather than a hand-rolled unit, for + # the same reason `services.nats`'s own `settings` is kept: the + # reviewed reasoning about flags and hardening lives there. + services.prometheus.exporters.nats = { + enable = true; + listenAddress = "127.0.0.1"; + port = deployCfg.nats.metricsPort; + url = monitorUrl; + + # ⚠️ NOT optional, despite the name. Upstream renders + # `-addr … -port … ${extraFlags} ${url}` and defaults + # `extraFlags` to the empty list, but the exporter REFUSES TO + # START without at least one collector: it exits 1 with + # "no Collectors specified". Shipped without this the unit logs + # `Started`, the process is gone milliseconds later, and the + # scrape is refused — measured, and invisible to evaluation + # because the empty list renders perfectly. + # + # Which three, and why not more: `varz` is the server itself + # (uptime, memory, slow consumers), `connz` is per-connection so + # a client that will not stay connected is visible, and `jsz` + # covers JetStream, which this swarm relies on for the status + # KV. The remaining collectors describe a clustered deployment + # this swarm does not have. + extraFlags = exporterFlags; + }; + + # A wrapper that includes upstream's rendered settings verbatim + # plus the runtime fragment; rendering the config ourselves + # instead would throw away upstream's `settings`, where the + # reviewed reasoning lives. `renderConfig` writes it at every start, + # because the includes must be siblings of the fragment (see + # `runtimeDir`). + # + # `mkForce`: upstream defines ExecStart inside an `mkMerge`, so a + # plain override conflicts rather than wins. + systemd.services.nats.serviceConfig.ExecStart = + lib.mkForce "${pkgs.nats-server}/bin/nats-server -c ${runtimeWrapper}"; + systemd.services.nats.serviceConfig.ExecStartPre = "+${renderConfig}"; + + # The auth-callout responder: the half that lets the server + # above say *yes*. Without it the `auth_callout` block is a + # door nobody can open, which is the deliberate interim state. + systemd.services.swarm-nats-auth = { + description = "swarm queue auth-callout responder"; + after = [ "nats.service" ]; + requires = [ "nats.service" ]; + # `nats.service` too: a server started late, once its keys arrived, + # brings the responder up with it. + wantedBy = [ + "multi-user.target" + "nats.service" + ]; + serviceConfig = { + ExecStart = lib.concatStringsSep " " [ + "${deployCfg.nats.authPackage}/bin/swarm-nats-auth" + # By name, like every other client: the leaf carries the name + # and no IP, so a loopback address fails verification. The + # container's resolver goes through the bridge, where dnsmasq + # answers it. + "--nats-url tls://${cfg.domain}:${toString cfg.port}" + "--client-id ${lib.escapeShellArg cfg.clientId}" + # The account admitted clients land in, by NAME: in + # server-config mode the server resolves `aud` against its + # own `accounts` block, so this and the block above have to + # be the same string — which is why both come from one let. + "--account ${lib.escapeShellArg clientAccount}" + "--introspection-url ${lib.escapeShellArg introspectionUrl}" + # Each of these names a principal some OTHER module mints, + # so each is read out of that module rather than spelled + # again here — same argument as `--account` above, one + # level wider. The responder denies a client id it does + # not recognise, and a NATS denial arrives as a timeout, + # so a drift here is silent at the point of change and + # misattributed at the point of failure. + "--hive-client-prefix ${lib.escapeShellArg autheliaCfg.hiveClientPrefix}" + "--reader-client ${lib.escapeShellArg controllerCfg.queueClientId}" + # Hears try-outs and answers each by reply, and nothing else. + "--review-classifier-client ${lib.escapeShellArg config.services.hyperhive.swarm.review-classifier.clientId}" + # Hears builds and answers each by reply, and nothing else. + "--builder-client ${lib.escapeShellArg config.services.hyperhive.swarm.builder.clientId}" + # Hears login steps and answers each by reply, and nothing else. + "--claude-login-client ${lib.escapeShellArg config.services.hyperhive.swarm.claude-login.clientId}" + # Drains its consumer on the forge events stream and queues + # agents' todo ops (`swarm-nats-auth`'s `notify_router_permissions`). + "--notify-router-client ${lib.escapeShellArg config.services.hyperhive.swarm.notify-router.clientId}" + # Hears voice memos on every agent's request subject and + # answers each by reply (`swarm-nats-auth`'s `stt_permissions`). + "--stt-client ${lib.escapeShellArg config.services.hyperhive.swarm.stt.clientId}" + # What an agent may publish to, keyed on its own name: its + # terminal rows and its turn-state header + # (`hive-agent::swarm_agent_state`), two subject families so a + # subscriber following one agent's terminal is not also handed + # every header. + # + # `$$`, not `$`: systemd substitutes `$NAME` in `ExecStart` + # whether or not it is quoted, so a single dollar reaches the + # responder as the empty expansion of an unset `SWARM`. + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$SWARM.term.{agent}"}" + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$SWARM.agent-state.{agent}"}" + # Its own key in the `agents-md` KV bucket + # (`swarm_queue_client::agents_md`), on the same terms: the + # harness mirrors its `AGENTS.md` there for the swarm to read. + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$KV.agents-md.{agent}"}" + # Its subagents' terminal rows + # (`swarm_wire::subagent_term`), publish only and no + # `$JS.API.*` subject: swarm-controller creates the + # `term-sub-{agent}` stream that keeps them, so its subjects + # and limits are never the agent's to choose. + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$SWARM.term.{agent}.sub.>"}" + # One key per subagent in the `subagent-status` KV bucket + # (`swarm_wire::subagent_status`): whether it is running. + # The key is `{agent}.`, so `*` is exactly one + # subagent token. As for the icon, a KV put is one publish + # and swarm-controller creates the bucket, so no + # `$$JS.API.*` subject. + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$KV.subagent-status.{agent}.*"}" + # Its own key in the `agent-commands` KV bucket + # (`swarm_wire::agent_commands`): the skills the swarm UI offers + # in its message box. As for the icon, one put and no + # `$$JS.API.*` subject; swarm-controller creates the bucket. + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$KV.agent-commands.{agent}"}" + # Its own key in the `agent-todos` KV bucket + # (`swarm_wire::agent_todos`): the open todos the swarm UI + # shows on its card. One put and no `$$JS.API.*` subject; + # swarm-controller creates the bucket. + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$KV.agent-todos.{agent}"}" + # Its bash tasks (`swarm_wire::bash_task`): one status key per + # task in the `bash-task-status` KV bucket and the task's output + # rows. Publish only and no `$JS.API.*` subject: + # swarm-controller creates the bucket and the + # `term-bash-{agent}` stream, so their limits are never the + # agent's to choose. + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$KV.bash-task-status.{agent}.*"}" + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$SWARM.term.{agent}.bash.>"}" + # Reading its own key of the `agent-schedules` KV bucket + # (`swarm_queue_client::agent_schedules`), and nothing else of + # JetStream: a direct get names the key in its subject, so + # this one subject is one key. No `STREAM.INFO`, no + # `CONSUMER.CREATE` (a watch's create subject carries no key, + # so it would cover every agent's) and no `$KV` write. + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$JS.API.DIRECT.GET.KV_agent-schedules.\$\$KV.agent-schedules.{agent}"}" + # Its own key of the `agent-inference` KV bucket + # (`swarm_wire::agent_inference`), on the same terms. + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$JS.API.DIRECT.GET.KV_agent-inference.\$\$KV.agent-inference.{agent}"}" + # Its own key of the `agent-permissions` KV bucket + # (`swarm_wire::agent_permissions`), on the same terms: + # the harness and the subagent daemon read the tool permissions + # it holds. + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$JS.API.DIRECT.GET.KV_agent-permissions.\$\$KV.agent-permissions.{agent}"}" + # Its own key of the `agents-md-initial` KV bucket + # (`swarm_queue_client::agents_md_initial`), on the same terms: the + # harness reads the text its `AGENTS.md` starts with. + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$JS.API.DIRECT.GET.KV_agents-md-initial.\$\$KV.agents-md-initial.{agent}"}" + # Its own durable consumer on the notification router's + # `ROUTER_TODOS` stream (`swarm_wire::router_todo`): create it + # in the extended form whose last tokens are the filter, which + # the server checks against the payload, so the consumer + # delivers this agent's subject alone; pull from it; ack what + # it delivered. No bare `CONSUMER.CREATE`, no `STREAM.INFO` + # and no publish on the subjects: the router is their writer. + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$JS.API.CONSUMER.CREATE.ROUTER_TODOS.todo-{agent}.\$\$SWARM.router.todo.{agent}"}" + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$JS.API.CONSUMER.MSG.NEXT.ROUTER_TODOS.todo-{agent}"}" + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$JS.ACK.ROUTER_TODOS.todo-{agent}.>"}" + # An agent sends its voice memo on its own request subject + # (`swarm_wire::stt`), publish only; the answer comes back on + # its inbox. + "--agent-token-publish-subject ${lib.escapeShellArg "\$\$SWARM.stt.transcribe.{agent}"}" + # Every agent also reads the operator list, the one key of the + # `operator-profiles` bucket, with one direct get. That grant + # names no agent, so the responder adds it itself + # (`swarm-nats-auth`'s `Policy::agent_token_permissions`). + "--store-cert-role ${lib.escapeShellArg authCertRole}" + ]; + # The store identity arrives by `LoadCredential` and is named + # only as a **path**: `argv` is world-readable via + # /proc//cmdline. Every secret the responder holds beyond + # it, its own OIDC client secret included, it reads from the + # store with that identity. + LoadCredential = lib.mapAttrsToList (id: _: "${id}:${inContainer id}") authStoreFiles; + DynamicUser = true; + # `always`: a clean exit comes back too. The delay grows from + # `RestartSec` to `RestartMaxDelaySec` over `RestartSteps` + # restarts (systemd.service(5)). + Restart = "always"; + RestartSec = "5s"; + RestartSteps = 4; + RestartMaxDelaySec = 60; + SyslogIdentifier = "swarm-nats-auth"; + }; + # No start limit: with one, a burst of starts (the server's, the + # trust bundle's, its own retries) leaves the responder failed and + # the queue refusing every client. A `[Unit]` setting; systemd + # ignores it under `[Service]`. `Restart=` does not revive a stop + # that came from the server failing (`Requires=`), so the host + # starts this unit after it restarts the server. + startLimitIntervalSec = 0; + # Started whenever it is inactive or failed while any unit it + # `Requires=` is active (`Upholds=` on each). A start job that fails + # on a dependency leaves the unit inactive, which `Restart=` never + # sees, so whichever requirement comes up last starts it with all of + # them up. It also undoes a manual `systemctl stop` of the responder, + # or of the server it pulls back in: stop the container instead. + upheldBy = container.config.systemd.services.swarm-nats-auth.requires; + # The store the responder reads the callout keys and agent + # credentials from. + environment = { + BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; + BAO_CLIENT_CERT = authCredential "bao-client.pem"; + BAO_CLIENT_KEY = authCredential "bao-client-key.pem"; + } + // lib.optionalAttrs (authStoreFiles ? "bao-ca.pem") { + BAO_CACERT = authCredential "bao-ca.pem"; + }; + }; + + # The server binary, so an operator with a shell in here can + # run `nats-server -t` against the generated config. The unit + # resolves ExecStart through the store path and puts nothing + # on PATH. + environment.systemPackages = [ pkgs.nats-server ]; + }; + + # The container's system, evaluated as `containers..config` evaluates + # it, for a host whose queue runs in the cluster and so has no such container. + podSystem = + (import "${pkgs.path}/nixos/lib/eval-config.nix" { + modules = [ + ( + { options, ... }: + { + config = { + nixpkgs = + if options.nixpkgs ? hostPlatform then + { inherit (pkgs.stdenv) hostPlatform; } + else + { localSystem = pkgs.stdenv.hostPlatform; }; + boot.isNspawnContainer = true; + networking.hostName = lib.mkDefault machine; + networking.useDHCP = false; + }; + } + ) + containerConfig + ]; + system = null; + }).config; + + # The system the units below are read from: the container's, or the same + # configuration evaluated alone. + natsSystem = if onK8s then podSystem else config.containers.${machine}.config; + + # What the queue's pod holds besides the responder's container + # (../k8s/render.nix gives the responder's own): the server, its exporter and + # the init containers that make the server's files, from the units and + # settings the container runs on the host. + # + # The server starts only once its files exist. The store guard checks the + # JetStream volume, then the leaf is issued and the callout's keys and + # config written, each into a volume of its own that the server reads. + pod = + { + env, + volumeMounts, + securityContext, + metaFor, + ... + }: + let + inherit (import ../images { inherit pkgs lib; }) mkServiceImage; + podAuth = import ./lib/bao-pod-auth.nix; + + tools = [ + baoDeploy.package + pkgs.jq + pkgs.openssl + pkgs.coreutils + pkgs.gnugrep + ]; + bao = + field: role: + "bao write -field=${field} auth/${podAuth.mount}/login role=${role} jwt=@${podAuth.tokenFile}"; + + dataDir = natsSystem.services.nats.settings.jetstream.store_dir; + stateClaim = "${machine}-state"; + + guard = pkgs.writeShellScriptBin "swarm-nats-store-guard" '' + export PATH=${lib.makeBinPath [ pkgs.coreutils ]} + set -eu + store=${lib.escapeShellArg dataDir} + if [ -d "$store/jetstream" ] && [ -n "$(ls -A "$store/jetstream")" ]; then + echo "the JetStream store at $store holds data" + exit 0 + fi + if [ "''${SWARM_NATS_FRESH_STORE:-false}" = true ]; then + echo "the JetStream store at $store is empty and marked fresh: the server starts on it" + exit 0 + fi + echo "empty JetStream store at $store: run \`swarmctl migrate\` first, or set services.hyperhive.deploy.nats.k8s.freshStore for a fresh install" >&2 + exit 1 + ''; + + leaf = pkgs.writeShellScriptBin "swarm-nats-tls-issue" '' + export PATH=${lib.makeBinPath tools} + ${tlsIssue.script { + dir = tlsDir; + login = bao "token" "swarm-nats"; + credential = "ServiceAccount token"; + createDir = false; + }} + ''; + + # The responder's own role creates the keys the store holds none of and + # reads their public halves, as `swarm-bao-nats-callout-xkey` does on the + # host. `renderConfig` is the host's script, which fails while a half is + # missing. + keys = pkgs.writeShellScriptBin "swarm-nats-callout-config" '' + export PATH=${lib.makeBinPath (tools ++ [ deployCfg.nats.authPackage ])} + set -euo pipefail + d=${lib.escapeShellArg runtimeDir} + swarm-nats-auth ensure-callout-keys --store-cert-role ${lib.escapeShellArg authCertRole} + BAO_TOKEN="$(${bao "token" authCertRole})" + export BAO_TOKEN + ${lib.concatMapStrings (k: '' + key="$(bao kv get -field=value ${lib.escapeShellArg k.storePath})" + if [ -z "$key" ]; then + echo "swarm-bao returned an empty ${k.storePath}." >&2 + exit 1 + fi + printf '%s\n' "$key" > "$d/${k.file}.new" + chmod 0444 "$d/${k.file}.new" + mv -f "$d/${k.file}.new" "$d/${k.file}" + '') calloutPublicKeys} + exec ${renderConfig} + ''; + + # The leaf lives 30 days and the server reads it as it starts. This + # runs the issuing script beside the server, which leaves a leaf in the + # first half of its window alone, and tells the server to read a new one: + # `SIGHUP` reloads the TLS files for new connections. + renew = pkgs.writeShellScriptBin "swarm-nats-tls-renew" '' + export PATH=${ + lib.makeBinPath [ + pkgs.coreutils + pkgs.procps + ] + } + while true; do + before="$(sha256sum "${tlsDir}/cert.pem" 2>/dev/null || true)" + if ${leaf}/bin/swarm-nats-tls-issue; then + if [ "$before" != "$(sha256sum "${tlsDir}/cert.pem")" ]; then + echo "the queue's leaf was renewed: the server reloads it" + pkill -HUP -x nats-server + fi + fi + sleep ${toString renewSeconds} + done + ''; + renewSeconds = 300; + + init = mkServiceImage { + name = "${machine}-init"; + package = pkgs.symlinkJoin { + name = "${machine}-init"; + paths = [ + guard + leaf + keys + renew + ]; + }; + bin = "swarm-nats-store-guard"; + }; + + # `renderConfig` links upstream's rendered settings into the config + # volume, so the server's image holds that file. The probe is `wget` and + # nothing else of busybox, the smallest HTTP client the image can hold. + server = mkServiceImage { + name = "${machine}-server"; + package = pkgs.nats-server; + bin = "nats-server"; + extraContents = [ + (pkgs.writeTextDir "share/hyperhive/${machine}-settings.refs" "${renderedSettings}\n") + (pkgs.runCommand "wget-only" { } '' + mkdir -p $out/bin + ln -s ${pkgs.pkgsStatic.busybox}/bin/busybox $out/bin/wget + '') + ]; + }; + exporter = mkServiceImage { + name = "${machine}-exporter"; + package = pkgs.prometheus-nats-exporter; + bin = "prometheus-nats-exporter"; + }; + ref = image: "${image.imageName}:${image.imageTag}"; + + mounts = names: lib.filter (m: lib.elem m.name names) volumeMounts; + volumeNamed = + name: path: readOnly: + { + inherit name; + mountPath = path; + } + // lib.optionalAttrs readOnly { inherit readOnly; }; + # `from` names the generic volumes the container mounts. + fromInit = name: bin: extraEnv: from: extraMounts: { + inherit name securityContext; + image = ref init; + imagePullPolicy = "Never"; + command = [ "/bin/${bin}" ]; + env = lib.mapAttrsToList (n: v: { + name = n; + value = v; + }) extraEnv; + volumeMounts = mounts from ++ extraMounts; + }; + # The volumes a container that logs in to the store mounts. + login = [ + "credentials" + "bao-token" + "tmp" + ]; + storeEnv = lib.filterAttrs (n: _: lib.hasPrefix "BAO_" n) env // { + HOME = "/tmp"; + }; + in + { + volumes = [ + { + name = "nats-tls"; + # In memory: the leaf's key never reaches the node's disk. + emptyDir.medium = "Memory"; + } + { + name = "nats-config"; + emptyDir = { }; + } + { + name = "nats-data"; + persistentVolumeClaim.claimName = stateClaim; + } + ]; + + # The server and the responder dial the queue by its name, which the pod + # answers with its own loopback: the leaf carries the name and no IP. + podSpec.shareProcessNamespace = true; + + hostAliases = [ + { + ip = "127.0.0.1"; + hostnames = [ cfg.domain ]; + } + ]; + + initContainers = [ + (fromInit "store-guard" "swarm-nats-store-guard" { + SWARM_NATS_FRESH_STORE = lib.boolToString deployCfg.nats.k8s.freshStore; + } [ "tmp" ] [ (volumeNamed "nats-data" dataDir true) ]) + (fromInit "tls-issue" "swarm-nats-tls-issue" storeEnv login [ + (volumeNamed "nats-tls" tlsDir false) + ]) + (fromInit "callout-config" "swarm-nats-callout-config" storeEnv login [ + (volumeNamed "nats-config" runtimeDir false) + ]) + ]; + + containers = [ + { + name = "nats"; + image = ref server; + imagePullPolicy = "Never"; + args = lib.tail (lib.splitString " " natsSystem.systemd.services.nats.serviceConfig.ExecStart); + # Every address of the node, which is where the queue listens today. + ports = [ + { + name = "client"; + containerPort = cfg.port; + hostPort = cfg.port; + hostIP = "0.0.0.0"; + } + ]; + # The monitor is on the pod's loopback, so the probe runs in the + # container. A server that has not opened its JetStream store is not + # ready. + readinessProbe = { + exec.command = [ + "/bin/wget" + "-q" + "-O" + "/dev/null" + "http://127.0.0.1:${toString deployCfg.nats.monitorPort}/healthz?js-enabled-only=true" + ]; + periodSeconds = 10; + timeoutSeconds = 5; + }; + volumeMounts = [ + (volumeNamed "nats-tls" tlsDir true) + (volumeNamed "nats-config" runtimeDir true) + (volumeNamed "nats-data" dataDir false) + ] + ++ mounts [ "tmp" ]; + inherit securityContext; + } + # Renews the leaf beside the server, which shares its process namespace + # with it so that it can signal the reload. + (fromInit "tls-renew" "swarm-nats-tls-renew" storeEnv login [ + (volumeNamed "nats-tls" tlsDir false) + ]) + { + name = "exporter"; + image = ref exporter; + imagePullPolicy = "Never"; + args = [ + "-addr" + "0.0.0.0" + "-port" + (toString deployCfg.nats.metricsPort) + ] + ++ exporterFlags + ++ [ monitorUrl ]; + # On the bridge's address, for the host's gateway: the exporter + # answers a request with every client's name, so the host's firewall + # lets only the host's own processes reach it. + ports = [ + { + name = "metrics"; + containerPort = deployCfg.nats.metricsPort; + hostPort = deployCfg.nats.metricsPort; + hostIP = networkCfg.bridgeIp; + } + ]; + inherit securityContext; + } + ]; + + objects."${machine}/persistentvolumeclaim" = { + apiVersion = "v1"; + kind = "PersistentVolumeClaim"; + metadata = metaFor stateClaim; + spec = { + accessModes = [ "ReadWriteOnce" ]; + resources.requests.storage = "10Gi"; + }; + }; + + images = [ + init + server + exporter + ]; + }; in { # The swarm's message queue: one NATS server, reached by every hive at @@ -532,866 +1242,582 @@ in Point `nats.` in the operator's upstream DNS at the address the other hives reach. + + With {option}`services.hyperhive.deploy.nats.runtime` set to `k8s` the + pod's published port has the same reach: a rule in the firewall's raw + table drops it from every interface but the host's loopback, the bridge + and the pods' unless this is set. + ''; + }; + + runtime = lib.mkOption { + type = lib.types.enum [ + "host" + "k8s" + ]; + default = "host"; + description = '' + Where the queue runs: `host` in its `swarm-nats` container, or `k8s` as + a pod in this host's cluster + ({option}`services.hyperhive.deploy.k8s.enable`), which the host's + configuration must enable. One switch covers the server and its auth + callout: the pod holds both, so the server never runs without the + responder that admits its clients. A swarm runs one queue, so a switch + moves it: the container goes and the pod is applied, or the pod is + deleted and the container returns. + + The pod's JetStream store is its own volume, which starts empty, and + the pod refuses to start the server on an empty store unless + {option}`services.hyperhive.deploy.nats.k8s.freshStore` is set. + Nothing here copies the container's store into it. + ''; + }; + + k8s.freshStore = lib.mkOption { + type = lib.types.bool; + default = false; + example = true; + description = '' + With {option}`services.hyperhive.deploy.nats.runtime` set to `k8s`: + let the pod start the server on an empty JetStream store. Off, the pod + stops before the server and says so: an empty store loses every + hive's declared desired state, which nothing regenerates. Set it on a + fresh install, which has none to lose. + ''; + }; + + unit = lib.mkOption { + type = lib.types.raw; + readOnly = true; + internal = true; + default = natsSystem.systemd.services.swarm-nats-auth; + description = '' + The responder's evaluated systemd unit, which the pod's main container + is rendered from (../host-modules/k8s/render.nix). It is the unit the + container runs, taken from the container's configuration, or from the + same configuration evaluated alone when the queue runs in the cluster + and the host has no container. + ''; + }; + + pod = lib.mkOption { + type = lib.types.raw; + readOnly = true; + internal = true; + default = pod; + description = '' + What the queue's pod holds besides the responder: a function of the + responder's container that ../host-modules/k8s/render.nix calls, giving + the server and exporter containers, the init containers, the volumes, + the host aliases and the objects. ''; }; }; - config = lib.mkIf deployCfg.nats.enable { - # The auth responder introspects authelia by name, and the gateway serves - # the exporter's `/metrics` below. - services.hyperhive.gateway.enable = lib.mkDefault true; - services.hyperhive.gateway.dns.enable = lib.mkDefault true; - - # The name every client dials, answered with the bridge IP on this host. - # Other hives resolve it through the operator's DNS, as they do bao's. - services.hyperhive.gateway.localNames = [ cfg.domain ]; - - # The exporter's metrics, for the swarm collector wherever it runs, and - # nothing else on this name: the monitoring endpoint (`/varz`, `/connz`) - # is never proxied, and every other path is 403. - # - # ⚠️ In self-signed mode this vhost serves the queue's own leaf - # (`certificate`; issued for exactly this name, `server_flag` set), not - # the gateway's pick for the name, and the name is not in - # `swarm.serviceDomains`. - # - # `forceSSL` for the reason ./swarm-victorialogs.nix gives: authelia - # answers a plain-http auth subrequest with 400. - services.hyperhive.gateway.vhosts."${cfg.domain}" = { - certificate = lib.mkIf gatewayServesQueueLeaf { - cert = "${gatewayTlsDir}/cert.pem"; - key = "${gatewayTlsDir}/key.pem"; - }; - forceSSL = true; - locations = { - "/".return = "403"; - - # The collector requests exactly this URL, declared as - # `publishedScrapeTargets.nats` in ./swarm-otel-service.nix; the - # two must agree, since that string is also the token's audience. - # Authelia's rules for it admit the collector's client and deny - # every other subject (`metricsRules` in ./swarm-authelia.nix). - "= /metrics" = { - proxyPass = "http://127.0.0.1:${toString deployCfg.nats.metricsPort}/metrics"; - extraConfig = '' - auth_request /__nats_metrics_authz; - ''; - }; - - # The subrequest, same shape as the forge's `= /__forge_metrics_authz` - # (./hive-forge/default.nix): no `error_page 401 =302`, so a scraper - # gets the 401 rather than a login page parsed as metrics. - "= /__nats_metrics_authz" = { - proxyPass = "https://${autheliaCfg.domain}/api/authz/auth-request"; - # nixpkgs appends its OWN `Host $host` after extraConfig, which - # would override verifiedProxyTo's — see hive-gateway/vhost-lib.nix. - recommendedProxySettings = false; - extraConfig = '' - internal; - ${gatewayCfg.lib.verifiedProxyTo autheliaCfg.domain} - proxy_pass_request_body off; - proxy_set_header Content-Length ""; - proxy_set_header X-Original-Method $request_method; - proxy_set_header X-Original-URL $scheme://$http_host$request_uri; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_set_header X-Forwarded-Host $http_host; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - ''; - }; - }; - }; - - # Puts a pair at the paths the vhost above names, before nginx starts: - # nginx refuses a config naming a missing cert file, and that takes the - # whole gateway down rather than this one name. The queue's leaf when it - # exists, else a throwaway self-signed pair until `swarm-bao-nats-tls` - # issues the leaf and starts this again. Never fails on a missing leaf. - systemd.services.swarm-nats-gateway-cert = lib.mkIf gatewayServesQueueLeaf { - description = "Copy the swarm queue's TLS leaf for the gateway's /metrics vhost"; - wantedBy = [ "nginx.service" ]; - before = [ "nginx.service" ]; - path = [ - pkgs.coreutils - pkgs.openssl - pkgs.systemd - ]; - serviceConfig = { - Type = "oneshot"; - UMask = "0077"; - SyslogIdentifier = "swarm-nats-gateway-cert"; - }; - script = '' - set -eu - src=${lib.escapeShellArg tlsDir} - d=${lib.escapeShellArg gatewayTlsDir} - install -d -m 0755 "$d" - if [ -s "$src/cert.pem" ] && [ -s "$src/key.pem" ]; then - cp "$src/cert.pem" "$d/cert.pem.new" - cp "$src/key.pem" "$d/key.pem.new" - elif [ -s "$d/cert.pem" ] && [ -s "$d/key.pem" ]; then - exit 0 - else - echo "no queue leaf yet — serving a throwaway self-signed certificate on ${cfg.domain} until swarm-bao-nats-tls issues one" >&2 - openssl req -x509 -newkey rsa:2048 -nodes -sha256 -days 30 \ - -subj "/CN=${cfg.domain}" -keyout "$d/key.pem.new" -out "$d/cert.pem.new" - fi - chmod 0644 "$d/cert.pem.new" - chgrp nginx "$d/key.pem.new" - chmod 0640 "$d/key.pem.new" - mv -f "$d/key.pem.new" "$d/key.pem" - mv -f "$d/cert.pem.new" "$d/cert.pem" - # `--no-block`: this unit is `Before=nginx.service`, so a blocking - # reload waits on nginx's job queue while nginx's start job waits on - # this unit. `try-` is a no-op while nginx is not running. - systemctl --no-block try-reload-or-restart nginx.service - ''; - }; - - assertions = [ - { - # The callout xkey and the responder's OIDC client secret are read - # from the store under this identity; without either the server or - # the responder does not start. - assertion = authStoreActive; - message = '' - services.hyperhive.deploy.nats.authBaoClientCertFile and - authBaoClientKeyFile must both be set. - - The queue's callout xkey and its responder's OIDC client secret - are read from the swarm's secret store with this certificate, and - neither the server nor the responder starts without them. They - default to the leaf the store mints where - services.hyperhive.deploy.bao.enable is set on this host; - elsewhere, issue a leaf whose CN is - services.hyperhive.deploy.bao.natsAuthCommonName and name it in - both options. - ''; - } - { - # The forwarder's route and the receiver behind it are two - # declarations of one fact; a mismatch is a 404 or a 401 on an export - # that looks healthy. - assertion = (swarmOtelCfg.serviceProducers.${machine}.clientId or null) == cfg.clientId; - message = '' - services.hyperhive.swarm.otel.serviceProducers has no entry - "${machine}" with clientId "${cfg.clientId}", so the swarm - collector has no receiver for the queue container's journal - forwarder. Declare it in swarm-otel-service.nix. - ''; - } - { - assertion = - let - ports = [ - cfg.port - deployCfg.nats.monitorPort - deployCfg.nats.metricsPort - deployCfg.nats.otel.telemetryPort - config.services.hyperhive.otel.telemetryPort - deployCfg.bao.otel.telemetryPort - ]; - in - lib.length (lib.unique ports) == lib.length ports; - message = '' - services.hyperhive.deploy.nats.otel.telemetryPort - (${toString deployCfg.nats.otel.telemetryPort}) collides with another port in - the host netns: the queue's own ports, or the telemetry port of the - hive collector or the store's forwarder. Pick - a free port. - ''; - } - ]; - - # Open the client port on the bridge, so agent containers can reach - # the queue. `privateNetwork = false` below means the server binds in - # the host netns, which is the precondition this option names — but - # sharing a netns is not reachability: the bridge interface is - # default-deny, so without this an agent's connect attempt is dropped - # by the firewall and looks exactly like every other NATS failure, - # a timeout. - # - # ⚠️ The bridge only, unless `openFirewall` opts in. What makes it safe to - # open at all is that the queue is fail-closed: `auth_callout` admits - # nobody until the responder above answers for them, so a client that - # reaches this port still has to present a token authelia vouches for. - # - # An agent reaches it by name, which dnsmasq answers with the bridge IP. - services.hyperhive.network.exposeHostPorts = [ cfg.port ]; - - # The server binds every address (the container shares the host netns and - # sets no listen host), so reachability is the firewall alone. - networking.firewall.allowedTCPPorts = lib.mkIf deployCfg.nats.openFirewall [ cfg.port ]; - - # The bind source has to exist before the container starts, leaf or not: - # nixos-container refuses to start over a missing one, which would take - # the whole queue down rather than only its TLS. - systemd.tmpfiles.rules = [ "d ${tlsDir} 0755 root root -" ]; - - containers.swarm-nats = { - autoStart = true; - ephemeral = false; - # No `--link-journal=host`: the journal stays in the guest, where the - # container's own forwarder reads it (../container-modules/swarm-journal-forwarder.nix). - inherit privateNetwork; - # The public trust bundle (empty when the gateway is not self-signed) - # and the queue's own TLS leaf, both read-only. - bindMounts = caTrust.bindMount // { - ${tlsDir} = { - hostPath = tlsDir; - isReadOnly = true; - }; - }; - config = - { ... }@container: + config = lib.mkMerge [ + { + assertions = [ { - imports = [ - ../container-modules/swarm-container.nix - ../container-modules/swarm-journal-forwarder.nix - (import ../container-modules/swarm-container-resolver.nix { - inherit (networkCfg) bridgeIp; - # The responder introspects authelia BY NAME on every auth - # request, and a responder that cannot resolve it denies - # every client — so it must not start before the resolver - # file exists. - # - # The forwarder and its secret fetch dial the swarm collector, - # authelia and the store by name too. - dnsConsumers = [ - "swarm-nats-auth.service" - "opentelemetry-collector.service" - "swarm-journal-forwarder-oidc.service" - ]; - }) - caBundleModule - ]; + assertion = !onK8s || deployCfg.k8s.enable; + message = '' + services.hyperhive.deploy.nats.runtime = "k8s" needs the cluster: set + services.hyperhive.deploy.k8s.enable on this host, or leave the + queue's runtime at "host". + ''; + } + ]; + } + (lib.mkIf deployCfg.nats.enable { + # The auth responder introspects authelia by name, and the gateway serves + # the exporter's `/metrics` below. + services.hyperhive.gateway.enable = lib.mkDefault true; + services.hyperhive.gateway.dns.enable = lib.mkDefault true; - services.hyperhive.swarmContainer = { inherit privateNetwork; }; + # The name every client dials, answered with the bridge IP on this host. + # Other hives resolve it through the operator's DNS, as they do bao's. + services.hyperhive.gateway.localNames = [ cfg.domain ]; - # Authenticated as the queue's own OIDC client, whose secret the - # responder's store identity already reads: one identity for the - # whole container. - services.hyperhive.swarmJournalForwarder = { - enable = true; - # The scrape job's name, so the queue's logs and metrics carry one - # `service.name`. - serviceName = "nats"; - endpoint = forwarderEndpoint; - inherit (cfg) clientId; - tokenUrl = "${toString autheliaUrl}/api/oidc/token"; - telemetryPort = deployCfg.nats.otel.telemetryPort; - store = { - package = baoDeploy.package; - addr = "https://${baoCfg.domain}:${toString baoCfg.port}"; - secretPath = "secret/swarm/services/${cfg.clientId}/oidc/client"; - clientCertFile = inContainer "bao-client.pem"; - clientKeyFile = inContainer "bao-client-key.pem"; - caFile = if authStoreFiles ? "bao-ca.pem" then inContainer "bao-ca.pem" else null; - }; - }; - - services.nats = { - enable = true; - - # Retention, so a reader can ask "what did this hive last - # say?" without anyone keeping a second copy. The upstream - # option also wires `settings.jetstream.store_dir = dataDir`; - # the container is `ephemeral = false`, so that survives a - # restart with no bind mount. - # - # ⚠️ Losing the store is not a correctness problem here: a - # reader then sees nothing for every hive, which is the true - # answer until each one publishes again. It degrades to - # honesty rather than to a stale "healthy". - jetstream = true; - - serverName = "swarm-nats"; - port = cfg.port; - # Off. The `tls` block below names a leaf that exists only at - # runtime, and `nats-server -t` loads it, so the build-time check - # fails on every hive; so do the callout keys, empty in - # `settings`. Upstream's own description names the case: disable - # it when the config includes other files. The check moves to - # server start. - validateConfig = false; - - settings = - calloutBlocks { - userKey = ""; - issuerKey = ""; - } - // { - # The most a single publish may be, in bytes, before the - # server answers `-ERR 'Maximum Payload Violation'` and - # closes the connection — not a truncation, a dropped row - # and a reconnect. This queue carries agent terminal rows - # published whole rather than split, so upstream's own - # default is sized to lose one of those rather than merely - # shorten it. Bounded from above by - # `max_pending`: nats-server refuses to start once this - # exceeds it, and widening that ceiling instead costs - # memory per connection, so this stays comfortably under it. - max_payload = 8388608; - - # The monitoring endpoint, which is what the exporter below - # reads. `//` adds a key `calloutBlocks` does not produce - # (`accounts`, `authorization`) — checked, because a shallow - # merge that collided here would drop the auth config while - # rendering a config the server starts on. - # - # ⚠️ Loopback: unauthenticated, and `/connz` lists every - # connected client. - http = "127.0.0.1:${toString deployCfg.nats.monitorPort}"; - - # TLS required on the client port: a server with a `tls` - # block advertises `tls_required` and refuses a client that - # does not upgrade. No `allow_non_tls`, which would keep the - # plaintext path open on the network. The 2s timeout is for - # a handshake that crosses the network; upstream's 0.5s is sized - # for a LAN. - tls = { - cert_file = tlsCertPath; - key_file = tlsKeyCredentialPath; - timeout = 2; - }; - }; - }; - - # The key as the `nats` user can read it; see `tlsDir`. Resolved at - # unit start only, which is why a renewed leaf restarts the server - # rather than reloading it. - systemd.services.nats.serviceConfig.LoadCredential = [ - "${tlsKeyCredential}:${tlsKeyPath}" - ]; - - # The translation layer. NATS has no Prometheus format of its - # own, so this reads the JSON monitoring endpoint above and - # re-serves it in the format the collector scrapes. - # - # Upstream's exporter module rather than a hand-rolled unit, for - # the same reason `services.nats`'s own `settings` is kept: the - # reviewed reasoning about flags and hardening lives there. - services.prometheus.exporters.nats = { - enable = true; - listenAddress = "127.0.0.1"; - port = deployCfg.nats.metricsPort; - url = "http://127.0.0.1:${toString deployCfg.nats.monitorPort}"; - - # ⚠️ NOT optional, despite the name. Upstream renders - # `-addr … -port … ${extraFlags} ${url}` and defaults - # `extraFlags` to the empty list, but the exporter REFUSES TO - # START without at least one collector: it exits 1 with - # "no Collectors specified". Shipped without this the unit logs - # `Started`, the process is gone milliseconds later, and the - # scrape is refused — measured, and invisible to evaluation - # because the empty list renders perfectly. - # - # Which three, and why not more: `varz` is the server itself - # (uptime, memory, slow consumers), `connz` is per-connection so - # a client that will not stay connected is visible, and `jsz` - # covers JetStream, which this swarm relies on for the status - # KV. The remaining collectors describe a clustered deployment - # this swarm does not have. - extraFlags = [ - "-varz" - "-connz" - "-jsz=all" - ]; - }; - - # A wrapper that includes upstream's rendered settings verbatim - # plus the runtime fragment; rendering the config ourselves - # instead would throw away upstream's `settings`, where the - # reviewed reasoning lives. `renderConfig` writes it at every start, - # because the includes must be siblings of the fragment (see - # `runtimeDir`). - # - # `mkForce`: upstream defines ExecStart inside an `mkMerge`, so a - # plain override conflicts rather than wins. - systemd.services.nats.serviceConfig.ExecStart = - lib.mkForce "${pkgs.nats-server}/bin/nats-server -c ${runtimeWrapper}"; - systemd.services.nats.serviceConfig.ExecStartPre = "+${renderConfig}"; - - # The auth-callout responder: the half that lets the server - # above say *yes*. Without it the `auth_callout` block is a - # door nobody can open, which is the deliberate interim state. - systemd.services.swarm-nats-auth = { - description = "swarm queue auth-callout responder"; - after = [ "nats.service" ]; - requires = [ "nats.service" ]; - # `nats.service` too: a server started late, once its keys arrived, - # brings the responder up with it. - wantedBy = [ - "multi-user.target" - "nats.service" - ]; - serviceConfig = { - ExecStart = lib.concatStringsSep " " [ - "${deployCfg.nats.authPackage}/bin/swarm-nats-auth" - # By name, like every other client: the leaf carries the name - # and no IP, so a loopback address fails verification. The - # container's resolver goes through the bridge, where dnsmasq - # answers it. - "--nats-url tls://${cfg.domain}:${toString cfg.port}" - "--client-id ${lib.escapeShellArg cfg.clientId}" - # The account admitted clients land in, by NAME: in - # server-config mode the server resolves `aud` against its - # own `accounts` block, so this and the block above have to - # be the same string — which is why both come from one let. - "--account ${lib.escapeShellArg clientAccount}" - "--introspection-url ${lib.escapeShellArg introspectionUrl}" - # Each of these names a principal some OTHER module mints, - # so each is read out of that module rather than spelled - # again here — same argument as `--account` above, one - # level wider. The responder denies a client id it does - # not recognise, and a NATS denial arrives as a timeout, - # so a drift here is silent at the point of change and - # misattributed at the point of failure. - "--hive-client-prefix ${lib.escapeShellArg autheliaCfg.hiveClientPrefix}" - "--reader-client ${lib.escapeShellArg controllerCfg.queueClientId}" - # Hears try-outs and answers each by reply, and nothing else. - "--review-classifier-client ${lib.escapeShellArg config.services.hyperhive.swarm.review-classifier.clientId}" - # Hears builds and answers each by reply, and nothing else. - "--builder-client ${lib.escapeShellArg config.services.hyperhive.swarm.builder.clientId}" - # Hears login steps and answers each by reply, and nothing else. - "--claude-login-client ${lib.escapeShellArg config.services.hyperhive.swarm.claude-login.clientId}" - # Drains its consumer on the forge events stream and queues - # agents' todo ops (`swarm-nats-auth`'s `notify_router_permissions`). - "--notify-router-client ${lib.escapeShellArg config.services.hyperhive.swarm.notify-router.clientId}" - # Hears voice memos on every agent's request subject and - # answers each by reply (`swarm-nats-auth`'s `stt_permissions`). - "--stt-client ${lib.escapeShellArg config.services.hyperhive.swarm.stt.clientId}" - # What an agent may publish to, keyed on its own name: its - # terminal rows and its turn-state header - # (`hive-agent::swarm_agent_state`), two subject families so a - # subscriber following one agent's terminal is not also handed - # every header. - # - # `$$`, not `$`: systemd substitutes `$NAME` in `ExecStart` - # whether or not it is quoted, so a single dollar reaches the - # responder as the empty expansion of an unset `SWARM`. - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$SWARM.term.{agent}"}" - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$SWARM.agent-state.{agent}"}" - # Its own key in the `agents-md` KV bucket - # (`swarm_queue_client::agents_md`), on the same terms: the - # harness mirrors its `AGENTS.md` there for the swarm to read. - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$KV.agents-md.{agent}"}" - # Its subagents' terminal rows - # (`swarm_wire::subagent_term`), publish only and no - # `$JS.API.*` subject: swarm-controller creates the - # `term-sub-{agent}` stream that keeps them, so its subjects - # and limits are never the agent's to choose. - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$SWARM.term.{agent}.sub.>"}" - # One key per subagent in the `subagent-status` KV bucket - # (`swarm_wire::subagent_status`): whether it is running. - # The key is `{agent}.`, so `*` is exactly one - # subagent token. As for the icon, a KV put is one publish - # and swarm-controller creates the bucket, so no - # `$$JS.API.*` subject. - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$KV.subagent-status.{agent}.*"}" - # Its own key in the `agent-commands` KV bucket - # (`swarm_wire::agent_commands`): the skills the swarm UI offers - # in its message box. As for the icon, one put and no - # `$$JS.API.*` subject; swarm-controller creates the bucket. - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$KV.agent-commands.{agent}"}" - # Its own key in the `agent-todos` KV bucket - # (`swarm_wire::agent_todos`): the open todos the swarm UI - # shows on its card. One put and no `$$JS.API.*` subject; - # swarm-controller creates the bucket. - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$KV.agent-todos.{agent}"}" - # Its bash tasks (`swarm_wire::bash_task`): one status key per - # task in the `bash-task-status` KV bucket and the task's output - # rows. Publish only and no `$JS.API.*` subject: - # swarm-controller creates the bucket and the - # `term-bash-{agent}` stream, so their limits are never the - # agent's to choose. - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$KV.bash-task-status.{agent}.*"}" - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$SWARM.term.{agent}.bash.>"}" - # Reading its own key of the `agent-schedules` KV bucket - # (`swarm_queue_client::agent_schedules`), and nothing else of - # JetStream: a direct get names the key in its subject, so - # this one subject is one key. No `STREAM.INFO`, no - # `CONSUMER.CREATE` (a watch's create subject carries no key, - # so it would cover every agent's) and no `$KV` write. - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$JS.API.DIRECT.GET.KV_agent-schedules.\$\$KV.agent-schedules.{agent}"}" - # Its own key of the `agent-inference` KV bucket - # (`swarm_wire::agent_inference`), on the same terms. - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$JS.API.DIRECT.GET.KV_agent-inference.\$\$KV.agent-inference.{agent}"}" - # Its own key of the `agent-permissions` KV bucket - # (`swarm_wire::agent_permissions`), on the same terms: - # the harness and the subagent daemon read the tool permissions - # it holds. - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$JS.API.DIRECT.GET.KV_agent-permissions.\$\$KV.agent-permissions.{agent}"}" - # Its own key of the `agents-md-initial` KV bucket - # (`swarm_queue_client::agents_md_initial`), on the same terms: the - # harness reads the text its `AGENTS.md` starts with. - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$JS.API.DIRECT.GET.KV_agents-md-initial.\$\$KV.agents-md-initial.{agent}"}" - # Its own durable consumer on the notification router's - # `ROUTER_TODOS` stream (`swarm_wire::router_todo`): create it - # in the extended form whose last tokens are the filter, which - # the server checks against the payload, so the consumer - # delivers this agent's subject alone; pull from it; ack what - # it delivered. No bare `CONSUMER.CREATE`, no `STREAM.INFO` - # and no publish on the subjects: the router is their writer. - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$JS.API.CONSUMER.CREATE.ROUTER_TODOS.todo-{agent}.\$\$SWARM.router.todo.{agent}"}" - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$JS.API.CONSUMER.MSG.NEXT.ROUTER_TODOS.todo-{agent}"}" - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$JS.ACK.ROUTER_TODOS.todo-{agent}.>"}" - # An agent sends its voice memo on its own request subject - # (`swarm_wire::stt`), publish only; the answer comes back on - # its inbox. - "--agent-token-publish-subject ${lib.escapeShellArg "\$\$SWARM.stt.transcribe.{agent}"}" - # Every agent also reads the operator list, the one key of the - # `operator-profiles` bucket, with one direct get. That grant - # names no agent, so the responder adds it itself - # (`swarm-nats-auth`'s `Policy::agent_token_permissions`). - "--store-cert-role ${lib.escapeShellArg authCertRole}" - ]; - # The store identity arrives by `LoadCredential` and is named - # only as a **path**: `argv` is world-readable via - # /proc//cmdline. Every secret the responder holds beyond - # it, its own OIDC client secret included, it reads from the - # store with that identity. - LoadCredential = lib.mapAttrsToList (id: _: "${id}:${inContainer id}") authStoreFiles; - DynamicUser = true; - # `always`: a clean exit comes back too. The delay grows from - # `RestartSec` to `RestartMaxDelaySec` over `RestartSteps` - # restarts (systemd.service(5)). - Restart = "always"; - RestartSec = "5s"; - RestartSteps = 4; - RestartMaxDelaySec = 60; - SyslogIdentifier = "swarm-nats-auth"; - }; - # No start limit: with one, a burst of starts (the server's, the - # trust bundle's, its own retries) leaves the responder failed and - # the queue refusing every client. A `[Unit]` setting; systemd - # ignores it under `[Service]`. `Restart=` does not revive a stop - # that came from the server failing (`Requires=`), so the host - # starts this unit after it restarts the server. - startLimitIntervalSec = 0; - # Started whenever it is inactive or failed while any unit it - # `Requires=` is active (`Upholds=` on each). A start job that fails - # on a dependency leaves the unit inactive, which `Restart=` never - # sees, so whichever requirement comes up last starts it with all of - # them up. It also undoes a manual `systemctl stop` of the responder, - # or of the server it pulls back in: stop the container instead. - upheldBy = container.config.systemd.services.swarm-nats-auth.requires; - # The store the responder reads the callout keys and agent - # credentials from. - environment = { - BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; - BAO_CLIENT_CERT = authCredential "bao-client.pem"; - BAO_CLIENT_KEY = authCredential "bao-client-key.pem"; - } - // lib.optionalAttrs (authStoreFiles ? "bao-ca.pem") { - BAO_CACERT = authCredential "bao-ca.pem"; - }; - }; - - # The server binary, so an operator with a shell in here can - # run `nats-server -t` against the generated config. The unit - # resolves ExecStart through the store path and puts nothing - # on PATH. - environment.systemPackages = [ pkgs.nats-server ]; + # The exporter's metrics, for the swarm collector wherever it runs, and + # nothing else on this name: the monitoring endpoint (`/varz`, `/connz`) + # is never proxied, and every other path is 403. + # + # ⚠️ In self-signed mode this vhost serves the queue's own leaf + # (`certificate`; issued for exactly this name, `server_flag` set), not + # the gateway's pick for the name, and the name is not in + # `swarm.serviceDomains`. + # + # `forceSSL` for the reason ./swarm-victorialogs.nix gives: authelia + # answers a plain-http auth subrequest with 400. + services.hyperhive.gateway.vhosts."${cfg.domain}" = { + certificate = lib.mkIf gatewayServesQueueLeaf { + cert = "${gatewayTlsDir}/cert.pem"; + key = "${gatewayTlsDir}/key.pem"; }; - }; + forceSSL = true; + locations = { + "/".return = "403"; - # Order the container after the host CA generator, so the bind source - # exists before nspawn sets the mount up. Without it a late CA fails the - # container start outright rather than degrading. - systemd.services."container@${machine}" = lib.mkMerge [ - caTrust.containerOrdering - (rootfsCheck.warnOnly machine) - ]; + # The collector requests exactly this URL, declared as + # `publishedScrapeTargets.nats` in ./swarm-otel-service.nix; the + # two must agree, since that string is also the token's audience. + # Authelia's rules for it admit the collector's client and deny + # every other subject (`metricsRules` in ./swarm-authelia.nix). + "= /metrics" = { + # In the cluster the exporter is a container of the pod, published on + # the bridge's address. + proxyPass = "http://${ + if onK8s then networkCfg.bridgeIp else "127.0.0.1" + }:${toString deployCfg.nats.metricsPort}/metrics"; + extraConfig = '' + auth_request /__nats_metrics_authz; + ''; + }; - # Deliver the responder's store identity into the container before it - # starts. A copy rather than a `bindMounts` entry: nixos-container refuses - # to start when a bind source is missing, so one absent file would take - # down the **whole container including the queue**, not merely the - # responder. - systemd.services.swarm-nats-auth-secrets = { - description = "deliver the swarm queue responder's credentials"; - before = [ "container@swarm-nats.service" ]; - wantedBy = [ "container@swarm-nats.service" ]; - # Where the store's PKI is minted on this host, the responder's leaf is - # one of its files, and the minting unit runs before every copy. Ordering - # alone is not enough: the queue's container, which pulls this unit in, - # starts from `machines.target`, outside the transaction that runs the - # minting unit from `multi-user.target`. Ignored elsewhere, where the unit - # does not exist. - after = [ "swarm-bao-pki.service" ]; - wants = [ "swarm-bao-pki.service" ]; - serviceConfig = { - Type = "oneshot"; - RemainAfterExit = true; - SyslogIdentifier = "swarm-nats-auth-secrets"; + # The subrequest, same shape as the forge's `= /__forge_metrics_authz` + # (./hive-forge/default.nix): no `error_page 401 =302`, so a scraper + # gets the 401 rather than a login page parsed as metrics. + "= /__nats_metrics_authz" = { + proxyPass = "https://${autheliaCfg.domain}/api/authz/auth-request"; + # nixpkgs appends its OWN `Host $host` after extraConfig, which + # would override verifiedProxyTo's — see hive-gateway/vhost-lib.nix. + recommendedProxySettings = false; + extraConfig = '' + internal; + ${gatewayCfg.lib.verifiedProxyTo autheliaCfg.domain} + proxy_pass_request_body off; + proxy_set_header Content-Length ""; + proxy_set_header X-Original-Method $request_method; + proxy_set_header X-Original-URL $scheme://$http_host$request_uri; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $http_host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + ''; + }; + }; }; - path = [ pkgs.coreutils ]; - script = '' - set -euo pipefail - install -d -m 0700 ${lib.escapeShellArg secretDir} - '' - + lib.concatStrings ( - lib.mapAttrsToList (id: source: '' - install -m 0400 ${lib.escapeShellArg source} ${lib.escapeShellArg (hostPath id)} - '') authStoreFiles + + # Puts a pair at the paths the vhost above names, before nginx starts: + # nginx refuses a config naming a missing cert file, and that takes the + # whole gateway down rather than this one name. The queue's leaf when it + # exists, else a throwaway self-signed pair until `swarm-bao-nats-tls` + # issues the leaf and starts this again. Never fails on a missing leaf. + systemd.services.swarm-nats-gateway-cert = lib.mkIf gatewayServesQueueLeaf { + description = "Copy the swarm queue's TLS leaf for the gateway's /metrics vhost"; + wantedBy = [ "nginx.service" ]; + before = [ "nginx.service" ]; + path = [ + pkgs.coreutils + pkgs.openssl + pkgs.systemd + ]; + serviceConfig = { + Type = "oneshot"; + UMask = "0077"; + SyslogIdentifier = "swarm-nats-gateway-cert"; + }; + script = '' + set -eu + src=${lib.escapeShellArg tlsDir} + d=${lib.escapeShellArg gatewayTlsDir} + install -d -m 0755 "$d" + if [ -s "$src/cert.pem" ] && [ -s "$src/key.pem" ]; then + cp "$src/cert.pem" "$d/cert.pem.new" + cp "$src/key.pem" "$d/key.pem.new" + elif [ -s "$d/cert.pem" ] && [ -s "$d/key.pem" ]; then + exit 0 + else + echo "no queue leaf yet — serving a throwaway self-signed certificate on ${cfg.domain} until swarm-bao-nats-tls issues one" >&2 + openssl req -x509 -newkey rsa:2048 -nodes -sha256 -days 30 \ + -subj "/CN=${cfg.domain}" -keyout "$d/key.pem.new" -out "$d/cert.pem.new" + fi + chmod 0644 "$d/cert.pem.new" + chgrp nginx "$d/key.pem.new" + chmod 0640 "$d/key.pem.new" + mv -f "$d/key.pem.new" "$d/key.pem" + mv -f "$d/cert.pem.new" "$d/cert.pem" + # `--no-block`: this unit is `Before=nginx.service`, so a blocking + # reload waits on nginx's job queue while nginx's start job waits on + # this unit. `try-` is a no-op while nginx is not running. + systemctl --no-block try-reload-or-restart nginx.service + ''; + }; + + assertions = [ + { + # The rules that keep the pod's ports as closed as the container's are + # iptables rules. + assertion = !onK8s || !config.networking.nftables.enable; + message = '' + services.hyperhive.deploy.nats.runtime = "k8s" writes iptables rules + that give the pod's ports the reach the container's have, and + networking.nftables.enable replaces iptables. Leave nftables off on + this host, or leave the queue's runtime at "host". + ''; + } + { + # The callout xkey and the responder's OIDC client secret are read + # from the store under this identity; without either the server or + # the responder does not start. + assertion = authStoreActive; + message = '' + services.hyperhive.deploy.nats.authBaoClientCertFile and + authBaoClientKeyFile must both be set. + + The queue's callout xkey and its responder's OIDC client secret + are read from the swarm's secret store with this certificate, and + neither the server nor the responder starts without them. They + default to the leaf the store mints where + services.hyperhive.deploy.bao.enable is set on this host; + elsewhere, issue a leaf whose CN is + services.hyperhive.deploy.bao.natsAuthCommonName and name it in + both options. + ''; + } + { + # The forwarder's route and the receiver behind it are two + # declarations of one fact; a mismatch is a 404 or a 401 on an export + # that looks healthy. + assertion = (swarmOtelCfg.serviceProducers.${machine}.clientId or null) == cfg.clientId; + message = '' + services.hyperhive.swarm.otel.serviceProducers has no entry + "${machine}" with clientId "${cfg.clientId}", so the swarm + collector has no receiver for the queue container's journal + forwarder. Declare it in swarm-otel-service.nix. + ''; + } + { + assertion = + let + ports = [ + cfg.port + deployCfg.nats.monitorPort + deployCfg.nats.metricsPort + deployCfg.nats.otel.telemetryPort + config.services.hyperhive.otel.telemetryPort + deployCfg.bao.otel.telemetryPort + ]; + in + lib.length (lib.unique ports) == lib.length ports; + message = '' + services.hyperhive.deploy.nats.otel.telemetryPort + (${toString deployCfg.nats.otel.telemetryPort}) collides with another port in + the host netns: the queue's own ports, or the telemetry port of the + hive collector or the store's forwarder. Pick + a free port. + ''; + } + ]; + + # Open the client port on the bridge, so agent containers can reach + # the queue. `privateNetwork = false` below means the server binds in + # the host netns, which is the precondition this option names — but + # sharing a netns is not reachability: the bridge interface is + # default-deny, so without this an agent's connect attempt is dropped + # by the firewall and looks exactly like every other NATS failure, + # a timeout. + # + # ⚠️ The bridge only, unless `openFirewall` opts in. What makes it safe to + # open at all is that the queue is fail-closed: `auth_callout` admits + # nobody until the responder above answers for them, so a client that + # reaches this port still has to present a token authelia vouches for. + # + # An agent reaches it by name, which dnsmasq answers with the bridge IP. + services.hyperhive.network.exposeHostPorts = [ cfg.port ]; + + # The server binds every address (the container shares the host netns and + # sets no listen host), so reachability is the firewall alone. + networking.firewall.allowedTCPPorts = lib.mkIf deployCfg.nats.openFirewall [ cfg.port ]; + + # The pod's `hostPort`s are DNAT rules, which the INPUT rules above never + # see: ./lib/swarm-nats-raw-rules.nix gives them the container's reach. + services.hyperhive.network.enable = lib.mkIf onK8s (lib.mkDefault true); + networking.firewall.extraCommands = lib.mkIf onK8s ( + import ./lib/swarm-nats-raw-rules.nix { inherit lib; } { + chain = "nixos-fw-nats"; + clientPort = cfg.port; + metricsPort = deployCfg.nats.metricsPort; + trusted = [ + "lo" + networkCfg.bridgeName + ] + ++ deployCfg.k8s.cniInterfaces; + openClient = deployCfg.nats.openFirewall; + } ); - }; + networking.firewall.extraStopCommands = lib.mkIf onK8s '' + iptables -t raw -D PREROUTING -j nixos-fw-nats 2>/dev/null || true + iptables -t raw -F nixos-fw-nats 2>/dev/null || true + iptables -t raw -X nixos-fw-nats 2>/dev/null || true + ''; - # The callout's three public keys, from the store into the files - # `renderConfig` reads at every server start. `ensure-callout-keys` first - # creates each pair the store holds none of; it needs no queue, so on a - # first boot the keys exist before the server that requires them, and - # nothing here waits on the responder, which itself waits on the server. - # - # An issuer or user seed file left on this host is what `ensure-callout-keys` - # stores for that key when the store holds none, so the key keeps its - # public half. It removes the file once a read of the store returns a seed, - # in this run and never before: a removal that ran ahead of the import, - # with the store sealed, would leave the next run to mint a new key. - # - # Before the container and wanted by it, the shape `swarm-bao-nats-tls` - # has: a store that comes up later fails this run, the server refuses to - # start without the files (or starts with the ones last fetched), and the - # retry that lands them starts or restarts the server. Under the - # responder's own leaf, the one principal that may create the keys' paths. - systemd.services.swarm-bao-nats-callout-xkey = { - description = "create the swarm queue's callout keys if absent and fetch their public halves for the server"; - # Ordered after the store where it runs here - # (./glue-bao-readers-store-order.nix); elsewhere the timeout below - # bounds the attempt. - before = [ "container@${machine}.service" ]; - wantedBy = [ - "multi-user.target" - "container@${machine}.service" - ]; - path = [ - deployCfg.nats.authPackage - baoDeploy.package - pkgs.coreutils - pkgs.systemd - ]; - inherit (storeRetry) startLimitBurst startLimitIntervalSec; - serviceConfig = storeRetry.serviceConfig // { - Type = "oneshot"; - RemainAfterExit = true; - SyslogIdentifier = "swarm-bao-nats-callout-xkey"; - TimeoutStartSec = 30; + # The bind source has to exist before the container starts, leaf or not: + # nixos-container refuses to start over a missing one, which would take + # the whole queue down rather than only its TLS. + systemd.tmpfiles.rules = [ "d ${tlsDir} 0755 root root -" ]; + + containers.swarm-nats = lib.mkIf (!onK8s) { + autoStart = true; + ephemeral = false; + # No `--link-journal=host`: the journal stays in the guest, where the + # container's own forwarder reads it (../container-modules/swarm-journal-forwarder.nix). + inherit privateNetwork; + # The public trust bundle (empty when the gateway is not self-signed) + # and the queue's own TLS leaf, both read-only. + bindMounts = caTrust.bindMount // { + ${tlsDir} = { + hostPath = tlsDir; + isReadOnly = true; + }; + }; + config = containerConfig; }; - environment = { - BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; - BAO_CLIENT_CERT = deployCfg.nats.authBaoClientCertFile; - BAO_CLIENT_KEY = deployCfg.nats.authBaoClientKeyFile; - } - // lib.optionalAttrs (baoDeploy.serverCaFile != null) { - BAO_CACERT = baoDeploy.serverCaFile; - }; - script = '' - set -euo pipefail - ${atomicWriteSecret} - ${refreshConsumer} + # Order the container after the host CA generator, so the bind source + # exists before nspawn sets the mount up. Without it a late CA fails the + # container start outright rather than degrading. + systemd.services."container@${machine}" = lib.mkIf (!onK8s) ( + lib.mkMerge [ + caTrust.containerOrdering + (rootfsCheck.warnOnly machine) + ] + ); - swarm-nats-auth ensure-callout-keys --store-cert-role ${lib.escapeShellArg authCertRole} \ - --import-issuer-seed-file ${lib.escapeShellArg importIssuerSeed} \ - --import-user-seed-file ${lib.escapeShellArg importUserSeed} - if [ -d ${lib.escapeShellArg importSeedDir} ]; then - rmdir --ignore-fail-on-non-empty ${lib.escapeShellArg importSeedDir} - fi - - err="$(mktemp)" - trap 'rm -f "$err"' EXIT - - if ! BAO_TOKEN="$(bao login -method=cert -token-only 2>"$err")"; then - echo "could not log in to swarm-bao with the queue responder's certificate; leaving the callout key files as they are." >&2 - cat "$err" >&2 - exit 1 - fi - export BAO_TOKEN - - install -d -m 0755 ${lib.escapeShellArg hostRuntimeDir} - '' - + lib.concatMapStrings ( - k: - let - file = "${hostRuntimeDir}/${k.file}"; - in + # Deliver the responder's store identity into the container before it + # starts. A copy rather than a `bindMounts` entry: nixos-container refuses + # to start when a bind source is missing, so one absent file would take + # down the **whole container including the queue**, not merely the + # responder. + systemd.services.swarm-nats-auth-secrets = { + # The pod logs in with its ServiceAccount token and holds no copy of the + # store identity. + enable = !onK8s; + description = "deliver the swarm queue responder's credentials"; + before = [ "container@swarm-nats.service" ]; + wantedBy = [ "container@swarm-nats.service" ]; + # Where the store's PKI is minted on this host, the responder's leaf is + # one of its files, and the minting unit runs before every copy. Ordering + # alone is not enough: the queue's container, which pulls this unit in, + # starts from `machines.target`, outside the transaction that runs the + # minting unit from `multi-user.target`. Ignored elsewhere, where the unit + # does not exist. + after = [ "swarm-bao-pki.service" ]; + wants = [ "swarm-bao-pki.service" ]; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + SyslogIdentifier = "swarm-nats-auth-secrets"; + }; + path = [ pkgs.coreutils ]; + script = '' + set -euo pipefail + install -d -m 0700 ${lib.escapeShellArg secretDir} '' - if ! key="$(bao kv get -field=value ${lib.escapeShellArg k.storePath} 2>"$err")"; then - echo "swarm-bao did not return ${k.storePath}." >&2 + + lib.concatStrings ( + lib.mapAttrsToList (id: source: '' + install -m 0400 ${lib.escapeShellArg source} ${lib.escapeShellArg (hostPath id)} + '') authStoreFiles + ); + }; + + # The callout's three public keys, from the store into the files + # `renderConfig` reads at every server start. `ensure-callout-keys` first + # creates each pair the store holds none of; it needs no queue, so on a + # first boot the keys exist before the server that requires them, and + # nothing here waits on the responder, which itself waits on the server. + # + # An issuer or user seed file left on this host is what `ensure-callout-keys` + # stores for that key when the store holds none, so the key keeps its + # public half. It removes the file once a read of the store returns a seed, + # in this run and never before: a removal that ran ahead of the import, + # with the store sealed, would leave the next run to mint a new key. + # + # Before the container and wanted by it, the shape `swarm-bao-nats-tls` + # has: a store that comes up later fails this run, the server refuses to + # start without the files (or starts with the ones last fetched), and the + # retry that lands them starts or restarts the server. Under the + # responder's own leaf, the one principal that may create the keys' paths. + systemd.services.swarm-bao-nats-callout-xkey = { + # The pod's init container creates the keys and fetches their public + # halves itself. + enable = !onK8s; + description = "create the swarm queue's callout keys if absent and fetch their public halves for the server"; + # Ordered after the store where it runs here + # (./glue-bao-readers-store-order.nix); elsewhere the timeout below + # bounds the attempt. + before = [ "container@${machine}.service" ]; + wantedBy = [ + "multi-user.target" + "container@${machine}.service" + ]; + path = [ + deployCfg.nats.authPackage + baoDeploy.package + pkgs.coreutils + pkgs.systemd + ]; + inherit (storeRetry) startLimitBurst startLimitIntervalSec; + serviceConfig = storeRetry.serviceConfig // { + Type = "oneshot"; + RemainAfterExit = true; + SyslogIdentifier = "swarm-bao-nats-callout-xkey"; + TimeoutStartSec = 30; + }; + environment = { + BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; + BAO_CLIENT_CERT = deployCfg.nats.authBaoClientCertFile; + BAO_CLIENT_KEY = deployCfg.nats.authBaoClientKeyFile; + } + // lib.optionalAttrs (baoDeploy.serverCaFile != null) { + BAO_CACERT = baoDeploy.serverCaFile; + }; + script = '' + set -euo pipefail + + ${atomicWriteSecret} + ${refreshConsumer} + + swarm-nats-auth ensure-callout-keys --store-cert-role ${lib.escapeShellArg authCertRole} \ + --import-issuer-seed-file ${lib.escapeShellArg importIssuerSeed} \ + --import-user-seed-file ${lib.escapeShellArg importUserSeed} + if [ -d ${lib.escapeShellArg importSeedDir} ]; then + rmdir --ignore-fail-on-non-empty ${lib.escapeShellArg importSeedDir} + fi + + err="$(mktemp)" + trap 'rm -f "$err"' EXIT + + if ! BAO_TOKEN="$(bao login -method=cert -token-only 2>"$err")"; then + echo "could not log in to swarm-bao with the queue responder's certificate; leaving the callout key files as they are." >&2 cat "$err" >&2 exit 1 fi - if [ -z "$key" ]; then - echo "swarm-bao returned an empty ${k.storePath}." >&2 - exit 1 - fi - if secret_differs ${lib.escapeShellArg file} "$key"; then - atomic_write_secret 0444 "" ${lib.escapeShellArg file} "$key" - fi + export BAO_TOKEN + + install -d -m 0755 ${lib.escapeShellArg hostRuntimeDir} '' - ) calloutPublicKeys - # `renderConfig` reads the files as the server starts, and only then. - + lib.concatMapStrings (k: '' - refresh_consumer ${lib.escapeShellArg machine} nats.service ${lib.escapeShellArg "${hostRuntimeDir}/${k.file}"} - '') calloutPublicKeys - + '' - if systemctl is-active --quiet ${lib.escapeShellArg "container@${machine}.service"}; then - ${rearmResponder} - fi - ''; - }; - - # The queue's TLS leaf, issued by the secret store's `pki/roles/swarm-nats` - # under this host's `swarm-nats` identity. Same shape as ./hive-tls.nix's - # `swarm-services-cert`, whose comments carry the reasoning for the login, - # the single `issue` call split with `jq`, and the unseal-sized retry. - # - # Before the container, so a normal boot starts the server with its leaf. - # A store that comes up later fails this run; the retry lands the leaf and - # restarts the server, which until then refuses to start (TLS required, - # and its key credential is missing). - systemd.services.swarm-bao-nats-tls = { - description = "Issue the swarm queue's TLS leaf from the secret store's PKI"; - wantedBy = [ - "multi-user.target" - "container@${machine}.service" - ]; - before = [ "container@${machine}.service" ]; - # Both absent where the store runs elsewhere, and ignored there; see - # `swarm-services-cert`. The ordering after this leaf's policy unit is - # ./glue-bao-readers-policy-order.nix's, because it holds only where the - # store is here too. - after = [ - "container@${baoCfg.machine}.service" - "swarm-bao-pki.service" - ]; - path = [ - baoDeploy.package - pkgs.jq - pkgs.openssl - pkgs.coreutils - pkgs.gnugrep - pkgs.systemd - ]; - startLimitBurst = 2880; - startLimitIntervalSec = 90000; - # No `RemainAfterExit`: the timer below starts this again, and starting - # an active unit is a no-op. - serviceConfig = { - Type = "oneshot"; - UMask = "0077"; - SyslogIdentifier = "swarm-bao-nats-tls"; - Restart = "on-failure"; - RestartSec = 30; - # An attempt that rotates the leaf waits on a blocking restart of the - # server in its container: up to 150s to stop (nixpkgs' nats module) - # and 90s to start. - TimeoutStartSec = "5min"; - }; - environment = { - BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; - } - // lib.optionalAttrs (deployCfg.nats.baoClientCertFile != null) { - BAO_CLIENT_CERT = deployCfg.nats.baoClientCertFile; - } - // lib.optionalAttrs (deployCfg.nats.baoClientKeyFile != null) { - BAO_CLIENT_KEY = deployCfg.nats.baoClientKeyFile; - } - // lib.optionalAttrs (baoDeploy.serverCaFile != null) { - BAO_CACERT = baoDeploy.serverCaFile; - }; - script = '' - set -euo pipefail - d=${lib.escapeShellArg tlsDir} - name=${lib.escapeShellArg cfg.domain} - 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 - - ${ - if deployCfg.nats.baoClientCertFile == null || deployCfg.nats.baoClientKeyFile == null then - '' - echo "no bao client certificate configured for the queue, so its TLS leaf" >&2 - echo "cannot be requested from the store." >&2 - echo "Set services.hyperhive.deploy.nats.baoClient{Cert,Key}File" >&2 - echo "to a leaf the store's CA signed with CN=${baoDeploy.natsCommonName}." >&2 - echo "They default to the leaf the store mints only where" >&2 - echo "services.hyperhive.deploy.bao.enable is set on this host." >&2 - exit 1'' - else - "" - } - - err="$(mktemp)" - trap 'rm -f "$err"' EXIT - - if ! BAO_TOKEN="$(bao login -method=cert -token-only 2>"$err")"; then - echo "could not log in to the swarm secret store with the queue's certificate." >&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 + + lib.concatMapStrings ( + k: + let + file = "${hostRuntimeDir}/${k.file}"; + in + '' + if ! key="$(bao kv get -field=value ${lib.escapeShellArg k.storePath} 2>"$err")"; then + echo "swarm-bao did not return ${k.storePath}." >&2 + cat "$err" >&2 + exit 1 + fi + if [ -z "$key" ]; then + echo "swarm-bao returned an empty ${k.storePath}." >&2 + exit 1 + fi + if secret_differs ${lib.escapeShellArg file} "$key"; then + atomic_write_secret 0444 "" ${lib.escapeShellArg file} "$key" + fi + '' + ) calloutPublicKeys + # `renderConfig` reads the files as the server starts, and only then. + + lib.concatMapStrings (k: '' + refresh_consumer ${lib.escapeShellArg machine} nats.service ${lib.escapeShellArg "${hostRuntimeDir}/${k.file}"} + '') calloutPublicKeys + + '' + if systemctl is-active --quiet ${lib.escapeShellArg "container@${machine}.service"}; then + ${rearmResponder} 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" - ${lib.optionalString gatewayServesQueueLeaf '' - - # The gateway's `/metrics` vhost serves a copy of this leaf. - systemctl start swarm-nats-gateway-cert.service''} - - # Renewal, or the late-store retry. On a normal boot the container is - # not up yet and starts the server with this leaf itself. A restart, - # not a reload: the key arrives by `LoadCredential`, which systemd - # resolves at start only. `reset-failed` because a server that found - # no key may have hit its start limit. - if systemctl is-active --quiet ${lib.escapeShellArg "container@${machine}.service"}; then - echo "queue leaf rotated — restarting the server in ${machine}" - systemctl --machine=${lib.escapeShellArg machine} reset-failed nats.service - systemctl --machine=${lib.escapeShellArg machine} restart nats.service - ${rearmResponder} - fi - ''; - }; - - systemd.timers.swarm-bao-nats-tls = { - description = "Daily renewal check for the swarm queue's TLS leaf"; - wantedBy = [ "timers.target" ]; - timerConfig = { - OnCalendar = "daily"; - Persistent = true; + ''; }; - }; - }; + + # The queue's TLS leaf, issued by the secret store's `pki/roles/swarm-nats` + # under this host's `swarm-nats` identity. Same shape as ./hive-tls.nix's + # `swarm-services-cert`, whose comments carry the reasoning for the login, + # the single `issue` call split with `jq`, and the unseal-sized retry. + # + # Before the container, so a normal boot starts the server with its leaf. + # A store that comes up later fails this run; the retry lands the leaf and + # restarts the server, which until then refuses to start (TLS required, + # and its key credential is missing). + # + # With the queue in the cluster this leaf is the gateway's `/metrics` vhost + # alone: the pod issues the one its server presents, and nothing here + # restarts a server. + systemd.services.swarm-bao-nats-tls = { + description = "Issue the swarm queue's TLS leaf from the secret store's PKI"; + wantedBy = [ + "multi-user.target" + ] + ++ lib.optional (!onK8s) "container@${machine}.service"; + before = lib.optional (!onK8s) "container@${machine}.service"; + # Both absent where the store runs elsewhere, and ignored there; see + # `swarm-services-cert`. The ordering after this leaf's policy unit is + # ./glue-bao-readers-policy-order.nix's, because it holds only where the + # store is here too. + after = [ + "container@${baoCfg.machine}.service" + "swarm-bao-pki.service" + ]; + path = [ + baoDeploy.package + pkgs.jq + pkgs.openssl + pkgs.coreutils + pkgs.gnugrep + pkgs.systemd + ]; + startLimitBurst = 2880; + startLimitIntervalSec = 90000; + # No `RemainAfterExit`: the timer below starts this again, and starting + # an active unit is a no-op. + serviceConfig = { + Type = "oneshot"; + UMask = "0077"; + SyslogIdentifier = "swarm-bao-nats-tls"; + Restart = "on-failure"; + RestartSec = 30; + # An attempt that rotates the leaf waits on a blocking restart of the + # server in its container: up to 150s to stop (nixpkgs' nats module) + # and 90s to start. + TimeoutStartSec = "5min"; + }; + environment = { + BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; + } + // lib.optionalAttrs (deployCfg.nats.baoClientCertFile != null) { + BAO_CLIENT_CERT = deployCfg.nats.baoClientCertFile; + } + // lib.optionalAttrs (deployCfg.nats.baoClientKeyFile != null) { + BAO_CLIENT_KEY = deployCfg.nats.baoClientKeyFile; + } + // lib.optionalAttrs (baoDeploy.serverCaFile != null) { + BAO_CACERT = baoDeploy.serverCaFile; + }; + script = '' + ${leafScript} + ${lib.optionalString gatewayServesQueueLeaf '' + + # The gateway's `/metrics` vhost serves a copy of this leaf. + systemctl start swarm-nats-gateway-cert.service''} + + # Renewal, or the late-store retry. On a normal boot the container is + # not up yet and starts the server with this leaf itself. A restart, + # not a reload: the key arrives by `LoadCredential`, which systemd + # resolves at start only. `reset-failed` because a server that found + # no key may have hit its start limit. + if systemctl is-active --quiet ${lib.escapeShellArg "container@${machine}.service"}; then + echo "queue leaf rotated — restarting the server in ${machine}" + systemctl --machine=${lib.escapeShellArg machine} reset-failed nats.service + systemctl --machine=${lib.escapeShellArg machine} restart nats.service + ${rearmResponder} + fi + ''; + }; + + systemd.timers.swarm-bao-nats-tls = { + description = "Daily renewal check for the swarm queue's TLS leaf"; + wantedBy = [ "timers.target" ]; + timerConfig = { + OnCalendar = "daily"; + Persistent = true; + }; + }; + }) + ]; }