Watch
0
0
Fork
You've already forked hyperhive
0

nats: runtime k8s runs the queue and its auth callout as one pod

This commit is contained in:
atlas 2026-11-22 17:31:51 +01:00 • committed by maia
commit dd7de4d1e1
4 changed files with 1487 additions and 842 deletions

View file

@ -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);

View file

@ -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}
''

View file

@ -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"
'';
}

File diff suppressed because it is too large Load diff