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
17 changed files with 720 additions and 69 deletions

View file

@ -9,11 +9,13 @@ holds the store's mechanics.
**Store secrets stay off disk.** A process pulls a value from the store at
runtime and holds it in memory only.
**The mTLS client certificate is the only credential on disk.** Each
**The mTLS client certificate is the only credential you place on disk.** Each
identity (an agent, a hive, a swarm-level service) has one. It's what logs a
principal in to the store, so you place a hive's or service's certificate by
hand. The nix option for it takes a path to the certificate, never its bytes,
because a literal in a nix expression lands in the world-readable nix store.
because a literal in a nix expression lands in the world-readable nix store. A
service that runs in the cluster has no certificate: its pod logs in with a
ServiceAccount token that the cluster projects into it, so you place nothing.
A hive hands each agent its certificate; the agent pulls everything else
itself.

View file

@ -104,8 +104,8 @@ every interface, and `deploy.bao.openFirewall` together with
on the addresses it listens on. Both default to off. Each exposes a service
beyond the agent bridge, which is the operator's decision. The queue requires TLS and
its `auth_callout` refuses every client it can't identify. The store requires a
client certificate on every listener, and evaluation fails when you
set `deploy.bao.openFirewall` without `deploy.bao.clientCaFile`. Point
client certificate on every listener that port reaches, and evaluation fails
when you set `deploy.bao.openFirewall` without `deploy.bao.clientCaFile`. Point
`nats.<swarm.domain>` and `bao.<swarm.domain>` in your upstream DNS at the
address the other hives reach.

View file

@ -19,11 +19,11 @@ cluster.
A service gets manifests on the host whose configuration deploys it:
| service | workload | other objects |
| --------------------- | ---------- | -------------------------------------------------------------------------------- |
| `swarm-controller` | Deployment | PersistentVolumeClaim `swarm-controller-state`, ConfigMap `swarm-controller-etc` |
| `swarm-notify-router` | Deployment | none |
| `swarm-ci-metrics` | CronJob | PersistentVolumeClaim `swarm-ci-metrics-state` |
| service | workload | other objects |
| --------------------- | ---------- | ------------------------------------------------------------------------------------------------ |
| `swarm-controller` | Deployment | ServiceAccount, PersistentVolumeClaim `swarm-controller-state`, ConfigMap `swarm-controller-etc` |
| `swarm-notify-router` | Deployment | ServiceAccount |
| `swarm-ci-metrics` | CronJob | ServiceAccount, PersistentVolumeClaim `swarm-ci-metrics-state` |
`namespace.yaml` holds the Namespace. NATS with its auth responder,
`swarm-review-classifier`, `swarm-claude-login` and `swarm-stt` have no
@ -38,7 +38,8 @@ The renderer reads the service's evaluated unit, not a copy of its settings:
directory it stands for. On a host with a hive collector, the OTLP endpoint
variables point at it ([Pod logs and metrics](telemetry.md)) instead. The
renderer fails if the unit's `path` holds anything beyond the NixOS default
tools, because the image doesn't carry them.
tools, because the image doesn't carry them. The other change is the store
login, [below](#the-store-login).
- **Files:** the pod mounts each file the unit names at the same path,
so the environment carries over unchanged:
- credentials at `/run/credentials/<service>.service/<id>`, from the Secret
@ -85,7 +86,8 @@ object.
with `fsGroup` its gid so the pod reads its credentials (mode `0440`),
read-only root filesystem with an `emptyDir` on `/tmp`, no privilege
escalation, every capability dropped, the runtime's default seccomp profile,
and no service account token.
and no mounted API token. A service that logs in to the store gets a token
of its own, [below](#the-store-login).
- **Probes:** a service with an opt-in health listener gets its variable set to
`0.0.0.0:8080`, with liveness on `/healthz` and readiness on `/readyz`
(see [Readiness checks](../swarm/readiness.md)). `swarm-controller` serves
@ -96,6 +98,31 @@ object.
- **Rollout:** each Deployment has one replica and the `Recreate` strategy,
because each service runs once per swarm.
## The store login
A service that has a role at the store's `jwt-k8s` auth mount
(`services.hyperhive.deploy.bao.k8sPrincipals`) logs in with its pod's
ServiceAccount token. A unit logs in with the client certificate in its
environment, so the pod differs from the unit in these places:
- **ServiceAccount:** one named like the service, in the rendered namespace,
with `automountServiceAccountToken: false`, and the pod runs under it.
- **Token:** a projected volume `bao-token` with one `serviceAccountToken`
source for the audience `bao`, expiring after 600 seconds (the shortest the
API server grants) and mounted read-only at `/var/run/secrets/hyperhive/bao`.
The kubelet rewrites the file before it expires, and the client reads it
afresh at each login. The store's role for the service accepts this
account and this audience only.
- **Environment:** the pod sets neither `BAO_CLIENT_CERT` nor
`BAO_CLIENT_KEY`, and the credentials they named aren't in the pod's
Secret. `BAO_AUTH=jwt`, `BAO_JWT_FILE`, `BAO_JWT_ROLE` (the service's name)
and `BAO_JWT_MOUNT` (`jwt-k8s`) take their place, and `BAO_ADDR` names the
store's own name at the port of the listener that asks for no client
certificate (`deploy.bao.podListenerPort`). `BAO_CACERT` stays.
[The cluster node](node.md#logging-in-to-the-secret-store) describes the
store's side.
## Not covered yet
- The pods reach the swarm's host-run services (store, queue, identity

View file

@ -28,6 +28,9 @@ service images loaded and no service's objects applied.
bridge's default subnet.
- **Firewall:** the pod network's interfaces, `cni0` and `flannel.1`, are
trusted, so the node reaches its pods.
- **Secret store:** the store gets a second listener and an auth mount for the
pods' ServiceAccount tokens, described under
[Logging in to the secret store](#logging-in-to-the-secret-store).
## What it leaves alone
@ -58,12 +61,53 @@ address to answer with, so it gets no ConfigMap.
The firewall trusts the pod network's interfaces, so a pod reaches
these listeners without a firewall rule per port. Each service still
authenticates its callers: the secret store refuses a connection without a
client certificate.
authenticates its callers: every listener of the secret store but its pods'
one refuses a connection without a client certificate.
## Logging in to the secret store
A pod holds no client certificate. It logs in to the secret store with a
ServiceAccount token the kubelet projects into it, and the store checks that
token against the node's own signing keys.
- **Listener:** the store binds a listener on the hive bridge's address at
`deploy.bao.podListenerPort` (default `8208`). It serves the store's server
certificate and asks for no client certificate. A pod dials it by the name it
dials the store by, `bao.<swarm domain>`, which CoreDNS answers with the
bridge's address.
- **Firewall:** that port is open on `cni0` and `flannel.1` and on no other
interface. The bridge's firewall refuses it, so an agent on the bridge can't
connect. Binding an address doesn't isolate a port, because the kernel
accepts a packet for any local address on any interface, so the firewall
rule does. Every other listener of the store keeps its client certificate
requirement.
- **Auth mount:** `jwt-k8s`. `swarm-bao-granter-role` enables it with the
bootstrap token, and `swarm-bao-k8s-jwt-policy` writes its config: the
public halves of the keys k3s signs ServiceAccount tokens with, derived from
the key files under `/var/lib/rancher/k3s/server/tls`, and the issuer the
node gives its API server, `https://kubernetes.default.svc.cluster.local`.
The unit runs after k3s and needs no manual step. Restart it after a rotation
of the node's signing keys.
- **Roles:** one per in-cluster service, named like the service and its cert
role (`swarm-controller`, `swarm-notify-router`, `swarm-ci-metrics`). A role
accepts the token of the ServiceAccount of that name in the services'
namespace (`system:serviceaccount:<namespace>:<service>`), and only with the
audience `bao`, so a token meant for the Kubernetes API is no use to the
store. It hands out the policy and token lifetimes of the service's cert role.
- **Pod:** the [rendered manifest](manifests.md#the-store-login) runs the pod
under that ServiceAccount, with a token projected for the audience `bao` and
`BAO_AUTH=jwt` in its environment.
The bootstrap policy that `swarmctl bao grant-bootstrap` applies carries
`sys/auth/jwt-k8s`, so a store set up before the node existed needs that step
once more.
## Validation
`module-eval-k8s` compares an all-local host with the option on against the
same host with it off, and checks the address ranges and the CoreDNS
ConfigMap. The VM test `k8s-node` boots a node through the module and runs a
pod against it.
pod against it. The VM test `k8s-bao-login` runs the node and the secret store
together: a pod under a service's ServiceAccount logs in and reads a value, a
pod under another account gets no token, and a client on the hive bridge can't
connect to the pods' port.

View file

@ -26,14 +26,15 @@ file is `services.hyperhive.deploy.bao.bootstrapTokenFile`, which all-local
names for you; on a store host that isn't all-local, set it and rebuild first.
`swarm-bao-granter-role` runs **on the host**. It enables the cert and oidc
auth methods (and disables `approle` if an older store still has it mounted),
auth methods, and `jwt-k8s` on a host with the cluster node (and disables
`approle` if an older store still has it mounted),
writes the `bao-granter` policy, and creates the `bao-granter` role, which
accepts the leaf `/var/lib/swarm-bao-pki/granter.pem`. Every
`swarm-bao-*-policy` unit then logs in with that leaf. The controller's unit
mounts the KV and pki engines and writes the `swarm-controller` role, and each
sibling unit writes its own principal's policy and role. Every one runs on the
host, because every API listener but the loopback UI one demands a client
certificate and the host is the side that has one.
host, because every API listener but the loopback UI one and the cluster
pods' one demands a client certificate and the host is the side that has one.
Until the granter exists, each `swarm-bao-*-policy` unit **fails** and logs
the bootstrap commands. It never skips. `swarm-bao-granter-role` skips while
@ -92,6 +93,17 @@ constrain what a policy says. What bounds it:
restarting `swarm-bao-pki` mints a new leaf, but doesn't invalidate the old
one.
## Pods in the cluster
A service that runs in the k3s cluster (`deploy.k8s.enable`) logs in with its
pod's ServiceAccount token instead of a certificate. The store has a `pod`
listener for it, on the hive bridge's address at `deploy.bao.podListenerPort`,
that asks for no client certificate, and a `jwt-k8s` auth mount with one role
per in-cluster service. Only the firewall keeps the port from the agents on
the bridge: it admits the port on the pod network's interfaces alone. The
roles, the keys they trust and the pods' side are in
[the cluster node](../k8s/node.md#logging-in-to-the-secret-store).
## Sealing
`services.hyperhive.deploy.bao.seal`:

View file

@ -183,9 +183,9 @@ On the host running
the store it's also at
`/var/lib/swarm-bao-services-pki/services-root.pem`. That's the file to
hand a browser, and reading it needs no store login — which matters,
because every store listener but the loopback UI one demands a client
certificate, and authelia gates that one to the `admins` group, not
open to an anonymous browser fetching a trust anchor.
because every store listener but the loopback UI one and the cluster pods'
one demands a client certificate, and authelia gates that one to the `admins`
group, not open to an anonymous browser fetching a trust anchor.
**The granting unit generates the root once, and never again.** It asks
the mount whether it already has an issuer (`bao list pki/issuers`)

View file

@ -158,6 +158,7 @@ pieces fit, and the reasoning behind them, is in [`credentials.md`](../../2-hand
| the gateway's client certificate for the controller's TCP listener | `swarm-controller-gateway-client.service` on the host that runs the controller, only where you set `swarm.controller.tcp.enable`. It logs in under the services-issuer identity and issues from the store's `swarm-controller-gateway-client` role: one name, `gateway-client.<swarm.domain>`, `clientAuth` only, so the services leaf can't stand in for it. A daily timer renews it | `<deploy.hive-controller.tls.stateDir>/controller-client.pem` and `controller-client-key.pem`, the key `0640` group `nginx`; the gateway's controller locations name them in `proxy_ssl_certificate`. Until the store answers, a throwaway self-signed pair keeps nginx's config loadable. The listener refuses that pair, so those locations answer 502. Every holder of the services-issuer identity can obtain this leaf: the listener trusts "a gateway of this swarm" | Nothing to place: the services-issuer identity is the one every gateway host already holds |
| the secret store's own contents | openbao, on first `bao operator init` — **an operator action, not a unit** | inside the `swarm-bao` container, at its own `/var/lib/openbao`, kept across rebuilds by `ephemeral = false`. ⚠️ **Not a host path**: `nixos-container destroy swarm-bao` takes the raft data with it, so back up the container's tree, not `/var/lib/`. Only the store's TLS material (`/var/lib/swarm-bao-tls`) and its PKCS11 token (`/var/lib/swarm-bao-token`) are host-level | n/a — there is one store; a hive elsewhere is a _client_ of it and holds none of this |
| the secret store's unseal material | the HSM/TPM under `deploy.bao.seal = "pkcs11"`; openbao itself under `"shamir"` | in the token; or held by whoever ran `bao operator init`, which is what `"shamir"` means and why it's stated rather than inferred | n/a — only the host running the store seals anything |
| a cluster pod's store login token (a ServiceAccount token) | the cluster's API server, which signs it for the pod's account and the audience `bao`. The kubelet projects it into the pod and rewrites it before it expires | `/var/run/secrets/hyperhive/bao/token` in the pod. The store accepts it at its `jwt-k8s` mount, for the role of that account only, against the public halves of the node's signing keys, which `swarm-bao-k8s-jwt-policy` derives from the key files. A node whose signing keys changed needs that unit restarted, and tokens signed with the old key fail to log in meanwhile | Nothing to place: the pods and the store run on the cluster's one host |
### Hive-level — one of each per hive

View file

@ -56,6 +56,7 @@ in
persistentvolumeclaim-v1 = "sha256-YTaHGsAzfxGkjaUjGigHQHxzhpZ+NDLzRBQbkC9qU4w=";
configmap-v1 = "sha256-4Ord69Z3wIqgkrLaImTYasT8NO7RErn6wpRbPwDB6bE=";
namespace-v1 = "sha256-Mk+uZ3uY0abVQ0DbDDNNBT6P+6/Os/czJuQd4mENWEM=";
serviceaccount-v1 = "sha256-gZPWw1YUdcbT1cROH67bHfU5BTc9kEvBcBVpQybWWc8=";
}
);
invalid = pkgs.writeText "invalid-deployment.yaml" ''

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

View file

@ -2743,6 +2743,7 @@ let
"sys/auth/cert"
"sys/auth/approle"
"sys/auth/oidc"
"sys/auth/jwt-k8s"
"sys/policies/acl/bao-granter"
"auth/cert/certs/bao-granter"
]

View file

@ -27,6 +27,8 @@ let
runGroup
hive
hiveWithController
baoSettings
bridgePorts
;
allLocal = shared.allLocal;
@ -97,6 +99,21 @@ let
# compared with themselves.
collectorEndpoint = "http://hive-collector.hive:4318";
# What the pod's environment changes about the store login: no client
# certificate or key, and the token login on the listener that asks for no
# certificate. Spelled out here, not read from the module.
storeLogin = name: {
BAO_ADDR = "https://${allLocal.services.hyperhive.swarm.bao.domain}:8208";
BAO_AUTH = "jwt";
BAO_JWT_FILE = "/var/run/secrets/hyperhive/bao/token";
BAO_JWT_ROLE = name;
BAO_JWT_MOUNT = "jwt-k8s";
};
clientVars = [
"BAO_CLIENT_CERT"
"BAO_CLIENT_KEY"
];
# What the pod adds on top of the unit's own environment.
added = {
swarm-controller = {
@ -136,6 +153,15 @@ let
) (lib.attrValues units);
rendered = builtins.unsafeDiscardStringContext (builtins.toJSON objects);
# The credentials that hold a client certificate or its key: the pods log in
# with a token instead.
clientCertIds = [
"bao-client.pem"
"bao-client-key.pem"
"notify-router-bao-cert"
"notify-router-bao-key"
];
ciTimer = allLocal.systemd.timers.swarm-ci-metrics.timerConfig;
cron = objects."swarm-ci-metrics/cronjob".spec;
@ -151,12 +177,18 @@ let
{
# Each service's own credential path is the control: the comparison
# reads a non-empty environment.
name = "each workload carries its unit's environment, plus only its directories and health listener";
name = "each workload carries its unit's environment, plus only its directories, its health listener and the token login to the store";
ok =
lib.all (name: envOf name == unitEnv name // added.${name}) (lib.attrNames units)
lib.all (
name: envOf name == removeAttrs (unitEnv name) clientVars // storeLogin name // added.${name}
) (lib.attrNames units)
# The units keep their certificates, and the pods name none.
&&
(envOf "swarm-controller").BAO_CLIENT_CERT
(unitEnv "swarm-controller").BAO_CLIENT_CERT
== "/run/credentials/swarm-controller.service/bao-client.pem"
&& lib.all (name: lib.all (v: (unitEnv name) ? ${v} && !((envOf name) ? ${v})) clientVars) (
lib.attrNames units
)
&& (envOf "swarm-notify-router") ? SWARM_NOTIFY_ROUTER_NATS_URL;
}
{
@ -166,7 +198,9 @@ let
ok =
lib.length credentialSources >= 7
&& !(lib.any (s: lib.hasInfix s rendered) credentialSources)
&& lib.all (id: lib.hasInfix "\"${id}\"" rendered) credentialIds
&& lib.all (id: lib.hasInfix "\"${id}\"" rendered) (lib.subtractLists clientCertIds credentialIds)
# The units load the client certificates and the pods do not.
&& lib.all (id: lib.elem id credentialIds && !(lib.hasInfix "\"${id}\"" rendered)) clientCertIds
&& !(lib.any (o: o.kind == "Secret") (lib.attrValues objects))
&&
(lib.head (podSpec "swarm-controller").volumes).secret.secretName == "swarm-controller-credentials";
@ -239,10 +273,13 @@ let
&& lib.length loaded == 4;
}
{
# Nothing the host already runs differs: every unit, timer and
# container is still there, the only new units are k3s's, every unit but
# the firewall (whose rules carry the trusted interfaces) starts the same
# command, and the manifests are the same derivation as without the node.
# Nothing the host already runs differs but the store's side of the pods'
# login: every unit, timer and container is still there, the only new
# units are k3s's and the one that writes the pods' login, every unit but
# the firewall (whose rules carry the pod network's interfaces) and the
# granter's role unit (which enables the login's auth mount) starts the
# same command, and the manifests are the same derivation as without the
# node.
name = "the node changes no unit, container, timer or manifest of the all-local host";
ok =
let
@ -253,7 +290,8 @@ let
&& names allLocal.containers == names withNode.containers
&& lib.subtractLists (names withNode.systemd.services) (names allLocal.systemd.services) == [ ]
&& lib.elem "k3s" added
&& lib.all (n: lib.hasPrefix "k3s" n) added
&& lib.all (n: lib.hasPrefix "k3s" n || n == "swarm-bao-k8s-jwt-policy") added
&& lib.elem "swarm-bao-k8s-jwt-policy" added
&&
lib.all
(
@ -265,6 +303,7 @@ let
lib.subtractLists [
"firewall"
"opentelemetry-collector"
"swarm-bao-granter-role"
] (names allLocal.systemd.services)
)
&& withNode.system.build.k8sManifests.drvPath == allLocal.system.build.k8sManifests.drvPath;
@ -425,6 +464,182 @@ let
&&
acls == [ "A+ /var/log/pods - - - - u:opentelemetry-collector:rX,d:u:opentelemetry-collector:rX" ];
}
{
# The projected token is the pod's only credential from its account, and
# the roles in the store bind exactly this account and audience.
name = "each in-cluster service runs under its own ServiceAccount, with a token projected for the store's audience";
ok =
lib.all (
name:
let
sa = objects."${name}/serviceaccount";
vol = lib.findFirst (v: v.name == "bao-token") null (podSpec name).volumes;
mount = lib.findFirst (m: m.name == "bao-token") null (container name).volumeMounts;
source = (lib.head vol.projected.sources).serviceAccountToken;
in
sa.kind == "ServiceAccount"
&& sa.metadata.name == name
&& sa.metadata.namespace == "hyperhive"
&& !sa.automountServiceAccountToken
&& (podSpec name).serviceAccountName == name
&& !(podSpec name).automountServiceAccountToken
&& vol != null
&& lib.attrNames (lib.head vol.projected.sources) == [ "serviceAccountToken" ]
&& source.audience == "bao"
&& source.expirationSeconds >= 600
&& mount.mountPath == "/var/run/secrets/hyperhive/bao"
&& mount.readOnly
&& (envOf name).BAO_JWT_FILE == "${mount.mountPath}/${source.path}"
) (lib.attrNames units)
# The control: the credentials volume is still there beside it.
&& lib.any (v: v.name == "credentials") (podSpec "swarm-controller").volumes
&& lib.length (lib.filter (v: v.name == "bao-token") (podSpec "swarm-controller").volumes) == 1;
}
{
# The off arm and the on arm read the same unit, so what differs is the
# node alone. Roles are written one to one with the principals' cert
# roles: the same name, policy and token lifetimes.
name = "the store writes one jwt role per in-cluster service, binding its account and audience, with its cert role's policy and lifetimes";
ok =
let
s = withNode.systemd.services;
script = s.swarm-bao-k8s-jwt-policy.script;
certScript = {
swarm-notify-router = s.swarm-bao-notify-router-policy.script;
swarm-ci-metrics = s.swarm-bao-ci-metrics-policy.script;
swarm-controller = s.swarm-bao-controller-policy.script;
};
roles = map lib.head (lib.filter lib.isList (builtins.split "auth/jwt-k8s/role/([a-z-]+)" script));
ttl = "token_ttl=1h \\\n token_max_ttl=1h";
roleText = name: ''
bao write auth/jwt-k8s/role/${name} \
role_type=jwt \
user_claim=sub \
bound_subject=system:serviceaccount:hyperhive:${name} \
bound_audiences=bao \
token_policies=${name} \
${ttl}
'';
in
lib.length roles == 3
&& lib.sort lib.lessThan roles == lib.sort lib.lessThan (lib.attrNames units)
&&
lib.sort lib.lessThan withNode.services.hyperhive.deploy.bao.k8sPrincipals
== lib.sort lib.lessThan roles
&& lib.all (
name:
lib.hasInfix (lib.removeSuffix "\n" (roleText name)) script
&& lib.hasInfix "auth/cert/certs/${name}" certScript.${name}
&& lib.hasInfix "token_policies=${name}" certScript.${name}
&& lib.hasInfix "token_ttl=1h" certScript.${name}
&& lib.hasInfix "token_max_ttl=1h" certScript.${name}
) roles
&& lib.hasInfix "bao write auth/jwt-k8s/config -" script;
}
{
# The keys come from the node's own files, and the issuer is the one the
# node's flags give its API server.
name = "the jwt config is the public half of k3s's ServiceAccount keys and its issuer, derived by a unit ordered after k3s";
ok =
let
u = withNode.systemd.services.swarm-bao-k8s-jwt-policy;
start = withNode.systemd.services.k3s.serviceConfig.ExecStart;
in
lib.hasInfix "/var/lib/rancher/k3s/server/tls/service.key" u.script
&& lib.hasInfix "/var/lib/rancher/k3s/server/tls/service.current.key" u.script
&& lib.hasInfix "openssl pkey -in \"$block\" -pubout" u.script
&& lib.hasInfix "jwt_validation_pubkeys" u.script
&& lib.hasInfix "https://kubernetes.default.svc.cluster.local" u.script
&& lib.hasInfix "\"RS256\", \"ES256\"" u.script
&& lib.hasInfix "--data-dir=/var/lib/rancher/k3s" start
&& lib.hasInfix "--cluster-domain=cluster.local" start
&& lib.elem "k3s.service" u.after
&& lib.elem "k3s.service" u.wants;
}
{
# The mount is a bootstrap-token act, like the oidc one, and the granter
# may then write its config and roles only.
name = "the granter's role unit enables the jwt mount, the bootstrap policy carries it and the granter writes its config and roles";
ok =
let
g = withNode.systemd.services.swarm-bao-granter-role;
hcl = builtins.readFile ../host-modules/bao-bootstrap-policy.hcl;
in
lib.hasInfix "bao auth enable -path=jwt-k8s jwt" g.script
&& lib.hasInfix "path \"auth/jwt-k8s/config\" {\n capabilities = [\"create\", \"update\"]\n}" g.script
&& lib.hasInfix "path \"auth/jwt-k8s/role/swarm-*\" {\n capabilities = [\"create\", \"update\"]\n}" g.script
&& lib.hasInfix "path \"sys/auth/jwt-k8s\" {\n capabilities = [\"create\", \"update\", \"sudo\"]\n}" hcl
&& !(lib.hasInfix "sys/auth/jwt-k8s" g.script)
&& lib.hasInfix "swarm-bao-k8s-jwt-policy.service" g.serviceConfig.ExecStartPost;
}
{
# The host with the node on is the control that each lookup finds what
# the host without it lacks.
name = "without the node the store has no pod listener, jwt mount, jwt unit or firewall rule for pods";
ok =
let
off = allLocal.systemd.services.swarm-bao-granter-role;
on = withNode.systemd.services.swarm-bao-granter-role;
in
(baoSettings withNode).listener ? pod
&& withNode.systemd.services ? swarm-bao-k8s-jwt-policy
&& lib.hasInfix "jwt-k8s" on.script
&& lib.hasInfix "swarm-bao-k8s-jwt-policy" on.serviceConfig.ExecStartPost
&& withNode.networking.firewall.interfaces ? cni0
&& !((baoSettings allLocal).listener ? pod)
&& !(allLocal.systemd.services ? swarm-bao-k8s-jwt-policy)
&& !(lib.hasInfix "jwt-k8s" off.script)
&& !(lib.hasInfix "swarm-bao-k8s-jwt-policy" off.serviceConfig.ExecStartPost)
&& lib.hasInfix "swarm-bao-operator-viewer-policy" off.serviceConfig.ExecStartPost
&& !(allLocal.networking.firewall.interfaces ? cni0)
&& !(allLocal.networking.firewall.interfaces ? "flannel.1");
}
{
# Pods log in on a listener that asks for no client certificate, and no
# other listener has lost the requirement.
name = "the pods' listener asks for no client certificate and every other API listener still does";
ok =
let
l = (baoSettings withNode).listener;
others = removeAttrs l [
"metrics"
"ui"
"pod"
];
in
l.pod.type == "tcp"
&& l.pod.address == "${withNode.services.hyperhive.network.bridgeIp}:8208"
&& l.pod.cluster_address == "127.0.0.1:8209"
&& l.pod ? tls_cert_file
&& l.pod.tls_client_ca_file == l.loopback.tls_client_ca_file
&& !(l.pod ? tls_require_and_verify_client_cert)
&& others ? loopback
&& lib.all (x: (x.tls_require_and_verify_client_cert or false) == true) (lib.attrValues others);
}
{
# An agent on the hive bridge reaches a port only if the bridge's own
# firewall lists it, so the port's absence there is the whole of its
# isolation. The bridge's listed ports are the control: they hold the
# store's other port.
name = "the pods' port is open on the pod network's interfaces and on no other, and not on the hive bridge";
ok =
let
fw = withNode.networking.firewall;
portsOn = i: fw.interfaces.${i}.allowedTCPPorts or [ ];
cni = withNode.services.hyperhive.deploy.k8s.cniInterfaces;
in
cni == [
"cni0"
"flannel.1"
]
&& lib.all (i: lib.elem 8208 (portsOn i)) cni
&& lib.all (i: lib.elem i cni || !(lib.elem 8208 (portsOn i))) (lib.attrNames fw.interfaces)
&& lib.elem 8200 (bridgePorts withNode)
&& lib.elem 443 (bridgePorts withNode)
&& !(lib.elem 8208 (bridgePorts withNode))
&& !(lib.elem 8208 fw.allowedTCPPorts)
&& !(lib.elem 8208 withNode.services.hyperhive.network.exposeHostPorts);
}
];
in
runGroup "k8s" cases