Watch
0
0
Fork
You've already forked hyperhive
0

keep the container's secret key through the pod's first start

Grafana wraps the data keys of its database with secret_key, and a different
key makes them undecryptable, which grafana cli's re-encrypt cannot repair
(it decrypts with the current key first). So the init container takes the
store's key, else the file the container generated, else a new key, and a new
key only over a database that holds no data_keys row; otherwise it exits
non-zero naming the leaf. The file reaches it read-only through a claim on a
static local volume, because the namespace refuses a hostPath.
This commit is contained in:
atlas 2026-11-28 00:21:37 +01:00
commit bd0cff47f9
2 changed files with 429 additions and 91 deletions

View file

@ -1,45 +1,67 @@
# The store's value for Grafana's datasource-encryption key, seeded once from
# the file an earlier release generated in the container.
#
# Grafana cannot read datasource secrets encrypted with another key, so a store
# with no value takes the file's, and a new key is minted only when there is no
# file either. The store is written with `-cas=0`, so a value it holds is never
# replaced and a lost race reads the winner's back. The file stays, unused.
# Grafana cannot read datasource secrets encrypted with another key: it wraps
# the data keys in its `data_keys` table with this one. So a store with no
# value takes the file's, and a new key is minted only when there is no file
# either and the database holds no data key. A database that does hold one has
# been encrypted under a key this run cannot name, so a new key would make
# every secret in it unreadable, and the helper refuses instead of minting.
#
# The store is written with `-cas=0`, so a value it holds is never replaced and
# a lost race reads the winner's back. The file stays, unused.
#
# `grafana_secret_key` sets `GRAFANA_KEY` and returns 0, or returns 1 when the
# store does not log in, answer or take a value; nothing is minted then.
# store does not answer or take a value, or when the refusal applies; nothing is
# minted then, and the reason is on stderr.
#
# Pure function — NOT a NixOS module. Call it from a unit's `script`, with
# `bao` and `coreutils` on its `path` and the `BAO_*` client environment set:
# Pure function — NOT a NixOS module. Call it from a script that has logged in
# (`BAO_TOKEN` set), with `bao`, `coreutils`, `grep`, `openssl` and `sqlite3`
# on its `PATH`:
#
# script = ''
# ${import ./lib/grafana-secret-key.nix { }}
# grafana_secret_key secret/swarm/services/foo/secret-key /path/to/seed openssl rand -hex 32 || exit 1
# grafana_secret_key secret/swarm/services/foo/secret-key /path/to/seed /path/to/grafana.db openssl rand -hex 32 || exit 1
# '';
{ }:
''
# <store leaf> <seed file> <mint command…>
# <store leaf> <seed file> <database> <mint command…>
grafana_secret_key() {
local leaf="$1" seed="$2" candidate err
shift 2
local leaf="$1" seed="$2" db="$3" candidate err rows readerr
shift 3
GRAFANA_KEY=""
err="$(mktemp)"
if ! BAO_TOKEN="$(bao login -method=cert -token-only 2>"$err")"; then
cat "$err" >&2
rm -f "$err"
echo "could not log in to the swarm secret store." >&2
return 1
fi
export BAO_TOKEN
if ! GRAFANA_KEY="$(bao kv get -field=value "$leaf" 2>"$err")" || [ -z "$GRAFANA_KEY" ]; then
readerr="$(cat "$err")"
if [ -s "$seed" ]; then
candidate="$(tr -d '\n' < "$seed")"
echo "storing the key at $seed in $leaf."
else
# Read-only and immutable: the pod's Grafana is not running yet, and
# a journal left by an earlier crash is none of this check's to replay.
rows=0
if [ -e "$db" ]; then
if ! rows="$(sqlite3 -readonly "file:$db?immutable=1" 'SELECT count(*) FROM data_keys;' 2>"$err")"; then
if grep -q 'no such table' "$err"; then
rows=0
else
cat "$err" >&2
rm -f "$err"
echo "could not read $db to tell whether it holds encrypted data, and $leaf holds no key; minting nothing." >&2
GRAFANA_KEY=""
return 1
fi
fi
fi
if [ "$rows" != 0 ]; then
rm -f "$err"
echo "refusing to mint a datasource encryption key: $db holds $rows data key(s), which only the key it was created under can decrypt, $leaf holds no key (or did not answer) and there is no earlier key file at $seed (the store said: $readerr). Store that key at $leaf, or remove the database." >&2
GRAFANA_KEY=""
return 1
fi
candidate="$("$@")"
echo "no earlier key; minting one in $leaf."
echo "no earlier key and no encrypted data; minting one in $leaf."
fi
if ! printf '%s' "$candidate" | bao kv put -cas=0 "$leaf" value=- >/dev/null 2>"$err"; then
cat "$err" >&2

View file

@ -312,6 +312,7 @@ let
autheliaUrl = toString hyperhiveCfg.swarm.authelia.url;
k8sCfg = hyperhiveCfg.k8s;
labels = import ./k8s/labels.nix;
inherit (import ../images { inherit pkgs lib; }) mkServiceImage;
storeAuth = import ./lib/store-auth.nix;
podAuth = import ./lib/bao-pod-auth.nix;
@ -362,13 +363,24 @@ let
# path outside it answers 403 rather than a miss, however correct it looks.
storeSecretPath = "secret/swarm/services/${cfg.oidc.clientId}/oidc/client";
# Grafana's datasource-encryption key. Created once in the store by the init
# container, which `swarm-bao.nix`'s `grafanaOidcReaders` grants create and
# read on this one leaf. Rotating it does not re-encrypt what it already
# encrypted, so a different key leaves Grafana unable to read its stored
# datasource secrets.
# Grafana's datasource-encryption key. Stored once in the store by the init
# container, which `swarm-bao-readers.nix`'s `grafanaOidcReaders` grants create
# and read on this one leaf. It wraps the data keys of Grafana's database, and
# rotating it does not re-encrypt them, so a different key leaves Grafana
# unable to read what the first one encrypted: the order of what the init
# container stores is in ./lib/grafana-secret-key.nix.
secretKeyStorePath = "secret/swarm/services/${cfg.oidc.clientId}/secret-key";
secretKeyPath = "${secretDir}/secret-key";
# The key an earlier release generated in the container, as the host sees it:
# the seed for an empty leaf. Once every host's leaf is filled it has no
# reader, and this volume, the helper's seed branch and the mount go with it. It sits beside the data directory, so the pod
# reads it through a volume of its own, read-only and in the init container
# only (the namespace's Pod Security level refuses a `hostPath`).
legacyKeyDir = "/var/lib/nixos-containers/swarm-grafana/var/lib/grafana-secret";
legacyKeyClaim = "${service}-legacy-key";
legacyKeyMount = "/legacy-secret-key";
databasePath = "${dataDir}/grafana.db";
grafanaSecretKey = import ./lib/grafana-secret-key.nix { };
# The built-in `admin` account's password. Grafana's API takes basic auth
# whatever the login form says, so this account is reachable from the public
@ -450,6 +462,7 @@ let
pkgs.gnugrep
pkgs.jq
pkgs.openssl
pkgs.sqlite
];
# Logs in with the pod's ServiceAccount token, under the role the pod's
@ -466,8 +479,9 @@ let
fetch = pkgs.writeShellScriptBin "swarm-grafana-fetch" ''
export PATH=${lib.makeBinPath tools}
set -euo pipefail
umask 0277
umask 0227
${login}
${grafanaSecretKey}
d=${lib.escapeShellArg secretDir}
put() {
@ -496,10 +510,16 @@ let
echo "swarm-bao holds nothing at ${storeSecretPath}; Grafana has no OIDC client secret yet." >&2
exit 1
fi
# Each value is read into a variable first: an `exit` inside a command
# substitution in an argument ends only the substitution, and `put` would
# write an empty file.
put ${lib.escapeShellArg "${cfg.oidc.clientId}.secret"} "$oidc"
put admin-password "$(seeded ${lib.escapeShellArg adminPasswordStorePath})"
put metrics-bearer "Bearer $(seeded ${lib.escapeShellArg metricsBearerStorePath})"
put secret-key "$(seeded ${lib.escapeShellArg secretKeyStorePath})"
admin="$(seeded ${lib.escapeShellArg adminPasswordStorePath})"
put admin-password "$admin"
bearer="$(seeded ${lib.escapeShellArg metricsBearerStorePath})"
put metrics-bearer "Bearer $bearer"
grafana_secret_key ${lib.escapeShellArg secretKeyStorePath} ${lib.escapeShellArg "${legacyKeyMount}/secret_key"} ${lib.escapeShellArg databasePath} openssl rand -hex 32 || exit 1
put secret-key "$GRAFANA_KEY"
echo "Grafana's secrets are in $d"
'';
@ -1178,17 +1198,27 @@ let
# The init container and the sidecar log in as the pod does, with the
# environment and mounts of Grafana's container.
#
# The init container also reads two things of the container this pod
# replaces, both read-only: the key it generated (a volume of its own, on the
# directory beside the data directory) and the data directory, to see whether
# the carried database already holds encrypted data. It runs as the uid that
# container ran under, because that user owns the key file (mode 0600, in a
# directory of 0700) and the database; its files in the pod's secret volume
# are group-readable by the pod's group, which Grafana reads them through.
pod =
{
env,
volumeMounts,
securityContext,
metaFor,
...
}:
let
ref = "${setupImage.imageName}:${setupImage.imageTag}";
container = name: bin: {
inherit name securityContext;
container = name: bin: mounts: extra: {
inherit name;
securityContext = securityContext // (extra.securityContext or { });
image = ref;
imagePullPolicy = "IfNotPresent";
command = [ "/bin/${bin}" ];
@ -1196,20 +1226,72 @@ let
name = n;
value = v;
}) (lib.filterAttrs (n: _: lib.hasPrefix "BAO_" n) env // { HOME = "/tmp"; });
volumeMounts = lib.filter (
m:
lib.elem m.name [
"credentials"
"bao-token"
"runtime"
"tmp"
]
) volumeMounts;
volumeMounts =
lib.filter (
m:
lib.elem m.name [
"credentials"
"bao-token"
"runtime"
"tmp"
]
) volumeMounts
++ mounts;
};
readOnlyState = map (m: m // { readOnly = true; }) (lib.filter (m: m.name == "state") volumeMounts);
in
{
initContainers = [ (container "fetch-secrets" "swarm-grafana-fetch") ];
containers = [ (container "controller-token" "swarm-grafana-controller-token") ];
initContainers = [
(container "fetch-secrets" "swarm-grafana-fetch" (
readOnlyState
++ [
{
name = "legacy-key";
mountPath = legacyKeyMount;
readOnly = true;
}
]
) { securityContext.runAsUser = config.ids.uids.grafana; })
];
containers = [ (container "controller-token" "swarm-grafana-controller-token" [ ] { }) ];
volumes = [
{
name = "legacy-key";
persistentVolumeClaim = {
claimName = legacyKeyClaim;
readOnly = true;
};
}
];
# A static local volume on the key's directory: the namespace's Pod
# Security level admits a claim and refuses a `hostPath`. Pinned to the
# node that holds Grafana's data, as the data volume is.
objects = {
"${legacyKeyClaim}/persistentvolume" = {
apiVersion = "v1";
kind = "PersistentVolume";
metadata = removeAttrs (metaFor legacyKeyClaim) [ "namespace" ];
spec = {
capacity.storage = "1Mi";
accessModes = [ "ReadOnlyMany" ];
persistentVolumeReclaimPolicy = "Retain";
storageClassName = legacyKeyClaim;
local.path = legacyKeyDir;
nodeAffinity = labels.stateAffinity "grafana";
};
};
"${legacyKeyClaim}/persistentvolumeclaim" = {
apiVersion = "v1";
kind = "PersistentVolumeClaim";
metadata = metaFor legacyKeyClaim;
spec = {
accessModes = [ "ReadOnlyMany" ];
resources.requests.storage = "1Mi";
storageClassName = legacyKeyClaim;
volumeName = legacyKeyClaim;
};
};
};
images = [ setupImage ];
};
in
@ -1469,7 +1551,12 @@ in
# The pod's volume is Grafana's data directory, which the rule makes when it
# is missing. It leaves an existing directory's owner and mode alone: the
# pod's group is given the tree when the pod starts.
systemd.tmpfiles.rules = [ "d ${hostDataDir} - - - -" ];
# pod's group is given the tree when the pod starts. The directory of the
# earlier key is made the same way, because the volume on it needs the path
# to exist.
systemd.tmpfiles.rules = [
"d ${hostDataDir} - - - -"
"d ${legacyKeyDir} - - - -"
];
};
}