From bd0cff47f9206112425f24b4ed11dc29534a9f9e Mon Sep 17 00:00:00 2001 From: atlas Date: Sat, 28 Nov 2026 00:21:37 +0100 Subject: [PATCH] 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. --- docs/4-implementation/k8s/runtime.md | 33 ++++- nix/host-modules/lib/grafana-secret-key.nix | 62 ++++++--- nix/host-modules/swarm-grafana.nix | 135 ++++++++++++++++---- nix/module-eval/core-toggle.nix | 2 +- nix/module-eval/grafana.nix | 54 ++++++-- nix/module-eval/k8s.nix | 36 ++++++ nix/script-tests/grafana-secret-key.nix | 20 +-- nix/script-tests/grafana-secret-key.sh | 64 ++++++++-- nix/vm-tests/k8s-services.nix | 118 ++++++++++++++++- 9 files changed, 431 insertions(+), 93 deletions(-) diff --git a/docs/4-implementation/k8s/runtime.md b/docs/4-implementation/k8s/runtime.md index aa86a80e2..12e959c4f 100644 --- a/docs/4-implementation/k8s/runtime.md +++ b/docs/4-implementation/k8s/runtime.md @@ -549,13 +549,32 @@ dials the pod's ClusterIP Service by name, as the stores' vhosts do, so which covers a database migration after an upgrade. - **The init container.** `fetch-secrets` logs in to the secret store with the pod's ServiceAccount token under the jwt role `swarm-grafana-oidc`, and writes - four files, mode 0400, to the pod's in-memory `runtime` volume: the OIDC client - secret, the administrator password, the bearer of the datasources and the - datasource encryption key. It reads the client secret from - `swarm/services//oidc/client`, which authelia's mint stores, and - exits non-zero when the store holds none, so the pod waits in `Init` and retries - until the mint has written it. The other three it creates when the store holds - none (a lost race reads the winner's value) and never replaces. + four files, mode 0440 and group-readable by the pod's group, to the pod's + in-memory `runtime` volume: the OIDC client secret, the administrator password, + the bearer of the datasources and the datasource encryption key. It reads the + client secret from `swarm/services//oidc/client`, which authelia's + mint stores, and exits non-zero when the store holds none, so the pod waits in + `Init` and retries until the mint has written it. The administrator password and + the bearer it creates when the store holds none (a lost race reads the winner's + value) and never replaces. The next item gives the order for the encryption key. +- **The encryption key.** Grafana wraps the data keys in its database's + `data_keys` table with this key, and only the key that made a database + decrypts them, so the init container never makes a new key for a + database that holds any. It takes, in this order: the store's value at + `swarm/services//secret-key`; else the file the earlier container + generated at `/var/lib/nixos-containers/swarm-grafana/var/lib/grafana-secret/secret_key`, + which it stores in the leaf; else a new key, stored the same way, but only when + the carried `grafana.db` is absent or holds no data key. With a database that + holds data keys, no file and an empty leaf, it exits non-zero and prints the + cause and the leaf: the fix is to store the key that made that database + at the leaf. It writes every value with `-cas=0`, so a later start reads the + store's. The file reaches the init container read-only, through a claim on a + static local volume on its directory (`swarm-grafana-legacy-key`, pinned like + the data volume), because the namespace's Pod Security level refuses a + `hostPath`; the init container also mounts the data directory read-only, and + runs as the uid that owns both (the container's `grafana` user). `sqlite3` + reads the database read-only and immutable. The file seeds a leaf that's + still empty: once every host's leaf holds a key, nothing reads it. - **Rotation.** Grafana reads the four files once, when it starts. A replaced OIDC client secret, administrator password or bearer takes effect when the pod restarts: `kubectl -n hyperhive rollout restart deployment/swarm-grafana`. No diff --git a/nix/host-modules/lib/grafana-secret-key.nix b/nix/host-modules/lib/grafana-secret-key.nix index fffcac83c..05d51ae5a 100644 --- a/nix/host-modules/lib/grafana-secret-key.nix +++ b/nix/host-modules/lib/grafana-secret-key.nix @@ -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 # ''; { }: '' - # + # 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 diff --git a/nix/host-modules/swarm-grafana.nix b/nix/host-modules/swarm-grafana.nix index afd479d5c..ec418840c 100644 --- a/nix/host-modules/swarm-grafana.nix +++ b/nix/host-modules/swarm-grafana.nix @@ -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} - - - -" + ]; }; } diff --git a/nix/module-eval/core-toggle.nix b/nix/module-eval/core-toggle.nix index e8ec0bc0a..e6cebd19a 100644 --- a/nix/module-eval/core-toggle.nix +++ b/nix/module-eval/core-toggle.nix @@ -1298,7 +1298,7 @@ let in ds.jsonData.httpHeaderName1 == "Authorization" && ds.secureJsonData.httpHeaderValue1 == "$__file{/run/grafana-secrets/metrics-bearer}" - && lib.hasInfix "put metrics-bearer \"Bearer $(seeded secret/${leaf})\"" fetch + && lib.hasInfix "bearer=\"$(seeded secret/${leaf})\"\nput metrics-bearer \"Bearer $bearer\"" fetch && builtins.elem leaf (lib.findFirst (c: c.name == "grafana-auth") null metricsPod.containers).args && lib.hasInfix "path \"secret/data/${leaf}\" {\n capabilities = [\"read\"]\n}" s.swarm-bao-metrics-auth-policy.script && lib.hasInfix "path \"secret/data/${leaf}\" {\n capabilities = [\"create\", \"read\"]\n}" s.swarm-bao-grafana-oidc-policy.script; diff --git a/nix/module-eval/grafana.nix b/nix/module-eval/grafana.nix index b24b36976..5f87b8e47 100644 --- a/nix/module-eval/grafana.nix +++ b/nix/module-eval/grafana.nix @@ -282,7 +282,7 @@ let start = r.scripts.start; in lib.hasInfix "bao kv put -cas=0 \"$1\" value=-" init - && lib.hasInfix "put admin-password \"$(seeded secret/swarm/services/swarm-grafana/admin/password)\"" init + && lib.hasInfix "admin=\"$(seeded secret/swarm/services/swarm-grafana/admin/password)\"\nput admin-password \"$admin\"" init && lib.hasInfix "openssl rand -hex 32" init && r.settings.security.admin_password == "$__file{/run/grafana-secrets/admin-password}" && lib.hasInfix "admin reset-admin-password --password-from-stdin < /run/grafana-secrets/admin-password" start @@ -291,22 +291,50 @@ let } { # Grafana's datasource-encryption key reaches Grafana from the store. A - # different key leaves Grafana unable to read its stored datasource - # secrets, so the store's value wins, `-cas=0` never replaces one, and a - # lost race reads the winner's back. No file of an earlier release is - # read: a host that never held a stored key gets a new one, and the - # provisioned datasources are written again at start. - name = "grafana's datasource key is created in the store once and delivered from the pod's memory"; + # different key leaves Grafana unable to read what the key it was + # created under encrypted (the data keys in its database), so the + # store's value wins, then the file the container generated, and a new + # key is minted only when there is neither and the database holds no + # data key. `-cas=0` never replaces a value, and a lost race reads the + # winner's back. The file is read from the pod's read-only mount and + # nothing writes it. + name = "grafana's datasource key is the store's, else the earlier container's file, else a new one only over a database with no data keys, and the file is only read"; ok = let r = rendered grafanaRemoteAuthelia; init = r.scripts.fetch; + at = needle: lib.stringLength (lib.head (lib.splitString needle init)); + call = "grafana_secret_key secret/swarm/services/swarm-grafana/secret-key /legacy-secret-key/secret_key /var/lib/grafana/grafana.db openssl rand -hex 32 || exit 1"; + # The helper's text is part of the script: store, then file, then + # the check of the database, then the mint. + readStore = "bao kv get -field=value \"$leaf\""; + readFile = "tr -d '\\n' < \"$seed\""; + readDb = "sqlite3 -readonly \"file:$db?immutable=1\" 'SELECT count(*) FROM data_keys;'"; + mint = "candidate=\"$(\"$@\")\""; + legacyUses = lib.length (lib.splitString "/legacy-secret-key" init) - 1; in - lib.hasInfix "put secret-key \"$(seeded secret/swarm/services/swarm-grafana/secret-key)\"" init - && lib.hasInfix "value=\"$(stored \"$1\")\"" init + lib.hasInfix call init + && lib.hasInfix "put secret-key \"$GRAFANA_KEY\"" init + && at readStore < at readFile + && at readFile < at readDb + && at readDb < at mint + && lib.hasInfix "refusing to mint a datasource encryption key" init + && lib.hasInfix "if [ \"$rows\" != 0 ]; then" init + && lib.hasInfix "return 1" init + && lib.hasInfix "no such table" init + && lib.hasInfix "kv put -cas=0 \"$leaf\" value=-" init + # The earlier file is named once, as the call's argument, and the + # script has no command that writes, moves or removes it. + && legacyUses == 1 + && !(lib.hasInfix "/var/lib/nixos-containers" init) + && !(lib.hasInfix "rm -f \"$seed\"" init) + && !(lib.hasInfix "> \"$seed\"" init) && r.settings.security.secret_key == "$__file{/run/grafana-secrets/secret-key}" - && !(lib.hasInfix "/var/lib/grafana-secret" init) - && !(lib.any (lib.hasInfix "/var/lib/grafana-secret") grafanaRemoteAuthelia.systemd.tmpfiles.rules); + # The directory the read-only volume sits on has to exist. + && lib.elem "d /var/lib/nixos-containers/swarm-grafana/var/lib/grafana-secret - - - -" grafanaRemoteAuthelia.systemd.tmpfiles.rules + && !(lib.any (lib.hasInfix "/var/lib/grafana-secret") ( + lib.filter (lib.hasPrefix "r ") grafanaRemoteAuthelia.systemd.tmpfiles.rules + )); } { # swarm-controller reads alerts with this token, so the account it @@ -389,8 +417,8 @@ let persistent = s: lib.hasInfix "/var/lib/nixos-containers" s || lib.hasInfix "/var/lib/grafana-" s; in lib.hasInfix "put swarm-grafana.secret \"$oidc\"" init - && lib.hasInfix "put metrics-bearer \"Bearer $(seeded secret/swarm/services/swarm-grafana/metrics/bearer)\"" init - && lib.hasInfix "umask 0277" init + && lib.hasInfix "bearer=\"$(seeded secret/swarm/services/swarm-grafana/metrics/bearer)\"\nput metrics-bearer \"Bearer $bearer\"" init + && lib.hasInfix "umask 0227" init && lib.hasInfix "d=/run/grafana-secrets" init && !(persistent init) && !(persistent r.scripts.controllerToken) diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix index c7c64a6bb..2b1fc27bc 100644 --- a/nix/module-eval/k8s.nix +++ b/nix/module-eval/k8s.nix @@ -2890,6 +2890,42 @@ let && hasInfix "auth/jwt-k8s/role/swarm-grafana-oidc" script && hasInfix "bound_subject=system:serviceaccount:hyperhive:swarm-grafana" script && lib.elem "swarm-grafana-oidc" withNode.services.hyperhive.deploy.bao.k8sPrincipals + # The earlier container's key file and the carried database reach the init + # container alone, read-only: the file through a claim on a static local + # volume (a `hostPath` is refused at this namespace's Pod Security + # level), the database through the data volume's own mount. The init + # container runs as the uid that owns them and as non-root. + && + (lib.findFirst (m: m.name == "legacy-key") null init.volumeMounts) == { + name = "legacy-key"; + mountPath = "/legacy-secret-key"; + readOnly = true; + } + && (lib.findFirst (m: m.name == "state") null init.volumeMounts).readOnly + && !(lib.elem "legacy-key" (mountsOf main)) + && !(lib.elem "legacy-key" (mountsOf side)) + && !((lib.findFirst (m: m.name == "state") null side.volumeMounts) != null) + && + (lib.findFirst (v: v.name == "legacy-key") null spec.volumes) == { + name = "legacy-key"; + persistentVolumeClaim = { + claimName = "swarm-grafana-legacy-key"; + readOnly = true; + }; + } + && !(lib.any (v: v ? hostPath) spec.volumes) + && + objects."swarm-grafana-legacy-key/persistentvolume".spec.local.path + == "/var/lib/nixos-containers/swarm-grafana/var/lib/grafana-secret" + && + objects."swarm-grafana-legacy-key/persistentvolume".spec.nodeAffinity.required.nodeSelectorTerms + != [ ] + && + objects."swarm-grafana-legacy-key/persistentvolumeclaim".spec.volumeName + == "swarm-grafana-legacy-key" + && init.securityContext.runAsUser == 196 + && init.securityContext.runAsNonRoot + && !(side.securityContext ? runAsUser) # The listener credential comes from the Secret the host publishes. && lib.any (s: (s.secret.name or null) == "swarm-grafana-credentials") credentials.projected.sources # The Service and the policy: only the node in, and out to DNS, the diff --git a/nix/script-tests/grafana-secret-key.nix b/nix/script-tests/grafana-secret-key.nix index c94c538c1..ce81cedc7 100644 --- a/nix/script-tests/grafana-secret-key.nix +++ b/nix/script-tests/grafana-secret-key.nix @@ -1,7 +1,7 @@ # `checks.script-test-grafana-secret-key` — runs # ../host-modules/lib/grafana-secret-key.nix's `grafana_secret_key` against a -# stub `bao` that keeps its leaves in files. The cases are in -# ./grafana-secret-key.sh. +# stub `bao` that keeps its leaves in files and a real `sqlite3` over small +# databases. The cases are in ./grafana-secret-key.sh. # # What runs is the rendered helper, sourced as the unit's script includes it. { @@ -9,20 +9,16 @@ ... }: let - # `login` answers from `FAKE_BAO_LOGIN_RC`. `kv get` and `kv put -cas=0` act - # on a file per leaf under `FAKE_BAO_KV`, and answer as bao does: a missing + # `kv get` and `kv put -cas=0` act on a file per leaf under `FAKE_BAO_KV`, and answer as bao does: a missing # leaf is "No value found at " on stderr, status 2. `FAKE_BAO_DENY_READ` - # and `FAKE_BAO_DENY_WRITE` answer 403 as a policy that grants neither does. + # and `FAKE_BAO_DENY_WRITE` answer 403 as a policy that grants neither does. A call without the pod's + # login token (`BAO_TOKEN`, set by the cases) answers 97. # `FAKE_BAO_RACE` has another run create the leaf with that value between # this one's read and its write. Every call is logged without the value # `put` reads from stdin. fakeBao = pkgs.writeShellScriptBin "bao" '' echo "$*" >> "$FAKE_BAO_LOG" case "$1 $2" in - "login -method=cert") - [ "$FAKE_BAO_LOGIN_RC" = 0 ] || { echo "fake bao: certificate refused" >&2; exit 2; } - printf 's.fake' - ;; "kv get") [ "''${BAO_TOKEN-}" = s.fake ] || { echo "fake bao: kv without the login's token" >&2; exit 97; } [ "$3" = -field=value ] || { echo "fake bao: get without -field=value" >&2; exit 95; } @@ -60,7 +56,11 @@ pkgs.runCommand "hyperhive-script-test-grafana-secret-key" import ../host-modules/lib/grafana-secret-key.nix { } ); FAKE_BAO_BIN = "${fakeBao}/bin"; - nativeBuildInputs = [ pkgs.coreutils ]; + nativeBuildInputs = [ + pkgs.coreutils + pkgs.gnugrep + pkgs.sqlite + ]; } '' ${pkgs.bash}/bin/bash ${./grafana-secret-key.sh} diff --git a/nix/script-tests/grafana-secret-key.sh b/nix/script-tests/grafana-secret-key.sh index 061d679ac..b4893efe7 100644 --- a/nix/script-tests/grafana-secret-key.sh +++ b/nix/script-tests/grafana-secret-key.sh @@ -1,7 +1,7 @@ # Cases for ./grafana-secret-key.nix. Each case sets up the store's leaf, the -# seed file and the stub's behaviour, runs `grafana_secret_key` the way the -# unit's script does, and compares its status, the key it hands over and what -# the store holds afterwards. +# seed file, the database and the stub's behaviour, runs `grafana_secret_key` +# the way the init container's script does, and compares its status, the key it +# hands over and what the store holds afterwards. set -uo pipefail failures=0 @@ -12,10 +12,11 @@ setup() { case=$1 dir=$(mktemp -d) mkdir "$dir/kv" - export FAKE_BAO_KV=$dir/kv FAKE_BAO_LOG=$dir/bao.log FAKE_BAO_LOGIN_RC=0 + export FAKE_BAO_KV=$dir/kv FAKE_BAO_LOG=$dir/bao.log unset FAKE_BAO_DENY_READ FAKE_BAO_DENY_WRITE FAKE_BAO_RACE : >"$FAKE_BAO_LOG" seed=$dir/secret_key + db=$dir/grafana.db stored=$FAKE_BAO_KV/$(printf '%s' "$leaf" | tr / _) } @@ -23,15 +24,21 @@ mint() { printf 'minted-key\n' } +# A database as Grafana leaves it: with `data_keys` rows, with the table and no +# rows, or with other tables only. +db_with_keys() { sqlite3 "$db" "CREATE TABLE data_keys (name TEXT); INSERT INTO data_keys VALUES ('a'), ('b');"; } +db_without_rows() { sqlite3 "$db" 'CREATE TABLE data_keys (name TEXT);'; } +db_without_table() { sqlite3 "$db" 'CREATE TABLE other (name TEXT);'; } + # expect expect() { ( PATH="$FAKE_BAO_BIN:$PATH" - unset BAO_TOKEN + export BAO_TOKEN=s.fake # shellcheck source=/dev/null . "$HELPER" rc=0 - grafana_secret_key "$leaf" "$seed" mint >/dev/null 2>"$dir/err" || rc=$? + grafana_secret_key "$leaf" "$seed" "$db" mint >"$dir/out" 2>"$dir/err" || rc=$? printf '%s' "$rc" >"$dir/rc" printf '%s' "$GRAFANA_KEY" >"$dir/key" ) @@ -52,26 +59,57 @@ expect 0 seed-key seed-key grep -q '^kv put -cas=0 ' "$FAKE_BAO_LOG" || fail "no create-only write" [ -e "$seed" ] || fail "the seed file was removed" +setup "an empty store takes the seed's key over a database that holds data keys" +printf 'seed-key\n' >"$seed" +db_with_keys +expect 0 seed-key seed-key + setup "a store that holds a key wins over the seed, and is not written" printf 'seed-key\n' >"$seed" printf 'store-key' >"$stored" expect 0 store-key store-key ! grep -q '^kv put' "$FAKE_BAO_LOG" || fail "wrote to the store" -setup "with no seed and an empty store, a key is minted and stored" +setup "a store that holds a key wins over a database that holds data keys, and is not written" +printf 'store-key' >"$stored" +db_with_keys +expect 0 store-key store-key +! grep -q '^kv put' "$FAKE_BAO_LOG" || fail "wrote to the store" + +setup "with no seed, an empty store and no database, a key is minted and stored" expect 0 minted-key minted-key -setup "a store that refuses the login mints nothing, with or without a seed" -export FAKE_BAO_LOGIN_RC=1 -expect 1 "" "" -printf 'seed-key\n' >"$seed" -expect 1 "" "" +setup "with no seed and an empty store, a database with the table and no rows takes a minted key" +db_without_rows +expect 0 minted-key minted-key -setup "a store that refuses the read stores and hands over nothing" +setup "with no seed and an empty store, a database without the table takes a minted key" +db_without_table +expect 0 minted-key minted-key + +setup "with no seed and an empty store, a database that holds data keys is refused and nothing is minted" +db_with_keys +expect 1 "" "" +grep -q 'refusing to mint' "$dir/err" || fail "the refusal does not say so: $(cat "$dir/err")" +grep -q "$leaf" "$dir/err" || fail "the refusal does not name the leaf" +grep -q '2 data key' "$dir/err" || fail "the refusal does not count the keys" +! grep -q '^kv put' "$FAKE_BAO_LOG" || fail "wrote to the store" + +setup "with no seed and an empty store, a database that cannot be read is refused and nothing is minted" +printf 'this is not a database, and is longer than a page header needs to be to be refused as one\n' >"$db" +expect 1 "" "" +grep -q 'minting nothing' "$dir/err" || fail "the refusal does not say so: $(cat "$dir/err")" + +setup "a store that refuses the read stores the seed and hands over nothing" printf 'seed-key\n' >"$seed" export FAKE_BAO_DENY_READ=1 expect 1 "" seed-key +setup "a store that refuses the read, with a database that holds data keys and no seed, mints nothing" +db_with_keys +export FAKE_BAO_DENY_READ=1 +expect 1 "" "" + setup "a store that refuses the write hands over nothing" export FAKE_BAO_DENY_WRITE=1 expect 1 "" "" diff --git a/nix/vm-tests/k8s-services.nix b/nix/vm-tests/k8s-services.nix index 4e2bd2ee3..8757867d0 100644 --- a/nix/vm-tests/k8s-services.nix +++ b/nix/vm-tests/k8s-services.nix @@ -95,6 +95,12 @@ let stubPort = 1443; legacyGrafanaUser = "legacy-grafana"; legacyGrafanaPort = 19430; + # The key the container generated, beside its data directory, and the value + # of a datasource secret the legacy database holds encrypted under it. A + # fixed fixture, not a secret. + legacyKeyDir = "/var/lib/nixos-containers/swarm-grafana/var/lib/grafana-secret"; + legacyKeyFile = "${legacyKeyDir}/secret_key"; + legacyDatasourceSecret = "legacy-datasource-secret"; # One nginx with the log and metrics stores' locations as the modules render # them: the Services they dial, the responders they check a bearer with and @@ -182,6 +188,7 @@ let # expects, and the points the body carried. tokenStub = pkgs.writeText "token-stub.py" '' import base64 + import hashlib import http.server import json import secrets @@ -242,6 +249,7 @@ let "host": self.headers.get("Host"), "path": path, "forge_token_ok": self.headers.get("Authorization") == "token ${forgeToken}", + "legacy_header_sha256": hashlib.sha256(self.headers["X-Legacy"].encode()).hexdigest() if self.headers.get("X-Legacy") else None, }) if path.endswith("/repos/search"): self.reply({"ok": True, "data": [{"full_name": "o/r", "has_actions": True, "archived": False, "mirror": False}]}) @@ -552,10 +560,15 @@ pkgs.testers.runNixOSTest { # What the dashboard's container left on the host: its data directory # with a database created under Grafana's default administrator, holding - # one annotation. The pinned binary writes it as a user of its own. + # one annotation and one datasource with a secret, encrypted under the key + # the container generated in a directory of its own (0700, the file 0600). + # The pinned binary writes them as a user of its own. users.users.${legacyGrafanaUser} = { isSystemUser = true; group = legacyGrafanaUser; + # The uid the container's Grafana ran under, which owns the key file + # and the database as the host sees them. + uid = config.ids.uids.grafana; }; users.groups.${legacyGrafanaUser} = { }; systemd.services.grafana-legacy = { @@ -566,6 +579,7 @@ pkgs.testers.runNixOSTest { pkgs.coreutils pkgs.findutils pkgs.gnugrep + pkgs.openssl ]; serviceConfig = { Type = "oneshot"; @@ -579,6 +593,9 @@ pkgs.testers.runNixOSTest { mkdir -p ${grafanaDir} chown ${legacyGrafanaUser}:${legacyGrafanaUser} ${grafanaDir} chmod 0700 ${grafanaDir} + mkdir -p ${legacyKeyDir} + chown ${legacyGrafanaUser}:${legacyGrafanaUser} ${legacyKeyDir} + chmod 0700 ${legacyKeyDir} ''}"; RuntimeDirectory = "grafana-legacy"; }; @@ -596,6 +613,12 @@ pkgs.testers.runNixOSTest { }; script = '' store=http://127.0.0.1:${toString legacyGrafanaPort} + # The container generated the key on its first boot, and Grafana read it + # from the file: the same here, so the database is encrypted under it. + if [ ! -s ${legacyKeyFile} ]; then + (umask 077; openssl rand -hex 32 > ${legacyKeyFile}) + fi + export GF_SECURITY_SECRET_KEY="$(tr -d '\n' < ${legacyKeyFile})" pkg=${config.services.hyperhive.deploy.grafana.package} ${lib.getExe' config.services.hyperhive.deploy.grafana.package "grafana"} server \ --homepath $pkg/share/grafana & @@ -604,6 +627,13 @@ pkgs.testers.runNixOSTest { # The default administrator of a database made without the setting. code=$(curl -s -o /dev/null -w '%{http_code}' -u admin:admin -H 'Content-Type: application/json' \ -d '{"text":"written before the switch","tags":["legacy"]}' $store/api/annotations) + # A datasource with a secret, which Grafana stores encrypted in a data + # key wrapped by the key above. It points at the identity provider's + # stand-in, which records what the secret decrypts to. + code2=$(curl -s -o /dev/null -w '%{http_code}' -u admin:admin -H 'Content-Type: application/json' \ + -d '{"name":"legacy-secret-ds","uid":"legacy-secret-ds","type":"prometheus","access":"proxy","url":"https://${authName}","jsonData":{"httpHeaderName1":"X-Legacy"},"secureJsonData":{"httpHeaderValue1":"${legacyDatasourceSecret}"}}' \ + $store/api/datasources) + [ "$code2" = 200 ] || { echo "the datasource post replied $code2"; exit 1; } found= for _ in $(seq 60); do if curl -s -u admin:admin "$store/api/annotations?tags=legacy" | grep -q 'written before the switch'; then @@ -620,6 +650,7 @@ pkgs.testers.runNixOSTest { kill -TERM "$pid" wait "$pid" || true test -s ${grafanaDir}/grafana.db + test -s ${legacyKeyFile} ''; }; @@ -744,9 +775,9 @@ pkgs.testers.runNixOSTest { GRAFANA = "swarm-grafana" GRAFANA_DIR = "${grafanaDir}" GRAFANA_GATEWAY = "http://${grafanaGateway}" - # The only Secrets the cluster holds: the two the host publishes for the - # stores' passwords. - STORE_SECRETS = {f"secret/{VL}-credentials", f"secret/{VM}-credentials"} + # The only Secrets the cluster holds: the three the host publishes for the + # two stores' and Grafana's listener credentials. + STORE_SECRETS = {f"secret/{VL}-credentials", f"secret/{VM}-credentials", "secret/swarm-grafana-credentials"} def other_secrets() -> set[str]: names = machine.succeed(f"kubectl -n {NS} get secrets -o name || true").split() @@ -1786,6 +1817,37 @@ pkgs.testers.runNixOSTest { grafana_ip = kube(machine, f"get pod {grafana_pod} -o jsonpath='{{.status.podIP}}'").strip() GRAFANA_ADMIN = as_root("bao kv get -mount=secret -field=value swarm/services/swarm-grafana/admin/password").strip() + import hashlib + + LEGACY_KEY_FILE = "${legacyKeyFile}" + LEGACY_DATASOURCE_SECRET = "${legacyDatasourceSecret}" + KEY_LEAF = "swarm/services/swarm-grafana/secret-key" + + def sha(value: str) -> str: + """The digest compared where the value itself is never printed.""" + return hashlib.sha256(value.strip().encode()).hexdigest() + + def key_leaf() -> str: + """The store's datasource key, or "" when the leaf holds none.""" + return machine.execute(f'BAO_TOKEN="$(jq -r .root_token {INIT})" bao kv get -mount=secret -field=value {KEY_LEAF} 2>/dev/null')[1].strip() + + def legacy_secret_decrypts() -> bool: + """Whether Grafana decrypts the datasource secret the earlier container + stored, which it does only with the key the database was created + under: the proxy sends it as a header to the identity provider's + stand-in, which records the header's digest.""" + grafana_request("/api/datasources/proxy/uid/legacy-secret-ds/legacy-probe", f"-u admin:{GRAFANA_ADMIN}") + sent = [r for r in requests() if r.get("path") == "/legacy-probe"] + return any(r.get("legacy_header_sha256") == sha(LEGACY_DATASOURCE_SECRET) for r in sent) + + def wait_legacy_secret_decrypts() -> None: + deadline = time.monotonic() + 180 + while not legacy_secret_decrypts(): + if time.monotonic() >= deadline: + print(machine.execute(f"kubectl -n {NS} logs {grafana_pod} -c {GRAFANA} --tail=100 2>&1")[1]) + raise AssertionError("Grafana did not decrypt the datasource secret written before the switch") + time.sleep(3) + with subtest("the dashboard refuses every route without an OIDC session and sends the browser to the identity provider"): # The page and the API refuse a caller with no session. code, target = grafana_head("/") @@ -1813,6 +1875,17 @@ pkgs.testers.runNixOSTest { status, body = grafana_request("/api/annotations?tags=legacy", f"-u admin:{GRAFANA_ADMIN}") assert status == 200 and "written before the switch" in body, (status, body[:300]) + with subtest("the pod adopted the earlier container's key, and decrypts a datasource secret written under it before the switch"): + # The leaf was empty when the pod's init container first ran, and the + # file was there: the store now holds the file's key. + held = key_leaf() + assert held != "" and sha(held) == sha(machine.succeed(f"cat {LEGACY_KEY_FILE}")), "the store does not hold the earlier container's key" + # The file is only read: owner, mode and content are as the container left them. + assert machine.succeed(f"stat -c '%u %a' {LEGACY_KEY_FILE}").strip() == f"{machine.succeed('id -u ${legacyGrafanaUser}').strip()} 600" + secured = json.loads(grafana_request("/api/datasources/uid/legacy-secret-ds", f"-u admin:{GRAFANA_ADMIN}")[1]) + assert secured["secureJsonFields"].get("httpHeaderValue1") is True, secured + wait_legacy_secret_decrypts() + with subtest("the dashboard reads the metrics store through the gateway with its own bearer, and its log datasource is provisioned"): deadline = time.monotonic() + 300 while True: @@ -1830,7 +1903,7 @@ pkgs.testers.runNixOSTest { time.sleep(3) status, body = grafana_request("/api/datasources", f"-u admin:{GRAFANA_ADMIN}") uids = {d["uid"] for d in json.loads(body)} - assert status == 200 and uids == {"swarm-victoriametrics", "swarm-victorialogs"}, (status, uids) + assert status == 200 and uids == {"swarm-victoriametrics", "swarm-victorialogs", "legacy-secret-ds"}, (status, uids) GRAFANA_CONF = f"{STORE_AUTH_DIR}/grafana.conf" GRAFANA_PASSWORD = f"{STORE_AUTH_DIR}/grafana.password" @@ -1916,6 +1989,8 @@ pkgs.testers.runNixOSTest { status, body = grafana_request("/api/prometheus/grafana/api/v1/alerts", f"-H 'Authorization: Bearer {token}'") assert status == 200, (status, body[:200]) assert as_root("bao kv get -mount=secret -field=value swarm/services/swarm-grafana/admin/password").strip() == GRAFANA_ADMIN + # The leaf is filled, so the store's key is the one in use again: the secret written before the switch still decrypts. + wait_legacy_secret_decrypts() with subtest("only the node reaches the dashboard's port, and its pod reaches the secret store and the gateway and no other port of the host"): machine.succeed(f"curl -sf --max-time 5 http://{grafana_ip}:3000/api/health") @@ -1933,6 +2008,39 @@ pkgs.testers.runNixOSTest { status = json.loads(kube(machine, f"get pod {grafana_pod} -o json"))["status"] assert all(c["ready"] for c in status["containerStatuses"]), status + with subtest("an empty leaf, no earlier key file and a database that holds data keys stop the init container with the cause, and nothing is minted; with the file back, the pod adopts it again"): + original = key_leaf() + assert original != "" + as_root(f"bao kv metadata delete secret/{KEY_LEAF}") + assert key_leaf() == "" + machine.succeed(f"mv {LEGACY_KEY_FILE} {LEGACY_KEY_FILE}.moved") + kube(machine, f"delete pod {grafana_pod} --wait=true", timeout=120) + deadline = time.monotonic() + 300 + while True: + pods = service_pods(GRAFANA) + logs = machine.execute(f"kubectl -n {NS} logs {pods[0].removeprefix('pod/')} -c fetch-secrets 2>&1")[1] if pods else "" + if "refusing to mint a datasource encryption key" in logs: + break + if time.monotonic() >= deadline: + print(logs) + print(machine.execute(f"kubectl -n {NS} describe pod {pods[0].removeprefix('pod/')} 2>&1")[1] if pods else "no pod") + raise AssertionError("the init container did not refuse") + time.sleep(3) + stuck = pods[0].removeprefix("pod/") + # The message names the leaf and the database, and holds no key. + assert KEY_LEAF in logs and "grafana.db" in logs, logs + assert original not in logs and sha(original) not in logs + # Nothing is minted, and the pod does not start Grafana without a key. + assert key_leaf() == "" + status = json.loads(kube(machine, f"get pod {stuck} -o json"))["status"] + assert status["phase"] == "Pending" and not any(c.get("state", {}).get("running") for c in status.get("containerStatuses", [])), status + # Back with the file, the init container adopts it and Grafana decrypts again. + machine.succeed(f"mv {LEGACY_KEY_FILE}.moved {LEGACY_KEY_FILE}") + grafana_pod = wait_pod_ready(GRAFANA, timeout=900) + grafana_ip = kube(machine, f"get pod {grafana_pod} -o jsonpath='{{.status.podIP}}'").strip() + assert sha(key_leaf()) == sha(original) + wait_legacy_secret_decrypts() + with subtest("the poller's Job completes against the forge and pushes the run to the poller's own route with a token the identity provider minted"): tokens_before = int(machine.succeed(f"grep -cF '/api/oidc/token ${ci}:{CI_SECRET}' ${tokenLog} || true")) job_log = ci_job(f"{CI}-first")