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

View file

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