Watch
0
0
Fork
You've already forked hyperhive
0

k8s: pods log in to the secret store with their ServiceAccount token

The store gets a listener for the pods that asks for no client certificate,
open on the pod network's interfaces only, and a jwt auth mount with one
role per in-cluster service. The rendered pods run under a ServiceAccount
with a projected token in place of their client certificate.
This commit is contained in:
atlas 2026-11-21 14:03:28 +01:00 • committed by maia
commit 7fff98687c
7 changed files with 720 additions and 69 deletions

View file

@ -34,6 +34,12 @@ path "sys/auth/oidc" {
capabilities = ["create", "update", "sudo"]
}
# The pods' login with a ServiceAccount token. Enabled only on a host that runs
# the cluster node; the stanza costs nothing elsewhere.
path "sys/auth/jwt-k8s" {
capabilities = ["create", "update", "sudo"]
}
# The granter's own policy and role, and nothing it may write.
path "sys/policies/acl/bao-granter" {
capabilities = ["create", "update"]

View file

@ -41,6 +41,11 @@ let
builtins.bitAnd pa.base keep == builtins.bitAnd pb.base keep;
cidrType = lib.types.strMatching "([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}";
# k3s's own defaults, named so the flags below and the ServiceAccount
# issuer and key paths read from one place.
dataDir = "/var/lib/rancher/k3s";
clusterDomain = "cluster.local";
in
{
options.services.hyperhive.deploy.k8s = {
@ -86,6 +91,45 @@ in
constraints as {option}`services.hyperhive.deploy.k8s.podCidr` apply.
'';
};
cniInterfaces = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [
"cni0"
"flannel.1"
];
readOnly = true;
internal = true;
description = ''
The pod network's interfaces. The firewall trusts them, and a
listener meant for pods only is opened on these and no other.
'';
};
serviceAccountIssuer = lib.mkOption {
type = lib.types.str;
readOnly = true;
internal = true;
default = "https://kubernetes.default.svc.${clusterDomain}";
description = ''
The `iss` claim of the ServiceAccount tokens the cluster issues, the
issuer k3s gives its API server for the cluster domain it runs with.
'';
};
serviceAccountKeyFiles = lib.mkOption {
type = lib.types.listOf lib.types.str;
readOnly = true;
internal = true;
default = [
"${dataDir}/server/tls/service.key"
"${dataDir}/server/tls/service.current.key"
];
description = ''
The files k3s keeps its ServiceAccount keys in: the key that verifies
tokens and the one that signs them, which differ after a rotation.
'';
};
};
config = lib.mkIf cfg.enable {
@ -136,6 +180,8 @@ in
"--secrets-encryption"
"--cluster-cidr=${cfg.podCidr}"
"--service-cidr=${cfg.serviceCidr}"
"--data-dir=${dataDir}"
"--cluster-domain=${clusterDomain}"
];
# k3s's own images come first: with no registry the node pulls nothing,
# not even CoreDNS.
@ -145,9 +191,6 @@ in
++ (config.system.build.k8sImages or [ ]);
};
networking.firewall.trustedInterfaces = [
"cni0"
"flannel.1"
];
networking.firewall.trustedInterfaces = cfg.cniInterfaces;
};
}

View file

@ -6,7 +6,10 @@
# The pod takes the unit's environment, credential ids, state and runtime
# directories, and timer. Every file the unit names is mounted at the path the
# unit names it by, so the environment carries over as it is and a change to a
# unit shows up in its manifest.
# unit shows up in its manifest. The one change is the store login: a service
# the store has a jwt role for (`deploy.bao.k8sPrincipals`) runs under a
# ServiceAccount of its name, with a projected token for the store's audience
# in place of its client certificate and key.
#
# Secrets are referenced by name and credential id only. The output lands in
# the world-readable nix store, so it never holds a credential's host path or
@ -20,6 +23,8 @@ let
hyperhiveCfg = config.services.hyperhive;
deployCfg = hyperhiveCfg.deploy;
k8sCfg = hyperhiveCfg.k8s;
baoDeployCfg = deployCfg.bao;
podAuth = import ../lib/bao-pod-auth.nix;
# `serviceUser` is the user every image runs its daemon as. Mounted files are
# group-owned by its group through `fsGroup`.
@ -125,7 +130,7 @@ let
credDir = "/run/credentials/${name}.service";
# `LoadCredential` entries are `id:source` on the host and a bare `id`
# inside a container. Only the id is rendered.
credIds = map (e: lib.head (lib.splitString ":" e)) (lib.toList (sc.LoadCredential or [ ]));
unitCredIds = map (e: lib.head (lib.splitString ":" e)) (lib.toList (sc.LoadCredential or [ ]));
runtimeDir = if sc ? RuntimeDirectory then "/run/${sc.RuntimeDirectory}" else null;
stateDir = if sc ? StateDirectory then "/var/lib/${sc.StateDirectory}" else null;
@ -137,6 +142,36 @@ let
lib.filterAttrs (n: v: v != null && n != "PATH") unit.environment
);
# A service the store knows by a jwt role as well as by its certificate
# 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;
baoClientCredIds =
map
(
var:
let
v = unitEnv.${var} or "";
in
if under credDir v then
lib.removePrefix "${credDir}/" v
else
fail name "${var} is not a credential of the unit, which the pod's login drops"
)
[
"BAO_CLIENT_CERT"
"BAO_CLIENT_KEY"
];
credIds = if baoLogin then lib.subtractLists baoClientCredIds unitCredIds else unitCredIds;
baoEnv = {
BAO_ADDR = "https://${hyperhiveCfg.swarm.bao.domain}:${toString baoDeployCfg.podListenerPort}";
BAO_AUTH = "jwt";
BAO_JWT_FILE = podAuth.tokenFile;
BAO_JWT_ROLE = name;
BAO_JWT_MOUNT = podAuth.mount;
};
# Trust bundles (../lib/hive-ca-trust.nix, ../hive-tls.nix): system roots
# plus the hive CA, assembled at runtime, so the cluster holds the one
# bundle as a ConfigMap and each path the unit names mounts it.
@ -145,7 +180,16 @@ let
);
env =
unitEnv
(
if baoLogin then
removeAttrs unitEnv [
"BAO_CLIENT_CERT"
"BAO_CLIENT_KEY"
]
// baoEnv
else
unitEnv
)
// podOtlpEnv unitEnv
// lib.optionalAttrs (runtimeDir != null) { RUNTIME_DIRECTORY = runtimeDir; }
// lib.optionalAttrs (stateDir != null) { STATE_DIRECTORY = stateDir; }
@ -158,6 +202,7 @@ let
"/nix/store"
]
++ caFiles
++ lib.optional baoLogin podAuth.tokenDir
++ lib.optional (runtimeDir != null) runtimeDir
++ lib.optional (stateDir != null) stateDir
++ map (f: "/etc/${f}") svc.etcFiles;
@ -195,6 +240,24 @@ let
}) credIds;
};
}
++ lib.optional baoLogin {
name = "bao-token";
projected = {
# 0440, as the credentials: the pod's group reads the token.
defaultMode = 288;
sources = [
{
serviceAccountToken = {
audience = podAuth.audience;
# The shortest the API server grants. The kubelet refreshes
# the file before it expires, and a login reads it afresh.
expirationSeconds = 600;
path = "token";
};
}
];
};
}
++ lib.optional (caFiles != [ ]) {
name = "ca-trust";
configMap.name = "hyperhive-ca-trust";
@ -226,6 +289,11 @@ let
mountPath = credDir;
readOnly = true;
}
++ lib.optional baoLogin {
name = "bao-token";
mountPath = podAuth.tokenDir;
readOnly = true;
}
++ map (f: {
name = "ca-trust";
mountPath = f;
@ -296,6 +364,8 @@ let
podSpec = {
inherit terminationGracePeriodSeconds volumes;
containers = [ container ];
# 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;
enableServiceLinks = false;
securityContext = {
@ -304,7 +374,8 @@ let
fsGroup = serviceUser.gid;
seccompProfile.type = "RuntimeDefault";
};
};
}
// lib.optionalAttrs baoLogin { serviceAccountName = name; };
podTemplate = restartPolicy: {
metadata.labels = labelsFor name;
@ -353,6 +424,15 @@ let
objects = {
"${name}/${lib.toLower svc.kind}" = main;
}
// lib.optionalAttrs baoLogin {
# Named after the service: the store's jwt role binds this account.
"${name}/serviceaccount" = {
apiVersion = "v1";
kind = "ServiceAccount";
metadata = metaFor name;
automountServiceAccountToken = false;
};
}
// lib.optionalAttrs (stateDir != null) {
"${name}/persistentvolumeclaim" = {
apiVersion = "v1";

View file

@ -0,0 +1,18 @@
# What the secret store's pod login and the pods' manifests agree on, in one
# place: the auth mount, the audience, and where the projected token is
# mounted. ../swarm-bao.nix writes the mount and its roles from it and
# ../k8s/render.nix renders the pods from it. `DEFAULT_JWT_FILE` in
# swarm-secret-client/src/client.rs is `tokenFile`.
#
# Pure attrset — NOT a NixOS module.
{
# Named in ../bao-bootstrap-policy.hcl, which is a static file.
mount = "jwt-k8s";
# The `aud` the pods ask the API server for and the roles require, so a token
# minted for the Kubernetes API is no use here.
audience = "bao";
tokenDir = "/var/run/secrets/hyperhive/bao";
tokenFile = "/var/run/secrets/hyperhive/bao/token";
}

View file

@ -465,6 +465,11 @@ let
clientCaPath = "${tlsDir}/client-ca.pem";
refreshConsumer = import ./refresh-consumer.nix { };
# The name both ends must agree on: the cert-auth role attaches this policy
# by spelling it the same way, and is itself named after it.
controllerPolicyName = "swarm-controller";
in
{
inherit
@ -497,6 +502,7 @@ in
controllerClientLeaf
controllerForgeTokenLeaf
controllerGrafanaTokenLeaf
controllerPolicyName
controllerWebhookSecretLeaf
createStanza
credentialMountPath

View file

@ -14,6 +14,12 @@ let
hyperhiveCfg = config.services.hyperhive;
deployCfg = hyperhiveCfg.deploy;
baoDeploy = deployCfg.bao;
# The cluster node on this host, and what its pods and this store agree on
# about the pods' login.
k8sNode = deployCfg.k8s;
podAuth = import ./lib/bao-pod-auth.nix;
shared = import ./lib/swarm-bao-shared.nix { inherit config lib pkgs; };
inherit (shared)
atticFactLeaves
@ -28,12 +34,15 @@ let
classifierApiKeyLeaf
controllerForgeTokenLeaf
controllerGrafanaTokenLeaf
controllerPolicyName
createStanza
credentialMountPath
grafanaAdminLeaf
grafanaMetricsBearerLeaf
grafanaSecretKeyLeaf
granterPolicyUnit
granterSetupSteps
haveGranter
haveServerTls
issuerPublicLeaf
issuerSeedLeaf
@ -362,6 +371,25 @@ let
bao policy write ${lib.escapeShellArg obj.name} -
'';
# The token lifetime arguments of a principal's role, as `bao write`
# arguments continuing the line before them. The cert role and the jwt role of
# one principal take the same ones.
#
# `batchToken = true` on an object makes its logins batch tokens, which the
# store does not persist and cannot renew or revoke. Only for a principal
# that logs in, reads and drops the token within one call: the five
# minutes outlast that read, and a leaked token dies as fast. A principal
# that holds a handle longer must not set it.
roleTokenArgs =
obj:
let
ttl = certRoleTokenTtl;
in
if obj.batchToken or false then
" \\\n token_type=batch \\\n token_ttl=5m"
else
" \\\n token_ttl=${ttl} \\\n token_max_ttl=${ttl}";
# ⚠️ Names are `swarm-<principal>[-<hive>]`, outside the `hive-*` namespace the
# controller may rewrite, for the reason the three service principals above
# state. A per-hive CN cannot collide with a hive's own leaf either — a hive's
@ -369,28 +397,33 @@ let
# `swarm` in one — and ./swarm.nix reserves the concrete per-hive spellings
# anyway, because the prefixes are operator-settable and an operator may spell
# one without that substring.
#
# `batchToken = true` on an object makes its logins batch tokens, which the
# store does not persist and cannot renew or revoke. Only for a principal
# that logs in, reads and drops the token within one call: the five
# minutes outlast that read, and a leaked token dies as fast. A principal
# that holds a handle longer must not set it.
readerRoleWrite =
obj:
let
ttlArgs =
if obj.batchToken or false then
" \\\n token_type=batch \\\n token_ttl=5m"
else
" \\\n token_ttl=${certRoleTokenTtl} \\\n token_max_ttl=${certRoleTokenTtl}";
in
''
bao write auth/cert/certs/${lib.escapeShellArg obj.name} \
certificate=@${tlsDir}/client-ca.pem \
allowed_common_names=${lib.escapeShellArg obj.cn} \
token_policies=${lib.escapeShellArg obj.name} \
display_name=${lib.escapeShellArg obj.cn}${ttlArgs}
'';
readerRoleWrite = obj: ''
bao write auth/cert/certs/${lib.escapeShellArg obj.name} \
certificate=@${tlsDir}/client-ca.pem \
allowed_common_names=${lib.escapeShellArg obj.cn} \
token_policies=${lib.escapeShellArg obj.name} \
display_name=${lib.escapeShellArg obj.cn}${roleTokenArgs obj}
'';
# The principals whose service runs in the cluster, and so logs in with its
# pod's ServiceAccount token as well as with its certificate: the records the
# cert roles above are written from, plus the controller's, whose cert role
# is written by `swarm-bao-controller-policy`. Each one's jwt role takes the
# principal's name, policy and token lifetimes, and its ServiceAccount is
# named after it (../k8s/render.nix renders the pod under that account).
k8sPrincipals = notifyRouterReaders ++ ciMetricsReaders ++ [ { name = controllerPolicyName; } ];
# The jwt role of one principal: the token of exactly its ServiceAccount, for
# this store's audience. Both the subject and the audience are bound, so a
# token of another account, or one minted for the Kubernetes API, is refused.
k8sJwtRoleWrite = obj: ''
bao write auth/${podAuth.mount}/role/${lib.escapeShellArg obj.name} \
role_type=jwt \
user_claim=sub \
bound_subject=${lib.escapeShellArg "system:serviceaccount:${hyperhiveCfg.k8s.namespace}:${obj.name}"} \
bound_audiences=${lib.escapeShellArg podAuth.audience} \
token_policies=${lib.escapeShellArg obj.name}${roleTokenArgs obj}
'';
# One unit per PRINCIPAL, not one unit for all of them: these names are
# operator-facing strings, the same reason `swarm-bao-secret-publisher-policy`
@ -405,6 +438,19 @@ let
in
{
options.services.hyperhive.deploy.bao.k8sPrincipals = lib.mkOption {
type = lib.types.listOf lib.types.str;
readOnly = true;
internal = true;
default = map (p: p.name) k8sPrincipals;
description = ''
The in-cluster services that log in to the store with a ServiceAccount
token. Each is one principal: its cert-auth role and its jwt role carry
the same name, policy and token lifetimes, and its pod runs under a
ServiceAccount of that name.
'';
};
config = lib.mkIf (deployCfg.bao.enable && haveServerTls) {
# 🩸 The principals that each log in with a leaf of their own, not as the
# hive. See the lists in this file for what each grant is; the
@ -442,5 +488,78 @@ in
systemd.services.swarm-bao-stt-policy = readerPolicyUnit "write the speech-to-text service's client-secret-reader bao policy and cert-auth role" sttReaders;
systemd.services.swarm-bao-forge-publisher-policy = readerPolicyUnit "write the forge's controller-token-publisher bao policy and cert-auth role" forgePublisherWriters;
# The pods' login: the `jwt` auth mount's config and one role per
# in-cluster service. The mount exists once `swarm-bao-granter-role` has
# run with a bootstrap token that carries `sys/auth/jwt-k8s`;
# until then this stops with exit 0, as the OIDC unit does, and
# `swarm-bao-granter-role` restarts it each time it succeeds.
#
# The tokens are checked against the public halves of the keys k3s signs
# them with, derived here from the key files, so no key is copied by hand.
# A rotation of those keys needs a restart of this unit.
systemd.services.swarm-bao-k8s-jwt-policy = lib.mkIf k8sNode.enable (
lib.mkMerge [
(granterPolicyUnit "write the pods' ServiceAccount-token login: the jwt auth mount's config and one role per in-cluster service" ''
caps="$(bao token capabilities auth/${podAuth.mount}/config)"
case "$caps" in
*update*) ;;
*)
echo "the granter may not configure auth/${podAuth.mount} yet (capabilities: $caps), so the pods' login stays off." >&2
echo "one-time step, as root on this host (docs/1-getting-started/setup.md):" >&2
${lib.concatMapStringsSep "\n" (l: "echo ${lib.escapeShellArg " ${l}"} >&2") granterSetupSteps}
echo "swarm-bao-granter-role re-runs this unit once it succeeds." >&2
exit 0
;;
esac
# One public key per private key in the files, which may each hold
# several. A file k3s has not written is skipped, and no key at all
# fails the unit, which retries.
work="$(mktemp -d)"
trap 'rm -rf "$work" "$err"' EXIT
: > "$work/public.pem"
for key_file in ${lib.escapeShellArgs k8sNode.serviceAccountKeyFiles}; do
[ -s "$key_file" ] || continue
rm -f "$work"/block-*
awk -v dir="$work" '
/-----BEGIN [A-Z ]*PRIVATE KEY-----/ { n++; out = dir "/block-" n }
out != "" { print > out }
/-----END [A-Z ]*PRIVATE KEY-----/ { if (out != "") close(out); out = "" }
' "$key_file"
for block in "$work"/block-*; do
[ -e "$block" ] || continue
openssl pkey -in "$block" -pubout >> "$work/public.pem"
done
done
if [ ! -s "$work/public.pem" ]; then
echo "no ServiceAccount signing key in ${lib.escapeShellArgs k8sNode.serviceAccountKeyFiles}: k3s has not written them yet." >&2
exit 1
fi
# A JSON body on stdin, because `jwt_validation_pubkeys` is a list.
# The tokens' signature algorithm follows the type of k3s's key.
keys="$(jq -Rs '[scan("-----BEGIN PUBLIC KEY-----[^-]+-----END PUBLIC KEY-----")] | unique' "$work/public.pem")"
jq -n --argjson keys "$keys" --arg issuer ${lib.escapeShellArg k8sNode.serviceAccountIssuer} '{
jwt_validation_pubkeys: $keys,
bound_issuer: $issuer,
jwt_supported_algs: ["RS256", "ES256"]
}' |
bao write auth/${podAuth.mount}/config -
${lib.concatMapStrings k8sJwtRoleWrite k8sPrincipals}
'')
(lib.mkIf haveGranter {
after = [ "k3s.service" ];
wants = [ "k3s.service" ];
path = [
pkgs.gawk
pkgs.jq
pkgs.openssl
];
})
]
);
};
}

View file

@ -41,6 +41,11 @@ let
baoDeploy = deployCfg.bao;
networkCfg = hyperhiveCfg.network;
# The cluster node on this host, and what its pods and this store agree on
# about the pods' login.
k8sNode = deployCfg.k8s;
podAuth = import ./lib/bao-pod-auth.nix;
shared = import ./lib/swarm-bao-shared.nix { inherit config lib pkgs; };
inherit (shared)
agentPkiMountPath
@ -67,6 +72,7 @@ let
controllerClientLeaf
controllerForgeTokenLeaf
controllerGrafanaTokenLeaf
controllerPolicyName
controllerWebhookSecretLeaf
createStanza
credentialMountPath
@ -316,6 +322,16 @@ let
path "${credentialMountPath}/data/${baoUiClientLeaf}" {
capabilities = ["read"]
}
''
+ lib.optionalString k8sNode.enable ''
path "auth/${podAuth.mount}/config" {
capabilities = ["create", "update"]
}
path "auth/${podAuth.mount}/role/swarm-*" {
capabilities = ["create", "update"]
}
'';
# The bootstrap token's first use, in `swarm-bao-granter-role`.
@ -329,10 +345,6 @@ let
setupSteps = granterSetupSteps;
};
# The name both ends must agree on: the cert-auth role below attaches this
# policy by spelling it the same way, and is itself named after it.
controllerPolicyName = "swarm-controller";
# An option rather than a literal because whatever mints the controller's
# leaf has to spell it identically, and that lives in another file.
controllerCn = baoDeploy.controllerCommonName;
@ -948,6 +960,25 @@ let
tls_require_and_verify_client_cert = true;
};
# The listener the cluster's pods log in on, with a ServiceAccount token.
# A pod holds no client certificate, so this is the one listener that does
# not require one; `tls_client_ca_file` stays, so a client that presents a
# certificate is still checked against it. Pods reach it on the bridge
# address, where the name every reader dials resolves for them. Nothing else
# may reach it: the firewall admits its port on the pod network's interfaces
# only (see `podListenerPort`), and an address on the bridge alone does not
# keep a bridge client out, because the kernel accepts a packet for any local
# address on any interface. Its cluster address stays on loopback, as
# nothing joins this store.
podListener = lib.optionalAttrs k8sNode.enable {
pod = {
type = "tcp";
address = "${networkCfg.bridgeIp}:${toString baoDeploy.podListenerPort}";
cluster_address = "127.0.0.1:${toString (baoDeploy.podListenerPort + 1)}";
}
// removeAttrs listenerTls [ "tls_require_and_verify_client_cert" ];
};
extraListeners = lib.listToAttrs (
lib.imap1 (
i: addr:
@ -985,6 +1016,7 @@ let
// listenerTls;
}
// extraListeners
// podListener
// metricsListener
// uiListener;
@ -1047,6 +1079,10 @@ let
(baoDeploy.uiPort + 1)
baoDeploy.uiProxyPort
baoDeploy.otel.telemetryPort
]
++ lib.optionals k8sNode.enable [
baoDeploy.podListenerPort
(baoDeploy.podListenerPort + 1)
];
# Paths a browser session has no business sending to the store: they unseal,
@ -2414,7 +2450,7 @@ in
LAN or the internet. Off by default: the port is otherwise open only on
the agent bridge.
⚠️ This exposes the secret store beyond the tunnel. Every listener
⚠️ This exposes the secret store beyond the tunnel. Every listener on that port
requires a client certificate signed by
{option}`services.hyperhive.deploy.bao.clientCaFile`, and nothing
answers without one, which is why setting this without that file, or
@ -2426,6 +2462,24 @@ in
address the other hives reach.
'';
};
podListenerPort = lib.mkOption {
type = lib.types.port;
default = 8208;
description = ''
Port of the listener the cluster's pods log in on, on the hive
bridge's address. It exists only with
{option}`services.hyperhive.deploy.k8s.enable`, and unlike every other
listener it asks for **no client certificate**: a pod authenticates
with its ServiceAccount token at the `jwt-k8s` auth mount. The firewall
admits this port on the pod network's interfaces only, so a client on
the hive bridge cannot reach it.
⚠️ openbao also binds this port **+ 1** as the listener's cluster
address, so neither may coincide with another port the store or its
container binds. An assertion checks this.
'';
};
};
# ⚠️ Gated on `deploy.bao.enable`, and that is load-bearing rather than
@ -2467,8 +2521,9 @@ in
${lib.concatMapStringsSep ", " toString containerPorts}. They are
services.hyperhive.swarm.bao.port and +1, deploy.bao.metricsPort and
+1, deploy.bao.uiPort and +1 (openbao binds each listener's port + 1
as its cluster address), deploy.bao.uiProxyPort, and
deploy.bao.otel.telemetryPort. Pick free ports.
as its cluster address), deploy.bao.uiProxyPort,
deploy.bao.otel.telemetryPort, and with deploy.k8s.enable
deploy.bao.podListenerPort and +1. Pick free ports.
'';
}
{
@ -2643,11 +2698,22 @@ in
# certificate its CA signed.
services.hyperhive.network.exposeHostPorts = [ cfg.port ];
# Every listener, bridge-IP passthrough included, requires the client
# certificate (see `listenerTls`), so opening the port host-wide adds
# reach and no unauthenticated path.
# Every listener on this port, bridge-IP passthrough included, requires
# the client certificate (see `listenerTls`), so opening the port
# host-wide adds reach and no unauthenticated path.
networking.firewall.allowedTCPPorts = lib.mkIf baoDeploy.openFirewall [ cfg.port ];
# The pods' listener asks for no client certificate, so its port opens on
# the pod network's interfaces and nowhere else: not on the hive bridge,
# whose firewall refuses every port it does not list. The pod network's
# interfaces are trusted already; naming the port here keeps the reach
# from depending on that.
networking.firewall.interfaces = lib.mkIf k8sNode.enable (
lib.genAttrs k8sNode.cniInterfaces (_: {
allowedTCPPorts = [ baoDeploy.podListenerPort ];
})
);
# The operators' door to the UI, shaped like ./swarm-victorialogs.nix's
# vhost. It proxies to the container's nginx over loopback (shared
# netns), so no port opens anywhere. `auth_request` only proves a
@ -2984,7 +3050,9 @@ in
# already running (or a `systemctl` that itself fails to enqueue
# the job) would mark the granter failed and trigger its own
# `Restart=on-failure` for a problem that isn't the granter's.
ExecStartPost = "-${pkgs.systemd}/bin/systemctl restart --no-block swarm-bao-operator-viewer-policy.service";
ExecStartPost =
"-${pkgs.systemd}/bin/systemctl restart --no-block swarm-bao-operator-viewer-policy.service"
+ lib.optionalString k8sNode.enable " swarm-bao-k8s-jwt-policy.service";
};
script = ''
set -euo pipefail
@ -3024,7 +3092,15 @@ in
*'"oidc/"'*) ;;
*) bao auth enable -listing-visibility=unauth oidc ;;
esac
${lib.optionalString k8sNode.enable ''
# The pods' login with a ServiceAccount token;
# `swarm-bao-k8s-jwt-policy` writes its config and roles.
case "$mounted" in
*'"${podAuth.mount}/"'*) ;;
*) bao auth enable -path=${podAuth.mount} jwt ;;
esac
''}
printf '%s' ${lib.escapeShellArg granterPolicyText} |
bao policy write ${lib.escapeShellArg granterPolicyName} -