From 9f62e71dae16d1d173822f75e6f6c3d0d35f9cbd Mon Sep 17 00:00:00 2001 From: atlas Date: Fri, 27 Nov 2026 22:51:25 +0100 Subject: [PATCH] run grafana as a pod in the cluster The Deployment swarm-grafana replaces the swarm-grafana container: one replica on a static local volume that is the container's data directory, an init container that fetches the OIDC client secret and creates the administrator password, the datasources' bearer and the encryption key in the secret store, and a sidecar that keeps the controller's Viewer token. The datasources reach the stores through the gateway with that bearer, and Grafana's /metrics asks for the stores' kind of credential, which the vhost sends. The five host units, the journal forwarder, its client glue and the unix-socket directory go with the container. --- docs/2-handbook/swarm/services.md | 6 +- docs/2-handbook/swarm/sso.md | 14 +- docs/4-implementation/k8s/manifests.md | 23 +- docs/4-implementation/k8s/node.md | 2 +- docs/4-implementation/k8s/runtime.md | 74 + .../swarm/credential-delivery.md | 26 +- .../swarm/credentials-reference.md | 24 +- docs/4-implementation/swarm/telemetry.md | 38 +- nix/host-modules/default.nix | 1 - .../glue-attic-otel-oidc-client.nix | 2 +- .../glue-bao-readers-policy-order.nix | 28 +- .../glue-bao-readers-store-order.nix | 6 - .../glue-grafana-otel-oidc-client.nix | 37 - nix/host-modules/k8s/node.nix | 4 +- nix/host-modules/k8s/render.nix | 32 + nix/host-modules/k8s/store-credentials.nix | 19 +- nix/host-modules/lib/store-auth.nix | 7 +- nix/host-modules/swarm-bao-readers.nix | 31 +- nix/host-modules/swarm-bao.nix | 17 +- nix/host-modules/swarm-ci-runner.nix | 2 +- nix/host-modules/swarm-controller.nix | 4 +- nix/host-modules/swarm-grafana-service.nix | 37 +- nix/host-modules/swarm-grafana.nix | 2375 +++++++---------- nix/host-modules/swarm-otel-service.nix | 7 +- nix/host-modules/swarm-otel.nix | 2 +- nix/host-modules/swarm-secret-publisher.nix | 3 +- nix/module-eval/bao-grants.nix | 54 +- nix/module-eval/core-toggle.nix | 28 +- nix/module-eval/grafana.nix | 351 ++- nix/module-eval/k8s.nix | 171 +- nix/module-eval/nats-authelia.nix | 20 +- nix/module-eval/secret-publisher.nix | 3 +- nix/module-eval/swarm-services-switch.nix | 57 +- nix/vm-tests/k8s-services.nix | 372 ++- 34 files changed, 1931 insertions(+), 1946 deletions(-) delete mode 100644 nix/host-modules/glue-grafana-otel-oidc-client.nix diff --git a/docs/2-handbook/swarm/services.md b/docs/2-handbook/swarm/services.md index ad4401127..b6a51083e 100644 --- a/docs/2-handbook/swarm/services.md +++ b/docs/2-handbook/swarm/services.md @@ -135,7 +135,11 @@ container, its sockets, secrets and metrics: The swarm's telemetry lands in one VictoriaMetrics, and one Grafana reads it, at `metrics.` and `grafana.`. They run apart so you -can restart or break Grafana without losing the time-series database. +can restart or break Grafana without losing the time-series database. Both +run as pods in the host's cluster, and Grafana keeps its database on the host's +disk. Grafana reads its secrets when its pod starts: after you replace its OIDC +client secret, restart it with +`kubectl -n hyperhive rollout restart deployment/swarm-grafana`. `deploy.victoriametrics.enable` turns [the cluster node](../../4-implementation/k8s/node.md) on with it. Enabling either enables both; to run one alone, set it directly with `deploy.victoriametrics.enable` or `deploy.grafana.enable`. diff --git a/docs/2-handbook/swarm/sso.md b/docs/2-handbook/swarm/sso.md index db19fe658..6a66cb6f1 100644 --- a/docs/2-handbook/swarm/sso.md +++ b/docs/2-handbook/swarm/sso.md @@ -164,14 +164,16 @@ gateway refuses its token too. See [`swarmctl/README.md`](../../../swarmctl/READ one minted into the swarm secret store, not the upstream `admin`. A dead provider locks out the SSO accounts but not that one: an operator reads the password from `swarm/services//admin/password` - in the store (or, as root on the Grafana host, from - `/run/swarm-grafana-secrets/admin-password`) - and calls the API with it. See [`services.md`](services.md#metrics-victoriametrics--grafana) + in the store and calls the API with it. See [`services.md`](services.md#metrics-victoriametrics--grafana) and [`credentials.md`](credentials.md). SSO logins are the everyday way in, which is why `swarm.grafana.oidc.role` defaults to `Admin`. - The three secrets Grafana reads live on the host's tmpfs, so after a reboot - Grafana stays down (no login, no dashboards) until the secret store - answers; the delivery units retry and start it with no manual step. + Grafana runs as a pod in the host's cluster and reads its secrets from the + secret store when the pod starts, so after a reboot Grafana stays down (no + login, no dashboards) until the secret store answers; the pod retries and + starts with no manual step. It reads them once: after you replace its OIDC + client secret, the administrator password or the datasources' bearer in the + store, restart it with + `kubectl -n hyperhive rollout restart deployment/swarm-grafana`. - **It doesn't provision users.** `swarmctl` creates and destroys agents continuously today, so the subject set belongs to a program rather than to a config file. diff --git a/docs/4-implementation/k8s/manifests.md b/docs/4-implementation/k8s/manifests.md index d3547b3e4..5f6b56956 100644 --- a/docs/4-implementation/k8s/manifests.md +++ b/docs/4-implementation/k8s/manifests.md @@ -32,6 +32,7 @@ A service gets manifests on the host whose configuration deploys it: | `swarm-logs-auth` | Deployment | ServiceAccount, two Services, NetworkPolicy | | `swarm-victoriametrics` | Deployment | Service, NetworkPolicy, PersistentVolume and Claim | | `swarm-metrics-auth` | Deployment | ServiceAccount, two Services, NetworkPolicy | +| `swarm-grafana` | Deployment | ServiceAccount, Service, NetworkPolicy, PersistentVolume and Claim | `namespace.yaml` holds the Namespace ([Pod Security](#pod-security)), and `default-deny-ingress/networkpolicy.yaml` its default-deny ingress policy @@ -150,15 +151,17 @@ credential directory. in the container, with a 5-second timeout, and a 503 fails it. The pod declares no port for the listener. `swarm-controller` is one of them, with `SWARM_CONTROLLER_HEALTH_ADDR`. A third-party daemon with no health variable, - `victoria-logs` and `victoria-metrics`, names a `probe` path instead (`/health`), which both probes - request on its listener. A `startupFailureThreshold` in it (`victoria-metrics`, 60) adds a + `victoria-logs`, `victoria-metrics` and `grafana`, names a `probe` path instead (`/health`; `/api/health` for `grafana`), which both probes + request on its listener. A `startupFailureThreshold` in it (`victoria-metrics`, 60, and `grafana`, 30) adds a startup probe on the same path, tried every ten seconds, before the other two begin. The health listener of our own daemons is unreachable from outside the pod: the node, other pods and the bridge get a refusal, so it needs no credential. - The one health route outside the pod is the `/health` of `victoria-logs` and - `victoria-metrics` on their main port. Upstream answers `/health`, `/ping`, - `/-/healthy` and `/-/ready` before it checks `-httpAuth`, and the gateway needs - the main port on the pod's IP, so no bind or probe can close it. It's + The health routes outside the pod are the `/health` of `victoria-logs` and + `victoria-metrics` on their main port, and the `/api/health` and `/healthz` of + Grafana on its own. Upstream answers `/health`, `/ping`, `/-/healthy` and + `/-/ready` before it checks `-httpAuth`, Grafana answers its two before its + login, and the gateway needs the main port on the pod's IP, so no bind or + probe can close them. It's reachable from the node only, through the default-deny ingress policy, and it returns a status and no data. - **Listener and init container:** a service with a TCP `listener` @@ -167,7 +170,7 @@ credential directory. gets an init container and a renewal container that issue its leaf into an `emptyDir` ([runtime](runtime.md#the-controller)). The image of those containers is part of `system.build.k8sImages`. A listener with no `tlsDir` - (`swarm-victorialogs`, `swarm-logs-auth`, `swarm-victoriametrics`, `swarm-metrics-auth`) serves plain HTTP: it gets the + (`swarm-victorialogs`, `swarm-logs-auth`, `swarm-victoriametrics`, `swarm-metrics-auth`, `swarm-grafana`) serves plain HTTP: it gets the Service and the policy and no leaf, init container or renewal container. - **More than the daemon:** a service whose pod holds more than its daemon (the queue, whose server and exporter run beside the responder) names a @@ -179,9 +182,11 @@ credential directory. holds two store roles has both bound to it ([runtime](runtime.md#the-queue)). The responders' pods of the log and metrics stores hold a second container the same way - ([runtime](runtime.md#the-log-store), [runtime](runtime.md#the-metrics-store)). + ([runtime](runtime.md#the-log-store), [runtime](runtime.md#the-metrics-store)), + and Grafana's pod holds an init container and a sidecar + ([runtime](runtime.md#the-grafana-pod)). - **A unit of the module's own making:** a service that never ran under systemd on the - host (`swarm-victorialogs`, `swarm-logs-auth`, `swarm-victoriametrics`, `swarm-metrics-auth`) gives the renderer the + host (`swarm-victorialogs`, `swarm-logs-auth`, `swarm-victoriametrics`, `swarm-metrics-auth`, `swarm-grafana`) gives the renderer the `serviceConfig`, `environment` and `path` of one as a plain attribute set, with the daemon's flags as a list in `ExecStart`. The renderer reads nothing else of a unit. `fsGroupChangePolicy` in the entry sets the pod's field of that name. diff --git a/docs/4-implementation/k8s/node.md b/docs/4-implementation/k8s/node.md index c340b1a60..047aff8a2 100644 --- a/docs/4-implementation/k8s/node.md +++ b/docs/4-implementation/k8s/node.md @@ -96,7 +96,7 @@ says so with a label. The module sets the labels (`services.hyperhive.deploy.k8s.nodeLabels`, passed to `services.k3s.nodeLabel`): - `hyperhive.darkest.space/state-=true`, one per service whose data - the cluster keeps. Today that's `nats`, `ci-metrics`, `victorialogs` and `victoriametrics`, each when its + the cluster keeps. Today that's `nats`, `ci-metrics`, `victorialogs`, `victoriametrics` and `grafana`, each when its `deploy..enable` is on. The service's static local volume has a `nodeAffinity` on the label, and its pod a `nodeSelector` on it, so a node without the label can't run the pod and shows diff --git a/docs/4-implementation/k8s/runtime.md b/docs/4-implementation/k8s/runtime.md index 969b09489..aa86a80e2 100644 --- a/docs/4-implementation/k8s/runtime.md +++ b/docs/4-implementation/k8s/runtime.md @@ -124,6 +124,10 @@ starts on an empty cache on every start of the pod; an upgrade from the container doesn't carry the old cache over. The whisper model isn't state: the pod's image holds it. +`swarm-grafana` keeps its database in the claim +`swarm-grafana-store`, a static local volume on the directory its container kept +([the Grafana pod](#the-grafana-pod)). + `swarm-ci-metrics` keeps a cursor, `cursor.json`, which holds the run numbers already pushed. It sits in the PersistentVolumeClaim `swarm-ci-metrics-store`, mounted at `/var/lib/private/swarm-ci-metrics`, which binds a static local volume on that @@ -525,6 +529,72 @@ pushes to the store and Grafana that reads it. `agentAuthVerdictTtl` and the store identity files). The host collector reads the pods' output from the node like any pod's. +## The Grafana pod + +`swarm-grafana` is the swarm's Grafana: one Deployment with one replica and the +`Recreate` strategy. The vhost `grafana.` stays on the host and +dials the pod's ClusterIP Service by name, as the stores' vhosts do, so +`gateway.dns.enable` has to be on. + +- **The pod.** The module defines Grafana's `ExecStart`, and the image holds the + nixpkgs Grafana with the plugins `deploy.grafana.plugins` names, its + configuration file and its provisioning directory (datasources, dashboards and + alert rules), all read-only. A start script applies the stored administrator + password to the database with `grafana cli admin reset-admin-password`, because + the `admin_password` setting gives its password to a new database only, + and then runs `grafana server`. Grafana serves plain HTTP on port 3000, + pushes no telemetry and logs in to nothing itself: its output is the pod's log, + which the host collector reads like any pod's ([logs](telemetry.md#logs)). The + startup probe requests `/api/health` every ten seconds for up to five minutes, + 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. +- **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 + `swarmctl` verb restarts it. The bearer is also read by the responders of both + stores, which pick up a replaced value within a minute. +- **The sidecar.** `controller-token` keeps `swarm-controller`'s Viewer service + account in Grafana and its token at + `swarm/controller/swarm-controller/grafana/token`. Every five minutes it calls + Grafana's API with the token it stored, and creates the account and a new + token when Grafana refuses it, as Grafana does after its database is + recreated. It reaches Grafana on the pod's loopback with the administrator + password. +- **The datasources.** Grafana dials `metrics.` and + `logs.` by name through the gateway and sends its bearer, which + the responders of those stores check. The pod holds no store's listener + credential: the only credential Secret it mounts is its own, + `swarm-grafana-credentials`. The cluster's DNS answers those names with the + bridge address, and the pod's policy allows port 443 of the host. +- **Who may use it.** The UI and the API need an OIDC session or the + administrator's basic auth, and the login form is off. `/api/health` is open + by Grafana's design. `/metrics` takes a credential of its own, set with + `[metrics] basic_auth_username` and `basic_auth_password` (the user + `swarm-store`, the password from the Secret `swarm-grafana-credentials`, which the unit of + [the stores' listener credential](#the-stores-listener-credential) creates at + `swarm/services/grafana/store-auth`). The vhost sends it after + authelia has checked the caller, so a request that reaches the pod without it + gets 401. +- **State.** Grafana's data directory on the host is + `/var/lib/nixos-containers/swarm-grafana/var/lib/grafana`: the claim + `swarm-grafana-store` binds a static local volume on it, so the database the + container kept is the pod's, with its dashboards, annotations and users. The + node label is `hyperhive.darkest.space/state-grafana` + ([node labels](node.md#node-labels)), and the pod's `fsGroup` is `65532` with + the `OnRootMismatch` policy, as for the stores. +- **Who reaches what.** The namespace's `default-deny-ingress` and the pod's own + policy admit the node alone, which is the host's nginx and the kubelet's + probes. The pod reaches cluster DNS, the secret store's pod listener and port + 443 of the host. + ## The stores' listener credential Each store listens on its pod's address behind a ClusterIP Service, and the @@ -544,6 +614,10 @@ every route but `/health` and the few built-in ones that answer a fixed text, the import, delete and admin routes of the metrics store included. Root can read the credentials, so treat the host as trusted for what root can do. +Grafana's `/metrics` route has a credential of the same kind, created by the same unit at +`swarm/services/grafana/store-auth` and sent by the vhost from +`/var/lib/swarm-store-auth/grafana.conf`: [the Grafana pod](#the-grafana-pod). + ## Resources and sandbox The pod takes the unit's `MemoryMax` and `CPUQuota` as its container's limits diff --git a/docs/4-implementation/swarm/credential-delivery.md b/docs/4-implementation/swarm/credential-delivery.md index 36f608c3b..354f9bfcb 100644 --- a/docs/4-implementation/swarm/credential-delivery.md +++ b/docs/4-implementation/swarm/credential-delivery.md @@ -124,15 +124,14 @@ symptom many layers from its cause. The store's **first reader** is Grafana's OIDC client secret, a _swarm service's_ own credential rather than a hive's. It has exactly -one delivery route: `swarm-bao-grafana-oidc.service` reads -`swarm/services//oidc/client` out of the store, on **every** host -that runs Grafana. Where authelia is doesn't enter into it — the mint in +one delivery route: the init container `fetch-secrets` of Grafana's pod reads +`swarm/services//oidc/client` out of the store with the pod's +ServiceAccount token, on the host that runs the pod. Where authelia is doesn't enter into it — the mint in authelia's container writes that path whether the reader is a network away or in the container next door. On a fresh swarm the mint writes it a moment after -the reader's first attempt, so a read that finds no value yet fails and the -unit asks again every 30 seconds until the value is there, as the forge's and -the homeserver's do. A unit that finished there would wait for its refresh -timer, about ten minutes on. +the reader's first attempt, so a read that finds no value yet fails the +container and the kubelet starts it again, with a growing delay, until the +value is there. The forge's and the homeserver's units retry the same way. That's a deliberate refusal of the shortcut. Copying the plaintext straight out of authelia's tree when the two happen to share a host is one @@ -163,12 +162,13 @@ the option pair, when that leaf is unset — neither the responder nor the homeserver starts without its secret, and the forge registers no login source without its. -Grafana's admin password rides the same leaf and the same store. Where Grafana -and the store run on different hosts, deploy the store's host first: -`swarm-bao-grafana-oidc-policy` there writes the grant that lets Grafana create -the password, and until it has, the store refuses `swarm-bao-grafana-admin` on -the Grafana host, which retries, while Grafana stays down because its config -reads that file. +Grafana's admin password, datasource bearer and encryption key ride the same role +and the same store. Where Grafana and the store run on different hosts, deploy the store's +host first: `swarm-bao-grafana-oidc-policy` there writes the grant that lets Grafana create +them, and until it has, the store refuses `fetch-secrets`, which fails and retries while +Grafana stays down because its config reads those files. The pod reads them once, when it +starts: a replaced value takes effect after +`kubectl -n hyperhive rollout restart deployment/swarm-grafana`. The **second reader** is the swarm collector's own OIDC client secret, the same shape one level down: `swarm-bao-otel-oidc.service` reads diff --git a/docs/4-implementation/swarm/credentials-reference.md b/docs/4-implementation/swarm/credentials-reference.md index 964969a60..960044614 100644 --- a/docs/4-implementation/swarm/credentials-reference.md +++ b/docs/4-implementation/swarm/credentials-reference.md @@ -25,7 +25,7 @@ the rest of the cell says how. | `swarm/controller/swarm-controller/matrix/appservice-registration` | `swarm-matrix-ctl appservice render` in `hive-matrix`, when the store answers and holds none; before that, the tokens an earlier version kept in the container, stored unchanged | `swarm-matrix-ctl` in `hive-matrix`; the controller has no grant to it | ❌ minted once; an operator who replaces it makes `sync` render the new pair and restart the homeserver | ✅ `sync` re-reads it every 10 minutes | | `swarm/controller/swarm-controller/oidc/client` | authelia, first boot | `swarm-controller` | ❌ minted once, straight into the store; minted again only when the store holds none | ✅ re-read when authelia refuses it | | `swarm/controller/swarm-controller/forge/token` | the forge, once | `swarm-controller` | ❌ minted once; delete `/var/lib/forgejo/swarm-controller-token-name` in the forge container to mint a new one | ✅ re-read on a 401 | -| `swarm/controller/swarm-controller/grafana/token` | `swarm-bao-grafana-controller-token` on Grafana's host | `swarm-controller` | ✅ every 10 minutes, when Grafana refuses it or none is stored | ✅ re-read on a 401 | +| `swarm/controller/swarm-controller/grafana/token` | the `controller-token` sidecar of Grafana's pod, under the pod's login | `swarm-controller` | ✅ every 5 minutes, when Grafana refuses it or none is stored | ✅ re-read on a 401 | | `swarm/controller/swarm-controller/forge/webhook-secret` | `swarm-controller`, at start, from its old `webhook-secret` file; a new one only when there is no file | `swarm-controller` | ❌ minted once; a rotated secret fails every delivery until the forge hooks are re-registered | ❌ read once; a store down at start is re-read in the background until it answers | | `swarm/agents//bao-mtls` | the store's agent PKI mount (`deploy.bao.agentPkiMountPath`), at agent creation, and by the renewal pass when none is stored or its cert-auth role is missing | `hive-c0re`, then the agent | ✅ re-issued every 5 minutes once past half its 7-day validity; minted when none is stored or its cert-auth role is missing, for agents not `Destroyed` | ✅ the agent re-reads every 10 minutes; it renews only while its current leaf is valid | | `swarm/agents//queue` | `swarm-controller`, at agent creation | the agent; the queue, log and metrics auth services | ✅ re-minted at 45 days; skipped for `Destroyed` agents, whose path is deleted | ✅ read on every reconnect; an open connection keeps the old secret for up to an hour; the log and metrics stores honour a replaced secret for up to `deploy.victorialogs.authVerdictTtl` and `deploy.victoriametrics.agentAuthVerdictTtl` (60 s by default) | @@ -44,12 +44,13 @@ the rest of the cell says how. | `swarm/services/k8s/agent-token` | `k3s-join-token-publish`, on the cluster's main node, as that node's hive: k3s's `agent-token`, written again whenever the file differs | a node that joins: `k3s-join-token`, as that node's hive, before k3s starts | ✅ at each start of the main node's k3s | ✅ at each start of the joining node's k3s | | `swarm/services/victorialogs/store-auth` | `swarm-bao-store-auth`, on the log store's host, as the `swarm-store-auth` principal: 32 random bytes as 64 hex digits, written only while the path holds nothing | the same unit, which hands it to the host's nginx and to the cluster; the log store's pod loads it as its `-httpAuth.password` | ❌ never replaced: to rotate, delete the leaf's metadata with a token that may and restart `swarm-bao-store-auth` | ✅ the unit reads it at each start and writes the nginx file and the Secret again when they differ; the store re-reads its file every two seconds | | `swarm/services/victoriametrics/store-auth` | `swarm-bao-store-auth`, on the metrics store's host, as the `swarm-store-auth` principal: 32 random bytes as 64 hex digits, written only while the path holds nothing | the same unit, which hands it to the host's nginx and to the cluster; the metrics store's pod loads it as its `-httpAuth.password` | ❌ never replaced: to rotate, delete the leaf's metadata with a token that may and restart `swarm-bao-store-auth` | ✅ the unit reads it at each start and writes the nginx file and the Secret again when they differ; the store re-reads its file every two seconds | +| `swarm/services/grafana/store-auth` | `swarm-bao-store-auth`, on Grafana's host, as the `swarm-store-auth` principal: 32 random bytes as 64 hex digits, written only while the path holds nothing | the same unit, which hands it to the host's nginx and to the cluster; Grafana's pod loads it as its `[metrics] basic_auth_password` | ❌ never replaced: to rotate, delete the leaf's metadata with a token that may, restart `swarm-bao-store-auth`, then restart Grafana's pod | ✅ the unit reads it at each start and writes the nginx file and the Secret again when they differ; ❌ Grafana reads it at start | | `swarm/services/nats/exporter-auth` | `swarm-bao-store-auth`, on the queue's host, as the `swarm-store-auth` principal: 32 random bytes as 64 hex digits, written only while the path holds nothing | the same unit, which hands the password to the host's nginx and its bcrypt hash to the cluster; the queue's exporter takes the hash as its `-http_pass` | ❌ never replaced: to rotate, delete the leaf's metadata with a token that may, restart `swarm-bao-store-auth`, then restart the queue's pod, which reads the hash only as it starts | ✅ the unit reads it at each start and writes the nginx file, the hash and the Secret again when they differ; a hash is made again only when the password changed | | `swarm/hives//oidc/client` | authelia, first boot, straight into the store | the hive | ❌ minted once, straight into the store; minted again only when the store holds none | ✅ re-read when authelia refuses it | | `swarm/services//oidc/client` | authelia | that service | must be stated | must be stated | | `swarm/services/ci-runner/registration-token` | `swarm-controller`, from the forge, at start and every 5 minutes | `swarm-bao-ci-runner` on the runner's host | ❌ the forge keeps one token until an admin resets it; the controller then writes the new one within 5 minutes | ✅ every 10 minutes; restarts the runner on a change | -| `swarm/services//metrics/bearer` | `swarm-bao-grafana-metrics-bearer` on Grafana's host, when none is stored | `swarm-metrics-auth` and `swarm-logs-grafana-auth` | ❌ delete it and restart `swarm-bao-grafana-metrics-bearer` | ✅ the auth services re-read within a minute, and while they can't reach the store they keep accepting the value they last read, for an hour at most; ❌ Grafana restarts when its copy changes | -| `swarm/services//secret-key` | `swarm-bao-grafana-secret-key` on Grafana's host, from the key an earlier release generated; a new one only when there is none | Grafana | ❌ minted once; a different key leaves Grafana unable to read its stored datasource secrets | ❌ Grafana reads it at start; the unit restarts Grafana when the file changes | +| `swarm/services//metrics/bearer` | the init container of Grafana's pod, when none is stored | `swarm-metrics-auth` and `swarm-logs-grafana-auth` | ❌ delete it and restart Grafana's pod | ✅ the auth services re-read within a minute, and while they can't reach the store they keep accepting the value they last read, for an hour at most; ❌ Grafana reads it at start, so restart its pod when it changes | +| `swarm/services//secret-key` | the init container of Grafana's pod, when none is stored: the key file the earlier container generated, else a new key, and a new key never over a database that holds data keys | Grafana | ❌ stored once; a different key leaves Grafana unable to read what the first one encrypted | ❌ Grafana reads it at start | | `swarm/services/swarm-authelia/keys/`, for `jwt`, `session`, `storage-encryption`, `oidc-hmac` and `oidc-issuer` | authelia's `authelia-swarm-secrets` unit in its container, under the secret publisher's identity, from the key file an earlier release generated; a new one only when there is none | authelia | ❌ minted once; a different storage-encryption key leaves authelia's database unreadable and a different issuer key invalidates every issued token | ❌ read when the unit runs; the unit restarts authelia when the file changes | | `swarm/services/review-classifier/anthropic-api-key` | you, in the store's UI, field `api_key` | `swarm-review-classifier` | ❌ write a new key | ✅ read on every run | | `swarm/services/review-classifier/acp-provider` | you, in the store's UI, field `api_key` | `swarm-review-classifier` | ❌ write a new key | ✅ read on every run | @@ -132,11 +133,12 @@ pieces fit, and the reasoning behind them, is in [`credentials.md`](../../2-hand | the swarm collector's copy of its OIDC secret | `swarm-bao-otel-oidc.service` reads it out of the swarm secret store, **on every host that runs the collector and holds a store identity** | `/run/swarm-otel-oidc/.secret` on the host's tmpfs, bind-mounted read-only into the `swarm-otel` container — never on persistent disk, so a reboot fetches it again | same unit, same path — one route, co-located or not. A collector with no store identity has `clientSecretFile == null`, its already-supported unauthenticated-push degrade — see [swarm-level secrets](../../2-handbook/swarm/credentials.md#swarm-level-secrets) | | the log store's listener credential | `swarm-bao-store-auth.service` creates it in the swarm secret store at `swarm/services/victorialogs/store-auth` when the store holds none, then copies it out, **on the host that runs the log store**. The grant is create and read, without update | `/var/lib/swarm-store-auth/victorialogs.conf` (root and the nginx group, `0640`, in a directory of `0750`): the `Authorization` header the vhost's store locations send, and `/var/lib/swarm-store-auth/victorialogs.password` (root only, `0600`), from which the unit publishes the Secret `swarm-victorialogs-credentials`, key `store-auth`, which the store's pod mounts | nothing to copy: the vhost and the store are on one host. If the nginx file and the Secret hold different values, every request through the gateway answers 401 until the unit runs again; it writes the nginx file first and the Secret after | | the metrics store's listener credential | `swarm-bao-store-auth.service` creates it in the swarm secret store at `swarm/services/victoriametrics/store-auth` when the store holds none, then copies it out, **on the host that runs the metrics store**. The grant is create and read, without update | `/var/lib/swarm-store-auth/victoriametrics.conf` (root and the nginx group, `0640`, in a directory of `0750`): the `Authorization` header the vhost's store locations send, and `/var/lib/swarm-store-auth/victoriametrics.password` (root only, `0600`), from which the unit publishes the Secret `swarm-victoriametrics-credentials`, key `store-auth`, which the store's pod mounts | nothing to copy: the vhost and the store are on one host. If the nginx file and the Secret hold different values, every request through the gateway answers 401 until the unit runs again; it writes the nginx file first and the Secret after | +| Grafana's listener credential | `swarm-bao-store-auth.service` creates it in the swarm secret store at `swarm/services/grafana/store-auth` when the store holds none, then copies it out, **on the host that runs Grafana**. The grant is create and read, without update | `/var/lib/swarm-store-auth/grafana.conf` (root and the nginx group, `0640`, in a directory of `0750`): the `Authorization` header the vhost's `/metrics` location sends, and `/var/lib/swarm-store-auth/grafana.password` (root only, `0600`), from which the unit publishes the Secret `swarm-grafana-credentials`, key `store-auth`, which Grafana's pod mounts | nothing to copy: the vhost and Grafana are on one host. If the nginx file and the Secret hold different values, `/metrics` through the gateway answers 401 until the unit runs again; it writes the nginx file first and the Secret after | | the queue exporter's listener credential | `swarm-bao-store-auth.service` creates it in the swarm secret store at `swarm/services/nats/exporter-auth` when the store holds none, then copies it out, **on the host that runs the queue**. The grant is create and read, without update | `/var/lib/swarm-store-auth/nats.conf` (root and the nginx group, `0640`, in a directory of `0750`): the `Authorization` header the gateway's `/metrics` location for the queue sends; `/var/lib/swarm-store-auth/nats.password` (the password, root only) and `/var/lib/swarm-store-auth/nats.hash` (its bcrypt hash, from which the unit publishes the Secret `swarm-nats-exporter-auth`, key `hash`, which the exporter container reads as `EXPORTER_HASH`). The password reaches nothing but the host: the Secret and the pod's command line hold the hash | nothing to copy: the vhost and the pod are on one host. An nginx file that doesn't match the hash makes the gateway's scrape answer 401 until the unit runs again; the exporter reads the hash as it starts, so a rotated password also needs a restart of the queue's pod | -| Grafana's copy of its OIDC secret | `swarm-bao-grafana-oidc.service` reads it out of the swarm secret store, **on every host that runs Grafana** | `/run/swarm-grafana-secrets/.secret` on the host's tmpfs, bind-mounted read-only into the `swarm-grafana` container — never on persistent disk, so a reboot fetches it again | same unit, same path — one route, co-located or not. Nothing for an operator to place beyond this host's store leaf, see [hive-level secrets](../../2-handbook/swarm/credentials.md#hive-level-secrets) | -| Grafana's admin password | `swarm-bao-grafana-admin.service` creates it in the swarm secret store at `swarm/services//admin/password` when the store holds none, then copies it out, **on every host that runs Grafana**. Grafana's leaf may create that leaf but not update it, so the store keeps the first value, and the secret publisher can't write it. To rotate, run `bao kv metadata delete secret/swarm/services//admin/password` with a token that may, such as the root token (Grafana's, the publisher's and the controller's can't), then `systemctl restart swarm-bao-grafana-admin`; a plain `bao kv delete` isn't enough, see [the callout xkey's section](credentials.md#the-queues-callout-xkey) | `/run/swarm-grafana-secrets/admin-password` on the host's tmpfs, bind-mounted read-only into the `swarm-grafana` container, never on persistent disk: `security.admin_password` for a new database, and `grafana cli admin reset-admin-password` in `grafana.service`'s `preStart` for an existing one, on every start | same unit, same path. After a reboot the unit fetches the file again, and Grafana doesn't start until it exists, so it stays down rather than falling back to the upstream default `admin` | -| Grafana's metrics bearer | `swarm-bao-grafana-metrics-bearer.service` creates it in the swarm secret store at `swarm/services//metrics/bearer` when the store holds none, then copies it out, **on every host that runs Grafana**. Same grant as the admin password, create without update. To rotate, run `bao kv metadata delete secret/swarm/services//metrics/bearer` with a token that may, then `systemctl restart swarm-bao-grafana-metrics-bearer` | `/run/swarm-grafana-secrets/metrics-bearer` on the host's tmpfs, bind-mounted read-only into the `swarm-grafana` container, holding `Bearer `: the metrics datasource's `Authorization` header. The logs datasource sends the same header. `swarm-metrics-auth` on the metrics store's host, and a second instance on the log store's host (`swarm-logs-grafana-auth`), read the stored value themselves, each under its own leaf | same unit, same path. The unit restarts Grafana when the file changes | -| Grafana's datasource encryption key | `swarm-bao-grafana-secret-key.service` stores it in the swarm secret store at `swarm/services//secret-key` when the store holds none, then copies it out, **on every host that runs Grafana**. It stores the key an earlier release generated at `/var/lib/grafana-secret/secret_key` in the container, so the key doesn't change, and mints a new one only on a host with no such file. Same grant as the admin password, create without update. The earlier file stays on disk, unused once the store holds the key. A store that's down or doesn't grant the leaf fails the unit, and Grafana doesn't start | `/run/swarm-grafana-secrets/secret-key` on the host's tmpfs, bind-mounted read-only into the `swarm-grafana` container: `security.secret_key` | same unit, same path. Grafana doesn't start until the file exists. Changing the key leaves Grafana unable to read the datasource secrets it stored, so never delete the store path to rotate it | +| Grafana's copy of its OIDC secret | the init container `fetch-secrets` of Grafana's pod reads it out of the swarm secret store with the pod's ServiceAccount token | `/run/grafana-secrets/.secret` in the pod's in-memory `runtime` volume, mode 0400, never on a disk; Grafana reads it with `$__file{}` | the same container, the same path, on every start. Nothing for an operator to place. A replaced secret takes effect when the pod restarts: `kubectl -n hyperhive rollout restart deployment/swarm-grafana` | +| Grafana's admin password | the init container creates it in the swarm secret store at `swarm/services//admin/password` when the store holds none, then writes it out. The pod's role may create that leaf but not update it, so the store keeps the first value, and the secret publisher can't write it. To rotate, run `bao kv metadata delete secret/swarm/services//admin/password` with a token that may, such as the root token (the pod's, the publisher's and the controller's can't), then restart the pod; a plain `bao kv delete` isn't enough, see [the callout xkey's section](credentials.md#the-queues-callout-xkey) | `/run/grafana-secrets/admin-password` in the pod's in-memory `runtime` volume: `security.admin_password` for a new database, and `grafana cli admin reset-admin-password` before `grafana server` for an existing one, on every start | the same container, the same path. Grafana doesn't start until the file exists, so it stays down rather than falling back to the upstream default `admin` | +| Grafana's metrics bearer | the init container creates it in the swarm secret store at `swarm/services//metrics/bearer` when the store holds none, then writes it out. Same grant as the admin password, create without update. To rotate, run `bao kv metadata delete secret/swarm/services//metrics/bearer` with a token that may, then restart the pod | `/run/grafana-secrets/metrics-bearer` in the pod's in-memory `runtime` volume, holding `Bearer `: the metrics datasource's `Authorization` header. The logs datasource sends the same header. `swarm-metrics-auth` and `swarm-logs-grafana-auth`, in the stores' responders' pods, read the stored value themselves, each under its own ServiceAccount | the same container, the same path, on every start | +| Grafana's datasource encryption key | the init container stores it in the swarm secret store at `swarm/services//secret-key` when the store holds none, then writes it out. The value it stores is the file the earlier container generated at `/var/lib/nixos-containers/swarm-grafana/var/lib/grafana-secret/secret_key` (read-only, through a claim on a static local volume) when there is one, else a new key; with no file, an empty leaf and a `grafana.db` that holds rows in `data_keys` it exits non-zero, names the leaf and stores nothing. Same grant as the admin password, create without update. A store that's down or doesn't grant the leaf fails the container, and Grafana doesn't start | `/run/grafana-secrets/secret-key` in the pod's in-memory `runtime` volume: `security.secret_key` | the same container, the same path. Changing the key leaves Grafana unable to read the data keys it wrapped, so never delete the store path to rotate it | | the swarm controller's webhook secret | `swarm-controller` stores it in the swarm secret store at `swarm/controller/swarm-controller/forge/webhook-secret` when the store holds none: the value of `webhook-secret` in its state directory, or a new one when there is no such file. The state directory file stays on disk and is the fallback while the store is unreachable or its policy doesn't grant the path yet | the swarm secret store; the controller holds it in memory and registers the same value with the forge's hooks | nothing to place: the controller's store leaf already exists. A store that stays unreachable on a start with no state directory file leaves the webhook endpoint answering 503 until the store answers: the controller re-reads it in the background, at most five minutes apart, and registers the forge hooks once it has the secret | | the secret store's unseal or recovery keys and root token, as `bao operator init -format=json` printed them | `bao operator init`, run once by `swarmctl bao init` (or `swarmctl setup`) on the host where the operator runs it | `bao-init.json` in swarmctl's state directory (`$XDG_STATE_HOME/swarmctl`, else `~/.local/state/swarmctl`, so `/root/.local/state/swarmctl` for root): file mode 0600 in a 0700 directory, written before swarmctl parses the output, so a parse failure leaves the keys on disk. Nothing reads it. The operator records the keys off the host, then runs `shred -u` on it; while it exists `swarmctl bao init` refuses to run | nothing: the file is on the host that ran `swarmctl bao init`, and no other host needs it | | the metrics store responder's own store leaf (cert + key) | `signLeaf` in `glue-bao-tls.nix` (`swarm-bao-pki.service`), on the host that runs the secret store, once, subject `deploy.bao.metricsAuthCommonName`. `swarm-bao-metrics-auth-policy.service` writes the `swarm-metrics-auth` role and its read grants on every agent's queue and observability leaves and on the bearer leaf, nothing else | `/var/lib/swarm-bao-pki/metrics-auth.pem` and `metrics-auth-key.pem` on the store's host, handed to `swarm-metrics-auth` through `LoadCredential` (paths in argv, never values) and read by path by `swarm-victoriametrics-forwarder-oidc` | **the operator** places a leaf with that subject on the metrics store's host and names it in `deploy.victoriametrics.authBaoClientCertFile` / `authBaoClientKeyFile`; evaluation fails naming both until then. If the store is on another host, deploy that host first: the role must exist before the responder's login succeeds, and until it does the gateway refuses every Grafana query (fail closed) | @@ -146,13 +148,13 @@ pieces fit, and the reasoning behind them, is in [`credentials.md`](../../2-hand | a hive's copy of its own OIDC secret | hive-c0re reads it out of the swarm secret store when it first connects to the queue, under the hive's own leaf | the daemon's memory only; never on disk | same read, co-located or not. Nothing for an operator to place beyond the hive's store leaf (`deploy.bao.clientCertFile`) | | the hive collector's copy of its hive's OIDC secret | `swarm-bao-hive-otel-oidc.service` reads it out of the swarm secret store under the hive's own leaf, **on every hive that runs the collector and holds that leaf**; the leaf is the source | `/run/hive-otel-oidc/hive-.secret` on the hive's host tmpfs, 0400 root, loaded by `LoadCredential` — never on persistent disk, so a reboot fetches it again | same unit, same path, co-located or not. Nothing for an operator to place beyond the hive's store leaf (`deploy.bao.clientCertFile`). Naming a secret file with `otel.clientSecretFile` instead is legacy for a host without a leaf: the build warns, and the fix is to place the leaf from `/var/lib/swarm-bao-pki/hives//` and drop the setting | | the swarm controller's forge token | the forge's `forgejo-swarm-controller-account`, in-container, once. An attempt that fails or runs past 30 seconds retries after 5 seconds, then at growing intervals up to 5 minutes | the swarm secret store at `swarm/controller/swarm-controller/forge/token`, written by the mint under the forge publisher's leaf, which the forge container loads as a credential; the controller holds it in memory only. `/var/lib/forgejo/swarm-controller-token-name` in the forge container holds its name, the minter's record that it has minted | nothing to place beyond the controller's store leaf. A forge host without the store needs the publisher's leaf placed (`deploy.bao.forgePublisherClientCertFile`) | -| the swarm controller's Grafana token | `swarm-bao-grafana-controller-token.service`, **on the host that runs Grafana**, as Grafana's built-in admin over its socket: it creates the `swarm-controller` service account as a Viewer (and sets it back to Viewer on every run), mints a token for it and writes it to the swarm secret store at `swarm/controller/swarm-controller/grafana/token` under Grafana's leaf. It waits up to 60 seconds for Grafana's socket to answer before its first call. Re-run every ten minutes: it keeps a stored token Grafana accepts, and replaces one Grafana refuses with 401 (or a missing one), deleting every other token of that account first | the swarm secret store only; the controller reads it for `GET /api/alerts` and holds it in memory, re-reading the store once when Grafana answers 401 | nothing to place: Grafana's leaf is already required to run Grafana. Until the unit has run, `/api/alerts` answers 503 naming the empty path | +| the swarm controller's Grafana token | the `controller-token` sidecar of Grafana's pod, as Grafana's built-in admin on the pod's loopback: it creates the `swarm-controller` service account as a Viewer (and sets it back to Viewer on every pass), mints a token for it and writes it to the swarm secret store at `swarm/controller/swarm-controller/grafana/token` under the pod's login. It waits for Grafana's health route before its first call. It runs every five minutes: it keeps a stored token Grafana accepts, and replaces one Grafana refuses with 401 (or a missing one), deleting every other token of that account first | the swarm secret store only; the controller reads it for `GET /api/alerts` and holds it in memory, re-reading the store once when Grafana answers 401 | nothing to place. Until the sidecar has run, `/api/alerts` answers 503 naming the empty path | | an agent's API-key environment (`ANTHROPIC_API_KEY`, `ANTHROPIC_BASE_URL`, an ACP provider key) | `hive-agent-backend-env.service`, in the agent's container, on every agent with a store, whatever its runtime or its login kind. When the store holds nothing at `swarm/agents//backend-env` and `backendEnvironmentFile` is a non-empty file, it creates the leaf with the file's exact bytes and `-cas=0`, under the agent's own leaf, which may create that path and not update it. It never rotates a value and never rewrites or deletes the file. To set or replace a key, use **set the API-key environment** in the swarm UI (`PUT /api/hives/{hive}/agents/{agent}/backend-env`): `swarm-controller` overwrites the leaf with its own grant, and the store's value then wins over the file. Its **remove** (`DELETE` on the same path) deletes the leaf, and an agent whose file has content then creates it from that file again | the swarm secret store at that path; the unit writes it to `/run/hive-agent-backend-env/env` (tmpfs, `0600`, root), and `hive-agent` and `hive-subagent-daemon` load that after `backendEnvironmentFile` as `EnvironmentFile=` | the same unit, same path. A variable in the store wins over the same one in the file. With the store down at a start, the file alone carries the agent, as it did before the store held a copy; with an older hive build the agent ignores the leaf and keeps reading the file | | an agent's proxy settings (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, the credential in the proxy URL) | `hive-agent-proxy-credential.service`, in the agent's container, as the agent user, at start and every 10 minutes: it reads `swarm/agents//proxy-credential` under the agent's own leaf and builds the file from it. It writes nothing while the path holds nothing or the hive's facts name no squid | `/run/hive-agent-proxy-credential/proxy.env` (tmpfs, `0600`, the agent user); the harness, its bash tool, the subagents, the MCP servers and the pollers load it as `EnvironmentFile=-` and read it when they start | With no credential, or on a hive that writes no `HIVE_SQUID_PROXY` and `HIVE_EGRESS_NO_PROXY` fact, nothing writes the file and a unit has no proxy variable and reaches the internet without the proxy; the host still redirects the web traffic of a `restricted` or `log` agent into squid (see [the network reference](../networking/network.md#intercepted-web-traffic)). A failed read keeps the file already in place. A unit started before the file appeared goes direct until its next start. The credential is also in the environment of every process those units start, so `env` in the agent's shell prints it | | an agent's claude login (`.credentials.json`) | `swarm-claude-login.service`, in its container, when an operator completes `claude auth login` from the agent's card in the swarm UI; it stores the file as a new version at `swarm/agents//claude-credentials` under its own leaf, which may create and update that path and read nothing under an agent | the swarm secret store at that path; the agent's `hive-agent` reads it under the agent's own leaf every 30 seconds while it waits for a login and writes it to `~/.claude/.credentials.json` | the same read, co-located or not; nothing for an operator to place beyond the agent's store leaf. When the store's copy and the agent's differ the KV version decides: the agent installs only a version newer than the last it installed (`claude-credentials-version` under the harness dir), because claude rotates the refresh token in its own copy and the stored one goes stale. The agent ignores a stale or equal version, and a relogin writes a newer one — [claude-login.md](../../2-handbook/swarm/claude-login.md) | | the queue responder's copy of its OIDC secret | the responder reads it out of the swarm secret store itself as it starts, under its own leaf, and again when authelia refuses it | the daemon's memory only; never on disk | same read, wherever authelia runs. Nothing for an operator to place beyond the responder's store leaf (`deploy.nats.authBaoClientCertFile`) | | the queue container's journal forwarder's copy of the queue's OIDC secret | `swarm-journal-forwarder-oidc.service` inside the `swarm-nats` container reads it out of the swarm secret store under the responder's store leaf, and again every 10 minutes | `/run/swarm-journal-forwarder-oidc/client-secret` on the container's tmpfs, root `0400`, never on persistent disk; `LoadCredential` hands it to the collector | same unit, same path. After a reboot the fetch fails fast while the store is down and retries with a delay that grows to 5 minutes; the attempt that succeeds starts the collector, which isn't part of the container's boot, and it resumes from its saved journal cursor. Nothing for an operator to place beyond the responder's store leaf (`deploy.nats.authBaoClientCertFile`) | -| the CI runner, Grafana, cache, forge and homeserver containers' journal forwarders' OIDC secrets | `swarm-journal-forwarder-oidc.service` inside each container reads its forwarder client's secret (`swarm..otel.clientId`) out of the swarm secret store under the store leaf the host already holds for that service, handed in as a system credential (bound in read-only, for the homeserver's), and again every 10 minutes | `/run/swarm-journal-forwarder-oidc/client-secret` on the container's tmpfs, root `0400`, never on persistent disk; `LoadCredential` hands it to the collector | same unit, same path. Nothing for an operator to place beyond those leaves (`deploy.bao.ciRunnerClientCertFile`, `deploy.bao.grafanaOidcClientCertFile`, `deploy.bao.forgePublisherClientCertFile`, `deploy.bao.atticClientCertFile`, `deploy.matrix.ctlBaoClientCertFile`) | +| the CI runner, cache, forge and homeserver containers' journal forwarders' OIDC secrets | `swarm-journal-forwarder-oidc.service` inside each container reads its forwarder client's secret (`swarm..otel.clientId`) out of the swarm secret store under the store leaf the host already holds for that service, handed in as a system credential (bound in read-only, for the homeserver's), and again every 10 minutes | `/run/swarm-journal-forwarder-oidc/client-secret` on the container's tmpfs, root `0400`, never on persistent disk; `LoadCredential` hands it to the collector | same unit, same path. Nothing for an operator to place beyond those leaves (`deploy.bao.ciRunnerClientCertFile`, `deploy.bao.forgePublisherClientCertFile`, `deploy.bao.atticClientCertFile`, `deploy.matrix.ctlBaoClientCertFile`) | | the CI run poller's forge token | `swarm-controller`, with the forge's admin API, for its `ci-metrics` account, at start and in a five-minute pass | the swarm secret store at `swarm/services/ci-metrics/forge/token`; `swarm-ci-metrics` reads it once per pass under its own leaf and holds it in memory for that pass. When the store's token no longer matches the forge's, the controller's next pass mints a new one; until then the poller's forge calls answer 401, the unit fails and no cursor moves | nothing to place beyond the poller's leaf (`deploy.bao.ciMetricsClientCertFile`), on a host without the store | | the CI run poller's copy of its OIDC secret | authelia's mint, which creates it in the swarm secret store | `swarm-ci-metrics` reads `swarm/services//oidc/client` once per pass under its own leaf, and again when authelia refuses it; memory only. While it differs from authelia's, the token request fails, nothing gets pushed and no cursor moves | same leaf, nothing else | | authelia's container's journal forwarder's OIDC secret | authelia's mint, in its container, like every client's secret (`swarm.authelia.otel.clientId`). It creates it at `swarm/services//oidc/client`, and `swarm-journal-forwarder-oidc.service` in the same container reads it back under the secret publisher's leaf, at start and every 10 minutes | `/run/swarm-journal-forwarder-oidc/client-secret` on the container's tmpfs, root `0400`; `LoadCredential` hands it to the collector. | none: the forwarder runs only in authelia's container, and is off there without the publisher's leaf | @@ -190,8 +192,8 @@ classifier's, the CI runner's, the builder's, the cache's, the CI run poller's, login minter's, the forge host's and Grafana's, which reach more than one: | unit | option pair under `deploy.bao.` | reads, or writes | +| Grafana's pod: the init container and the sidecar, through the jwt role `swarm-grafana-oidc` | `grafanaOidcClientCertFile` / `grafanaOidcClientKeyFile` | reads `swarm/services//oidc/client`; creates and reads `swarm/services//admin/password`, `swarm/services//metrics/bearer` and `swarm/services//secret-key`; reads and writes `swarm/controller/swarm-controller/grafana/token` | | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `swarm-bao-grafana-oidc`, `swarm-bao-grafana-admin`, `swarm-bao-grafana-secret-key`, and Grafana's journal forwarder in its container | `grafanaOidcClientCertFile` / `grafanaOidcClientKeyFile` | reads `swarm/services//oidc/client` and `swarm/services//oidc/client`; creates and reads `swarm/services//admin/password` and `swarm/services//secret-key` | | `swarm-bao-otel-oidc` | `otelOidcClientCertFile` / `otelOidcClientKeyFile` | `swarm/services//oidc/client` | | `swarm-bao-forwarder-oidc` | `forwarderOidcClientCertFile` / `forwarderOidcClientKeyFile` | `swarm/services//oidc/client` | | `swarm-bao-ci-runner`, and the runner's journal forwarder in its container | `ciRunnerClientCertFile` / `ciRunnerClientKeyFile` | `swarm/services/ci-runner/registration-token` and `swarm/services//oidc/client` | @@ -204,7 +206,7 @@ login minter's, the forge host's and Grafana's, which reach more than one: | `swarm-archive-users`, `swarm-archive-prune`, `swarm-archive-check` and, with an S3 bucket, `swarm-archive` | `archiveClientCertFile` / `archiveClientKeyFile` | reads `swarm/services/archive/users/*`, `swarm/services/archive/restic/*` and `swarm/services/archive/s3/*`, lists `swarm/services/archive/users/` | | `swarm-ci-metrics` | `ciMetricsClientCertFile` / `ciMetricsClientKeyFile` | `swarm/services/ci-metrics/forge/token` and `swarm/services//oidc/client` | | `swarm-bao-forge-oidc` and the forge's controller-token mint and its journal forwarder in its container | `forgePublisherClientCertFile` / `forgePublisherClientKeyFile` | writes `swarm/controller/swarm-controller/forge/token`; reads `swarm/services//oidc/client` and `swarm/services//oidc/client` | -| `swarm-bao-store-auth` | `storeAuthClientCertFile` / `storeAuthClientKeyFile` | creates and reads `swarm/services/victorialogs/store-auth`, `swarm/services/victoriametrics/store-auth` and `swarm/services/nats/exporter-auth` | +| `swarm-bao-store-auth` | `storeAuthClientCertFile` / `storeAuthClientKeyFile` | creates and reads `swarm/services/victorialogs/store-auth`, `swarm/services/victoriametrics/store-auth`, `swarm/services/grafana/store-auth` and `swarm/services/nats/exporter-auth` | The option names are `deploy.bao.`; the common names, what a missing leaf costs and how to place a leaf by hand are in diff --git a/docs/4-implementation/swarm/telemetry.md b/docs/4-implementation/swarm/telemetry.md index dd99a9b41..8d8a9bb29 100644 --- a/docs/4-implementation/swarm/telemetry.md +++ b/docs/4-implementation/swarm/telemetry.md @@ -10,15 +10,13 @@ how to open each service, is on The swarm's telemetry lands in one VictoriaMetrics, and one Grafana reads it, at `metrics.` and `grafana.`. They run apart so you can restart or break Grafana without taking the time-series -database with it: VictoriaMetrics as a pod in the host's cluster -([the metrics store](../k8s/runtime.md#the-metrics-store)), Grafana in a container. -restart or break Grafana without taking the time-series database with it. +database with it: both run as pods in the host's cluster +([the metrics store](../k8s/runtime.md#the-metrics-store), +[the Grafana pod](../k8s/runtime.md#the-grafana-pod)). -The Grafana container sits on the hive bridge in a network namespace of its -own and dials authelia, the secret store, the collector and both datasources -by name through it. It binds no TCP port: it listens on the unix socket -`/run/swarm-grafana/grafana.sock`, a directory only the gateway's nginx and -the container can open. +Grafana's pod dials authelia, the secret store and both datasources by name +through the gateway, and listens on port 3000 for the host's own traffic only: +the vhost on the host's nginx is the one way in. They derive together: a store with no UI is unreadable and a UI with no store is empty. To run one without the other, set it directly: @@ -103,16 +101,15 @@ The `controller` panels come from the controller itself. It exports OTLP through the gateway to the swarm's collector from whatever host it runs on, whether or not that host runs the collector. -Neither is reachable except through the gateway: Grafana listens on a unix -socket only the gateway's nginx can open, and VictoriaMetrics behind a Service -that admits only the host's own traffic. VictoriaMetrics asks every request for +Neither is reachable except through the gateway: both sit behind Services +that admit only the host's own traffic. VictoriaMetrics asks every request for a credential of its own, which the gateway's nginx supplies once the `metrics.` vhost has checked the caller: - **The read API** (the Prometheus query, series, label and metadata routes): Grafana's datasource, an agent, or an operator. Grafana sends a - bearer that `swarm-bao-grafana-metrics-bearer` creates in the swarm secret - store, and Grafana's responder (the second container of the responders' pod) + bearer that the init container of Grafana's pod creates in the swarm + secret store, and Grafana's responder (the second container of the responders' pod) checks it against the same store path. An agent's `swarm-metrics` sends its `swarm-agent..` bearer, which the agents' responder (the first @@ -155,8 +152,11 @@ from the node like any pod's ([logs](../k8s/telemetry.md#logs)). The collector scrapes Grafana's own metrics at `https:///metrics`, so a collector on a host without -Grafana still gets them. The gateway admits only the collector's client to -that path; any other session gets `deny`. +Grafana still gets them. Grafana asks that route for a credential of its own +(`[metrics] basic_auth_username` and `basic_auth_password`), which the +gateway's nginx supplies once authelia has checked the caller; the gateway +admits only the collector's client to that path, and any other session gets +`deny`. A request that reaches the pod without the credential gets 401. The collector scrapes the store's own metrics the same way, at `https:///metrics`, so a collector on a host @@ -198,7 +198,7 @@ collector is the only intended writer. agent presents its `swarm-agent..` bearer, checked by `swarm-logs-auth`. The agent must also hold the `logs` permission, which is off by default; without it the answer is a 403 (`docs/5-project/process/conventions.md`, Permissions). Grafana's datasource presents the same bearer as its -metrics datasource, which `swarm-bao-grafana-metrics-bearer` creates, and a +metrics datasource, which the init container of Grafana's pod creates, and a second `swarm-metrics-auth` instance (`swarm-logs-grafana-auth`, in the same pod as `swarm-logs-auth`) checks it against the same store path; the gateway tells it from the others by its shape, 64 hex digits. Anything else needs an operator's @@ -288,17 +288,17 @@ gateway either way. | `swarm.otel.domain` | Only to rename it — the default already resolves correctly for every hive in the swarm. | The `swarm-bao`, `swarm-nats`, `swarm-builder`, `swarm-claude-login`, -`swarm-notify-router`, `swarm-review-classifier`, `swarm-ci-runner`, `swarm-grafana`, +`swarm-notify-router`, `swarm-review-classifier`, `swarm-ci-runner`, `swarm-authelia`, `swarm-attic`, `hive-forge` and `hive-matrix` containers each run a collector of their own that forwards the container's journal here, on a route and receiver per service (`https:////`), authenticated as an OIDC client of that service's. The queue, builder, login minter, notification router and -classifier reuse the service's own client; the store, CI runner, Grafana, +classifier reuse the service's own client; the store, CI runner, authelia, cache, forge and homeserver have a forwarder client of their own (`swarm..otel.clientId`). Their records carry `service.name` (`bao`, `nats`, `builder`, `claude-login`, `notify-router`, `review-classifier`, `ci-runner`, -`grafana`, `authelia`, `attic`, `forgejo`, +`authelia`, `attic`, `forgejo`, `tuwunel`) and the `sender` of its own client id. The forwarder of all but the store's is `nix/container-modules/swarm-journal-forwarder.nix`. diff --git a/nix/host-modules/default.nix b/nix/host-modules/default.nix index 2c02033bd..ac050b0ee 100644 --- a/nix/host-modules/default.nix +++ b/nix/host-modules/default.nix @@ -59,7 +59,6 @@ ./glue-stt-oidc-client.nix ./glue-attic-otel-oidc-client.nix ./glue-forge-otel-oidc-client.nix - ./glue-grafana-otel-oidc-client.nix ./glue-matrix-otel-oidc-client.nix ./glue-review-classifier-oidc-client.nix ./glue-secret-publisher-authelia.nix diff --git a/nix/host-modules/glue-attic-otel-oidc-client.nix b/nix/host-modules/glue-attic-otel-oidc-client.nix index ee3a99904..bf6c01c3f 100644 --- a/nix/host-modules/glue-attic-otel-oidc-client.nix +++ b/nix/host-modules/glue-attic-otel-oidc-client.nix @@ -7,7 +7,7 @@ # # Gated on authelia being HERE, not on this host running the cache: a client is # a row in THIS host's provider config, the split -# ./glue-grafana-otel-oidc-client.nix makes for the same reason. +# ./glue-forge-otel-oidc-client.nix makes for the same reason. { lib, config, diff --git a/nix/host-modules/glue-bao-readers-policy-order.nix b/nix/host-modules/glue-bao-readers-policy-order.nix index d353ad9ac..082306395 100644 --- a/nix/host-modules/glue-bao-readers-policy-order.nix +++ b/nix/host-modules/glue-bao-readers-policy-order.nix @@ -31,8 +31,6 @@ let # Reader unit → the gate its own module defines it under. readersHere = { - # ./swarm-grafana.nix - swarm-bao-grafana-oidc = deployCfg.grafana.enable; # ./swarm-otel.nix swarm-bao-otel-oidc = deployCfg.swarm-otel.enable @@ -46,7 +44,12 @@ let swarm-bao-ci-runner = deployCfg.ci-runner.enable; # ./k8s/store-credentials.nix swarm-bao-store-auth = - (deployCfg.victorialogs.enable || deployCfg.victoriametrics.enable || deployCfg.nats.enable) + ( + deployCfg.victorialogs.enable + || deployCfg.victoriametrics.enable + || deployCfg.nats.enable + || deployCfg.grafana.enable + ) && deployCfg.k8s.enable && hyperhiveCfg.k8s.enable && havePair baoDeploy.storeAuthClientCertFile baoDeploy.storeAuthClientKeyFile; @@ -55,25 +58,6 @@ let # Readers that log in under another unit's principal: reader unit → the # gate its own module defines it under, and the policy units it waits for. readersOfOtherPolicy = { - # ./swarm-grafana.nix, under Grafana's leaf, which may create the admin - # password, the metrics bearer, the datasource key and the controller's - # Grafana token only once that policy is written. - swarm-bao-grafana-admin = { - here = deployCfg.grafana.enable; - policies = [ "swarm-bao-grafana-oidc-policy" ]; - }; - swarm-bao-grafana-metrics-bearer = { - here = deployCfg.grafana.enable; - policies = [ "swarm-bao-grafana-oidc-policy" ]; - }; - swarm-bao-grafana-secret-key = { - here = deployCfg.grafana.enable; - policies = [ "swarm-bao-grafana-oidc-policy" ]; - }; - swarm-bao-grafana-controller-token = { - here = deployCfg.grafana.enable; - policies = [ "swarm-bao-grafana-oidc-policy" ]; - }; # ./swarm-attic.nix, under the cache's leaf, which may create the signing # key, the two tokens and the cache's public facts only once that policy is # written. diff --git a/nix/host-modules/glue-bao-readers-store-order.nix b/nix/host-modules/glue-bao-readers-store-order.nix index bca4a0808..fecbbb7e2 100644 --- a/nix/host-modules/glue-bao-readers-store-order.nix +++ b/nix/host-modules/glue-bao-readers-store-order.nix @@ -56,12 +56,6 @@ let && hyperhiveCfg.deploy.hive-controller.hiveName != null && havePair baoDeploy.clientCertFile baoDeploy.clientKeyFile && otel.clientSecretFile == hiveOtelSecret.path; - # ./swarm-grafana.nix - swarm-bao-grafana-oidc = deployCfg.grafana.enable; - swarm-bao-grafana-admin = deployCfg.grafana.enable; - swarm-bao-grafana-metrics-bearer = deployCfg.grafana.enable; - swarm-bao-grafana-secret-key = deployCfg.grafana.enable; - swarm-bao-grafana-controller-token = deployCfg.grafana.enable; # ./swarm-ci-runner.nix swarm-bao-ci-runner = deployCfg.ci-runner.enable; # ./swarm-attic.nix diff --git a/nix/host-modules/glue-grafana-otel-oidc-client.nix b/nix/host-modules/glue-grafana-otel-oidc-client.nix deleted file mode 100644 index 6a1913081..000000000 --- a/nix/host-modules/glue-grafana-otel-oidc-client.nix +++ /dev/null @@ -1,37 +0,0 @@ -# Glue: register the Grafana container's journal forwarder as an OIDC -# client wherever authelia runs. -# -# ONE PAIRING PER FILE: that forwarder ← authelia, and nothing else. -# Without it authelia mints no secret, the publisher has nothing to copy into -# the store, and the forwarder's export is a 401. -# -# Gated on authelia being HERE, not on this host running Grafana: a -# client is a row in THIS host's provider config, the split -# ./glue-swarm-bao-otel-oidc-client.nix makes for the same reason. -{ - lib, - config, - ... -}: -let - hyperhiveCfg = config.services.hyperhive; - clientId = hyperhiveCfg.swarm.grafana.otel.clientId; -in -{ - config = lib.mkIf hyperhiveCfg.deploy.authelia.enable { - services.hyperhive.swarm.authelia.oidc.clients = [ - { - id = clientId; - description = "HyperHive Grafana journal forwarder"; - kind = "machine"; - redirectUris = [ ]; - # Its own id as its own permitted audience, the one the swarm - # collector's receiver for this container checks. - audience = [ clientId ]; - # The receiver verifies the token offline against `/jwks.json`; - # authelia's default opaque handle fails there. - accessTokenSignedResponseAlg = "RS256"; - } - ]; - }; -} diff --git a/nix/host-modules/k8s/node.nix b/nix/host-modules/k8s/node.nix index ae7a3db1e..7e03e0e29 100644 --- a/nix/host-modules/k8s/node.nix +++ b/nix/host-modules/k8s/node.nix @@ -168,6 +168,7 @@ let "swarm-controller" "victorialogs" "victoriametrics" + "grafana" ]; enabledServices = lib.filter (name: deployCfg.${name}.enable) swarmServices; @@ -179,6 +180,7 @@ let ci-metrics victorialogs victoriametrics + grafana ; }; in @@ -320,7 +322,7 @@ in none of those pods. - `hyperhive.darkest.space/state-` for each service whose data the - cluster keeps: `nats`, `ci-metrics`, `victorialogs` and `victoriametrics`, each when enabled. A volume's `nodeAffinity` and the pod's `nodeSelector` name it. + cluster keeps: `nats`, `ci-metrics`, `victorialogs`, `victoriametrics` and `grafana`, each when enabled. A volume's `nodeAffinity` and the pod's `nodeSelector` name it. - `hyperhive.darkest.space/entry`: the node the hosts' DNS points at. - `svccontroller.k3s.cattle.io/enablelb`: with it on any node, the service load balancer binds a published port on the labelled nodes diff --git a/nix/host-modules/k8s/render.nix b/nix/host-modules/k8s/render.nix index bc38065e2..2420195a0 100644 --- a/nix/host-modules/k8s/render.nix +++ b/nix/host-modules/k8s/render.nix @@ -344,6 +344,38 @@ let egress = [ "store" ]; otlp = "none"; }; + # Grafana: the swarm's metrics UI, on a static local volume that is its + # data directory. Its configuration, provisioning and plugins are in the + # image; an init container fetches its secrets and a sidecar keeps the + # controller's token (`pod`). It logs in to nothing itself and pushes no + # telemetry. The UI and the API take Grafana's own login; its `/metrics` + # takes the listener credential. + swarm-grafana = { + inherit (deployCfg.grafana) enable unit pod; + package = deployCfg.grafana.startPackage; + kind = "Deployment"; + healthEnv = null; + probe = { + path = "/api/health"; + startupFailureThreshold = 30; + }; + etcFiles = [ ]; + publicCredentials."bao-ca.pem" = baoServerCaKey; + listener.port = deployCfg.grafana.servicePort; + # The secret store, and the gateway's 443: authelia's token and userinfo + # routes and both datasources. + egress = [ + "store" + "identity" + ]; + baoRole = "swarm-grafana-oidc"; + localState = { + service = "grafana"; + hostDir = deployCfg.grafana.hostDataDir; + }; + fsGroupChangePolicy = "OnRootMismatch"; + otlp = "none"; + }; }; # Where a pod pushes telemetry. A `"hive"` service pushes to the hive diff --git a/nix/host-modules/k8s/store-credentials.nix b/nix/host-modules/k8s/store-credentials.nix index 0133f6dd5..c8a530fa5 100644 --- a/nix/host-modules/k8s/store-credentials.nix +++ b/nix/host-modules/k8s/store-credentials.nix @@ -1,10 +1,10 @@ -# The listener credentials of the Victoria stores the cluster runs and of the -# queue's exporter: the unit that creates each in the swarm secret store when it +# The listener credentials of the Victoria stores and Grafana the cluster runs and +# of the queue's exporter: the unit that creates each in the swarm secret store when it # holds none, hands it to the gateway's nginx and publishes it to the cluster as # the Secret the pod reads it from (the store's password, the exporter's bcrypt -# hash). The stores' flags and the locations that send the credential are in -# ../swarm-victorialogs.nix and ../swarm-victoriametrics.nix, the exporter's in -# ../swarm-nats.nix; ../lib/store-auth.nix names what they share. +# hash). The flags and the locations that send the credential are in +# ../swarm-victorialogs.nix, ../swarm-victoriametrics.nix and ../swarm-grafana.nix, +# the exporter's in ../swarm-nats.nix; ../lib/store-auth.nix names what they share. # docs/4-implementation/k8s/runtime.md has the design. { pkgs, @@ -27,10 +27,11 @@ let # the files `include`d into the store locations. nginxGroup = config.services.nginx.group; - # The stores this host runs, by the name `store-auth.nix` takes. + # The pods this host runs that take the credential, by the name `store-auth.nix` takes. stores = lib.optional deployCfg.victorialogs.enable "victorialogs" - ++ lib.optional deployCfg.victoriametrics.enable "victoriametrics"; + ++ lib.optional deployCfg.victoriametrics.enable "victoriametrics" + ++ lib.optional deployCfg.grafana.enable "grafana"; # The queue's exporter runs in the queue's pod. exporterOn = deployCfg.nats.enable; @@ -96,7 +97,7 @@ in ]; systemd.services.swarm-bao-store-auth = lib.mkIf haveIdentity { - description = "create the Victoria stores' and the queue exporter's listener credentials in the swarm secret store if absent, and publish them"; + description = "create the stores', Grafana's and the queue exporter's listener credentials in the swarm secret store if absent, and publish them"; wantedBy = [ "multi-user.target" ]; wants = [ "network-online.target" ]; after = [ @@ -216,7 +217,7 @@ in store_init store_login if [ "$STORE_UP" != 1 ]; then - echo "could not log in to the swarm secret store; the stores' credentials are not published." >&2 + echo "could not log in to the swarm secret store; the listener credentials are not published." >&2 exit 1 fi ${lib.concatMapStrings publish stores} diff --git a/nix/host-modules/lib/store-auth.nix b/nix/host-modules/lib/store-auth.nix index 731087bda..77cb9e766 100644 --- a/nix/host-modules/lib/store-auth.nix +++ b/nix/host-modules/lib/store-auth.nix @@ -1,4 +1,4 @@ -# What the Victoria stores' listener credential is, where it lives, and who +# What the listener credential of the Victoria stores and of Grafana is, where it lives, and who # names it. The store's pod, the gateway's vhost and the unit that mints and # publishes it (../k8s/store-credentials.nix) all spell it from here. # @@ -7,6 +7,9 @@ # leaf of the swarm secret store, created by that unit when the store holds # none. The pod reads it from the Secret `secretName`; nginx sends it in the # `Authorization` header that `nginxFile` sets. +# +# Grafana asks for the same login on `/metrics` alone (`[metrics] basic_auth_*`); +# its other routes take its own login. rec { # The Basic login's user name, the same for every store. user = "swarm-store"; @@ -16,7 +19,7 @@ rec { credentialId = "store-auth"; # Under KV v2's `secret/` mount, as `bao kv` takes it. `store` is - # `victorialogs` or `victoriametrics`. + # `victorialogs`, `victoriametrics` or `grafana`. leaf = store: "swarm/services/${store}/store-auth"; # On the host, a directory for root and the gateway's group (`0750`): the nginx diff --git a/nix/host-modules/swarm-bao-readers.nix b/nix/host-modules/swarm-bao-readers.nix index ee9d86c55..6cac032ed 100644 --- a/nix/host-modules/swarm-bao-readers.nix +++ b/nix/host-modules/swarm-bao-readers.nix @@ -85,23 +85,20 @@ let # below takes a list either way and the units stay identical apart from # the objects they write. # - # Grafana's leaf also creates its admin password (`swarm-bao-grafana-admin` - # in ./swarm-grafana.nix) and the bearer its metrics datasource presents - # (`swarm-bao-grafana-metrics-bearer`) and its datasource-encryption key - # (`swarm-bao-grafana-secret-key`). `create` without `update`, so a stored - # value is never replaced. + # Grafana's pod logs in under this role. It creates its admin password, the + # bearer its datasources present and its datasource-encryption key + # (`swarm-grafana-fetch` in ./swarm-grafana.nix), `create` without `update`, so a + # stored value is never replaced. # - # The controller's Grafana token is the one it may replace: - # `swarm-bao-grafana-controller-token` mints a new one when Grafana refuses - # the stored one, as it does after its database is recreated. + # The controller's Grafana token is the one it may replace: its sidecar mints a + # new one when Grafana refuses the stored one, as it does after its database + # is recreated. grafanaOidcReaders = [ { name = "swarm-grafana-oidc"; cn = baoDeploy.grafanaOidcCommonName; policyText = readStanza "${credentialMountPath}/data/swarm/services/${hyperhiveCfg.swarm.grafana.oidc.clientId}/oidc/client" - # The journal forwarder in its container, under this same leaf. - + readStanza "${credentialMountPath}/data/swarm/services/${hyperhiveCfg.swarm.grafana.otel.clientId}/oidc/client" + createStanza "${credentialMountPath}/data/${grafanaAdminLeaf}" + createStanza "${credentialMountPath}/data/${grafanaMetricsBearerLeaf}" + createStanza "${credentialMountPath}/data/${grafanaSecretKeyLeaf}" @@ -362,11 +359,11 @@ let } ]; - # The unit that publishes the stores' listener credentials + # The unit that publishes the stores' and Grafana's listener credentials # (`swarm-bao-store-auth`, ./k8s/store-credentials.nix): it creates each # credential when the store holds none and reads it back, `create` without - # `update`, so a stored value is never replaced. One principal for both - # stores and the queue's exporter, a leaf each. + # `update`, so a stored value is never replaced. One principal for the + # stores, Grafana and the queue's exporter, a leaf each. storeAuthWriters = [ { name = "swarm-store-auth"; @@ -376,6 +373,7 @@ let [ "victorialogs" "victoriametrics" + "grafana" ] + createReadStanza "${credentialMountPath}/data/${storeAuth.exporter.leaf}"; } @@ -441,6 +439,9 @@ let # The metrics store's two responders, likewise under the ServiceAccount of # their pod (./k8s/render.nix, `swarm-metrics-auth`). ++ metricsAuthReaders + # Grafana's pod runs under the ServiceAccount of its service, `swarm-grafana`, + # and logs in under the role its certificate has always had. + ++ map (obj: obj // { serviceAccount = grafanaPodAccount; }) grafanaOidcReaders ++ [ { name = controllerPolicyName; } ] # The queue's pod holds both of its roles under one ServiceAccount: the # server's leaf is issued with `swarm-nats`, and the responder reads its @@ -453,6 +454,10 @@ let # it: the pod is the service `swarm-nats`. natsPodAccount = "swarm-nats"; + # The ServiceAccount Grafana's pod runs under: the pod is the service + # `swarm-grafana`. + grafanaPodAccount = "swarm-grafana"; + # The jwt role of one principal: the token of exactly its ServiceAccount (the # one of its name, unless the record names another), for this store's # audience. Both the subject and the audience are bound, so a diff --git a/nix/host-modules/swarm-bao.nix b/nix/host-modules/swarm-bao.nix index 1610f15e0..c757bdf15 100644 --- a/nix/host-modules/swarm-bao.nix +++ b/nix/host-modules/swarm-bao.nix @@ -117,9 +117,8 @@ let collectorServiceName = "bao"; # Upstream's own default, kept so its documentation matches. The raft data - # lives INSIDE the container on `ephemeral = false`, the same way - # ./swarm-grafana.nix keeps its sqlite database — no sibling service binds - # its state out to the host. + # lives INSIDE the container on `ephemeral = false`; no container of + # the swarm binds its state out to the host. # # ⚠️ Do not bind-mount this path. Upstream pairs `StateDirectory=` with # `DynamicUser=`, which makes systemd hold the state at @@ -1799,7 +1798,8 @@ in example = "swarm-bao-grafana-oidc.svc"; description = '' Subject the store's `swarm-grafana-oidc` cert-auth role accepts — the - identity the unit that fetches Grafana's OIDC client secret presents. + identity the fetch of Grafana's OIDC client secret presents; the pod's + `swarm-grafana-oidc` jwt role carries the same policy. Its grant is one path, `swarm/services//oidc/client`, and read only. Not @@ -2051,11 +2051,12 @@ in default = "swarm-store-auth"; description = '' Subject the store's `swarm-store-auth` cert-auth role accepts: the - identity the unit that publishes the log store's, the metrics store's and the - queue exporter's listener credentials presents from the host - (./k8s/store-credentials.nix). Its grant is create and read on + identity the unit that publishes the log store's, the metrics store's, + Grafana's and the queue exporter's listener credentials presents from the + host (./k8s/store-credentials.nix). Its grant is create and read on `swarm/services/victorialogs/store-auth`, - `swarm/services/victoriametrics/store-auth` and + `swarm/services/victoriametrics/store-auth`, + `swarm/services/grafana/store-auth` and `swarm/services/nats/exporter-auth`, and nothing else. ⚠️ Reserved as a hive name by ./swarm.nix, like its siblings. diff --git a/nix/host-modules/swarm-ci-runner.nix b/nix/host-modules/swarm-ci-runner.nix index 0e125d865..e085998bd 100644 --- a/nix/host-modules/swarm-ci-runner.nix +++ b/nix/host-modules/swarm-ci-runner.nix @@ -254,7 +254,7 @@ in services.hyperhive.gateway.enable = lib.mkDefault true; services.hyperhive.gateway.dns.enable = lib.mkDefault true; - # Shaped after ./swarm-grafana.nix's `swarm-bao-grafana-oidc`, except that + # Shaped after the forge's `swarm-bao-forge-oidc`, except that # a missing token fails too: swarm-controller publishes it at its start and # every five minutes, so a retry is what turns "no value there" into one. systemd.services.swarm-bao-ci-runner = { diff --git a/nix/host-modules/swarm-controller.nix b/nix/host-modules/swarm-controller.nix index dadb83760..b8e43c474 100644 --- a/nix/host-modules/swarm-controller.nix +++ b/nix/host-modules/swarm-controller.nix @@ -1145,8 +1145,8 @@ in SWARM_CONTROLLER_MATRIX_ADMIN_SYNC_IGNORE_USERS = lib.concatStringsSep " " deployCfg.swarm-controller.matrixAdminSync.ignoreUsers; # Where `GET /api/alerts` reads alerts (swarm-controller/src/observability/alerts.rs). # Every swarm has one Grafana, reached by name wherever it runs. The - # token is in the store, written by `swarm-bao-grafana-controller-token` - # on Grafana's host. + # token is in the store, written by the `controller-token` + # container of Grafana's pod. SWARM_CONTROLLER_GRAFANA_URL = "https://${swarmCfg.grafana.domain}"; # The names squid allows every authenticated agent by default. The # allow-list route refuses them as entries diff --git a/nix/host-modules/swarm-grafana-service.nix b/nix/host-modules/swarm-grafana-service.nix index 710efaeeb..cea247a07 100644 --- a/nix/host-modules/swarm-grafana-service.nix +++ b/nix/host-modules/swarm-grafana-service.nix @@ -1,6 +1,6 @@ # The swarm's metrics UI as every hive sees it: the name it is served under # and the OIDC client it is registered as, identical on every host. What the -# host running it decides, and the container itself, are in +# host running it decides, and its pod, are in # ./swarm-grafana.nix. { lib, @@ -23,38 +23,9 @@ in # Here is what the service IS to every hive: the name it is served under # and the OIDC client it is registered as. What the host running it # decides — which build it runs, where its datasources point, which plugins - # are in its store path, and the socket directory it shares with nginx — is + # are in its store path — is # `deploy.grafana`, in ./swarm-grafana.nix. options.services.hyperhive.swarm.grafana = { - machine = lib.mkOption { - type = lib.types.str; - readOnly = true; - default = "swarm-grafana"; - description = '' - Container name. Read-only: the name appears in host paths and in - `machinectl`, so it is a fact other modules may read rather than a - knob. - ''; - }; - - otel.clientId = lib.mkOption { - type = lib.types.str; - readOnly = true; - default = "swarm-grafana-collector"; - description = '' - OAuth2 client id the journal forwarder inside Grafana's container - authenticates as, and the audience it asks its token for. Its own, - not {option}`services.hyperhive.swarm.grafana.oidc.clientId`, which - is the browser login's. - - Read-only because three hosts have to agree on it: authelia - registers the client (`glue-grafana-otel-oidc-client.nix`), the - swarm collector admits it on the container's receiver - (`swarm.otel.serviceProducers`), and authelia's mint stores - its secret in the store. - ''; - }; - domain = lib.mkOption { type = lib.types.str; default = "grafana.${domainBase}"; @@ -98,8 +69,8 @@ in OAuth callback authelia sends the browser back to, and the URI it matches **exactly**. - Read-only, like {option}`services.hyperhive.swarm.grafana.machine` - and for the same reason: Grafana derives it from its own + Read-only + because Grafana derives it from its own `root_url` (`/login/generic_oauth`), so it is a fact other modules may read rather than a knob. The glue that registers this client wherever authelia runs reads it from here instead of diff --git a/nix/host-modules/swarm-grafana.nix b/nix/host-modules/swarm-grafana.nix index 2bb4bdaee..afd479d5c 100644 --- a/nix/host-modules/swarm-grafana.nix +++ b/nix/host-modules/swarm-grafana.nix @@ -1,13 +1,11 @@ -# The swarm's metrics UI: one Grafana for the whole swarm, in a -# `swarm-grafana` nixos-container, reading the VictoriaMetrics store. +# The swarm's metrics UI: one Grafana for the whole swarm, a pod in the host's +# cluster (./k8s/render.nix, docs/4-implementation/k8s/runtime.md), reading the +# VictoriaMetrics and VictoriaLogs stores through the gateway. # -# Two containers rather than one, on the operator's call: Grafana can be -# restarted, reconfigured or broken without taking the TSDB down with it. -# They are a pair, not a unit. -# -# Dashboards are provisioned from files in this repo, deliberately not created -# in the UI: the store path is immutable, so Grafana is told not to accept UI -# edits it would lose on the next rebuild. +# Dashboards, datasources and alert rules are provisioned from this repo and +# baked into the pod's image, deliberately not created in the UI: the store path +# is immutable, so Grafana is told not to accept UI edits it would lose on the +# next rebuild. { pkgs, lib, @@ -24,8 +22,6 @@ let baoCfg = hyperhiveCfg.swarm.bao; baoDeploy = deployCfg.bao; - rootfsCheck = import ./lib/container-rootfs-check.nix { inherit config; }; - caTrust = import ./lib/hive-ca-trust.nix { inherit lib gatewayCfg; tlsCfg = deployCfg.hive-controller.tls; @@ -315,137 +311,913 @@ let autheliaUrl = toString hyperhiveCfg.swarm.authelia.url; - # The container's journal forwarder pushes to its own receiver on the swarm - # collector, the route `serviceProducers.swarm-grafana` in - # ./swarm-otel-service.nix declares, as a client of its own rather than the - # browser login's. - forwarderClientId = cfg.otel.clientId; - forwarderEndpoint = "https://${hyperhiveCfg.swarm.otel.domain}/${cfg.machine}"; - forwarderUnit = "swarm-journal-forwarder-oidc"; - # Loopback port of the forwarder's own metrics, inside the container's netns: - # no other collector shares it. The module requires a value. - forwarderTelemetryPort = 8896; + k8sCfg = hyperhiveCfg.k8s; + inherit (import ../images { inherit pkgs lib; }) mkServiceImage; + storeAuth = import ./lib/store-auth.nix; + podAuth = import ./lib/bao-pod-auth.nix; - # Grafana's store identity, handed into the container as system credentials - # (credential id → host source) for the forwarder's fetch unit. The host units - # below keep reading the same files directly. - storeFiles = lib.filterAttrs (_: source: source != null) { - grafana-bao-cert = baoDeploy.grafanaOidcClientCertFile; - grafana-bao-key = baoDeploy.grafanaOidcClientKeyFile; - grafana-bao-server-ca = baoDeploy.serverCaFile; - }; - # nixos-container expands `extraFlags` unquoted, so a source path must be - # one word. - oneWord = path: builtins.match ".*[[:space:]].*" path == null; - forwarderCredential = id: "/run/credentials/${forwarderUnit}.service/${id}"; + # The workload, as the cluster names it. Its Service has the name, which the + # gateway dials. The pod runs under the ServiceAccount of that name and logs + # in to the secret store with the role the certificate's holds + # (`grafanaOidcReaders` in ./swarm-bao-readers.nix). + service = "swarm-grafana"; + oidcRole = "swarm-grafana-oidc"; + grafanaPort = 3000; + dataDir = "/var/lib/grafana"; + hostDataDir = "/var/lib/nixos-containers/swarm-grafana${dataDir}"; + credDir = "/run/credentials/${service}.service"; - # The three secrets below land on the host's /run (tmpfs), which the - # container bind-mounts read-only at the same path: none reaches persistent - # disk, and a reboot fetches them again. Each file is absent until its - # delivery unit has run, and Grafana does not start without them — `$__file{}` - # on a missing path is a startup error, and an empty admin password would - # fall back to the upstream default. A delivery unit that writes a file - # restarts or starts Grafana (`refresh_consumer`). + serviceHost = name: "${name}.${k8sCfg.namespace}.svc.${deployCfg.k8s.clusterDomain}"; + + # What a location needs to dial the Service: the host's resolver, which hands + # the cluster's domain to CoreDNS, and the name in a variable, so that nginx + # looks it up per request (./swarm-victoriametrics.nix says why). + grafanaVariable = "$swarm_grafana_upstream"; + viaGrafana = '' + resolver ${networkCfg.bridgeIp} valid=10s ipv6=off; + set ${grafanaVariable} ${serviceHost service}:${toString grafanaPort}; + ''; + + # The secrets land in the pod's in-memory runtime directory: the init + # container writes them before Grafana starts, and none reaches a disk. Each + # file is absent until the init container has run, and Grafana does not + # start without them: `$__file{}` on a missing path is a startup error, and an + # empty admin password would fall back to the upstream default. They are + # read once, at start (docs/4-implementation/k8s/runtime.md says what a + # rotation needs). # - # Spelled once: the unit that writes a file and the config that names it are - # a few hundred lines apart, and a Grafana reading a path nothing writes is - # a login that fails with nothing in any log about the file. - secretDir = "/run/swarm-grafana-secrets"; + # Spelled once: the script that writes a file and the config that names it + # are a few hundred lines apart, and a Grafana reading a path nothing writes + # is a login that fails with nothing in any log about the file. + secretDirName = "grafana-secrets"; + secretDir = "/run/${secretDirName}"; secretPath = "${secretDir}/${cfg.oidc.clientId}.secret"; - # Where the three files sat on persistent disk before they moved to /run. - legacyHostSecretPaths = map (p: "/var/lib/nixos-containers/${cfg.machine}${p}") [ - "/var/lib/grafana-oidc/${cfg.oidc.clientId}.secret" - "/var/lib/grafana-admin/password" - "/var/lib/grafana-metrics/bearer" - ]; - # Where authelia's mint, in its container, stores this client's secret. A # swarm service's client is registered once for the whole swarm, so its # secret is one value and not one per hive. Both ends compose this from the # same swarm-wide client id, so a rename cannot leave one of them behind. # - # ⚠️ The prefix is not decoration: it is what this host's read grant covers, - # so a path outside it answers 403 rather than a miss, however correct it - # looks. + # ⚠️ The prefix is not decoration: it is what the role's grant covers, so a + # 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. Minted once into the store by - # `swarm-bao-grafana-secret-key` below, seeded from the file an earlier - # release generated in the 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. 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. secretKeyStorePath = "secret/swarm/services/${cfg.oidc.clientId}/secret-key"; secretKeyPath = "${secretDir}/secret-key"; - # The earlier file as the host sees it: the seed for an empty store. It stays - # on disk, unused once the store holds the key. - legacySecretKeyPath = "/var/lib/nixos-containers/${cfg.machine}/var/lib/grafana-secret/secret_key"; # 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 - # vhost and its password cannot be the upstream default. Minted once into the - # store by `swarm-bao-grafana-admin` below, which `swarm-bao.nix`'s - # `grafanaOidcReaders` grants create and read on this one leaf. + # vhost and its password cannot be the upstream default. Created once in the + # store by the init container, under the same grant as the key. adminPasswordStorePath = "secret/swarm/services/${cfg.oidc.clientId}/admin/password"; adminPasswordPath = "${secretDir}/admin-password"; - # The bearer the metrics datasource presents at the metrics store's query - # API, which `swarm-metrics-auth` on the store's host checks against the - # same store path, and the logs datasource at the log store's query API, - # which a second `swarm-metrics-auth` instance in ./swarm-victorialogs.nix - # checks against it. Minted once by `swarm-bao-grafana-metrics-bearer` - # below, under the same grant as the admin password. The file holds the whole + # The bearer the datasources present at the stores' query APIs through the + # gateway, which the stores' Grafana responders check against the same store + # path (`swarm-metrics-grafana-auth` and `swarm-logs-grafana-auth`). Created + # once by the init container, under the same grant. The file holds the whole # header value, `Bearer `: nixpkgs accepts a `secureJsonData` entry # only when it is exactly one `$__file{}`. metricsBearerStorePath = "secret/swarm/services/${cfg.oidc.clientId}/metrics/bearer"; metricsBearerPath = "${secretDir}/metrics-bearer"; - # swarm-controller's token for Grafana's API, minted by - # `swarm-bao-grafana-controller-token` below for a Viewer service account of - # this name. `controllerGrafanaTokenLeaf` in ./swarm-bao.nix is the nix half - # of the path, `swarm_secret_client::grafana::controller_token_path` the Rust - # half. + # swarm-controller's token for Grafana's API, minted by the sidecar for a + # Viewer service account of this name. `controllerGrafanaTokenLeaf` in + # ./swarm-bao.nix is the nix half of the path, + # `swarm_secret_client::grafana::controller_token_path` the Rust half. controllerAccountName = "swarm-controller"; controllerTokenStorePath = "secret/swarm/controller/swarm-controller/grafana/token"; - socketPath = "${deployCfg.grafana.socketDir}/grafana.sock"; + pluginDir = pkgs.linkFarm "grafana-plugins" ( + map (pkg: { + name = pkg.pname; + path = pkg; + }) deployCfg.grafana.plugins + ); - # Both static NixOS ids, and both checked rather than assumed: nginx has - # `ids.gids.nginx = 60`, Grafana has `ids.uids.grafana = 196` — but there is - # deliberately no `ids.gids.grafana`, which is why the OIDC-secret unit - # below lands its file root-group at 0400 instead of reaching for one. - nginxGid = config.ids.gids.nginx; - grafanaUid = config.ids.uids.grafana; + # The provisioning directory upstream's module builds, as a link farm: the + # same three kinds of file in the same places. + yaml = pkgs.formats.yaml { }; + provisioningDir = pkgs.linkFarm "grafana-provisioning" [ + { + name = "datasources/datasource.yaml"; + path = yaml.generate "datasource.yaml" grafana.provision.datasources.settings; + } + { + name = "dashboards/dashboard.yaml"; + path = yaml.generate "dashboard.yaml" grafana.provision.dashboards.settings; + } + { + name = "alerting/rules.yaml"; + path = yaml.generate "rules.yaml" grafana.provision.alerting.rules.settings; + } + ]; - atomicWriteSecret = import ./lib/atomic-write-secret.nix { }; - refreshConsumer = import ./lib/refresh-consumer.nix { }; - grafanaSecretKey = import ./lib/grafana-secret-key.nix { }; + # The ini file as nixpkgs' module renders it. + settingsFormat = pkgs.formats.ini { + listToValue = lib.concatMapStringsSep " " (lib.generators.mkValueStringDefault { }); + mkKeyValue = lib.generators.mkKeyValueDefault { + mkValueString = v: if v == null then "" else lib.generators.mkValueStringDefault { } v; + } "="; + }; + configFile = settingsFormat.generate "config.ini" grafana.settings; + homePath = "${deployCfg.grafana.package}/share/grafana"; - # First statement of each delivery script, ahead of the store login: the - # directory is the container's bind source, so it has to exist even when the - # store does not answer. tmpfiles creates it too, but unordered with the - # container on a switch. - ensureSecretDir = "install -d -m 0755 ${lib.escapeShellArg secretDir}"; + # What the pod runs: the admin password is applied to the database before the + # server listens, because the setting gives only a newly created database + # its password and a database created earlier keeps the one it was created + # with. `grafana cli` opens the database the server opens, which the same + # config names. + start = pkgs.writeShellScriptBin service '' + set -euo pipefail + grafana=${lib.getExe' deployCfg.grafana.package "grafana"} + "$grafana" cli --homepath ${homePath} --config ${configFile} \ + admin reset-admin-password --password-from-stdin < ${adminPasswordPath} + exec "$grafana" server --homepath ${homePath} --config ${configFile} + ''; - # A netns of its own on the hive bridge: the container dials the store, - # authelia, the swarm collector and both datasources through the bridge, and - # the gateway reaches Grafana over its socket, so no TCP port is bound. - privateNetwork = true; - storeRetry = import ./lib/store-retry.nix { }; - storeRefreshTimer = import ./lib/store-refresh-timer.nix { }; - retryInJob = import ./lib/retry-in-job.nix { }; + # Everything the init container and the sidecar need to speak to the store + # and Grafana's API. The store's `bao` is the one client both scripts use. + tools = [ + baoDeploy.package + pkgs.coreutils + pkgs.curl + pkgs.gnugrep + pkgs.jq + pkgs.openssl + ]; - # How long the controller-token unit waits for Grafana's socket before it - # fails into `storeRetry`'s restart. `container@` is ready when the guest's - # boot finishes, which can be before Grafana listens. - socketWaitSec = 60; + # Logs in with the pod's ServiceAccount token, under the role the pod's + # environment names (`BAO_JWT_*`, from ./k8s/render.nix). + login = '' + BAO_TOKEN="$(bao write -field=token "auth/$BAO_JWT_MOUNT/login" role="$BAO_JWT_ROLE" jwt="@$BAO_JWT_FILE")" + export BAO_TOKEN + ''; + + # The init container: Grafana's secrets, from the store. The store's value + # wins and a leaf that holds none is created, so the first value stored is + # the one every later start reads (`-cas=0` never replaces one, and a lost + # race reads the winner's back). + fetch = pkgs.writeShellScriptBin "swarm-grafana-fetch" '' + export PATH=${lib.makeBinPath tools} + set -euo pipefail + umask 0277 + ${login} + d=${lib.escapeShellArg secretDir} + + put() { + printf '%s' "$2" > "$d/$1.new" + mv -f "$d/$1.new" "$d/$1" + } + stored() { + bao kv get -field=value "$1" 2>/dev/null || true + } + seeded() { + local value + value="$(stored "$1")" + if [ -z "$value" ]; then + openssl rand -hex 32 | tr -d '\n' | bao kv put -cas=0 "$1" value=- >/dev/null 2>&1 || true + value="$(stored "$1")" + fi + if [ -z "$value" ]; then + echo "swarm-bao holds nothing at $1 and took no value; Grafana does not start without it." >&2 + exit 1 + fi + printf '%s' "$value" + } + + oidc="$(stored ${lib.escapeShellArg storeSecretPath})" + if [ -z "$oidc" ]; then + echo "swarm-bao holds nothing at ${storeSecretPath}; Grafana has no OIDC client secret yet." >&2 + exit 1 + fi + 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})" + echo "Grafana's secrets are in $d" + ''; + + # The sidecar: keeps swarm-controller's Viewer service account and its token. + # Every pass checks the stored token with the call the controller makes with + # it, and replaces it when Grafana refuses it, as it does after its database + # is recreated. Grafana's API takes the admin password the init container + # wrote, on the pod's loopback. + controllerToken = pkgs.writeShellScriptBin "swarm-grafana-controller-token" '' + export PATH=${lib.makeBinPath tools} + set -uo pipefail + base=http://127.0.0.1:${toString grafanaPort} + body="$(mktemp)" + + grafana() { + local auth="$1" method="$2" path="$3" + shift 3 + curl --silent --show-error --connect-timeout 5 --max-time 15 \ + -H @<(printf 'Authorization: %s\n' "$auth") \ + -H 'Content-Type: application/json' \ + -X "$method" -o "$body" -w '%{http_code}' "$@" \ + "$base$path" + } + + expect() { + local what="$1" status="$2" + shift 2 + for ok in "$@"; do + [ "$status" = "$ok" ] && return 0 + done + echo "Grafana answered $status to $what:" >&2 + cat "$body" >&2 + return 1 + } + + pass() { + local admin status account id stored key token_id + admin="Basic $(printf 'admin:%s' "$(< ${lib.escapeShellArg adminPasswordPath})" | base64 -w0)" + + status="$(grafana "$admin" GET '/api/serviceaccounts/search?perpage=1000&query=${controllerAccountName}')" + expect "the service account search" "$status" 200 || return 1 + account="$(jq -c --arg n ${controllerAccountName} '[.serviceAccounts[] | select(.name == $n)][0] // empty' "$body")" + if [ -z "$account" ]; then + status="$(grafana "$admin" POST /api/serviceaccounts \ + --data '{"name":"${controllerAccountName}","role":"Viewer","isDisabled":false}')" + expect "creating the ${controllerAccountName} service account" "$status" 200 201 || return 1 + account="$(jq -c . "$body")" + echo "created the ${controllerAccountName} service account as a Viewer" + fi + id="$(jq -r .id <<<"$account")" + if [ "$(jq -r '"\(.role) \(.isDisabled // false)"' <<<"$account")" != "Viewer false" ]; then + status="$(grafana "$admin" PATCH "/api/serviceaccounts/$id" \ + --data '{"role":"Viewer","isDisabled":false}')" + expect "setting the ${controllerAccountName} service account to an enabled Viewer" "$status" 200 || return 1 + echo "set the ${controllerAccountName} service account back to an enabled Viewer" + fi + + ${login} + + stored="$(bao kv get -field=value ${lib.escapeShellArg controllerTokenStorePath} 2>/dev/null || true)" + if [ -n "$stored" ]; then + status="$(grafana "Bearer $stored" GET /api/prometheus/grafana/api/v1/alerts)" + case "$status" in + 200) return 0 ;; + 401) echo "Grafana refuses the stored token for ${controllerAccountName}; replacing it." ;; + *) expect "reading alerts with the stored token" "$status" 200 || return 1 ;; + esac + fi + + status="$(grafana "$admin" GET "/api/serviceaccounts/$id/tokens")" + expect "listing the ${controllerAccountName} tokens" "$status" 200 || return 1 + for token_id in $(jq -r '.[].id' "$body"); do + status="$(grafana "$admin" DELETE "/api/serviceaccounts/$id/tokens/$token_id")" + expect "deleting token $token_id of ${controllerAccountName}" "$status" 200 || return 1 + done + + status="$(grafana "$admin" POST "/api/serviceaccounts/$id/tokens" \ + --data "{\"name\":\"${controllerAccountName}-$(date +%s)\"}")" + expect "minting a ${controllerAccountName} token" "$status" 200 || return 1 + key="$(jq -r .key "$body")" + : >"$body" + if ! printf '%s' "$key" | bao kv put ${lib.escapeShellArg controllerTokenStorePath} value=- >/dev/null; then + echo "could not store the new ${controllerAccountName} token at ${controllerTokenStorePath}; the next pass replaces it." >&2 + return 1 + fi + echo "stored a new ${controllerAccountName} token at ${controllerTokenStorePath}" + } + + while true; do + if curl --silent --fail --output /dev/null --connect-timeout 5 --max-time 15 "$base/api/health"; then + pass || echo "the pass failed; the next one retries." >&2 + sleep 300 + else + sleep 5 + fi + done + ''; + + setupImage = mkServiceImage { + name = "${service}-setup"; + package = pkgs.symlinkJoin { + name = "${service}-setup"; + paths = [ + fetch + controllerToken + ]; + }; + bin = "swarm-grafana-fetch"; + }; + + # Upstream's `services.grafana` options, as plain data: what the pod's + # config file, provisioning and plugins are rendered from (above). + grafana = { + package = deployCfg.grafana.package; + + # Passed through unconditionally, empty default included. + # Upstream distinguishes `null` from `[ ]`, and both differences + # favour always handing it a list: + # + # - `null` points the plugin path at grafana's mutable + # `/plugins`; any list points it at a store path. + # Switching on the day someone adds their first plugin would + # bury that change inside an unrelated one. + # - upstream defaults its plugin update-check to + # `declarativePlugins == null`, so a list also stops the + # pod phoning grafana.com. That is the no-runtime-egress + # property this option exists for — it should not arrive only + # once a plugin happens to be listed. + # + # - 🩸 it also sets upstream's `plugins.preinstall_disabled` + # (nixpkgs' + # grafana.nix defaults it to `declarativePlugins != null`, + # saying preinstall "causes issues with declarativePlugins"). + # Preinstall is what fetches the Drilldown apps on first + # start, so claiming this directory silently removes them. + # That is why the option's default is not empty. + # + # Taking this directory over is not harmless on a hive with no + # plugins: that reasoning covers only plugins a PERSON installs, + # and upstream installs some itself. + declarativePlugins = deployCfg.grafana.plugins; + + settings = { + server = { + # TCP, for the gateway on the node: the pod's Service reaches + # this port and the namespace's policy admits only the node to + # it. Grafana's own login (SSO, or basic auth on the API) is + # the credential of every route but `/api/health`, `/healthz` + # and `/metrics`, which `metrics.basic_auth_*` below gates. + protocol = "http"; + http_addr = "0.0.0.0"; + http_port = grafanaPort; + domain = cfg.domain; + # Grafana builds its own OAuth redirect from this. Left at + # upstream's `%(protocol)s://%(domain)s:%(http_port)s/` it + # would name `http://:3000/`, which authelia has + # never heard of. + root_url = "https://${cfg.domain}/"; + }; + + paths = { + data = dataDir; + plugins = pluginDir; + provisioning = provisioningDir; + }; + + # Pod logs are the container's output: the host collector reads + # them from the node. + log.mode = "console"; + + analytics = { + reporting_enabled = false; + check_for_updates = false; + # The plugin directory is the store's, so nothing checks for updates. + check_for_plugin_updates = false; + }; + + # Stated rather than inherited. This is upstream's default, but + # a scrape target now depends on it, and a default that changes + # silently takes the target with it — the endpoint disappears, + # nginx keeps answering, and the scrape fails with a 404 far + # from anything that mentions Grafana. + # + # The endpoint answers anyone who reaches the port, so it takes the + # login every store takes (`swarm-store` and the password the + # unit publishes as the Secret the pod loads): the vhost sends it + # after authelia has admitted the collector. Both keys are read at + # start by Grafana's settings (`MetricsEndpointBasicAuthUsername` + # and `...Password`, in `pkg/setting/setting.go`). + metrics = { + enabled = true; + basic_auth_username = storeAuth.user; + basic_auth_password = "$__file{${credDir}/${storeAuth.credentialId}}"; + }; + + # Grafana hands an external backend plugin only an allow-list of + # its environment (the proxy variables), so without this the logs + # datasource never sees the unit's `SSL_CERT_FILE` and rejects the + # log store's certificate as `x509: unknown authority`. The value + # is plugin ids, not variable names: each listed plugin gets the + # whole environment. + plugins = { + forward_host_env_vars = "victoriametrics-logs-datasource"; + preinstall_disabled = true; + }; + + users.auto_assign_org_role = cfg.oidc.role; + + # ⚠️ `$__file{}`, and required rather than optional: nixpkgs + # dropped the default and asserts on null, so without this the + # whole host fails to build. Written by the init container. + security.secret_key = "$__file{${secretKeyPath}}"; + + # The password a newly created database gets; the start script + # gives an existing one the same. Written by the init container. + security.admin_password = "$__file{${adminPasswordPath}}"; + + # No password box on the public login page: people log in through + # SSO. This hides the form only; the API still takes basic auth, + # which is why the admin password above is minted. + # + # Not conditional on anything, and the block below is not + # either, which is what keeps the two from ever disagreeing. + # Whether a password box sits on a public login page cannot + # depend on which host happens to run authelia. + auth.disable_login_form = true; + + # Emitted in every deployment, because SSO is a requirement of + # running this service rather than a feature of some topologies: + # the assertions above refuse to build a Grafana that lacks an + # IdP to point at or the identity to fetch its secret with. A + # `lib.optionalAttrs` here would be the silent half of that pair, + # dropping the only login this pod has whenever a value + # went null. + "auth.generic_oauth" = { + enabled = true; + name = "HyperHive"; + client_id = cfg.oidc.clientId; + # ⚠️ `$__file{}`, never the secret itself — anything else + # here is world-readable in the nix store. Note the module's + # own leak assertion does NOT cover this key (it checks + # `database.password`, `security.admin_password` and + # datasource `secureJsonData`), so nothing but this comment + # stands between a literal and the store. + # + # The init container `fetch-secrets` writes this path before + # Grafana starts. + client_secret = "$__file{${secretPath}}"; + scopes = "openid profile email groups"; + auth_url = "${autheliaUrl}/api/oidc/authorization"; + token_url = "${autheliaUrl}/api/oidc/token"; + api_url = "${autheliaUrl}/api/oidc/userinfo"; + use_pkce = true; + }; + }; + + provision.datasources.settings = { + apiVersion = 1; + datasources = [ + { + name = "VictoriaMetrics"; + type = "prometheus"; + uid = datasourceUid; + url = deployCfg.grafana.datasourceUrl; + access = "proxy"; + isDefault = true; + # The store's query routes admit this bearer or an operator's + # session, and nothing else. + jsonData.httpHeaderName1 = "Authorization"; + secureJsonData.httpHeaderValue1 = "$__file{${metricsBearerPath}}"; + } + { + name = "VictoriaLogs"; + # The plugin's own id, read from its `plugin.json` rather + # than guessed. A `type` Grafana does not recognise is + # provisioned without complaint and every query against it + # fails at use, far from anything naming this file. + type = "victoriametrics-logs-datasource"; + uid = logsDatasourceUid; + url = deployCfg.grafana.logsDatasourceUrl; + access = "proxy"; + # Exactly one datasource may claim this, and metrics has it: + # two defaults is a coin toss over which one an untyped panel + # gets. + isDefault = false; + # See `logLevelRules` above for why the level lives here and + # not in the pipeline. + jsonData = { + inherit logLevelRules; + httpHeaderName1 = "Authorization"; + }; + # The metrics datasource's bearer; the log store's vhost + # accepts it on `/select/logsql/`. + secureJsonData.httpHeaderValue1 = "$__file{${metricsBearerPath}}"; + } + ]; + }; + + provision.dashboards.settings = { + apiVersion = 1; + providers = [ + { + name = "hyperhive"; + type = "file"; + # Read-only in the UI: the store path is immutable, so an edit + # saved here would be silently discarded on the next rebuild. + # Better to refuse the edit than to lose it. + allowUiUpdates = false; + options.path = dashboardDir; + } + ]; + }; + + # Rules only. With no policy provisioned, Grafana routes every alert + # to its built-in `empty` receiver, which has no integrations: a + # firing rule shows under Alerting → Alert rules and is sent nowhere. + provision.alerting.rules.settings = { + apiVersion = 1; + groups = [ + { + orgId = 1; + name = "hyperhive"; + folder = "hyperhive"; + interval = "1m"; + rules = [ + # The controller re-runs the forge objects pass every 5m + # (`RECONCILE_INTERVAL` in swarm-controller's + # forge/objects.rs) and warns once per failed write. A + # 10m window always spans the previous tick, so a pass + # failing on every tick keeps the count above zero + # continuously and fires after `for`. One failed pass + # keeps it above zero for only 10m, short of the 15m + # `for`, so it never fires; about three failed passes in + # a row do. + (logCountRule { + uid = "hh-forge-objects-write-failed"; + title = "forge reconcile failing"; + windowSeconds = 600; + expr = ''_time:10m _msg:"swarm forge objects: write failed; retrying next pass" | stats count() as failures''; + for = "15m"; + summary = "swarm-controller has failed to write forge objects on consecutive reconcile passes"; + }) + # `agent` is the resource attribute every agent container's log + # forwarder carries, and agent names are unique in the swarm, so + # each agent is its own alert instance. + (logCountRule { + uid = "hh-swarm-term-publish-skipped"; + title = "swarm terminal publish skipped"; + windowSeconds = 900; + expr = ''_time:15m _msg:"swarm terminal: publish skipped" | stats by (agent) count() as skipped''; + for = "5m"; + summary = "{{ $labels.agent }} is dropping swarm terminal rows: the harness is not connected to the queue"; + }) + # `CONNECT_EXHAUSTED` in hive-agent's swarm_queue.rs, + # logged when the harness's first-connect retries + # (about five minutes) all fail, just before it exits. + # systemd restarts it 30s later, so an agent that never + # connects logs it about every six minutes. The window + # is how long the rule stays firing after the last one. + (logCountRule { + uid = "hh-swarm-queue-connect-failed"; + title = "swarm queue connect failed"; + windowSeconds = 3600; + expr = ''_time:1h _msg:"no swarm queue connection; exiting, since this agent cannot run without one" | stats by (agent) count() as failures''; + for = "0s"; + summary = "{{ $labels.agent }} could not connect to the swarm queue and its harness exited; systemd starts it again 30s later"; + }) + # A run that ends without a verdict leaves that PR with no + # classifier review. `swarm-review-classifier` logs four + # `warn` lines for it: `review classification run failed` + # (a rejected or unreadable API key, a failed model call; + # the cause is in `F_ERROR`), an undecodable request, and a + # reply it could not encode or publish. The window is how + # long the rule stays firing after the last one. + (logCountRule { + uid = "hh-review-classifier-run-failed"; + title = "review classifier run failed"; + windowSeconds = 1800; + expr = ''_time:30m (_msg:"review classification run failed" OR _msg:"an undecodable try-out; answering with the error" OR _msg:"encoding a try-out's reply failed" OR _msg:"publishing a try-out's reply failed") | stats count() as failures''; + for = "0s"; + summary = "a review-classifier run ended without a verdict, so that PR has no classifier review; the log line names the cause (F_ERROR on a failed run)"; + }) + (logCountRule { + uid = "hh-swarm-agent-state-publish-skipped"; + title = "swarm agent state publish skipped"; + windowSeconds = 900; + expr = ''_time:15m _msg:"swarm agent state: publish skipped" | stats by (agent) count() as skipped''; + for = "5m"; + summary = "{{ $labels.agent }} is dropping agent state updates: the harness is not connected to the queue"; + }) + # Logged on every connection attempt, so it repeats under + # the reconnect backoff for as long as the path is empty. + (logCountRule { + uid = "hh-swarm-queue-credential-missing"; + title = "swarm queue credential missing"; + windowSeconds = 900; + expr = ''_time:15m _msg:"nothing is stored at this agent's queue credential path; its queue connection retries under backoff" | stats by (agent) count() as missing''; + for = "5m"; + summary = "{{ $labels.agent }} finds nothing at its queue credential path and cannot connect to the queue"; + }) + # Logged once per failed turn, by `emit_turn_end` in + # hive-agent's turn.rs; the window is how long the rule + # stays firing after it. The exact `_msg` match and the + # unit keep out the subagent daemon's `subagent: turn + # failed` and the ACP backend's `ACP checkpoint turn + # failed`, which a phrase match would also count. + (logCountRule { + uid = "hh-agent-turn-failed"; + title = "agent turn failed"; + windowSeconds = 900; + expr = ''_time:15m _SYSTEMD_UNIT:="hive-agent.service" _msg:="turn failed" | stats by (agent) count() as failures''; + for = "0s"; + summary = "{{ $labels.agent }} had a claude turn fail; the reason is the `F_ERROR` field of the harness's `turn failed` log line"; + }) + # Same cadence as the forge rule: one pass every 5m + # (`RECONCILE_INTERVAL` in swarm-controller's + # agent_renewal.rs), one line per failed pass, so one + # failed pass never fires and about three in a row do. + (logCountRule { + uid = "hh-agent-credential-renewal-failed"; + title = "agent credential renewal failing"; + windowSeconds = 600; + expr = ''_time:10m _msg:"agent credential renewal: pass failed; retrying next tick" | stats count() as failures''; + for = "15m"; + summary = "swarm-controller has failed the agent credential renewal pass on consecutive ticks"; + }) + # `MINT_IDENTITY_FAILED` in swarm-controller's jobq.rs, + # logged once per failed `MintAgentIdentity` job node, at + # agent creation or on a certificate renewal; the window + # is how long the rule stays firing after it. Host + # journal records carry the tracing fields as `F_`. + (logCountRule { + uid = "hh-agent-identity-mint-failed"; + title = "agent identity mint failed"; + windowSeconds = 900; + expr = ''_time:15m _SYSTEMD_UNIT:="swarm-controller.service" _msg:"swarm jobq: mint_agent_identity failed" | stats by (F_AGENT) count() as failures''; + for = "0s"; + summary = "swarm-controller failed to mint agent {{ $labels.F_AGENT }}'s store identity; the reason is the `F_ERROR` field of the swarm-controller log line"; + }) + # `hive-archive-backup` (nix/host-modules/hive-archive-backup.nix) + # prints one `archive backup failed: ` line per agent + # it could not back up, and one for a hive swarm-controller + # has granted nothing. The backup runs hourly, so `for` + # rides out the minutes a newly placed agent waits for its + # grant, and a second failed run keeps it firing. + (logCountRule { + uid = "hh-archive-backup-failed"; + title = "archive backup failed"; + windowSeconds = 7800; + expr = ''_time:130m _SYSTEMD_UNIT:="hive-archive-backup.service" _msg:"archive backup failed" | stats by (_HOSTNAME) count() as failures''; + for = "30m"; + summary = "{{ $labels._HOSTNAME }} failed to back up an agent to the archive; the unit's journal names the agent and the cause"; + }) + # `swarm-archive-prune` prints `archive prune failed: `. + (logCountRule { + uid = "hh-archive-prune-failed"; + title = "archive prune failed"; + windowSeconds = 90000; + expr = ''_time:25h _SYSTEMD_UNIT:="swarm-archive-prune.service" _msg:"archive prune failed" | stats count() as failures''; + for = "0s"; + summary = "the archive's daily prune failed for an agent's repository, so its retention is not applied; the unit's journal names the agent"; + }) + # `swarm-archive-check` prints `archive check failed: `; it runs + # weekly, so the window spans a missed week. + (logCountRule { + uid = "hh-archive-check-failed"; + title = "archive check failed"; + windowSeconds = 700000; + expr = ''_time:8d _SYSTEMD_UNIT:="swarm-archive-check.service" _msg:"archive check failed" | stats count() as failures''; + for = "0s"; + summary = "the archive's weekly integrity check failed for an agent's repository, so its backups may not restore; the unit's journal names the agent and the restic error"; + }) + # Logged once per detected crash, by `emit_crash_transitions` + # in hive-c0re's crash_watch.rs (10s poll interval). Replaces + # the old per-hive dashboard `agents_crashing` banner — see + # that function's module doc for why the banner went away + # in favour of this. Host journal records carry the + # tracing fields as `F_` and no `sender` attribute, + # so the machine is `_HOSTNAME`. The unit + # filter keeps out an agent's own log line if one ever + # quotes the same message. + (logCountRule { + uid = "hh-container-crashed"; + title = "container crashed"; + windowSeconds = 900; + expr = ''_time:15m _SYSTEMD_UNIT:="hive-c0re.service" _msg:"container crash detected" | stats by (_HOSTNAME, F_AGENT) count() as crashes''; + for = "0s"; + summary = "{{ $labels._HOSTNAME }} detected agent {{ $labels.F_AGENT }}'s container crash (not an operator-initiated stop)"; + }) + # hive-c0re's readiness verdict, the one `/health/ready` + # gives: degraded while any `crit`-level warning is raised. + # Read from the per-warning series (`hyperhive.hive.warning`) + # rather than the `hyperhive.hive.degraded` gauge, so each + # critical `kind` is its own instance and the alert names + # the warning that triggered it. `for` rides out a + # restart-time blip. + (metricThresholdRule { + uid = "hh-hive-degraded"; + title = "hive degraded"; + expr = ''max by (sender, kind) ({__name__="hyperhive.hive.warning", level="crit"})''; + threshold = 0; + for = "2m"; + summary = "{{ $labels.sender }} is degraded by the critical warning {{ $labels.kind }}; the message is the `hive warning raised` line in the hive-c0re log"; + }) + # One series per raised warning (`hyperhive.hive.warning`), + # so each `kind` is its own alert instance. The text is the + # `hive warning raised` line in the hive-c0re log. Disk + # pressure is left out: it has its own thresholds below, on + # the filesystem metric rather than the registry entry. + # Sweeps raise their warning only after several misses, so + # `for` is short. `pending_logins` is dropped for a hive that exports + # `hyperhive.agent.needs_login`, where `hh-agent-needs-login` + # below pages once per agent; a hive on an older hive-c0re + # has no such series, so it keeps paging here. + (metricThresholdRule { + uid = "hh-hive-warning"; + title = "hive warning raised"; + expr = ''max by (sender, kind, level) ({__name__="hyperhive.hive.warning", kind!~"disk_pressure|pending_logins"} or ({__name__="hyperhive.hive.warning", kind="pending_logins"} unless on (sender) group by (sender) ({__name__="hyperhive.agent.needs_login"})))''; + threshold = 0; + for = "2m"; + summary = "{{ $labels.sender }} has a {{ $labels.level }} warning raised: {{ $labels.kind }}; the message is the `hive warning raised` line in the hive-c0re log"; + }) + # `hyperhive.agent.needs_login` is `1` for a running agent + # without a usable claude login; stopped agents report + # nothing. One alert instance per `agent`; `for` + # lets a login in progress finish first. + (metricThresholdRule { + uid = "hh-agent-needs-login"; + title = "agent needs a claude login"; + expr = ''max by (agent) ({__name__="hyperhive.agent.needs_login"}) == 1''; + threshold = 0; + for = "5m"; + summary = "agent {{ $labels.agent }} has needed a claude login for 5 minutes; open its page in the dashboard to complete it"; + }) + # Processes the kernel OOM-killed in an agent's container, from + # the counter hive-c0re exports (`otel_metrics.rs`). A budgeted + # agent has no swap, so each kill is a subagent run, bash task or + # the agent's claude that hit its RAM budget. More than three in + # an hour is a budget that is too small for the work, not a + # one-off peak. One alert instance per `agent`. + (metricThresholdRule { + uid = "hh-agent-oom-kills"; + title = "agent OOM-killed repeatedly"; + windowSeconds = 3600; + expr = ''sum by (agent) (increase({__name__="hyperhive.container.memory.oom_kills", agent!=""}[1h]))''; + threshold = 3; + for = "0m"; + summary = "agent {{ $labels.agent }} had more than 3 processes OOM-killed in the last hour: it keeps hitting its RAM budget; see \"OOM kills by agent\" on the agents dashboard, and raise its memory cap if the work needs it"; + }) + # `hyperhive.hive.nix_store.utilization` is the used fraction of the + # filesystem holding the nix store, the one that failed CI + # with ENOSPC before the GC guardrails. + (metricThresholdRule { + uid = "hh-host-disk-high"; + title = "host disk filling"; + expr = ''max by (sender) ({__name__="hyperhive.hive.nix_store.utilization"})''; + threshold = 0.85; + for = "10m"; + summary = "the nix store's filesystem of {{ $labels.sender }} is over 85% full; garbage-collect before it runs out of space"; + }) + (metricThresholdRule { + uid = "hh-host-disk-critical"; + title = "host disk almost full"; + expr = ''max by (sender) ({__name__="hyperhive.hive.nix_store.utilization"})''; + threshold = 0.95; + for = "2m"; + summary = "the nix store's filesystem of {{ $labels.sender }} is over 95% full; garbage-collect now"; + }) + # The fraction of a store client certificate's validity + # already used, from the `bao.client_cert.*` gauges the + # services export (`swarm_secret_client::cert_metrics`). Both gauges of a + # series carry identical labels, so the division matches + # one-to-one on all of them without `on()`/`group_left`. + # `last_over_time` rides out the five-minute cadence of + # the one-shot reporter (`swarm-ci-metrics`). Agent leaves + # renew at half their life, so a fraction over 0.8 means + # the renewal has been stuck for days. `sender` and `agent` + # stay in the grouping so the alert names the holder. + # Agents whose deploy the build gate holds back, from the gauge + # swarm-controller exports (`observability/held_deploys.rs`): a build that + # fails, or that keeps getting no answer from the builder. A deploy + # whose facts copy to its hive fails is held too. + # Thirty minutes covers a builder restart and the controller's + # ten-minute retries. + (metricThresholdRule { + uid = "hh-deploys-held"; + title = "deploys held by the build gate"; + expr = ''sum({__name__="swarm.deploys.held"})''; + threshold = 0; + for = "30m"; + summary = "swarm-controller is holding back the deploy of one or more agents because the builder's build of internal/meta fails or gets no answer, or the cache facts can't be copied to its hive; the failed `build_meta` or `copy_attic_facts` node on the Jobs page says which"; + }) + (metricThresholdRule { + uid = "hh-bao-client-cert-lifetime"; + title = "bao client certificate past 80% of its lifetime"; + expr = ''max by ("service.name", cert, sender, agent) ((time() - last_over_time({__name__="bao.client_cert.not_before"}[15m])) / (last_over_time({__name__="bao.client_cert.not_after"}[15m]) - last_over_time({__name__="bao.client_cert.not_before"}[15m])))''; + threshold = 0.8; + for = "10m"; + summary = "the store client certificate {{ $labels.cert }} (sender {{ $labels.sender }}, agent {{ $labels.agent }}) is past 80% of its validity"; + }) + # Usage share ahead of the clock share, per claude account and + # window: percent used minus the percent of the window already + # elapsed, so above zero means ahead. The window length comes + # from the `window` label (`seven_day`, `five_hour`); other + # windows are not selected. `account` is stamped by hive-agent + # (`claude_usage_watch`); series without it (older agent builds) + # are not selected. `max by` collapses the agents that share an + # account. A `resets_at` in the past makes the elapsed share + # exceed 100, so a stale series cannot fire. + (metricThresholdRule { + uid = "hh-claude-usage-ahead-of-clock"; + title = "claude usage ahead of the clock"; + expr = + let + ahead = + window: seconds: + ''max by (account, window) (last_over_time({__name__="hyperhive.agent.claude_usage.percent", window="${window}", account!=""}[15m])) - 100 * (1 - (max by (account, window) (last_over_time({__name__="hyperhive.agent.claude_usage.resets_at", window="${window}", account!=""}[15m])) - time()) / ${toString seconds})''; + in + "(${ahead "seven_day" 604800}) or (${ahead "five_hour" 18000})"; + threshold = 0; + for = "1h"; + summary = "claude account {{ $labels.account }} has used more of its {{ $labels.window }} usage window than the window has elapsed"; + }) + ] + # One rule per declared hive's collector rather than one grouped by + # `sender`, so a collector that sends nothing at all still has an + # instance to fire. The swarm collector stamps `sender` with the + # client id the hive's collector authenticated as, the same + # `hiveClientPrefix` name the OIDC client is registered under. + ++ lib.mapAttrsToList ( + name: _: + logAbsenceRule { + uid = "hh-logs-absent-${name}"; + title = "no log records from ${name}"; + windowSeconds = 600; + expr = ''_time:10m sender:="${hyperhiveCfg.swarm.authelia.hiveClientPrefix}${name}" | stats count() as records''; + for = "5m"; + summary = "hive ${name} has sent no log records to VictoriaLogs for at least 10m"; + } + ) hyperhiveCfg.swarm.hives; + } + ]; + }; + }; + + # The credentials the unit names are ids: the store identity the pod's login + # replaces, the store's CA (a public file the pod mounts from the cluster's CA + # ConfigMap) and the listener credential the pod loads from its Secret. + unit = { + serviceConfig = { + ExecStart = "${start}/bin/${service}"; + StateDirectory = "grafana"; + RuntimeDirectory = secretDirName; + LoadCredential = [ + "bao-client.pem" + "bao-client-key.pem" + storeAuth.credentialId + ] + ++ lib.optional (baoDeploy.serverCaFile != null) "bao-ca.pem"; + }; + environment = { + BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; + BAO_CLIENT_CERT = "${credDir}/bao-client.pem"; + BAO_CLIENT_KEY = "${credDir}/bao-client-key.pem"; + } + // lib.optionalAttrs (baoDeploy.serverCaFile != null) { + BAO_CACERT = "${credDir}/bao-ca.pem"; + } + # Go: `SSL_CERT_FILE` replaces its trust store, which the hive's CA joins + # for the names the pod dials through the gateway. + // lib.optionalAttrs caTrust.useSelfSigned { + SSL_CERT_FILE = caTrust.bundlePathFor service; + }; + path = [ ]; + }; + + # The init container and the sidecar log in as the pod does, with the + # environment and mounts of Grafana's container. + pod = + { + env, + volumeMounts, + securityContext, + ... + }: + let + ref = "${setupImage.imageName}:${setupImage.imageTag}"; + container = name: bin: { + inherit name securityContext; + image = ref; + imagePullPolicy = "IfNotPresent"; + command = [ "/bin/${bin}" ]; + env = lib.mapAttrsToList (n: v: { + 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; + }; + in + { + initContainers = [ (container "fetch-secrets" "swarm-grafana-fetch") ]; + containers = [ (container "controller-token" "swarm-grafana-controller-token") ]; + images = [ setupImage ]; + }; in { # What the service IS to every hive is `swarm.grafana` in # ./swarm-grafana-service.nix. What the host running it decides is here: # which build it runs, where its datasources point, which plugins sit in its - # store path, and the directory it shares a socket with nginx through. + # store path. # `enable` already lives in ./deploy.nix, which also carries the renames. # # Both datasource URLs are wiring, so they live here. @@ -457,30 +1229,6 @@ in description = "Grafana package to run."; }; - socketDir = lib.mkOption { - type = lib.types.str; - default = "/run/swarm-grafana"; - readOnly = true; - description = '' - Directory holding the unix socket Grafana serves on, shared between - the host (where nginx runs) and the container (where Grafana runs). - - Fixed, not configurable: the directory's mode is what keeps the socket - private, so it has to be dedicated to this one socket, and a settable - path could be pointed at a directory that carries something else. - - ⚠️ **Grafana takes no TCP port at all, and that is the point.** Every - swarm service container shares the host's network namespace, so a - port is a swarm-wide resource that two modules can silently both - claim — which is exactly what happened: Grafana defaulted to - upstream's 3000, so does the forge, and `grafana.` - served the forge with no bind error and nothing in any log. - - A socket has a path, and a path collision is a build-time conflict - rather than a runtime coin toss. - ''; - }; - datasourceUrl = lib.mkOption { type = lib.types.str; default = "https://${hyperhiveCfg.swarm.victoriametrics.domain}"; @@ -490,7 +1238,7 @@ in store's swarm name, served by the gateway of whichever host runs the store, so Grafana and the store need not share a host. - The datasource sends the bearer `swarm-bao-grafana-metrics-bearer` + The datasource sends the bearer the init container of Grafana's pod keeps in the swarm secret store, which is what the store's query routes on that vhost check. Whatever URL this names receives that bearer. @@ -541,8 +1289,8 @@ in That is a deliberate pair of decisions rather than an oversight, and this option is the way through it: plugins live in the store - and in git, so they survive a container rebuild and a state reset, - and the container needs no runtime egress to grafana.com. + and in git, so they survive a rebuild of the pod and a state reset, + and the pod needs no runtime egress to grafana.com. ⚠️ This list is the ONLY way a plugin reaches this Grafana. Setting it at all disables upstream's `preinstall` mechanism (see @@ -567,35 +1315,88 @@ in }; }; + options.services.hyperhive.deploy.grafana.unit = lib.mkOption { + type = lib.types.raw; + readOnly = true; + internal = true; + default = unit; + description = '' + Grafana's unit, the `serviceConfig`, `environment` and `path` that + ./k8s/render.nix renders its pod from. + ''; + }; + + options.services.hyperhive.deploy.grafana.rendered = lib.mkOption { + type = lib.types.raw; + readOnly = true; + internal = true; + default = grafana // { + scripts = { + start = builtins.unsafeDiscardStringContext start.text; + fetch = builtins.unsafeDiscardStringContext fetch.text; + controllerToken = builtins.unsafeDiscardStringContext controllerToken.text; + }; + configFile = builtins.unsafeDiscardStringContext (toString configFile); + }; + description = '' + What the pod is rendered from, as data: upstream's `services.grafana` + settings and provisioning, the config file, and the text of the scripts + the pod runs. The module-eval cases read it. + ''; + }; + + options.services.hyperhive.deploy.grafana.startPackage = lib.mkOption { + type = lib.types.package; + readOnly = true; + internal = true; + default = start; + description = "The pod's entry point, the `swarm-grafana` script that applies the admin password and starts the server."; + }; + + options.services.hyperhive.deploy.grafana.pod = lib.mkOption { + type = lib.types.raw; + readOnly = true; + internal = true; + default = pod; + description = '' + What the pod holds besides Grafana: a function of Grafana's container that + ./k8s/render.nix calls, giving the init container that fetches the + secrets, the sidecar that keeps the controller's token, and their image. + ''; + }; + + options.services.hyperhive.deploy.grafana.servicePort = lib.mkOption { + type = lib.types.port; + readOnly = true; + internal = true; + default = grafanaPort; + description = "The port the Service publishes."; + }; + + options.services.hyperhive.deploy.grafana.hostDataDir = lib.mkOption { + type = lib.types.str; + readOnly = true; + internal = true; + default = hostDataDir; + description = '' + Grafana's data directory on the host, which the pod's volume is. A host + without it gets the directory made. + ''; + }; + config = lib.mkIf deployCfg.grafana.enable { - # The gateway name, inside `deploy.grafana` — that - # guard is the load-bearing part. Every hive in a swarm may know this UI - # exists, but only the host that RUNS it may claim the name; a client - # hive declaring the vhost would answer for a service it does not have. services.hyperhive.gateway.localNames = [ cfg.domain ]; - # This host serves the vhost, and the container behind it resolves + # This host serves the vhost and resolves the cluster's names for it # through the hive's dnsmasq. services.hyperhive.gateway.enable = lib.mkDefault true; services.hyperhive.gateway.dns.enable = lib.mkDefault true; - # The hive bridge carries the container's DHCP lease and its resolver. + # The pod reaches the secret store through the hive bridge. services.hyperhive.network.enable = lib.mkDefault true; - # Registering the client is NOT here: it has to happen on the host that - # runs authelia, and this whole block is gated on the host that runs - # Grafana. ./glue-grafana-oidc-client.nix does it. - - # This arm fires only where Grafana runs — this whole block is under - # `deploy.grafana.enable`. SSO itself needs no assertion: - # `swarm.authelia.url` is non-nullable, so every swarm has one and the - # OIDC block below always names a real endpoint. assertions = [ { - # The other half of one login: the OIDC block names a `$__file{}` that - # `swarm-bao-grafana-oidc.service` below writes, and that unit reads - # the store with this host's client certificate. No certificate, no - # secret, and the same no-way-in Grafana as the arm above. assertion = haveClientIdentity; message = '' services.hyperhive.deploy.grafana.enable requires this host to hold a @@ -621,55 +1422,25 @@ in from that CA out of band and named here — see docs/2-handbook/swarm/credentials.md. ''; } - { - assertion = lib.all oneWord (lib.attrValues storeFiles); - message = '' - Grafana's store identity paths must not contain whitespace: nspawn's - --load-credential receives them through nixos-container's unquoted - extra flags. - ''; - } - { - assertion = - (hyperhiveCfg.swarm.otel.serviceProducers.${cfg.machine}.clientId or null) == forwarderClientId; - message = '' - services.hyperhive.swarm.otel.serviceProducers has no entry - "${cfg.machine}" with clientId "${forwarderClientId}", so the swarm - collector has no receiver for Grafana's journal forwarder. Declare - it in swarm-otel-service.nix. - ''; - } ]; - # Websockets: Grafana Live streams panel updates over one, and without - # the upgrade headers dashboards load and then never refresh — which - # reads as stale data rather than as a proxy fault. + # Grafana's own login is the credential of the UI and the API, and the + # gateway adds no second check there. `/metrics` answers anyone who + # reaches the port, so the gateway asks authelia whether the caller is the + # swarm collector and then sends the login the pod's `[metrics]` section + # takes (./lib/store-auth.nix). The file is empty until the unit that + # publishes the credential has run (./k8s/store-credentials.nix), and + # Grafana then refuses the scrape. services.hyperhive.gateway.vhosts."${cfg.domain}" = { - # Grafana serves its Prometheus exposition to anyone, signed in or not - # (`metrics.enabled` below, no `basic_auth_*`), so this location's auth - # is the only gate on it. `=` is enough: nginx matches the decoded, - # normalised path, so `//metrics`, `/./metrics`, `/%6detrics` and - # `/metrics?x` all land here, and Grafana itself answers `/metrics/` with - # a login redirect. - # - # The collector requests exactly this URL, declared as - # `publishedScrapeTargets.grafana` in ./swarm-otel-service.nix; the two - # must agree, since that string is also the token's audience. Authelia's - # rules for it admit the collector's client and deny every other subject - # (`metricsRules` in ./swarm-authelia.nix). locations."= /metrics" = { - proxyPass = "http://unix:${socketPath}:/metrics"; - extraConfig = '' + proxyPass = "http://${grafanaVariable}/metrics$is_args$args"; + extraConfig = viaGrafana + '' + include ${storeAuth.nginxFile "grafana"}; auth_request /__grafana_metrics_authz; ''; }; - # The subrequest, same shape as the forge's `= /__forge_metrics_authz` - # (./hive-forge/default.nix): no `error_page 401 =302`, so a scraper - # gets the 401 rather than a login page parsed as metrics. locations."= /__grafana_metrics_authz" = { proxyPass = "https://${autheliaDomain}/api/authz/auth-request"; - # nixpkgs appends its OWN `Host $host` after extraConfig, which would - # override verifiedProxyTo's — see hive-gateway/vhost-lib.nix. recommendedProxySettings = false; extraConfig = '' internal; @@ -683,14 +1454,12 @@ in proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; ''; }; + # No URI part: the request's own path and query reach Grafana as the + # caller sent them. locations."/" = { - proxyPass = "http://unix:${socketPath}:/"; + proxyPass = "http://${grafanaVariable}"; proxyWebsockets = true; - extraConfig = '' - # Grafana builds its OAuth redirect from the ORIGINAL request. - # Without these every request looks like it arrived at 127.0.0.1 - # over plain http, and the redirect sent to authelia names a - # host the browser cannot reach. + extraConfig = viaGrafana + '' proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; @@ -698,1217 +1467,9 @@ in }; }; - # Order the container after the host CA service so the bind source below - # exists before nspawn sets the mount up. nspawn also fails to start it - # when a credential source is missing, so where this host mints the leaf - # the container pulls the minting unit in and waits for it, as - # ./swarm-builder.nix's does. - systemd.services."container@${cfg.machine}" = lib.mkMerge [ - caTrust.containerOrdering - (rootfsCheck.warnOnly cfg.machine) - { - after = [ "swarm-bao-pki.service" ]; - wants = [ "swarm-bao-pki.service" ]; - } - ]; - - # The socket directory, created host-side before the container starts. - # nixos-container refuses to start when a bind source is missing, so this - # rule is a prerequisite of the mount rather than a tidiness measure. - # - # Owned by Grafana's uid so it can create the socket, group nginx so the - # gateway can traverse; `0750` keeps everything else out. Numeric ids - # because the host has no `grafana` account — Grafana lives in the - # container, and only the number crosses that boundary. - # - # The secrets directory is the container's read-only bind source, so it - # has to exist before the container starts even when the store does not - # answer. The delivery units create it before their store login too - # (`ensureSecretDir`), which covers a switch, where this rule is unordered - # with the container restart. 0755 because Grafana reads the files as its - # own uid; each file is 0400 and owned by it. The legacy files are removed - # so no superseded secret stays behind on the host's disk. - systemd.tmpfiles.rules = [ - "d ${deployCfg.grafana.socketDir} 0750 ${toString grafanaUid} ${toString nginxGid} - -" - "d ${secretDir} 0755 root root -" - ] - ++ map (p: "r ${p}") legacyHostSecretPaths; - - # THE delivery unit — one route, in every deployment. The secret authelia - # minted arrives out of the swarm secret store, which authelia's mint, - # in its container, wrote it into, and that is true whether authelia is - # a network away or in the container next door. - # - # 🩸 No second unit copies the plaintext out of authelia's tree - # where the two are co-located. The store exists so a host holds ONE - # out-of-band secret — its client certificate — and reads everything else - # with it, so skipping the store when the producer is local would buy a - # round trip and cost a second delivery path, a second way for the file - # to be wrong, and a gate whose false arm is a Grafana with no login. - # Recorded in docs/2-handbook/swarm/credentials.md. - # - # It is a store reader, and this is what the store's readers do: a cert - # login that fails LOUDLY, since every state it fails on is one a retry - # fixes, then a read that fails the same way when the value is not there - # yet. - # - # ⚠️ An ABSENT secret is "not published yet", not a fault of this host's. - # The mint runs in authelia's container and authelia mints on its - # first boot, so early in a swarm's life there is legitimately nothing to - # read, and a retry finds it a moment later. A unit that exited 0 on it - # would not run again until the refresh timer, about ten minutes on. - # Nothing here writes a stand-in: there is no such thing as a locally valid - # OIDC client secret, and a placeholder would turn a Grafana that cannot - # log anyone in into one whose token exchange is refused. - # - # ⇒ So the unit fails, and leaves the journal line that says which of the - # three it was: a secret that does not arrive is a Grafana nobody can log - # into, and a named cause is the only thing separating that from a mystery. - systemd.services.swarm-bao-grafana-oidc = { - description = "fetch Grafana's OIDC client secret from the swarm secret store"; - # Ordered after the store where it runs here - # (./glue-bao-readers-store-order.nix); elsewhere the timeout below - # bounds the attempt. - before = [ "container@${cfg.machine}.service" ]; - wantedBy = [ - "multi-user.target" - "container@${cfg.machine}.service" - ]; - path = [ - baoDeploy.package - pkgs.coreutils - pkgs.systemd - ]; - # ./lib/store-retry.nix. Grafana's container is ordered after this unit - # and waits for one attempt; a secret a later attempt lands restarts - # Grafana (below). - inherit (storeRetry) startLimitBurst startLimitIntervalSec; - serviceConfig = storeRetry.serviceConfig // { - # No `RemainAfterExit`: the timer below starts this again, and - # starting an active unit is a no-op. - Type = "oneshot"; - SyslogIdentifier = "swarm-bao-grafana-oidc"; - # What actually bounds each attempt below. Stated here rather than left - # to systemd's default, so the number a boot waits on is in the file - # that waits. - TimeoutStartSec = 30; - }; - environment = { - BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; - BAO_CLIENT_CERT = baoDeploy.grafanaOidcClientCertFile; - BAO_CLIENT_KEY = baoDeploy.grafanaOidcClientKeyFile; - } - # Absent means the system trust store, which is what a deployment with a - # real CA wants and what a self-signed one must not be left with. - // lib.optionalAttrs (baoDeploy.serverCaFile != null) { - BAO_CACERT = baoDeploy.serverCaFile; - }; - script = '' - set -euo pipefail - - ${atomicWriteSecret} - ${refreshConsumer} - - ${ensureSecretDir} - - # `bao`'s own message is the only thing separating a missing value from - # a refused identity from an unreachable host. Retrying is right for - # all three, so this unit reports which one rather than asserting all - # three in a sentence of ours. - err="$(mktemp)" - trap 'rm -f "$err"' EXIT - - # Cert auth is a login, not a transport setting. The `BAO_CLIENT_*` - # variables above only decide which certificate the TLS handshake - # presents; without a token `bao` asks its token helper instead, and - # that is a `sh` this unit's `path` does not carry. `-token-only` - # answers on stdout and skips the helper on both sides. - if ! BAO_TOKEN="$(bao login -method=cert -token-only 2>"$err")"; then - echo "could not log in to swarm-bao with this host's certificate; leaving Grafana's OIDC client secret as it is." >&2 - if [ -s "$err" ]; then - cat "$err" >&2 - else - echo "bao failed without writing a diagnostic." >&2 - fi - exit 1 - fi - export BAO_TOKEN - - # 75 is EX_TEMPFAIL: not there yet, ask again. `Restart=on-failure` - # (./lib/store-retry.nix) asks every 30 s until the mint has written it, - # and the status line says "no value" rather than "no login" (1). - if ! secret="$(bao kv get -field=value ${lib.escapeShellArg storeSecretPath} 2>"$err")"; then - echo "swarm-bao did not return ${storeSecretPath}; Grafana has no OIDC client secret yet." >&2 - if [ -s "$err" ]; then - cat "$err" >&2 - else - echo "bao failed without writing a diagnostic." >&2 - fi - exit 75 - fi - - if [ -z "$secret" ]; then - echo "swarm-bao returned an empty ${storeSecretPath}; leaving the file as it is." >&2 - exit 75 - fi - - # Written with a shell builtin, never handed to a program: `printf` is - # bash's own, so the plaintext never becomes an argument in /proc the - # way `install <<<"$secret"` or an `echo` from `path` would. - # - # Owned by Grafana's own uid, unlike the matrix sibling which lands - # root-owned: tuwunel's secret is read by `LoadCredential` as root - # before the sandbox exists, whereas Grafana expands `$__file{}` - # itself, as itself, while parsing its config. This container sets no - # `privateUsers`, so the host uid is the container uid, and both sides - # take it from the same static NixOS id. - # - # Group is root, not grafana, and that is forced rather than chosen: - # `ids.uids.grafana` is a static id but there is no `ids.gids.grafana` - # — the group's gid is allocated at activation inside the container, so - # the host cannot know it at eval time. Harmless here because 0400 - # grants the group nothing; if this mode ever widens, the gid has to be - # discovered at runtime rather than assumed. - if secret_differs ${lib.escapeShellArg secretPath} "$secret"; then - atomic_write_secret 0400 ${lib.escapeShellArg "${toString config.ids.uids.grafana}:0"} ${lib.escapeShellArg secretPath} "$secret" - fi - - # `$__file{}` is expanded once, while Grafana parses its config. - refresh_consumer ${lib.escapeShellArg cfg.machine} grafana.service ${lib.escapeShellArg secretPath} - ''; - }; - - systemd.timers.swarm-bao-grafana-oidc = storeRefreshTimer "re-read Grafana's OIDC client secret from the swarm secret store"; - - # The admin password: created in the store if it holds none, then copied - # into the container, under Grafana's own leaf. The grant is - # `create` without `update`, so the first password stored is the one every - # later run reads, and a race between two runs leaves one value. - # - # Grafana does not start without the file (`$__file{}` on a missing path is - # a startup error), so a store that is unreachable on first boot keeps - # Grafana down rather than up with the upstream default. - systemd.services.swarm-bao-grafana-admin = { - description = "create Grafana's admin password in the swarm secret store if absent and fetch it"; - # Ordered after the store where it runs here: - # ./glue-bao-readers-store-order.nix. - before = [ "container@${cfg.machine}.service" ]; - wantedBy = [ - "multi-user.target" - "container@${cfg.machine}.service" - ]; - path = [ - baoDeploy.package - pkgs.coreutils - pkgs.openssl - pkgs.systemd - ]; - inherit (storeRetry) startLimitBurst startLimitIntervalSec; - serviceConfig = storeRetry.serviceConfig // { - Type = "oneshot"; - RemainAfterExit = true; - SyslogIdentifier = "swarm-bao-grafana-admin"; - TimeoutStartSec = 30; - }; - environment = { - BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; - BAO_CLIENT_CERT = baoDeploy.grafanaOidcClientCertFile; - BAO_CLIENT_KEY = baoDeploy.grafanaOidcClientKeyFile; - } - // lib.optionalAttrs (baoDeploy.serverCaFile != null) { - BAO_CACERT = baoDeploy.serverCaFile; - }; - script = '' - set -euo pipefail - - ${atomicWriteSecret} - ${refreshConsumer} - - ${ensureSecretDir} - - err="$(mktemp)" - trap 'rm -f "$err"' EXIT - - if ! BAO_TOKEN="$(bao login -method=cert -token-only 2>"$err")"; then - echo "could not log in to swarm-bao with Grafana's certificate; leaving Grafana's admin password file as it is." >&2 - cat "$err" >&2 - exit 1 - fi - export BAO_TOKEN - - # `bao kv get` exits 2 both for "nothing stored" and for a refusal, so - # a failed read always tries the create, and the second read decides. - # The value reaches `bao` on stdin, never in an argument. - if ! password="$(bao kv get -field=value ${lib.escapeShellArg adminPasswordStorePath} 2>"$err")"; then - minted="$(openssl rand -hex 32)" - if ! printf '%s' "$minted" | bao kv put -cas=0 ${lib.escapeShellArg adminPasswordStorePath} value=- >/dev/null 2>"$err"; then - echo "could not create ${adminPasswordStorePath}; reading it back in case another run created it." >&2 - cat "$err" >&2 - fi - if ! password="$(bao kv get -field=value ${lib.escapeShellArg adminPasswordStorePath} 2>"$err")"; then - echo "swarm-bao did not return ${adminPasswordStorePath}; Grafana does not start without it." >&2 - cat "$err" >&2 - exit 1 - fi - fi - if [ -z "$password" ]; then - echo "swarm-bao returned an empty ${adminPasswordStorePath}; leaving the file as it is." >&2 - exit 1 - fi - - # Owner and mode as for the OIDC secret above, for its reasons. - if secret_differs ${lib.escapeShellArg adminPasswordPath} "$password"; then - atomic_write_secret 0400 ${lib.escapeShellArg "${toString config.ids.uids.grafana}:0"} ${lib.escapeShellArg adminPasswordPath} "$password" - fi - - # Grafana's `preStart` applies the file to the database, so a file that - # changed after it started needs a restart. - refresh_consumer ${lib.escapeShellArg cfg.machine} grafana.service ${lib.escapeShellArg adminPasswordPath} - ''; - }; - - # The metrics datasource's bearer: created in the store if it holds none, - # then copied into the container, under Grafana's own leaf. Same shape and - # grant as the admin password above. The store's `swarm-metrics-auth` - # reads the same path, so nothing is placed by hand on either host. - systemd.services.swarm-bao-grafana-metrics-bearer = { - description = "create Grafana's metrics store bearer in the swarm secret store if absent and fetch it"; - # Ordered after the store where it runs here: - # ./glue-bao-readers-store-order.nix. - before = [ "container@${cfg.machine}.service" ]; - wantedBy = [ - "multi-user.target" - "container@${cfg.machine}.service" - ]; - path = [ - baoDeploy.package - pkgs.coreutils - pkgs.openssl - pkgs.systemd - ]; - inherit (storeRetry) startLimitBurst startLimitIntervalSec; - serviceConfig = storeRetry.serviceConfig // { - Type = "oneshot"; - RemainAfterExit = true; - SyslogIdentifier = "swarm-bao-grafana-metrics-bearer"; - TimeoutStartSec = 30; - }; - environment = { - BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; - BAO_CLIENT_CERT = baoDeploy.grafanaOidcClientCertFile; - BAO_CLIENT_KEY = baoDeploy.grafanaOidcClientKeyFile; - } - // lib.optionalAttrs (baoDeploy.serverCaFile != null) { - BAO_CACERT = baoDeploy.serverCaFile; - }; - script = '' - set -euo pipefail - - ${atomicWriteSecret} - ${refreshConsumer} - - ${ensureSecretDir} - - err="$(mktemp)" - trap 'rm -f "$err"' EXIT - - if ! BAO_TOKEN="$(bao login -method=cert -token-only 2>"$err")"; then - echo "could not log in to swarm-bao with Grafana's certificate; leaving Grafana's metrics bearer file as it is." >&2 - cat "$err" >&2 - exit 1 - fi - export BAO_TOKEN - - # Read, create on a miss, read again: the admin password's sequence - # above, for its reasons. - if ! bearer="$(bao kv get -field=value ${lib.escapeShellArg metricsBearerStorePath} 2>"$err")"; then - minted="$(openssl rand -hex 32)" - if ! printf '%s' "$minted" | bao kv put -cas=0 ${lib.escapeShellArg metricsBearerStorePath} value=- >/dev/null 2>"$err"; then - echo "could not create ${metricsBearerStorePath}; reading it back in case another run created it." >&2 - cat "$err" >&2 - fi - if ! bearer="$(bao kv get -field=value ${lib.escapeShellArg metricsBearerStorePath} 2>"$err")"; then - echo "swarm-bao did not return ${metricsBearerStorePath}; Grafana does not start without it." >&2 - cat "$err" >&2 - exit 1 - fi - fi - if [ -z "$bearer" ]; then - echo "swarm-bao returned an empty ${metricsBearerStorePath}; leaving the file as it is." >&2 - exit 1 - fi - - # Owner and mode as for the OIDC secret above, for its reasons. - if secret_differs ${lib.escapeShellArg metricsBearerPath} "Bearer $bearer"; then - atomic_write_secret 0400 ${lib.escapeShellArg "${toString config.ids.uids.grafana}:0"} ${lib.escapeShellArg metricsBearerPath} "Bearer $bearer" - fi - - # `$__file{}` in a provisioned datasource is read as Grafana starts. - refresh_consumer ${lib.escapeShellArg cfg.machine} grafana.service ${lib.escapeShellArg metricsBearerPath} - ''; - }; - - # Grafana's datasource-encryption key: the store's value is copied into the - # container; when the store holds none, the earlier file's key is stored - # first, and a new key only when there is no earlier file either. Same - # shape and grant as the admin password above. - # - # The key never changes. An earlier release generated it in the container on - # first boot, so a host that has run Grafana stores that same key - # (`grafana_secret_key`, ./lib/grafana-secret-key.nix). The earlier file is - # only a seed: with the store down or not granting the leaf the unit fails - # and retries, and Grafana does not start without the key in /run. - systemd.services.swarm-bao-grafana-secret-key = { - description = "create Grafana's datasource encryption key in the swarm secret store if absent and fetch it"; - # Ordered after the store where it runs here: - # ./glue-bao-readers-store-order.nix. - before = [ "container@${cfg.machine}.service" ]; - wantedBy = [ - "multi-user.target" - "container@${cfg.machine}.service" - ]; - path = [ - baoDeploy.package - pkgs.coreutils - pkgs.openssl - pkgs.systemd - ]; - inherit (storeRetry) startLimitBurst startLimitIntervalSec; - serviceConfig = storeRetry.serviceConfig // { - Type = "oneshot"; - RemainAfterExit = true; - SyslogIdentifier = "swarm-bao-grafana-secret-key"; - TimeoutStartSec = 30; - }; - environment = { - BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; - BAO_CLIENT_CERT = baoDeploy.grafanaOidcClientCertFile; - BAO_CLIENT_KEY = baoDeploy.grafanaOidcClientKeyFile; - } - // lib.optionalAttrs (baoDeploy.serverCaFile != null) { - BAO_CACERT = baoDeploy.serverCaFile; - }; - script = '' - set -euo pipefail - - ${atomicWriteSecret} - ${refreshConsumer} - - ${ensureSecretDir} - - ${grafanaSecretKey} - - grafana_secret_key ${lib.escapeShellArg secretKeyStorePath} ${lib.escapeShellArg legacySecretKeyPath} openssl rand -hex 32 || exit 1 - - # Owner and mode as for the OIDC secret above, for its reasons. - # `$__file{}` is read as Grafana starts, so a changed file needs a - # restart. - if secret_differs ${lib.escapeShellArg secretKeyPath} "$GRAFANA_KEY"; then - atomic_write_secret 0400 ${lib.escapeShellArg "${toString config.ids.uids.grafana}:0"} ${lib.escapeShellArg secretKeyPath} "$GRAFANA_KEY" - fi - refresh_consumer ${lib.escapeShellArg cfg.machine} grafana.service ${lib.escapeShellArg secretKeyPath} - ''; - }; - - # swarm-controller reads Grafana's alerts with a token of a Viewer service - # account, created here through Grafana's API as the built-in admin and - # handed over through the store. - # - # Re-run by the timer below. A stored token Grafana still accepts is kept; - # one it refuses with 401, or none at all, is replaced: every token of the - # account is deleted and one new one is minted and stored. The account's - # role is set back to Viewer on every run. - systemd.services.swarm-bao-grafana-controller-token = { - description = "give swarm-controller a Viewer token for Grafana's API through the swarm secret store"; - # Ordered after the store where it runs here: - # ./glue-bao-readers-store-order.nix. - after = [ - "container@${cfg.machine}.service" - "swarm-bao-grafana-admin.service" - ]; - wantedBy = [ "multi-user.target" ]; - path = [ - baoDeploy.package - pkgs.coreutils - pkgs.curl - pkgs.jq - ]; - # ./lib/store-retry.nix. A Grafana still starting refuses the - # connection, and that attempt fails into the same retry. - inherit (storeRetry) startLimitBurst startLimitIntervalSec; - serviceConfig = storeRetry.serviceConfig // { - # No `RemainAfterExit`: the timer below starts this again. - Type = "oneshot"; - SyslogIdentifier = "swarm-bao-grafana-controller-token"; - # Grafana's answers, the new token among them, pass through a temp file. - PrivateTmp = true; - # The socket wait (`socketWaitSec`) plus the calls below, each bounded - # by curl's own timeouts; a run makes up to about ten of them. - TimeoutStartSec = "4min"; - }; - environment = { - BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; - BAO_CLIENT_CERT = baoDeploy.grafanaOidcClientCertFile; - BAO_CLIENT_KEY = baoDeploy.grafanaOidcClientKeyFile; - } - // lib.optionalAttrs (baoDeploy.serverCaFile != null) { - BAO_CACERT = baoDeploy.serverCaFile; - }; - script = '' - set -euo pipefail - - err="$(mktemp)" - body="$(mktemp)" - trap 'rm -f "$err" "$body"' EXIT - - # One call to Grafana's API through its socket. Prints the HTTP - # status; the body lands in "$body". The credential reaches curl as - # a header file, never as an argument. - grafana() { - local auth="$1" method="$2" path="$3" - shift 3 - curl --silent --show-error --connect-timeout 5 --max-time 15 \ - --unix-socket ${lib.escapeShellArg socketPath} \ - -H @<(printf 'Authorization: %s\n' "$auth") \ - -H 'Content-Type: application/json' \ - -X "$method" -o "$body" -w '%{http_code}' "$@" \ - "http://localhost$path" - } - - # Fails the attempt unless the last call answered one of the statuses - # given. - expect() { - local what="$1" status="$2" - shift 2 - for ok in "$@"; do - [ "$status" = "$ok" ] && return 0 - done - echo "Grafana answered $status to $what:" >&2 - cat "$body" >&2 - exit 1 - } - - ${retryInJob} - - # Any HTTP answer counts; a refused connection is curl's exit status 7. - grafana_listening() { - curl --silent --output /dev/null --connect-timeout 5 --max-time 15 \ - --unix-socket ${lib.escapeShellArg socketPath} http://localhost/api/health - } - if ! retry_in_job ${toString socketWaitSec} grafana_listening; then - echo "Grafana's socket ${socketPath} did not answer within ${toString socketWaitSec} seconds." >&2 - exit 1 - fi - - if [ ! -s ${lib.escapeShellArg adminPasswordPath} ]; then - echo "no Grafana admin password at ${adminPasswordPath} yet; swarm-bao-grafana-admin writes it." >&2 - exit 1 - fi - admin="Basic $(printf 'admin:%s' "$(< ${lib.escapeShellArg adminPasswordPath})" | base64 -w0)" - - status="$(grafana "$admin" GET '/api/serviceaccounts/search?perpage=1000&query=${controllerAccountName}')" - expect "the service account search" "$status" 200 - account="$(jq -c --arg n ${controllerAccountName} '[.serviceAccounts[] | select(.name == $n)][0] // empty' "$body")" - if [ -z "$account" ]; then - status="$(grafana "$admin" POST /api/serviceaccounts \ - --data '{"name":"${controllerAccountName}","role":"Viewer","isDisabled":false}')" - expect "creating the ${controllerAccountName} service account" "$status" 200 201 - account="$(jq -c . "$body")" - echo "created the ${controllerAccountName} service account as a Viewer" - fi - id="$(jq -r .id <<<"$account")" - if [ "$(jq -r '"\(.role) \(.isDisabled // false)"' <<<"$account")" != "Viewer false" ]; then - status="$(grafana "$admin" PATCH "/api/serviceaccounts/$id" \ - --data '{"role":"Viewer","isDisabled":false}')" - expect "setting the ${controllerAccountName} service account to an enabled Viewer" "$status" 200 - echo "set the ${controllerAccountName} service account back to an enabled Viewer" - fi - - if ! BAO_TOKEN="$(bao login -method=cert -token-only 2>"$err")"; then - echo "could not log in to swarm-bao with Grafana's certificate; leaving swarm-controller's Grafana token as it is." >&2 - cat "$err" >&2 - exit 1 - fi - export BAO_TOKEN - - # Checked against the call the controller makes with it. - if stored="$(bao kv get -field=value ${lib.escapeShellArg controllerTokenStorePath} 2>"$err")" && [ -n "$stored" ]; then - status="$(grafana "Bearer $stored" GET /api/prometheus/grafana/api/v1/alerts)" - case "$status" in - 200) exit 0 ;; - 401) echo "Grafana refuses the stored token for ${controllerAccountName}; replacing it." ;; - *) expect "reading alerts with the stored token" "$status" 200 ;; - esac - fi - - status="$(grafana "$admin" GET "/api/serviceaccounts/$id/tokens")" - expect "listing the ${controllerAccountName} tokens" "$status" 200 - for token_id in $(jq -r '.[].id' "$body"); do - status="$(grafana "$admin" DELETE "/api/serviceaccounts/$id/tokens/$token_id")" - expect "deleting token $token_id of ${controllerAccountName}" "$status" 200 - done - - status="$(grafana "$admin" POST "/api/serviceaccounts/$id/tokens" \ - --data "{\"name\":\"${controllerAccountName}-$(date +%s)\"}")" - expect "minting a ${controllerAccountName} token" "$status" 200 - key="$(jq -r .key "$body")" - : >"$body" - if ! printf '%s' "$key" | bao kv put ${lib.escapeShellArg controllerTokenStorePath} value=- >/dev/null 2>"$err"; then - echo "could not store the new ${controllerAccountName} token at ${controllerTokenStorePath}; the next run replaces it." >&2 - cat "$err" >&2 - exit 1 - fi - echo "stored a new ${controllerAccountName} token at ${controllerTokenStorePath}" - ''; - }; - - systemd.timers.swarm-bao-grafana-controller-token = storeRefreshTimer "check swarm-controller's Grafana token and replace it if Grafana refuses it"; - - containers.${cfg.machine} = { - autoStart = true; - ephemeral = false; - # No `--link-journal=host`: the journal stays in the guest, where the - # container's own forwarder reads it (../container-modules/swarm-journal-forwarder.nix). - extraFlags = lib.mapAttrsToList (id: source: "--load-credential=${id}:${source}") storeFiles; - inherit privateNetwork; - hostBridge = networkCfg.bridgeName; - - # The socket directory, shared with the host so nginx can reach in. - # - # ⚠️ It has to be a bind mount rather than a path both sides happen to - # know: a container's `/run` is an nspawn tmpfs, so it is NOT visible - # from the host at `/var/lib/nixos-containers//run`. The host - # creates the directory (tmpfiles rule below, which also fixes - # ownership) and nspawn mounts it in — the same shape the per-agent - # `/run/hive-agent//web.sock` already uses. - bindMounts = { - ${deployCfg.grafana.socketDir} = { - hostPath = deployCfg.grafana.socketDir; - isReadOnly = false; - }; - # The three delivered secrets, read-only: the container reads them and - # never writes one. - ${secretDir} = { - hostPath = secretDir; - isReadOnly = true; - }; - } - // caTrust.bindMount; - - config = - { config, ... }: - { - imports = [ - ../container-modules/swarm-container.nix - ../container-modules/swarm-journal-forwarder.nix - (import ../container-modules/swarm-container-resolver.nix { - inherit (networkCfg) bridgeIp; - # The forwarder and its secret fetch dial the swarm collector, - # authelia and the store by name too. - dnsConsumers = [ - "grafana.service" - "opentelemetry-collector.service" - "${forwarderUnit}.service" - ]; - }) - # Grafana is Go, and `SSL_CERT_FILE` *replaces* the default store - # rather than adding to it — so it needs the system CAs and the - # store's root concatenated, not the root alone. Without it the - # browser half of the login succeeds and the server-to-server - # token exchange fails `x509: unknown authority`. - (caTrust.trustBundle { - inherit pkgs; - name = cfg.machine; - consumers = [ - "grafana" - # Go too, for the swarm collector's and authelia's names. - "opentelemetry-collector" - ]; - }) - ]; - - services.hyperhive.swarmContainer = { inherit privateNetwork; }; - - # The bridge address comes from the gateway's DHCP. `swarm-bridge-dns` - # owns resolv.conf, so dhcpcd must not write it over that unit. - networking.interfaces.eth0.useDHCP = true; - networking.dhcpcd.extraConfig = "nohook resolv.conf"; - - # Authenticated as the forwarder's own OIDC client, with Grafana's - # store identity: one identity for the whole container. It is a - # system credential, so the fetch unit loads it. - services.hyperhive.swarmJournalForwarder = { - enable = true; - serviceName = "grafana"; - endpoint = forwarderEndpoint; - clientId = forwarderClientId; - tokenUrl = "${autheliaUrl}/api/oidc/token"; - telemetryPort = forwarderTelemetryPort; - store = { - package = baoDeploy.package; - addr = "https://${baoCfg.domain}:${toString baoCfg.port}"; - secretPath = "secret/swarm/services/${forwarderClientId}/oidc/client"; - clientCertFile = forwarderCredential "grafana-bao-cert"; - clientKeyFile = forwarderCredential "grafana-bao-key"; - caFile = - if storeFiles ? grafana-bao-server-ca then forwarderCredential "grafana-bao-server-ca" else null; - }; - }; - systemd.services.${forwarderUnit}.serviceConfig.LoadCredential = lib.attrNames storeFiles; - - # Upstream applies `security.admin_password` only when it creates the - # database, so a database created before that setting keeps the - # password it was created with. This resets it from the delivered - # file on every start, before the server listens. - # - # `grafana cli` must open the database the server opens, which the - # server's config.ini names. nixpkgs keeps that file private, so it - # is rendered again from the same settings with nixpkgs' formatter. - systemd.services.grafana.preStart = - let - grafana = config.services.grafana; - configFile = - (pkgs.formats.ini { - listToValue = lib.concatMapStringsSep " " (lib.generators.mkValueStringDefault { }); - mkKeyValue = lib.generators.mkKeyValueDefault { - mkValueString = v: if v == null then "" else lib.generators.mkValueStringDefault { } v; - } "="; - }).generate - "config.ini" - grafana.settings; - in - lib.mkAfter '' - ${lib.getExe' grafana.package "grafana"} cli --homepath ${grafana.dataDir} --config ${configFile} \ - admin reset-admin-password --password-from-stdin < ${adminPasswordPath} - ''; - - # The group Grafana chgrps its socket to. Declared here because a - # container has its own user database — the host knowing gid 60 as - # `nginx` means nothing in here, only the number crosses. - # - # The name is local and arbitrary; the gid is the contract. - users.groups.gateway-nginx.gid = nginxGid; - users.users.grafana.extraGroups = [ "gateway-nginx" ]; - - services.grafana = { - enable = true; - package = deployCfg.grafana.package; - - # Passed through unconditionally, empty default included. - # Upstream distinguishes `null` from `[ ]`, and both differences - # favour always handing it a list: - # - # - `null` points the plugin path at grafana's mutable - # `/plugins`; any list points it at a store path. - # Switching on the day someone adds their first plugin would - # bury that change inside an unrelated one. - # - upstream defaults its plugin update-check to - # `declarativePlugins == null`, so a list also stops the - # container phoning grafana.com. That is the no-runtime-egress - # property this option exists for — it should not arrive only - # once a plugin happens to be listed. - # - # - 🩸 it also sets upstream's `plugins.preinstall_disabled` - # (nixpkgs' - # grafana.nix defaults it to `declarativePlugins != null`, - # saying preinstall "causes issues with declarativePlugins"). - # Preinstall is what fetches the Drilldown apps on first - # start, so claiming this directory silently removes them. - # That is why the option's default is not empty. - # - # Taking this directory over is not harmless on a hive with no - # plugins: that reasoning covers only plugins a PERSON installs, - # and upstream installs some itself. - declarativePlugins = deployCfg.grafana.plugins; - - settings = { - server = { - # Already upstream's default (measured), but pinned rather - # than inherited: the gateway is the only intended client, - # and this being loopback is what keeps the UI from being - # published on whatever else the host is reachable on. - # A unix socket, not a port. `socket_gid` is nginx's, so the - # gateway can connect; `0660` keeps everyone else out. - # - # ⚠️ Grafana chowns the socket to `socket_gid`, and a - # non-root process may only chgrp to a group it is a MEMBER - # of — hence the group declared for `grafana` in this - # container's own user database below. Without that - # membership Grafana starts, fails the chown, and the socket - # is unreachable by nginx with nothing obviously wrong. - protocol = "socket"; - socket = socketPath; - socket_gid = nginxGid; - socket_mode = "0660"; - domain = cfg.domain; - # Grafana builds its own OAuth redirect from this. Left at - # upstream's `%(protocol)s://%(domain)s:%(http_port)s/` it - # would name `http://:3000/`, which authelia has - # never heard of. - root_url = "https://${cfg.domain}/"; - }; - - analytics = { - reporting_enabled = false; - check_for_updates = false; - }; - - # Stated rather than inherited. This is upstream's default, but - # a scrape target now depends on it, and a default that changes - # silently takes the target with it — the endpoint disappears, - # nginx keeps answering, and the scrape fails with a 404 far - # from anything that mentions Grafana. - metrics.enabled = true; - - # Grafana hands an external backend plugin only an allow-list of - # its environment (the proxy variables), so without this the logs - # datasource never sees the unit's `SSL_CERT_FILE` and rejects the - # log store's certificate as `x509: unknown authority`. The value - # is plugin ids, not variable names: each listed plugin gets the - # whole environment. - plugins.forward_host_env_vars = "victoriametrics-logs-datasource"; - - users.auto_assign_org_role = cfg.oidc.role; - - # ⚠️ `$__file{}`, and required rather than optional: nixpkgs - # dropped the default and asserts on null, so without this the - # whole host fails to build. Written by `swarm-bao-grafana-secret-key` - # on the host. - security.secret_key = "$__file{${secretKeyPath}}"; - - # The password a newly created database gets; the `preStart` - # above gives an existing one the same. Written by - # `swarm-bao-grafana-admin` on the host. - security.admin_password = "$__file{${adminPasswordPath}}"; - - # No password box on the public login page: people log in through - # SSO. This hides the form only; the API still takes basic auth, - # which is why the admin password above is minted. - # - # Not conditional on anything, and the block below is not - # either, which is what keeps the two from ever disagreeing. - # Whether a password box sits on a public login page cannot - # depend on which host happens to run authelia. - auth.disable_login_form = true; - - # Emitted in every deployment, because SSO is a requirement of - # running this service rather than a feature of some topologies: - # the assertions above refuse to build a Grafana that lacks an - # IdP to point at or the identity to fetch its secret with. A - # `lib.optionalAttrs` here would be the silent half of that pair, - # dropping the only login this container has whenever a value - # went null. - "auth.generic_oauth" = { - enabled = true; - name = "HyperHive"; - client_id = cfg.oidc.clientId; - # ⚠️ `$__file{}`, never the secret itself — anything else - # here is world-readable in the nix store. Note the module's - # own leak assertion does NOT cover this key (it checks - # `database.password`, `security.admin_password` and - # datasource `secureJsonData`), so nothing but this comment - # stands between a literal and the store. - # - # `swarm-bao-grafana-oidc.service` above is what writes this - # path, on every host that runs Grafana. - client_secret = "$__file{${secretPath}}"; - scopes = "openid profile email groups"; - auth_url = "${autheliaUrl}/api/oidc/authorization"; - token_url = "${autheliaUrl}/api/oidc/token"; - api_url = "${autheliaUrl}/api/oidc/userinfo"; - use_pkce = true; - }; - }; - - provision.datasources.settings = { - apiVersion = 1; - datasources = [ - { - name = "VictoriaMetrics"; - type = "prometheus"; - uid = datasourceUid; - url = deployCfg.grafana.datasourceUrl; - access = "proxy"; - isDefault = true; - # The store's query routes admit this bearer or an operator's - # session, and nothing else. - jsonData.httpHeaderName1 = "Authorization"; - secureJsonData.httpHeaderValue1 = "$__file{${metricsBearerPath}}"; - } - { - name = "VictoriaLogs"; - # The plugin's own id, read from its `plugin.json` rather - # than guessed. A `type` Grafana does not recognise is - # provisioned without complaint and every query against it - # fails at use, far from anything naming this file. - type = "victoriametrics-logs-datasource"; - uid = logsDatasourceUid; - url = deployCfg.grafana.logsDatasourceUrl; - access = "proxy"; - # Exactly one datasource may claim this, and metrics has it: - # two defaults is a coin toss over which one an untyped panel - # gets. - isDefault = false; - # See `logLevelRules` above for why the level lives here and - # not in the pipeline. - jsonData = { - inherit logLevelRules; - httpHeaderName1 = "Authorization"; - }; - # The metrics datasource's bearer; the log store's vhost - # accepts it on `/select/logsql/`. - secureJsonData.httpHeaderValue1 = "$__file{${metricsBearerPath}}"; - } - ]; - }; - - provision.dashboards.settings = { - apiVersion = 1; - providers = [ - { - name = "hyperhive"; - type = "file"; - # Read-only in the UI: the store path is immutable, so an edit - # saved here would be silently discarded on the next rebuild. - # Better to refuse the edit than to lose it. - allowUiUpdates = false; - options.path = dashboardDir; - } - ]; - }; - - # Rules only. With no policy provisioned, Grafana routes every alert - # to its built-in `empty` receiver, which has no integrations: a - # firing rule shows under Alerting → Alert rules and is sent nowhere. - provision.alerting.rules.settings = { - apiVersion = 1; - groups = [ - { - orgId = 1; - name = "hyperhive"; - folder = "hyperhive"; - interval = "1m"; - rules = [ - # The controller re-runs the forge objects pass every 5m - # (`RECONCILE_INTERVAL` in swarm-controller's - # forge/objects.rs) and warns once per failed write. A - # 10m window always spans the previous tick, so a pass - # failing on every tick keeps the count above zero - # continuously and fires after `for`. One failed pass - # keeps it above zero for only 10m, short of the 15m - # `for`, so it never fires; about three failed passes in - # a row do. - (logCountRule { - uid = "hh-forge-objects-write-failed"; - title = "forge reconcile failing"; - windowSeconds = 600; - expr = ''_time:10m _msg:"swarm forge objects: write failed; retrying next pass" | stats count() as failures''; - for = "15m"; - summary = "swarm-controller has failed to write forge objects on consecutive reconcile passes"; - }) - # `agent` is the resource attribute every agent container's log - # forwarder carries, and agent names are unique in the swarm, so - # each agent is its own alert instance. - (logCountRule { - uid = "hh-swarm-term-publish-skipped"; - title = "swarm terminal publish skipped"; - windowSeconds = 900; - expr = ''_time:15m _msg:"swarm terminal: publish skipped" | stats by (agent) count() as skipped''; - for = "5m"; - summary = "{{ $labels.agent }} is dropping swarm terminal rows: the harness is not connected to the queue"; - }) - # `CONNECT_EXHAUSTED` in hive-agent's swarm_queue.rs, - # logged when the harness's first-connect retries - # (about five minutes) all fail, just before it exits. - # systemd restarts it 30s later, so an agent that never - # connects logs it about every six minutes. The window - # is how long the rule stays firing after the last one. - (logCountRule { - uid = "hh-swarm-queue-connect-failed"; - title = "swarm queue connect failed"; - windowSeconds = 3600; - expr = ''_time:1h _msg:"no swarm queue connection; exiting, since this agent cannot run without one" | stats by (agent) count() as failures''; - for = "0s"; - summary = "{{ $labels.agent }} could not connect to the swarm queue and its harness exited; systemd starts it again 30s later"; - }) - # A run that ends without a verdict leaves that PR with no - # classifier review. `swarm-review-classifier` logs four - # `warn` lines for it: `review classification run failed` - # (a rejected or unreadable API key, a failed model call; - # the cause is in `F_ERROR`), an undecodable request, and a - # reply it could not encode or publish. The window is how - # long the rule stays firing after the last one. - (logCountRule { - uid = "hh-review-classifier-run-failed"; - title = "review classifier run failed"; - windowSeconds = 1800; - expr = ''_time:30m (_msg:"review classification run failed" OR _msg:"an undecodable try-out; answering with the error" OR _msg:"encoding a try-out's reply failed" OR _msg:"publishing a try-out's reply failed") | stats count() as failures''; - for = "0s"; - summary = "a review-classifier run ended without a verdict, so that PR has no classifier review; the log line names the cause (F_ERROR on a failed run)"; - }) - (logCountRule { - uid = "hh-swarm-agent-state-publish-skipped"; - title = "swarm agent state publish skipped"; - windowSeconds = 900; - expr = ''_time:15m _msg:"swarm agent state: publish skipped" | stats by (agent) count() as skipped''; - for = "5m"; - summary = "{{ $labels.agent }} is dropping agent state updates: the harness is not connected to the queue"; - }) - # Logged on every connection attempt, so it repeats under - # the reconnect backoff for as long as the path is empty. - (logCountRule { - uid = "hh-swarm-queue-credential-missing"; - title = "swarm queue credential missing"; - windowSeconds = 900; - expr = ''_time:15m _msg:"nothing is stored at this agent's queue credential path; its queue connection retries under backoff" | stats by (agent) count() as missing''; - for = "5m"; - summary = "{{ $labels.agent }} finds nothing at its queue credential path and cannot connect to the queue"; - }) - # Logged once per failed turn, by `emit_turn_end` in - # hive-agent's turn.rs; the window is how long the rule - # stays firing after it. The exact `_msg` match and the - # unit keep out the subagent daemon's `subagent: turn - # failed` and the ACP backend's `ACP checkpoint turn - # failed`, which a phrase match would also count. - (logCountRule { - uid = "hh-agent-turn-failed"; - title = "agent turn failed"; - windowSeconds = 900; - expr = ''_time:15m _SYSTEMD_UNIT:="hive-agent.service" _msg:="turn failed" | stats by (agent) count() as failures''; - for = "0s"; - summary = "{{ $labels.agent }} had a claude turn fail; the reason is the `F_ERROR` field of the harness's `turn failed` log line"; - }) - # Same cadence as the forge rule: one pass every 5m - # (`RECONCILE_INTERVAL` in swarm-controller's - # agent_renewal.rs), one line per failed pass, so one - # failed pass never fires and about three in a row do. - (logCountRule { - uid = "hh-agent-credential-renewal-failed"; - title = "agent credential renewal failing"; - windowSeconds = 600; - expr = ''_time:10m _msg:"agent credential renewal: pass failed; retrying next tick" | stats count() as failures''; - for = "15m"; - summary = "swarm-controller has failed the agent credential renewal pass on consecutive ticks"; - }) - # `MINT_IDENTITY_FAILED` in swarm-controller's jobq.rs, - # logged once per failed `MintAgentIdentity` job node, at - # agent creation or on a certificate renewal; the window - # is how long the rule stays firing after it. Host - # journal records carry the tracing fields as `F_`. - (logCountRule { - uid = "hh-agent-identity-mint-failed"; - title = "agent identity mint failed"; - windowSeconds = 900; - expr = ''_time:15m _SYSTEMD_UNIT:="swarm-controller.service" _msg:"swarm jobq: mint_agent_identity failed" | stats by (F_AGENT) count() as failures''; - for = "0s"; - summary = "swarm-controller failed to mint agent {{ $labels.F_AGENT }}'s store identity; the reason is the `F_ERROR` field of the swarm-controller log line"; - }) - # `hive-archive-backup` (nix/host-modules/hive-archive-backup.nix) - # prints one `archive backup failed: ` line per agent - # it could not back up, and one for a hive swarm-controller - # has granted nothing. The backup runs hourly, so `for` - # rides out the minutes a newly placed agent waits for its - # grant, and a second failed run keeps it firing. - (logCountRule { - uid = "hh-archive-backup-failed"; - title = "archive backup failed"; - windowSeconds = 7800; - expr = ''_time:130m _SYSTEMD_UNIT:="hive-archive-backup.service" _msg:"archive backup failed" | stats by (_HOSTNAME) count() as failures''; - for = "30m"; - summary = "{{ $labels._HOSTNAME }} failed to back up an agent to the archive; the unit's journal names the agent and the cause"; - }) - # `swarm-archive-prune` prints `archive prune failed: `. - (logCountRule { - uid = "hh-archive-prune-failed"; - title = "archive prune failed"; - windowSeconds = 90000; - expr = ''_time:25h _SYSTEMD_UNIT:="swarm-archive-prune.service" _msg:"archive prune failed" | stats count() as failures''; - for = "0s"; - summary = "the archive's daily prune failed for an agent's repository, so its retention is not applied; the unit's journal names the agent"; - }) - # `swarm-archive-check` prints `archive check failed: `; it runs - # weekly, so the window spans a missed week. - (logCountRule { - uid = "hh-archive-check-failed"; - title = "archive check failed"; - windowSeconds = 700000; - expr = ''_time:8d _SYSTEMD_UNIT:="swarm-archive-check.service" _msg:"archive check failed" | stats count() as failures''; - for = "0s"; - summary = "the archive's weekly integrity check failed for an agent's repository, so its backups may not restore; the unit's journal names the agent and the restic error"; - }) - # Logged once per detected crash, by `emit_crash_transitions` - # in hive-c0re's crash_watch.rs (10s poll interval). Replaces - # the old per-hive dashboard `agents_crashing` banner — see - # that function's module doc for why the banner went away - # in favour of this. Host journal records carry the - # tracing fields as `F_` and no `sender` attribute, - # so the machine is `_HOSTNAME`. The unit - # filter keeps out an agent's own log line if one ever - # quotes the same message. - (logCountRule { - uid = "hh-container-crashed"; - title = "container crashed"; - windowSeconds = 900; - expr = ''_time:15m _SYSTEMD_UNIT:="hive-c0re.service" _msg:"container crash detected" | stats by (_HOSTNAME, F_AGENT) count() as crashes''; - for = "0s"; - summary = "{{ $labels._HOSTNAME }} detected agent {{ $labels.F_AGENT }}'s container crash (not an operator-initiated stop)"; - }) - # hive-c0re's readiness verdict, the one `/health/ready` - # gives: degraded while any `crit`-level warning is raised. - # Read from the per-warning series (`hyperhive.hive.warning`) - # rather than the `hyperhive.hive.degraded` gauge, so each - # critical `kind` is its own instance and the alert names - # the warning that triggered it. `for` rides out a - # restart-time blip. - (metricThresholdRule { - uid = "hh-hive-degraded"; - title = "hive degraded"; - expr = ''max by (sender, kind) ({__name__="hyperhive.hive.warning", level="crit"})''; - threshold = 0; - for = "2m"; - summary = "{{ $labels.sender }} is degraded by the critical warning {{ $labels.kind }}; the message is the `hive warning raised` line in the hive-c0re log"; - }) - # One series per raised warning (`hyperhive.hive.warning`), - # so each `kind` is its own alert instance. The text is the - # `hive warning raised` line in the hive-c0re log. Disk - # pressure is left out: it has its own thresholds below, on - # the filesystem metric rather than the registry entry. - # Sweeps raise their warning only after several misses, so - # `for` is short. `pending_logins` is dropped for a hive that exports - # `hyperhive.agent.needs_login`, where `hh-agent-needs-login` - # below pages once per agent; a hive on an older hive-c0re - # has no such series, so it keeps paging here. - (metricThresholdRule { - uid = "hh-hive-warning"; - title = "hive warning raised"; - expr = ''max by (sender, kind, level) ({__name__="hyperhive.hive.warning", kind!~"disk_pressure|pending_logins"} or ({__name__="hyperhive.hive.warning", kind="pending_logins"} unless on (sender) group by (sender) ({__name__="hyperhive.agent.needs_login"})))''; - threshold = 0; - for = "2m"; - summary = "{{ $labels.sender }} has a {{ $labels.level }} warning raised: {{ $labels.kind }}; the message is the `hive warning raised` line in the hive-c0re log"; - }) - # `hyperhive.agent.needs_login` is `1` for a running agent - # without a usable claude login; stopped agents report - # nothing. One alert instance per `agent`; `for` - # lets a login in progress finish first. - (metricThresholdRule { - uid = "hh-agent-needs-login"; - title = "agent needs a claude login"; - expr = ''max by (agent) ({__name__="hyperhive.agent.needs_login"}) == 1''; - threshold = 0; - for = "5m"; - summary = "agent {{ $labels.agent }} has needed a claude login for 5 minutes; open its page in the dashboard to complete it"; - }) - # Processes the kernel OOM-killed in an agent's container, from - # the counter hive-c0re exports (`otel_metrics.rs`). A budgeted - # agent has no swap, so each kill is a subagent run, bash task or - # the agent's claude that hit its RAM budget. More than three in - # an hour is a budget that is too small for the work, not a - # one-off peak. One alert instance per `agent`. - (metricThresholdRule { - uid = "hh-agent-oom-kills"; - title = "agent OOM-killed repeatedly"; - windowSeconds = 3600; - expr = ''sum by (agent) (increase({__name__="hyperhive.container.memory.oom_kills", agent!=""}[1h]))''; - threshold = 3; - for = "0m"; - summary = "agent {{ $labels.agent }} had more than 3 processes OOM-killed in the last hour: it keeps hitting its RAM budget; see \"OOM kills by agent\" on the agents dashboard, and raise its memory cap if the work needs it"; - }) - # `hyperhive.hive.nix_store.utilization` is the used fraction of the - # filesystem holding the nix store, the one that failed CI - # with ENOSPC before the GC guardrails. - (metricThresholdRule { - uid = "hh-host-disk-high"; - title = "host disk filling"; - expr = ''max by (sender) ({__name__="hyperhive.hive.nix_store.utilization"})''; - threshold = 0.85; - for = "10m"; - summary = "the nix store's filesystem of {{ $labels.sender }} is over 85% full; garbage-collect before it runs out of space"; - }) - (metricThresholdRule { - uid = "hh-host-disk-critical"; - title = "host disk almost full"; - expr = ''max by (sender) ({__name__="hyperhive.hive.nix_store.utilization"})''; - threshold = 0.95; - for = "2m"; - summary = "the nix store's filesystem of {{ $labels.sender }} is over 95% full; garbage-collect now"; - }) - # The fraction of a store client certificate's validity - # already used, from the `bao.client_cert.*` gauges the - # services export (`swarm_secret_client::cert_metrics`). Both gauges of a - # series carry identical labels, so the division matches - # one-to-one on all of them without `on()`/`group_left`. - # `last_over_time` rides out the five-minute cadence of - # the one-shot reporter (`swarm-ci-metrics`). Agent leaves - # renew at half their life, so a fraction over 0.8 means - # the renewal has been stuck for days. `sender` and `agent` - # stay in the grouping so the alert names the holder. - # Agents whose deploy the build gate holds back, from the gauge - # swarm-controller exports (`observability/held_deploys.rs`): a build that - # fails, or that keeps getting no answer from the builder. A deploy - # whose facts copy to its hive fails is held too. - # Thirty minutes covers a builder restart and the controller's - # ten-minute retries. - (metricThresholdRule { - uid = "hh-deploys-held"; - title = "deploys held by the build gate"; - expr = ''sum({__name__="swarm.deploys.held"})''; - threshold = 0; - for = "30m"; - summary = "swarm-controller is holding back the deploy of one or more agents because the builder's build of internal/meta fails or gets no answer, or the cache facts can't be copied to its hive; the failed `build_meta` or `copy_attic_facts` node on the Jobs page says which"; - }) - (metricThresholdRule { - uid = "hh-bao-client-cert-lifetime"; - title = "bao client certificate past 80% of its lifetime"; - expr = ''max by ("service.name", cert, sender, agent) ((time() - last_over_time({__name__="bao.client_cert.not_before"}[15m])) / (last_over_time({__name__="bao.client_cert.not_after"}[15m]) - last_over_time({__name__="bao.client_cert.not_before"}[15m])))''; - threshold = 0.8; - for = "10m"; - summary = "the store client certificate {{ $labels.cert }} (sender {{ $labels.sender }}, agent {{ $labels.agent }}) is past 80% of its validity"; - }) - # Usage share ahead of the clock share, per claude account and - # window: percent used minus the percent of the window already - # elapsed, so above zero means ahead. The window length comes - # from the `window` label (`seven_day`, `five_hour`); other - # windows are not selected. `account` is stamped by hive-agent - # (`claude_usage_watch`); series without it (older agent builds) - # are not selected. `max by` collapses the agents that share an - # account. A `resets_at` in the past makes the elapsed share - # exceed 100, so a stale series cannot fire. - (metricThresholdRule { - uid = "hh-claude-usage-ahead-of-clock"; - title = "claude usage ahead of the clock"; - expr = - let - ahead = - window: seconds: - ''max by (account, window) (last_over_time({__name__="hyperhive.agent.claude_usage.percent", window="${window}", account!=""}[15m])) - 100 * (1 - (max by (account, window) (last_over_time({__name__="hyperhive.agent.claude_usage.resets_at", window="${window}", account!=""}[15m])) - time()) / ${toString seconds})''; - in - "(${ahead "seven_day" 604800}) or (${ahead "five_hour" 18000})"; - threshold = 0; - for = "1h"; - summary = "claude account {{ $labels.account }} has used more of its {{ $labels.window }} usage window than the window has elapsed"; - }) - ] - # One rule per declared hive's collector rather than one grouped by - # `sender`, so a collector that sends nothing at all still has an - # instance to fire. The swarm collector stamps `sender` with the - # client id the hive's collector authenticated as, the same - # `hiveClientPrefix` name the OIDC client is registered under. - ++ lib.mapAttrsToList ( - name: _: - logAbsenceRule { - uid = "hh-logs-absent-${name}"; - title = "no log records from ${name}"; - windowSeconds = 600; - expr = ''_time:10m sender:="${hyperhiveCfg.swarm.authelia.hiveClientPrefix}${name}" | stats count() as records''; - for = "5m"; - summary = "hive ${name} has sent no log records to VictoriaLogs for at least 10m"; - } - ) hyperhiveCfg.swarm.hives; - } - ]; - }; - }; - }; - }; + # 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} - - - -" ]; }; } diff --git a/nix/host-modules/swarm-otel-service.nix b/nix/host-modules/swarm-otel-service.nix index 8c5ed79b4..c0458e0bb 100644 --- a/nix/host-modules/swarm-otel-service.nix +++ b/nix/host-modules/swarm-otel-service.nix @@ -242,17 +242,14 @@ in swarm-stt = { clientId = hyperhiveCfg.swarm.stt.clientId; }; - # The forwarders in ./swarm-attic.nix, ./swarm-ci-runner.nix and - # ./swarm-grafana.nix, each authenticated as a client of its own. + # The forwarders in ./swarm-attic.nix and ./swarm-ci-runner.nix, each + # authenticated as a client of its own. swarm-attic = { clientId = hyperhiveCfg.swarm.attic.otel.clientId; }; swarm-ci-runner = { clientId = hyperhiveCfg.swarm.ci-runner.otel.clientId; }; - swarm-grafana = { - clientId = hyperhiveCfg.swarm.grafana.otel.clientId; - }; # The forwarders in ./hive-forge/default.nix and ./hive-matrix.nix, each # authenticated as a client of its own. hive-forge = { diff --git a/nix/host-modules/swarm-otel.nix b/nix/host-modules/swarm-otel.nix index 182fa1874..9d21389eb 100644 --- a/nix/host-modules/swarm-otel.nix +++ b/nix/host-modules/swarm-otel.nix @@ -249,7 +249,7 @@ let # journal in the guest, so the host directory holds the host's units only. # Every container with a `serviceProducers` entry (`swarm-bao`, `swarm-nats`, # `swarm-builder`, `swarm-claude-login`, `swarm-notify-router`, - # `swarm-review-classifier`, `swarm-ci-runner`, `swarm-grafana`, + # `swarm-review-classifier`, `swarm-ci-runner`, # `hive-forge`, `hive-matrix`, `swarm-authelia`, `swarm-attic`) forwards its own # journal from its own collector, so this receiver never sees their units. hostJournalDir = "/var/log/journal"; diff --git a/nix/host-modules/swarm-secret-publisher.nix b/nix/host-modules/swarm-secret-publisher.nix index 8f6c532d1..d41ff712e 100644 --- a/nix/host-modules/swarm-secret-publisher.nix +++ b/nix/host-modules/swarm-secret-publisher.nix @@ -55,12 +55,11 @@ let hyperhiveCfg.swarm.notify-router.clientId # The speech-to-text service, which reads it itself inside its container. hyperhiveCfg.swarm.stt.clientId - # The journal forwarders in the CI runner's, Grafana's, the cache's, the + # The journal forwarders in the CI runner's, the cache's, the # forge's and the homeserver's containers, each reading it inside its # container. hyperhiveCfg.swarm.attic.otel.clientId hyperhiveCfg.swarm.ci-runner.otel.clientId - hyperhiveCfg.swarm.grafana.otel.clientId hyperhiveCfg.swarm.forge.otel.clientId hyperhiveCfg.swarm.matrix.otel.clientId # The CI run poller, which reads it itself on its host. diff --git a/nix/module-eval/bao-grants.nix b/nix/module-eval/bao-grants.nix index 778fd22d2..4e05da270 100644 --- a/nix/module-eval/bao-grants.nix +++ b/nix/module-eval/bao-grants.nix @@ -101,7 +101,6 @@ let baoGrantWithConsumers = hiveWithController { deploy.bao.enable = true; deploy.bao.bootstrapTokenFile = "/run/secrets/bao-bootstrap.token"; - deploy.grafana.enable = true; deploy.swarm-otel.enable = true; }; @@ -131,7 +130,6 @@ let # Every reader against a store it does not run, each with a leaf placed by # hand. The deployment in which there is no local policy unit to wait for. baoRemoteReaders = hiveWithController { - deploy.grafana.enable = true; deploy.swarm-otel.enable = true; deploy.bao.clientCertFile = "/etc/pki/bao-client.pem"; deploy.bao.clientKeyFile = "/etc/pki/bao-client-key.pem"; @@ -144,7 +142,6 @@ let # The readers ./glue-bao-readers-policy-order.nix orders after their policy # units. policyReaders = [ - "swarm-bao-grafana-oidc" "swarm-bao-otel-oidc" ]; @@ -706,7 +703,7 @@ let # run rotate a value Grafana or the metrics store already holds. The # controller's Grafana token is the one leaf it may replace, which it # does when Grafana refuses the stored token. - name = "the Grafana reader reads its own and its forwarder's client secrets, creates its admin password, metrics bearer and datasource key, and writes the controller's Grafana token, and nothing else"; + name = "the Grafana reader reads its own client secret, creates its admin password, metrics bearer and datasource key, and writes the controller's Grafana token, and nothing else"; ok = let s = baoGrantHere.systemd.services.swarm-bao-grafana-oidc-policy.script; @@ -716,10 +713,6 @@ let path = "secret/data/swarm/services/swarm-grafana/oidc/client"; caps = [ "read" ]; } - { - path = "secret/data/swarm/services/swarm-grafana-collector/oidc/client"; - caps = [ "read" ]; - } { path = "secret/data/swarm/services/swarm-grafana/admin/password"; caps = [ @@ -997,7 +990,7 @@ let lib.all (p: p != null) own && !(lib.any (p: lib.elem p hiveLeaf) own) && lib.length (lib.unique own) == lib.length own - && presents "swarm-bao-grafana-oidc" b.grafanaOidcClientCertFile b.grafanaOidcClientKeyFile + && presents "swarm-bao-otel-oidc" b.otelOidcClientCertFile b.otelOidcClientKeyFile && presents "swarm-bao-forwarder-oidc" b.forwarderOidcClientCertFile b.forwarderOidcClientKeyFile; } @@ -1098,29 +1091,6 @@ let && !(noReaders ? swarm-bao-matrix-oidc) && !(noReaders ? swarm-bao-nats-callout-xkey); } - { - # The admin password and the controller's Grafana token are written under - # Grafana's leaf, so their units wait for the unit writing that leaf's - # role and policy; before it, the write is refused. The last arm is the - # absence control. - name = "grafana's admin password and controller token units are ordered after grafana's policy unit"; - ok = - lib.all - ( - unit: - let - u = baoGrantWithConsumers.systemd.services.${unit}; - in - lib.elem "swarm-bao-grafana-oidc-policy.service" u.after - && lib.elem "swarm-bao-grafana-oidc-policy.service" u.wants - && !(lib.elem "swarm-bao-grafana-oidc-policy.service" u.requires) - && !(baoGrantNoReaders.systemd.services ? ${unit}) - ) - [ - "swarm-bao-grafana-admin" - "swarm-bao-grafana-controller-token" - ]; - } { # The ordering is set apart from each reader's own definition, so it can # define a reader by itself: `after` on a unit nothing else declares is a @@ -1312,9 +1282,6 @@ let [ "swarm-services-cert" "swarm-bao-forwarder-oidc" - "swarm-bao-grafana-admin" - "swarm-bao-grafana-metrics-bearer" - "swarm-bao-grafana-controller-token" ] ++ policyReaders ); @@ -2245,8 +2212,9 @@ let } { # Create without update: the first value stored is the one every later - # run reads, and no run replaces it. Two leaves are the stores', the third the exporter's. - name = "the store credential publisher's grant is create and read on the two stores' and the queue exporter's credentials and nothing else, and the PKI unit signs its leaf"; + # run reads, and no run replaces it. Three leaves are the stores' and + # Grafana's, the fourth the exporter's. + name = "the store credential publisher's grant is create and read on the two stores', Grafana's and the queue exporter's credentials and nothing else, and the PKI unit signs its leaf"; ok = let s = baoGrantHere.systemd.services.swarm-bao-store-auth-policy.script; @@ -2262,12 +2230,17 @@ let "create" "read" ] + && + (grantFor grants "secret/data/swarm/services/grafana/store-auth").caps == [ + "create" + "read" + ] && (grantFor grants "secret/data/swarm/services/nats/exporter-auth").caps == [ "create" "read" ] - && lib.length grants == 3 + && lib.length grants == 4 && lib.hasInfix "auth/cert/certs/swarm-store-auth" s && lib.hasInfix "allowed_common_names=swarm-store-auth" s && lib.hasInfix "token_policies=swarm-store-auth" s @@ -3217,11 +3190,6 @@ let machine = baoGrantWithConsumers.services.hyperhive.swarm.otel.machine; consumer = "opentelemetry-collector.service"; } - { - fetch = "swarm-bao-grafana-oidc"; - machine = baoGrantWithConsumers.services.hyperhive.swarm.grafana.machine; - consumer = "grafana.service"; - } { fetch = "swarm-bao-forwarder-oidc"; machine = baoGrantWithConsumers.services.hyperhive.swarm.bao.machine; diff --git a/nix/module-eval/core-toggle.nix b/nix/module-eval/core-toggle.nix index 343dd4d08..e8ec0bc0a 100644 --- a/nix/module-eval/core-toggle.nix +++ b/nix/module-eval/core-toggle.nix @@ -195,10 +195,6 @@ let # changes (../host-modules/lib/refresh-consumer.nix), each on a fixture # that renders it. storeRefreshed = [ - { - unit = "swarm-bao-grafana-oidc"; - machine = allLocal; - } { unit = "swarm-bao-otel-oidc"; machine = allLocal; @@ -1284,7 +1280,7 @@ let && lib.all (n: l.${n}.proxyPass == store) (lib.attrNames prefixes); } { - # Grafana's host creates the bearer and its datasource sends it; the + # Grafana's init container creates the bearer and its datasource sends it; the # store's responder reads it. Three modules spell the path, and the # store's grants name it twice: if any one drifts, Grafana sends a value # the responder never reads, or one of them is refused by the store. @@ -1294,16 +1290,15 @@ let leaf = "swarm/services/${allLocal.services.hyperhive.swarm.grafana.oidc.clientId}/metrics/bearer"; ds = lib.findFirst (d: d.uid == "swarm-victoriametrics") null - allLocal.containers.swarm-grafana.config.services.grafana.provision.datasources.settings.datasources; - bearerUnit = allLocal.systemd.services.swarm-bao-grafana-metrics-bearer; + allLocal.services.hyperhive.deploy.grafana.rendered.provision.datasources.settings.datasources; + fetch = allLocal.services.hyperhive.deploy.grafana.rendered.scripts.fetch; metricsPod = allLocal.services.hyperhive.k8s.rendered.services.swarm-metrics-auth.objects."swarm-metrics-auth/deployment".spec.template.spec; s = allLocal.systemd.services; in ds.jsonData.httpHeaderName1 == "Authorization" - && ds.secureJsonData.httpHeaderValue1 == "$__file{/run/swarm-grafana-secrets/metrics-bearer}" - && lib.hasInfix "bao kv put -cas=0 secret/${leaf} value=-" bearerUnit.script - && lib.hasInfix "/run/swarm-grafana-secrets/metrics-bearer \"Bearer $bearer\"" bearerUnit.script + && ds.secureJsonData.httpHeaderValue1 == "$__file{/run/grafana-secrets/metrics-bearer}" + && lib.hasInfix "put metrics-bearer \"Bearer $(seeded secret/${leaf})\"" 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; @@ -1316,7 +1311,7 @@ let ok = let datasources = - allLocal.containers.swarm-grafana.config.services.grafana.provision.datasources.settings.datasources; + allLocal.services.hyperhive.deploy.grafana.rendered.provision.datasources.settings.datasources; metrics = lib.findFirst (d: d.uid == "swarm-victoriametrics") null datasources; logs = lib.findFirst (d: d.uid == "swarm-victorialogs") null datasources; leaf = "swarm/services/${allLocal.services.hyperhive.swarm.grafana.oidc.clientId}/metrics/bearer"; @@ -1494,7 +1489,7 @@ let # The controls: the match finds the sockets the gateway's vhosts still # dial, and the predicate flags a unit that is exactly the hazard and # passes one that is not. - lib.elem "swarm-grafana" upstreamDirs + lib.elem "swarm-authelia" upstreamDirs && lib.elem "swarm-otel" upstreamDirs && hidden { DynamicUser = true; @@ -2862,11 +2857,11 @@ let { # Control: a store fetch with no timer still renders `RemainAfterExit`, # so the cases below read a real value rather than a missing one. - name = "Grafana's admin-password fetch stays active after it exits and has no timer"; + name = "the store credential unit stays active after it exits and has no timer"; ok = - allLocal.systemd.services ? swarm-bao-grafana-admin - && remainsAfterExit allLocal.systemd.services.swarm-bao-grafana-admin - && !(allLocal.systemd.timers ? swarm-bao-grafana-admin); + allLocal.systemd.services ? swarm-bao-store-auth + && remainsAfterExit allLocal.systemd.services.swarm-bao-store-auth + && !(allLocal.systemd.timers ? swarm-bao-store-auth); } { # A timer whose unit does not exist fails to load, so each timer is @@ -2949,7 +2944,6 @@ let "swarm-authelia" "swarm-bao" "swarm-builder" - "swarm-grafana" "swarm-otel" ] && lib.all (carries allLocal) names diff --git a/nix/module-eval/grafana.nix b/nix/module-eval/grafana.nix index f756d2878..b24b36976 100644 --- a/nix/module-eval/grafana.nix +++ b/nix/module-eval/grafana.nix @@ -31,14 +31,6 @@ let deploy.grafana.package = grafanaStub; }; - # A host that tries to move the socket directory; reading the option throws. - grafanaSocketDirSet = hive { - deploy.grafana.enable = true; - deploy.grafana.socketDir = "/run/test-grafana-sock"; - deploy.grafana.plugins = [ ]; - deploy.grafana.package = grafanaStub; - }; - # Same pairing `nix/module-eval/bao-otel-collector.nix` uses for its own # cases: the store's container with its own collector on, so # `.containers.swarm-bao.config` carries a real, evaluated @@ -104,6 +96,9 @@ let # # Matched on the option name the message names, not on its prose, so the # wording stays rewordable: the option name is the part an operator has to + # What a host's Grafana pod is rendered from. + rendered = m: m.services.hyperhive.deploy.grafana.rendered; + # act on, and a message that stopped naming it would be the actual defect. grafanaRefusedFor = m: option: @@ -115,24 +110,34 @@ let ) m.assertions; cases = [ { - # The socket's directory is its access control, so it must stay dedicated - # to this one socket. `readOnly` is what makes that inexpressible: a - # definition anywhere — here at the `deploy` path — has to fail the eval, - # and an unset host has to render the default into nginx's upstream. - name = "grafana's socket directory cannot be set and renders its default"; + # The UI is reached by name, through the gateway, so the vhost dials the + # pod's Service and the host binds nothing for it: no socket directory + # option, no directory of it. The Service's name is in a variable that + # nginx resolves per request. + name = "grafana has no socket directory and its vhost dials the pod's Service by name"; ok = - !(builtins.tryEval grafanaSocketDirSet.services.hyperhive.deploy.grafana.socketDir).success + let + g = grafanaHere.services.hyperhive.swarm.grafana; + locs = grafanaHere.services.nginx.virtualHosts.${g.domain}.locations; + in + !(grafanaHere.services.hyperhive.deploy.grafana ? socketDir) + && locs."= /metrics".proxyPass == "http://$swarm_grafana_upstream/metrics$is_args$args" + && locs."/".proxyPass == "http://$swarm_grafana_upstream" && - grafanaHere.services.nginx.virtualHosts.${grafanaHere.services.hyperhive.swarm.grafana.domain}.locations."= /metrics".proxyPass - == "http://unix:/run/swarm-grafana/grafana.sock:/metrics"; + lib.hasInfix "set $swarm_grafana_upstream swarm-grafana.hyperhive.svc.cluster.local:3000;" + locs."/".extraConfig + && !(lib.any (lib.hasInfix "/run/swarm-grafana") grafanaHere.systemd.tmpfiles.rules); } { - # Grafana serves `/metrics` unauthenticated, so the published name gates - # it on the collector's auth subrequest: no `error_page 401 =302` (a - # scraper would parse a login page as metrics) and no `/__hive_authelia`. - # `=` is what catches the normalised variants and still leaves the rest - # of Grafana proxied. - name = "grafana's published vhost serves /metrics only behind the collector's auth subrequest"; + # Grafana serves `/metrics` to anyone who reaches the port, so the + # published name gates it on the collector's auth subrequest: no + # `error_page 401 =302` (a scraper would parse a login page as metrics) + # and no `/__hive_authelia`. `=` is what catches the normalised variants + # and still leaves the rest of Grafana proxied. After that check the + # vhost sends the listener credential the pod's `[metrics]` section asks + # for; `/` sends none, because Grafana's own login is the credential + # there. + name = "grafana's published vhost serves /metrics only behind the collector's auth subrequest, with the pod's credential"; ok = let g = grafanaHere.services.hyperhive.swarm.grafana; @@ -144,10 +149,43 @@ let && locs."= /metrics".return == null && checksOf locs."= /metrics" == [ "auth_request /__grafana_metrics_authz;" ] && !(lib.hasInfix "error_page" locs."= /metrics".extraConfig) + && lib.hasInfix "include /var/lib/swarm-store-auth/grafana.conf;" locs."= /metrics".extraConfig + && !(lib.hasInfix "swarm-store-auth" locs."/".extraConfig) && authz.proxyPass == "https://auth.t.local/api/authz/auth-request" && lib.hasInfix "internal;" authz.extraConfig - && !(grafanaHere.services.nginx.virtualHosts ? "grafana-metrics") - && lib.hasPrefix "http://unix:" locs."/".proxyPass; + && !(grafanaHere.services.nginx.virtualHosts ? "grafana-metrics"); + } + { + # The credential the vhost sends is the one the pod's settings ask for: + # the same user name, the password from the Secret's credential, and the + # endpoint on. Grafana reads both keys at start (`pkg/setting/setting.go` + # in the pinned release), and the pod's login is the only other way in to + # `/metrics`. + name = "grafana's metrics endpoint asks for the listener credential the vhost sends"; + ok = + let + s = (rendered grafanaHere).settings; + in + s.metrics.enabled + && s.metrics.basic_auth_username == "swarm-store" + && s.metrics.basic_auth_password == "$__file{/run/credentials/swarm-grafana.service/store-auth}" + && lib.elem "store-auth" grafanaHere.services.hyperhive.deploy.grafana.unit.serviceConfig.LoadCredential; + } + { + # The UI and the API are Grafana's own to authenticate: no anonymous + # access, a Viewer or otherwise, and the listener is the pod's port on all + # its addresses because the Service is what reaches it. + name = "grafana takes no anonymous access and listens on the pod's port"; + ok = + let + s = (rendered grafanaHere).settings; + in + !(s ? "auth.anonymous") + && !(s."auth.basic".enabled or true == false) + && s.server.protocol == "http" + && s.server.http_addr == "0.0.0.0" + && s.server.http_port == 3000 + && s.server.root_url == "https://grafana.t.local/"; } { # This fixture enables grafana and NOT authelia, so the login-form toggle @@ -155,7 +193,7 @@ let # this host". Its vhost is on the public gateway, so a password box there # is a way in whatever the topology. name = "grafana disables its local login form even where authelia is not on this host"; - ok = grafanaHere.containers.swarm-grafana.config.services.grafana.settings.auth.disable_login_form; + ok = (rendered grafanaHere).settings.auth.disable_login_form; } { # The absence class this whole file is for, and the reported defect in one @@ -169,7 +207,7 @@ let name = "grafana's OIDC block names the swarm's IdP, wherever that IdP runs"; ok = let - oauth = m: m.containers.swarm-grafana.config.services.grafana.settings."auth.generic_oauth"; + oauth = m: (rendered m).settings."auth.generic_oauth"; remote = oauth grafanaRemoteAuthelia; local = oauth grafanaWithAuthelia; in @@ -181,25 +219,28 @@ let } { # 🩸 The arm that guards the ruling this slice landed under. There is ONE - # delivery route: the store reader, on every host that runs Grafana. The - # negative names the deleted unit rather than a generic absence, because - # the way this regresses is someone re-adding the co-located copy as an - # optimisation — a second writer of one path, and a second shape of "the - # secret is wrong" to debug. - name = "grafana's OIDC secret has exactly one delivery unit, the store reader, in both topologies"; + # delivery route: the pod's init container, with the store, on every host + # that runs Grafana. The negatives name the deleted units rather than a + # generic absence, because the way this regresses is someone re-adding a + # co-located copy as an optimisation — a second writer of one path, and a + # second shape of "the secret is wrong" to debug. + name = "grafana's OIDC secret has exactly one delivery route, the pod's init container, in both topologies"; ok = let local = grafanaWithAuthelia.systemd.services; remote = grafanaRemoteAuthelia.systemd.services; + init = m: (rendered m).scripts.fetch; in - local ? swarm-bao-grafana-oidc - && remote ? swarm-bao-grafana-oidc + lib.hasInfix "secret/swarm/services/swarm-grafana/oidc/client" (init grafanaWithAuthelia) + && lib.hasInfix "secret/swarm/services/swarm-grafana/oidc/client" (init grafanaRemoteAuthelia) + && !(local ? swarm-bao-grafana-oidc) + && !(remote ? swarm-bao-grafana-oidc) && !(local ? swarm-grafana-oidc-secret) && !(remote ? swarm-grafana-oidc-secret); } { # What the deleted warning became. The shape is unchanged — a Grafana host - # holding no store leaf — but silence there is a container nobody can log + # holding no store leaf — but silence there is a pod nobody can log # into for a reason no log names, and a warning is read back by nothing. # The second arm is what makes this a refusal about the IDENTITY: this # fixture names an IdP, so a message about `swarm.authelia.url` here would @@ -232,110 +273,75 @@ let # reset, a database created before the setting keeps `admin`. # # The reset's `--config` must be the file the server reads, or it resets - # a different database: compared by store path against the server's own - # command line. - name = "grafana's admin password is minted into the store and applied to new and existing databases"; + # a different database: the same store path in both commands. + name = "grafana's admin password is created in the store and applied to new and existing databases"; ok = let - unit = grafanaRemoteAuthelia.systemd.services.swarm-bao-grafana-admin; - grafana = grafanaRemoteAuthelia.containers.swarm-grafana.config.services.grafana; - service = grafanaRemoteAuthelia.containers.swarm-grafana.config.systemd.services.grafana; - resetConfig = lib.head ( - lib.head (lib.filter lib.isList (builtins.split "--config ([^ ]+)" service.preStart)) - ); + r = rendered grafanaRemoteAuthelia; + init = r.scripts.fetch; + start = r.scripts.start; in - lib.hasInfix "bao kv put -cas=0 secret/swarm/services/swarm-grafana/admin/password value=-" unit.script - && lib.hasInfix "openssl rand -hex 32" unit.script - && lib.hasInfix "atomic_write_secret 0400 196:0 /run/swarm-grafana-secrets/admin-password" unit.script - && lib.elem "container@swarm-grafana.service" unit.before - && unit.environment.BAO_CLIENT_CERT == "/etc/pki/bao-grafana-oidc.pem" - && grafana.settings.security.admin_password == "$__file{/run/swarm-grafana-secrets/admin-password}" - && lib.hasInfix "admin reset-admin-password --password-from-stdin < /run/swarm-grafana-secrets/admin-password" service.preStart - && lib.hasInfix "-config ${resetConfig}" service.script; + 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 "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 + && lib.hasInfix "--config ${r.configFile}" start + && lib.length (lib.splitString "--config ${r.configFile}" start) == 3; } { - # Grafana's datasource-encryption key reaches Grafana from the store, - # seeded from the file an earlier release generated in the container, - # which stays on disk. A different key leaves Grafana unable to read its - # stored datasource secrets, so nothing may mint ahead of that seed, and - # the superseded in-container generator must be gone: left in place it - # would write a second key beside the delivered one. The last two arms - # are the presence controls for the absence arms: the guest's `grafana` - # unit is found by the same lookup, and the admin password's legacy file - # is among the removals. - name = "grafana's datasource key is seeded into the store from the earlier file, delivered from /run, and the earlier file is kept"; + # 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"; ok = let - m = grafanaRemoteAuthelia; - unit = m.systemd.services.swarm-bao-grafana-secret-key; - guest = m.containers.swarm-grafana.config; - earlier = "/var/lib/nixos-containers/swarm-grafana/var/lib/grafana-secret/secret_key"; + r = rendered grafanaRemoteAuthelia; + init = r.scripts.fetch; in - lib.hasInfix "bao kv put -cas=0 \"\$leaf\" value=-" unit.script - && lib.hasInfix "grafana_secret_key secret/swarm/services/swarm-grafana/secret-key ${earlier} openssl rand -hex 32" unit.script - && lib.length (lib.splitString earlier unit.script) == 2 - && lib.hasInfix "atomic_write_secret 0400 196:0 /run/swarm-grafana-secrets/secret-key" unit.script - && lib.elem "container@swarm-grafana.service" unit.before - && unit.environment.BAO_CLIENT_CERT == "/etc/pki/bao-grafana-oidc.pem" - && - guest.services.grafana.settings.security.secret_key - == "$__file{/run/swarm-grafana-secrets/secret-key}" - && !(guest.systemd.services ? swarm-grafana-secret-key) - && guest.systemd.services ? grafana - && !(lib.any (lib.hasInfix "/var/lib/grafana-secret") m.systemd.tmpfiles.rules) - && lib.any (lib.hasInfix "/var/lib/grafana-admin") m.systemd.tmpfiles.rules - && lib.elem "r /var/lib/nixos-containers/swarm-grafana/var/lib/grafana-admin/password" m.systemd.tmpfiles.rules; + lib.hasInfix "put secret-key \"$(seeded secret/swarm/services/swarm-grafana/secret-key)\"" init + && lib.hasInfix "value=\"$(stored \"$1\")\"" 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); } { # swarm-controller reads alerts with this token, so the account it # belongs to is created and kept a Viewer, the token lands at the path - # the controller's grant reads, and an attempt against a Grafana or a - # store that never answers ends and retries. The timer re-runs it, so - # the unit must not stay active. - name = "the controller's Grafana token is a Viewer account's, stored under Grafana's leaf, and each attempt is bounded"; + # the controller's grant reads, and a call against a Grafana or a store + # that never answers ends and is retried on the next pass. + name = "the controller's Grafana token is a Viewer account's, stored under Grafana's leaf, and each call is bounded"; ok = let - unit = grafanaRemoteAuthelia.systemd.services.swarm-bao-grafana-controller-token; - s = unit.script; + s = (rendered grafanaRemoteAuthelia).scripts.controllerToken; in - !(lib.elem (toString (unit.serviceConfig.TimeoutStartSec or "infinity")) [ - "infinity" - "0" - ]) - && lib.hasInfix "curl --silent --show-error --connect-timeout 5 --max-time 15" s + lib.hasInfix "curl --silent --show-error --connect-timeout 5 --max-time 15" s && lib.hasInfix "--data '{\"name\":\"swarm-controller\",\"role\":\"Viewer\",\"isDisabled\":false}'" s && lib.hasInfix "--data '{\"role\":\"Viewer\",\"isDisabled\":false}'" s && lib.hasInfix "bao kv put secret/swarm/controller/swarm-controller/grafana/token value=-" s - && lib.hasInfix "--unix-socket /run/swarm-grafana/grafana.sock" s - && unit.environment.BAO_CLIENT_CERT == "/etc/pki/bao-grafana-oidc.pem" - && unit.serviceConfig.Restart == "on-failure" - && !(unit.serviceConfig.RemainAfterExit or false) - && lib.elem "swarm-bao-grafana-admin.service" unit.after - && grafanaRemoteAuthelia.systemd.timers ? swarm-bao-grafana-controller-token; + && lib.hasInfix "base=http://127.0.0.1:3000" s + && !(lib.hasInfix "--unix-socket" s) + && lib.hasInfix "sleep 300" s; } { - # The container is ready when the guest's boot finishes, which can be - # before Grafana listens, so the unit waits for the socket inside its own - # start job, ahead of every call that needs it. The wait is bounded and - # sits inside the unit's own timeout, or systemd kills the job first. - name = "the controller's Grafana token waits a bounded time for Grafana's socket before its first call"; + # The pod is ready when its containers start, which can be before Grafana + # listens, so the sidecar asks `/api/health` first and sleeps and asks + # again when it does not answer. The pass is only called on the answer. + name = "the controller's Grafana token sidecar calls Grafana only after /api/health answers"; ok = let - unit = grafanaRemoteAuthelia.systemd.services.swarm-bao-grafana-controller-token; - s = unit.script; - parts = lib.splitString "if ! retry_in_job " s; - budget = lib.toInt (lib.head (lib.splitString " " (lib.elemAt parts 1))); + s = (rendered grafanaRemoteAuthelia).scripts.controllerToken; at = needle: lib.stringLength (lib.head (lib.splitString needle s)); + loop = lib.last (lib.splitString "while true; do" s); in - lib.length parts == 2 - && lib.hasInfix "retry_in_job() {" s - && lib.hasInfix "${toString budget} grafana_listening; then" s - && lib.hasInfix "http://localhost/api/health" s - && budget > 0 - && budget <= 120 - && unit.serviceConfig.TimeoutStartSec == "4min" - && at "retry_in_job ${toString budget} grafana_listening" < at "no Grafana admin password at" - && at "retry_in_job ${toString budget} grafana_listening" < at "status=\"$(grafana \"$admin\" GET"; + lib.hasInfix "\"$base/api/health\"" loop + && lib.hasInfix "pass || echo" loop + && at "\"$base/api/health\"" > at "while true; do" + && at "pass || echo" > at "\"$base/api/health\"" + && lib.hasInfix "sleep 5" loop; } { # Same 403-not-a-miss reason as the matrix and queue arms below: the @@ -346,7 +352,7 @@ let name = "grafana's OIDC secret is read from the prefix the mint writes"; ok = let - s = grafanaRemoteAuthelia.systemd.services.swarm-bao-grafana-oidc.script; + s = (rendered grafanaRemoteAuthelia).scripts.fetch; in lib.hasInfix "secret/swarm/services/swarm-grafana/oidc/client" s && !(lib.hasInfix "secret/swarm/hives/" s); @@ -354,67 +360,54 @@ let { # Authelia's mint writes the secret a moment after a fresh swarm's first # boot, so a read that finds nothing yet has to fail and be asked again. - # A unit that exits 0 there is done until the refresh timer, ten minutes - # on, and Grafana has no login in the meantime. - name = "grafana's OIDC delivery unit fails on no value yet, so the store retry asks again"; + # An init container that exits 0 there starts Grafana with no login: the + # init fails, and the kubelet starts it again. + name = "grafana's init container fails on no OIDC value yet, so the pod starts it again"; ok = let - u = grafanaRemoteAuthelia.systemd.services.swarm-bao-grafana-oidc; - afterRead = lib.last (lib.splitString "bao kv get" u.script); - beforeWrite = lib.head (lib.splitString "atomic_write_secret" afterRead); + s = (rendered grafanaRemoteAuthelia).scripts.fetch; + afterRead = lib.last (lib.splitString "oidc=\"$(stored" s); + beforeWrite = lib.head (lib.splitString "put swarm-grafana.secret" afterRead); in - # Both arms: the read that returns nothing and the one that returns an - # empty value. - lib.length (lib.splitString "exit 75" beforeWrite) == 3 + lib.hasInfix "exit 1" beforeWrite && !(lib.hasInfix "exit 0" beforeWrite) - && u.serviceConfig.Restart == "on-failure"; + && lib.hasInfix "set -euo pipefail" s; } { # A copy on persistent disk outlives the secret's rotation and lands in - # backups of the container's root. - name = "grafana's OIDC secret, admin password and metrics bearer are written to the host's /run only, and the old copies removed"; + # backups. The pod writes them to its memory-backed runtime directory, + # which the settings name, and the host keeps no copy, no unit and no + # directory for them. + name = "grafana's OIDC secret, admin password, bearer and key are written to the pod's memory only, and the host has no copy"; ok = let m = grafanaRemoteAuthelia; + r = rendered m; services = m.systemd.services; - mount = m.containers.swarm-grafana.bindMounts."/run/swarm-grafana-secrets"; rules = m.systemd.tmpfiles.rules; - guest = m.containers.swarm-grafana.config.services.grafana; + init = r.scripts.fetch; persistent = s: lib.hasInfix "/var/lib/nixos-containers" s || lib.hasInfix "/var/lib/grafana-" s; - oidc = services.swarm-bao-grafana-oidc.script; - admin = services.swarm-bao-grafana-admin.script; - bearer = services.swarm-bao-grafana-metrics-bearer.script; - # The bind source must exist when the store refuses the login, so the - # directory is made ahead of it in every delivery script. - dirBeforeLogin = - s: - lib.hasInfix "install -d -m 0755 /run/swarm-grafana-secrets" ( - lib.head (lib.splitString "bao login -method=cert" s) - ); in - lib.hasInfix "atomic_write_secret 0400 196:0 /run/swarm-grafana-secrets/swarm-grafana.secret" oidc - && lib.hasInfix "atomic_write_secret 0400 196:0 /run/swarm-grafana-secrets/metrics-bearer" bearer - && dirBeforeLogin oidc - && dirBeforeLogin admin - && dirBeforeLogin bearer - && !(persistent oidc) - && !(persistent admin) - && !(persistent bearer) - && !(persistent services.swarm-bao-grafana-controller-token.script) - && lib.hasInfix "< /run/swarm-grafana-secrets/admin-password" services.swarm-bao-grafana-controller-token.script - && mount.hostPath == "/run/swarm-grafana-secrets" - && mount.isReadOnly + 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 "d=/run/grafana-secrets" init + && !(persistent init) + && !(persistent r.scripts.controllerToken) + && lib.hasInfix "< /run/grafana-secrets/admin-password" r.scripts.controllerToken && - guest.settings."auth.generic_oauth".client_secret - == "$__file{/run/swarm-grafana-secrets/swarm-grafana.secret}" + r.settings."auth.generic_oauth".client_secret + == "$__file{/run/grafana-secrets/swarm-grafana.secret}" && lib.any ( - d: d.secureJsonData.httpHeaderValue1 or null == "$__file{/run/swarm-grafana-secrets/metrics-bearer}" - ) guest.provision.datasources.settings.datasources - && lib.elem "d /run/swarm-grafana-secrets 0755 root root -" rules - && lib.elem "r /var/lib/nixos-containers/swarm-grafana/var/lib/grafana-oidc/swarm-grafana.secret" rules - && lib.elem "r /var/lib/nixos-containers/swarm-grafana/var/lib/grafana-admin/password" rules - && lib.elem "r /var/lib/nixos-containers/swarm-grafana/var/lib/grafana-metrics/bearer" rules - && !(lib.any (lib.hasPrefix "f /run/swarm-grafana-secrets") rules); + d: d.secureJsonData.httpHeaderValue1 or null == "$__file{/run/grafana-secrets/metrics-bearer}" + ) r.provision.datasources.settings.datasources + && !(services ? swarm-bao-grafana-admin) + && !(services ? swarm-bao-grafana-metrics-bearer) + && !(services ? swarm-bao-grafana-secret-key) + && !(services ? swarm-bao-grafana-controller-token) + && !(m.systemd.timers ? swarm-bao-grafana-controller-token) + && !(lib.any (lib.hasInfix "swarm-grafana-secrets") rules) + && !(m.containers ? swarm-grafana); } { # Both halves of the co-location assumption, which was one host's @@ -440,7 +433,7 @@ let name = "the forge dashboard ships, and its CI runs tab queries the metric names the CI run poller and the controller record"; ok = let - provider = lib.head grafanaWithAuthelia.containers.swarm-grafana.config.services.grafana.provision.dashboards.settings.providers; + provider = lib.head grafanaWithAuthelia.services.hyperhive.deploy.grafana.rendered.provision.dashboards.settings.providers; shipped = lib.attrNames provider.options.path.entries; board = builtins.fromJSON (builtins.readFile ../host-modules/swarm-grafana/dashboards/forge.json); exprs = lib.concatMap (el: map (q: q.spec.query.spec.expr or "") el.spec.data.spec.queries) ( @@ -484,7 +477,7 @@ let name = "the review classifier dashboard ships, and queries the metric names the controller and the classifier record"; ok = let - provider = lib.head grafanaWithAuthelia.containers.swarm-grafana.config.services.grafana.provision.dashboards.settings.providers; + provider = lib.head grafanaWithAuthelia.services.hyperhive.deploy.grafana.rendered.provision.dashboards.settings.providers; shipped = lib.attrNames provider.options.path.entries; board = builtins.fromJSON ( builtins.readFile ../host-modules/swarm-grafana/dashboards/review-classifier.json @@ -644,7 +637,7 @@ let name = "the builds dashboard ships, and reads the fields hive-c0re logs on a container build"; ok = let - provider = lib.head grafanaWithAuthelia.containers.swarm-grafana.config.services.grafana.provision.dashboards.settings.providers; + provider = lib.head grafanaWithAuthelia.services.hyperhive.deploy.grafana.rendered.provision.dashboards.settings.providers; shipped = lib.attrNames provider.options.path.entries; board = builtins.fromJSON (builtins.readFile ../host-modules/swarm-grafana/dashboards/builds.json); exprs = map (e: (lib.head e.spec.data.spec.queries).spec.query.spec.expr) ( @@ -687,7 +680,7 @@ let name = "the host dashboard ships, and every panel query filters on host"; ok = let - provider = lib.head grafanaWithAuthelia.containers.swarm-grafana.config.services.grafana.provision.dashboards.settings.providers; + provider = lib.head grafanaWithAuthelia.services.hyperhive.deploy.grafana.rendered.provision.dashboards.settings.providers; shipped = lib.attrNames provider.options.path.entries; board = builtins.fromJSON (builtins.readFile ../host-modules/swarm-grafana/dashboards/host.json); exprs = lib.concatMap (p: map (t: t.expr) p.targets) board.panels; @@ -708,7 +701,7 @@ let let h = grafanaHere.services.hyperhive; groups = - grafanaHere.containers.swarm-grafana.config.services.grafana.provision.alerting.rules.settings.groups; + grafanaHere.services.hyperhive.deploy.grafana.rendered.provision.alerting.rules.settings.groups; rules = lib.concatMap (g: g.rules) groups; expr = uid: @@ -751,7 +744,7 @@ let name = "the egress dashboard ships, and reads the field layout of squid's log lines"; ok = let - provider = lib.head grafanaWithAuthelia.containers.swarm-grafana.config.services.grafana.provision.dashboards.settings.providers; + provider = lib.head grafanaWithAuthelia.services.hyperhive.deploy.grafana.rendered.provision.dashboards.settings.providers; shipped = lib.attrNames provider.options.path.entries; board = builtins.fromJSON (builtins.readFile ../host-modules/swarm-grafana/dashboards/egress.json); exprs = map (e: (lib.head e.spec.data.spec.queries).spec.query.spec.expr) ( @@ -845,7 +838,7 @@ let ok = let datasources = - grafanaWithAuthelia.containers.swarm-grafana.config.services.grafana.provision.datasources.settings.datasources; + grafanaWithAuthelia.services.hyperhive.deploy.grafana.rendered.provision.datasources.settings.datasources; metrics = lib.findFirst (d: d.uid == "swarm-victoriametrics") null datasources; logs = lib.findFirst (d: d.uid == "swarm-victorialogs") null datasources; in @@ -862,7 +855,7 @@ let name = "the logs datasource's plugin is handed Grafana's environment"; ok = let - grafana = grafanaWithAuthelia.containers.swarm-grafana.config.services.grafana; + grafana = grafanaWithAuthelia.services.hyperhive.deploy.grafana.rendered; logs = lib.findFirst ( d: d.uid == "swarm-victorialogs" ) null grafana.provision.datasources.settings.datasources; @@ -888,7 +881,7 @@ let ok = let sources = - grafanaHere.containers.swarm-grafana.config.services.grafana.provision.datasources.settings.datasources; + grafanaHere.services.hyperhive.deploy.grafana.rendered.provision.datasources.settings.datasources; logs = lib.head (lib.filter (d: d.uid == "swarm-victorialogs") sources); rules = logs.jsonData.logLevelRules or [ ]; # `overwrite_text` makes the stored text the OpenTelemetry short name @@ -916,7 +909,7 @@ let ok = let groups = - grafanaHere.containers.swarm-grafana.config.services.grafana.provision.alerting.rules.settings.groups; + grafanaHere.services.hyperhive.deploy.grafana.rendered.provision.alerting.rules.settings.groups; rules = lib.concatMap (g: g.rules) groups; rule = lib.findFirst (r: r.uid == "hh-agent-turn-failed") null rules; expr = (lib.head rule.data).model.expr; @@ -934,7 +927,7 @@ let ok = let groups = - grafanaHere.containers.swarm-grafana.config.services.grafana.provision.alerting.rules.settings.groups; + grafanaHere.services.hyperhive.deploy.grafana.rendered.provision.alerting.rules.settings.groups; rules = lib.concatMap (g: g.rules) groups; rule = lib.findFirst (r: r.uid == "hh-review-classifier-run-failed") null rules; expr = (lib.head rule.data).model.expr; @@ -960,7 +953,7 @@ let ok = let groups = - grafanaHere.containers.swarm-grafana.config.services.grafana.provision.alerting.rules.settings.groups; + grafanaHere.services.hyperhive.deploy.grafana.rendered.provision.alerting.rules.settings.groups; rules = lib.concatMap (g: g.rules) groups; source = builtins.readFile ../../hive-c0re/src/stats/otel_metrics.rs; expected = { @@ -994,7 +987,7 @@ let ok = let groups = - grafanaHere.containers.swarm-grafana.config.services.grafana.provision.alerting.rules.settings.groups; + grafanaHere.services.hyperhive.deploy.grafana.rendered.provision.alerting.rules.settings.groups; rules = lib.concatMap (g: g.rules) groups; rule = lib.findFirst (r: r.uid == "hh-hive-degraded") null rules; expr = (lib.head rule.data).model.expr; @@ -1016,7 +1009,7 @@ let ok = let groups = - grafanaHere.containers.swarm-grafana.config.services.grafana.provision.alerting.rules.settings.groups; + grafanaHere.services.hyperhive.deploy.grafana.rendered.provision.alerting.rules.settings.groups; rules = lib.concatMap (g: g.rules) groups; source = builtins.readFile ../../swarm-secret-client/src/cert.rs; threshold = @@ -1052,7 +1045,7 @@ let ok = let groups = - grafanaHere.containers.swarm-grafana.config.services.grafana.provision.alerting.rules.settings.groups; + grafanaHere.services.hyperhive.deploy.grafana.rendered.provision.alerting.rules.settings.groups; rules = lib.concatMap (g: g.rules) groups; source = builtins.readFile ../../hive-agent/src/otel_turn_metrics.rs; rule = lib.findFirst (r: r.uid == "hh-claude-usage-ahead-of-clock") null rules; @@ -1091,7 +1084,7 @@ let ok = let groups = - grafanaHere.containers.swarm-grafana.config.services.grafana.provision.alerting.rules.settings.groups; + grafanaHere.services.hyperhive.deploy.grafana.rendered.provision.alerting.rules.settings.groups; rules = lib.concatMap (g: g.rules) groups; source = builtins.readFile ../../hive-c0re/src/stats/otel_metrics.rs; rule = uid: lib.findFirst (r: r.uid == uid) null rules; @@ -1121,7 +1114,7 @@ let ok = let groups = - grafanaHere.containers.swarm-grafana.config.services.grafana.provision.alerting.rules.settings.groups; + grafanaHere.services.hyperhive.deploy.grafana.rendered.provision.alerting.rules.settings.groups; rules = lib.concatMap (g: g.rules) groups; source = builtins.readFile ../../hive-c0re/src/stats/otel_metrics.rs; rule = uid: lib.findFirst (r: r.uid == uid) null rules; @@ -1151,7 +1144,7 @@ let ok = let groups = - grafanaHere.containers.swarm-grafana.config.services.grafana.provision.alerting.rules.settings.groups; + grafanaHere.services.hyperhive.deploy.grafana.rendered.provision.alerting.rules.settings.groups; rules = lib.concatMap (g: g.rules) groups; source = builtins.readFile ../../swarm-controller/src/observability/held_deploys.rs; rule = uid: lib.findFirst (r: r.uid == uid) null rules; diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix index 8032b8218..c7c64a6bb 100644 --- a/nix/module-eval/k8s.nix +++ b/nix/module-eval/k8s.nix @@ -55,6 +55,7 @@ let deploy.nats.enable = false; deploy.victorialogs.enable = false; deploy.victoriametrics.enable = false; + deploy.grafana.enable = false; } ); @@ -449,10 +450,10 @@ let loaded = map toString withNode.services.k3s.images; rendered = map toString withNode.system.build.k8sImages; in - lib.length rendered == 17 + lib.length rendered == 19 && lib.all (i: lib.elem i loaded) rendered && lib.elem (toString withNode.services.k3s.package.airgap-images) loaded - && lib.length loaded == 18; + && lib.length loaded == 20; } { # The all-local host's assertions are the control: they all hold. @@ -766,13 +767,14 @@ let lib.filter lib.isList (builtins.split "auth/jwt-k8s/role/([a-z-]+)" script) ); # The queue's two roles share one account, and the log and metrics stores' - # responders hold one role each of their own: a case each. + # responders and Grafana hold one role each of their own: a case each. roles = lib.filter ( r: !(lib.hasPrefix "swarm-nats" r) && !(lib.elem r [ "swarm-logs-auth" "swarm-metrics-auth" + "swarm-grafana-oidc" ]) ) allRoles; ttl = "token_ttl=1h \\\n token_max_ttl=1h"; @@ -950,10 +952,11 @@ let && !(onCluster.systemd.services ? "container@swarm-claude-login") && !(onCluster.containers ? swarm-nats) && !(onCluster.systemd.services ? "container-nats") - # The log and metrics stores and their responders: no container, no - # unit, no socket directory. The Grafana container beside them, the CA + # The log and metrics stores, Grafana and their responders: no container, + # no unit, no socket directory. The swarm collector's container, the CA # publisher and a runtime directory of the host's own are the controls # that the lookups find what a host still runs. + # that the lookups find what a host still runs. && !(onCluster.containers ? swarm-victorialogs) && !(onCluster.systemd.services ? "container@swarm-victorialogs") && !(onCluster.systemd.services ? swarm-logs-auth) @@ -966,8 +969,17 @@ let && !(onCluster.systemd.services ? swarm-victoriametrics-forwarder-oidc) && !(onCluster.systemd.timers ? swarm-victoriametrics-forwarder-oidc) && !(lib.any (lib.hasPrefix "d /run/swarm-victoriametrics") onCluster.systemd.tmpfiles.rules) - && onCluster.containers ? swarm-grafana - && onCluster.systemd.services ? "container@swarm-grafana" + && !(onCluster.containers ? swarm-grafana) + && !(onCluster.systemd.services ? "container@swarm-grafana") + && !(onCluster.systemd.services ? swarm-bao-grafana-oidc) + && !(onCluster.systemd.services ? swarm-bao-grafana-admin) + && !(onCluster.systemd.services ? swarm-bao-grafana-metrics-bearer) + && !(onCluster.systemd.services ? swarm-bao-grafana-secret-key) + && !(onCluster.systemd.services ? swarm-bao-grafana-controller-token) + && !(onCluster.systemd.timers ? swarm-bao-grafana-oidc) + && !(lib.any (lib.hasPrefix "d /run/swarm-grafana") onCluster.systemd.tmpfiles.rules) + && onCluster.containers ? swarm-otel + && onCluster.systemd.services ? "container@swarm-otel" && onCluster.systemd.services ? hyperhive-k8s-ca-trust && lib.any (lib.hasPrefix "d /run/swarm-") onCluster.systemd.tmpfiles.rules && @@ -977,6 +989,7 @@ let "swarm-ci-metrics" "swarm-claude-login" "swarm-controller" + "swarm-grafana" "swarm-logs-auth" "swarm-metrics-auth" "swarm-nats" @@ -1270,6 +1283,7 @@ let == [ "default-deny-ingress/networkpolicy" "swarm-controller/networkpolicy" + "swarm-grafana/networkpolicy" "swarm-logs-auth/networkpolicy" "swarm-metrics-auth/networkpolicy" "swarm-nats/networkpolicy" @@ -2168,7 +2182,7 @@ let && ns."pod-security.kubernetes.io/warn" == "restricted" && ns."pod-security.kubernetes.io/audit" == "restricted" && ns."app.kubernetes.io/part-of" == "hyperhive" - && lib.length specs == 11 + && lib.length specs == 12 && lib.all (s: problems s == [ ]) specs && problems withHostPort != [ ] && problems withCaps != [ ] @@ -2328,6 +2342,10 @@ let variable = "$swarm_metrics_store_upstream"; store = "victoriametrics"; }; + grafanaLocations = allLocal.services.nginx.virtualHosts.${h.swarm.grafana.domain}.locations; + grafanaSent = lib.filterAttrs ( + _: l: hasInfix "/var/lib/swarm-store-auth/grafana.conf" (l.extraConfig or "") + ) grafanaLocations; in # The log store's four: the operator's `/`, the collector's ingest, the # query API and the store's own metrics. @@ -2366,20 +2384,24 @@ let && lib.all (store: hasInfix "secret/swarm/services/${store}/store-auth" unit.script) [ "victorialogs" "victoriametrics" + "grafana" ] && lib.all (store: hasInfix "/var/lib/swarm-store-auth/${store}.conf" unit.script) [ "victorialogs" "victoriametrics" + "grafana" ] && lib.all (store: hasInfix "swarm-${store}-credentials" unit.script) [ "victorialogs" "victoriametrics" + "grafana" ] && hasInfix "--from-file=store-auth=/var/lib/swarm-store-auth/victoriametrics.password" unit.script && unit.environment.BAO_CLIENT_CERT == h.deploy.bao.storeAuthClientCertFile && hasInfix "store-auth.pem" h.deploy.bao.storeAuthClientCertFile && lib.elem (rule "victorialogs") allLocal.systemd.tmpfiles.rules && lib.elem (rule "victoriametrics") allLocal.systemd.tmpfiles.rules + && lib.elem (rule "grafana") allLocal.systemd.tmpfiles.rules # nginx runs as `User=nginx`: the directory and the nginx files are its # group's to read, written that way and fixed when they already hold the # value, and the passwords stay root's. @@ -2393,9 +2415,19 @@ let && !(noNode.systemd.services ? swarm-bao-store-auth) && !(lib.elem (rule "victorialogs") noNode.systemd.tmpfiles.rules) && !(lib.elem (rule "victoriametrics") noNode.systemd.tmpfiles.rules) + && !(lib.elem (rule "grafana") noNode.systemd.tmpfiles.rules) && !(lib.elem "d /var/lib/swarm-store-auth 0750 root nginx - -" noNode.systemd.tmpfiles.rules) && !(noNode.services.nginx.virtualHosts ? ${h.swarm.victorialogs.domain}) - && !(noNode.services.nginx.virtualHosts ? ${h.swarm.victoriametrics.domain}); + && !(noNode.services.nginx.virtualHosts ? ${h.swarm.victoriametrics.domain}) + # Grafana's vhost sends it on `/metrics` alone, after the identity + # provider's check; `/` dials the same Service and carries none, which + # is Grafana's own login's. The Service's variable is the control that + # the lookup finds the location. + && lib.attrNames grafanaSent == [ "= /metrics" ] + && hasInfix "auth_request /__grafana_metrics_authz;" grafanaLocations."= /metrics".extraConfig + && hasInfix "$swarm_grafana_upstream" grafanaLocations."/".proxyPass + && !(hasInfix "swarm-store-auth" grafanaLocations."/".extraConfig) + && !(noNode.services.nginx.virtualHosts ? ${h.swarm.grafana.domain}); } { # The exporter's login has the same three ends as the stores', with the @@ -2773,6 +2805,125 @@ let && !(spec ? initContainers) && !(lib.any (v: v.name == "tls") spec.volumes); } + { + # Grafana's pod: the server on a static local volume that is its data + # directory, an init container that fetches its secrets into memory + # before it starts, and a sidecar that keeps the controller's token. The + # server's is the only port, and the pod logs in with its account's token. + # The metrics store's pod, which has neither container, is the control + # for the lookups that name them. + name = "Grafana's pod is the server on a static local volume that is its data directory, with an init container that fetches its secrets into memory and a sidecar that keeps the controller's token"; + ok = + let + spec = podSpec "swarm-grafana"; + named = n: lib.findFirst (c: c.name == n) null spec.containers; + main = named "swarm-grafana"; + side = named "controller-token"; + init = lib.head spec.initContainers; + dir = "/var/lib/nixos-containers/swarm-grafana/var/lib/grafana"; + pv = objects."swarm-grafana/persistentvolume"; + label = "hyperhive.darkest.space/state-grafana"; + probe = { + path = "/api/health"; + port = "api"; + }; + envOfC = c: lib.listToAttrs (map (e: lib.nameValuePair e.name e.value) c.env); + mountsOf = c: map (m: m.name) c.volumeMounts; + script = withNode.systemd.services.swarm-bao-k8s-jwt-policy.script; + credentials = lib.findFirst (v: v.name == "credentials") null spec.volumes; + policy = objects."swarm-grafana/networkpolicy".spec; + in + map (c: c.name) spec.containers == [ + "swarm-grafana" + "controller-token" + ] + && map (c: c.name) spec.initContainers == [ "fetch-secrets" ] + && !((podSpec "swarm-victoriametrics") ? initContainers) + && main.livenessProbe.httpGet == probe + && main.readinessProbe.httpGet == probe + && main.startupProbe.httpGet == probe + && main.startupProbe.failureThreshold == 30 + # One port, named once: the init container and the sidecar declare none. + && + main.ports == [ + { + name = "api"; + containerPort = 3000; + } + ] + && !(init ? ports) + && !(side ? ports) + && objects."swarm-grafana/deployment".spec.strategy.type == "Recreate" + && pv.spec.local.path == dir + && !(lib.hasInfix "/private/" pv.spec.local.path) + && spec.nodeSelector == { ${label} = "true"; } + && spec.securityContext.fsGroupChangePolicy == "OnRootMismatch" + # The secrets are in memory, and all three containers mount them where + # the settings name them. The `tmp` volume is the control that the + # lookup finds a plain one. + && + (lib.findFirst (v: v.name == "runtime") null spec.volumes) == { + name = "runtime"; + emptyDir.medium = "Memory"; + } + && + (lib.findFirst (v: v.name == "tmp") null spec.volumes) == { + name = "tmp"; + emptyDir = { }; + } + && lib.all (c: lib.elem "runtime" (mountsOf c)) [ + main + init + side + ] + && + (lib.findFirst (m: m.name == "runtime") null main.volumeMounts).mountPath == "/run/grafana-secrets" + # It logs in with its account's token, under the role its certificate has. + && spec.serviceAccountName == "swarm-grafana" + && objects."swarm-grafana/serviceaccount".metadata.name == "swarm-grafana" + && lib.all (c: (envOfC c).BAO_JWT_ROLE == "swarm-grafana-oidc") [ + main + init + side + ] + && !(lib.any (e: lib.hasPrefix "BAO_CLIENT" e.name) (init.env ++ side.env)) + && 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 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 + # store and the gateway. + && + objects."swarm-grafana/service".spec.ports == [ + { + name = "api"; + protocol = "TCP"; + port = 3000; + targetPort = "api"; + } + ] + && + policy.policyTypes == [ + "Ingress" + "Egress" + ] + && !(policy ? ingress) + && lib.length policy.egress == 2 + && + (lib.elemAt policy.egress 1).ports == [ + { + protocol = "TCP"; + port = 8208; + } + { + protocol = "TCP"; + port = 443; + } + ] + && lib.elem "d ${dir} - - - -" onCluster.systemd.tmpfiles.rules + && !(lib.any (lib.hasPrefix "d ${dir} ") noNode.systemd.tmpfiles.rules); + } { # A named `targetPort` resolves to the first container of the pod that # declares the name, so a second container declaring it too is reached by @@ -2826,6 +2977,7 @@ let "hyperhive.darkest.space/state-ci-metrics=true" "hyperhive.darkest.space/state-victorialogs=true" "hyperhive.darkest.space/state-victoriametrics=true" + "hyperhive.darkest.space/state-grafana=true" ] ) && @@ -2836,6 +2988,7 @@ let "hyperhive.darkest.space/state-ci-metrics" = "true"; "hyperhive.darkest.space/state-victorialogs" = "true"; "hyperhive.darkest.space/state-victoriametrics" = "true"; + "hyperhive.darkest.space/state-grafana" = "true"; } && noNode.services.k3s.nodeLabel == [ ]; } diff --git a/nix/module-eval/nats-authelia.nix b/nix/module-eval/nats-authelia.nix index 5f96b4432..db9c55643 100644 --- a/nix/module-eval/nats-authelia.nix +++ b/nix/module-eval/nats-authelia.nix @@ -176,10 +176,6 @@ let machine = "swarm-ci-runner"; option = "ci-runner"; } - { - machine = "swarm-grafana"; - option = "grafana"; - } { machine = "hive-forge"; option = "forge"; @@ -193,14 +189,6 @@ let # Those that share the host netns, on the shared services host. hostNetnsForwarders = [ - { - machine = "swarm-grafana"; - option = "grafana"; - name = "grafana"; - cert = "grafana-bao-cert"; - key = "grafana-bao-key"; - port = 8896; - } { machine = "hive-forge"; option = "forge"; @@ -712,7 +700,7 @@ let lib.all ok1 (map (svc: svc.machine) forwarderServices); } { - name = "the swarm collector admits the CI runner, Grafana, log store, forge and homeserver forwarders on receivers of their own"; + name = "the swarm collector admits the CI runner, forge and homeserver forwarders on receivers of their own"; ok = let h = shared.baoWithCollector; @@ -753,11 +741,7 @@ let && c.kind == "machine"; browser = find h.services.hyperhive.swarm.grafana.oidc.clientId; in - lib.all ok1 ownClientForwarders - && - h.services.hyperhive.swarm.grafana.otel.clientId != h.services.hyperhive.swarm.grafana.oidc.clientId - && browser != null - && browser.kind != "machine"; + lib.all ok1 ownClientForwarders && browser != null && browser.kind != "machine"; } { # The homeserver's container already holds matrix-ctl's identity, bound diff --git a/nix/module-eval/secret-publisher.nix b/nix/module-eval/secret-publisher.nix index 40499d907..fd31e9eeb 100644 --- a/nix/module-eval/secret-publisher.nix +++ b/nix/module-eval/secret-publisher.nix @@ -217,7 +217,7 @@ let # The forwarders in the CI runner's, Grafana's, the log store's, the # forge's, the homeserver's and authelia's containers read their secrets # from these paths, and the metrics store's host reads its container's. - name = "the mint stores the CI runner, Grafana, log store, cache, forge, homeserver, metrics store and authelia forwarders' secrets"; + name = "the mint stores the CI runner, cache, forge, homeserver and authelia forwarders' secrets"; ok = lib.all ( @@ -228,7 +228,6 @@ let ) [ "swarm-ci-runner-collector" - "swarm-grafana-collector" "swarm-forge-collector" "swarm-matrix-collector" "swarm-authelia-collector" diff --git a/nix/module-eval/swarm-services-switch.nix b/nix/module-eval/swarm-services-switch.nix index 568177fdc..27097975f 100644 --- a/nix/module-eval/swarm-services-switch.nix +++ b/nix/module-eval/swarm-services-switch.nix @@ -201,7 +201,6 @@ let "swarm-bao" "swarm-builder" "swarm-ci-runner" - "swarm-grafana" "swarm-otel" ]; @@ -259,7 +258,6 @@ let "authelia-swarm.service" "forgejo.service" "gitea-runner-swarm.service" - "grafana.service" "opentelemetry-collector.service" ]; } @@ -749,7 +747,6 @@ let lib.all (m: c ? ${m}) [ "swarm-authelia" "swarm-bao" - "swarm-grafana" "swarm-otel" "hive-matrix" "hive-forge" @@ -797,7 +794,7 @@ let # that lost a container can't pass by comparing fewer of them. name = "every service container restates its host-side privateNetwork"; ok = - lib.length (lib.attrNames serviceContainers) == 9 + lib.length (lib.attrNames serviceContainers) == 8 && lib.all ( c: c.privateNetwork == (c.config.services.hyperhive.swarmContainer.privateNetwork or null) ) (lib.attrValues serviceContainers); @@ -986,37 +983,6 @@ let && bridge.serviceConfig.Group == "gateway-nginx" && lib.elem dir unit.serviceConfig.ReadWritePaths; } - { - # On the bridge by DHCP, listening on a socket (protocol `socket` ignores the - # upstream-default `http_port`, which stays in the settings): the - # gateway's locations (UI, metrics, websocket upgrade) all forward to it. - # `forwarded != []` keeps an empty filter from passing. - name = "grafana runs on a netns of its own and the gateway reaches it over its socket"; - ok = - let - host = serviceContainersWithCi; - net = host.services.hyperhive.network; - c = host.containers.swarm-grafana; - dir = "/run/swarm-grafana"; - sock = "${dir}/grafana.sock"; - locs = host.services.nginx.virtualHosts.${host.services.hyperhive.swarm.grafana.domain}.locations; - forwarded = lib.filter (p: p != null && !(lib.hasPrefix "https://" p)) ( - map (l: l.proxyPass) (lib.attrValues locs) - ); - server = c.config.services.grafana.settings.server; - in - c.privateNetwork - && c.hostBridge == net.bridgeName - && c.hostAddress == null - && c.localAddress == null - && c.config.networking.interfaces.eth0.useDHCP - && c.config.networking.firewall.enable - && server.protocol == "socket" - && server.socket == sock - && forwarded != [ ] - && lib.all (lib.hasPrefix "http://unix:${sock}:") forwarded - && c.bindMounts.${dir}.hostPath == dir; - } { # atticd listens on the container's own loopback, a relay there forwards # the socket nginx connects to, and the host unit that drives the @@ -1096,7 +1062,7 @@ let && inner.networking.firewall.enable && onSocket "h1" && onSocket otel.producerName - && onSocket "swarm-grafana" + && onSocket "swarm-attic" && lib.all (n: (receivers.${n}.protocols.http.transport or null) == "unix") ( lib.attrNames receivers ) @@ -1148,7 +1114,7 @@ let verdict locs && lib.elem "/run/swarm-otel/h1.sock" receiverSocks && lib.elem "/run/swarm-otel/${otel.producerName}.sock" receiverSocks - && lib.elem "/run/swarm-otel/swarm-grafana.sock" receiverSocks + && lib.elem "/run/swarm-otel/swarm-attic.sock" receiverSocks && lib.length unixReceivers == lib.length (lib.attrNames host.services.hyperhive.swarm.hives) + 1 @@ -1338,9 +1304,9 @@ let in lib.length routes > 2 && lib.elem "h1" routes - && lib.elem "swarm-grafana" routes + && lib.elem "swarm-attic" routes && verdict script - && !verdict (lib.replaceStrings [ " swarm-grafana" ] [ "" ] script) + && !verdict (lib.replaceStrings [ " swarm-attic" ] [ "" ] script) && !verdict (lib.replaceStrings [ "000 | 502 | 504" ] [ "000 | 504" ] script) && !verdict (lib.replaceStrings [ "--resolve" ] [ "--noresolve" ] script) && !verdict (lib.replaceStrings [ "%header{x-swarm-otel-route}" ] [ "" ] script) @@ -1348,7 +1314,7 @@ let } { name = "a service container that sets no stateVersion of its own is on 26.05"; - ok = serviceContainers.swarm-grafana.config.system.stateVersion == "26.05"; + ok = serviceContainers.swarm-attic.config.system.stateVersion == "26.05"; } { name = "a service container that pins its own stateVersion keeps it"; @@ -1473,11 +1439,6 @@ let readers = [ "swarm-bao-forge-oidc" "swarm-bao-matrix-oidc" - "swarm-bao-grafana-oidc" - "swarm-bao-grafana-admin" - "swarm-bao-grafana-metrics-bearer" - "swarm-bao-grafana-secret-key" - "swarm-bao-grafana-controller-token" "swarm-bao-ci-runner" "swarm-bao-otel-oidc" ]; @@ -1501,9 +1462,9 @@ let !(lib.any (n: lib.elem n (s.after ++ s.wants ++ s.requires)) storeUnits); in lib.all waits readers - && lib.length readersHere == 9 - && lib.elem "swarm-bao-grafana-admin" readersHere - && lib.length readersElsewhere == 7 + && lib.length readersHere == 4 + && lib.elem "swarm-bao-forge-oidc" readersHere + && lib.length readersElsewhere == 2 && lib.all namesNoStoreUnit readersElsewhere && !(lib.any (u: storeOnlyNoHive.systemd.services ? ${u}) readers); } diff --git a/nix/vm-tests/k8s-services.nix b/nix/vm-tests/k8s-services.nix index fbfc1b5eb..4e2bd2ee3 100644 --- a/nix/vm-tests/k8s-services.nix +++ b/nix/vm-tests/k8s-services.nix @@ -1,7 +1,7 @@ # `vmTests..k8s-services`: the notification router, the speech-to-text -# service, the CI run poller, the review classifier and the claude login minter -# run as pods in the host's cluster, against the real secret store and a real -# queue. The script asserts that: +# service, the CI run poller, the review classifier, the claude login minter, +# the log and metrics stores and Grafana run as pods in the host's cluster, +# against the real secret store and a real queue. The script asserts that: # # - each runs once, as a pod or CronJob: the host has no container, unit, timer or # prune unit for it; @@ -9,22 +9,22 @@ # token, read its client secret and minted a token with it. The router # routes an event and a deleted pod exits 0 within its grace period; the # speech-to-text pod carries its limits and keeps its cache in an emptyDir, -# with no claim and no state gate, in a user namespace, and its NetworkPolicy -# lets a queue request in and only DNS and four host ports out; -# - the log and metrics stores run as pods on the directories their old -# containers kept, which units of this test filled as other users: each pod -# reads that record and writes a new one, the gateway's own locations -# (rendered by the modules) reach the stores and the responders, bearers are -# granted or refused as the store says, the metrics gateway refuses the -# store's write and admin routes, and no other pod reaches either store; +# in a user namespace, and its NetworkPolicy lets a queue request in and +# only DNS and four host ports out; +# - the stores and Grafana run on the directories their old containers kept, +# which units of this test filled as other users: the gateway's own +# locations (rendered by the modules) reach the stores and the responders, +# bearers are granted or refused as the store says, and no other pod +# reaches a store or Grafana's port 3000; +# - Grafana's database made under the default administrator takes the stored +# password and survives a pod delete, every route refuses a caller with no +# session, `/metrics` takes the listener credential the gateway adds and +# nothing else, a datasource query reaches the metrics store through the +# gateway, and the controller's Viewer token is in the secret store; # - the poller's Job completes against a forge that lists one run, pushes it to -# its own route of the swarm collector, holds no Secret, and keeps its cursor -# in a volume, so a second Job pushes nothing, and starts with no state -# gate; +# its own route of the swarm collector, and keeps its cursor in a volume; # - the minter's jwt token writes an agent's credentials and the classifier's -# cannot; the daemons' pods have a read-only root, and `claude` writes its -# config under `HOME` in the /tmp volume only, as the real login step does. -# +# cannot; the daemons' pods have a read-only root. # The queue is a plain nats-server with TLS, and one stub is the token endpoint, # the forge and the swarm collector, which records what it is given. The # speech-to-text model is a placeholder; the hive's CA and leaves come at boot. @@ -87,6 +87,15 @@ let legacyVmUser = "legacy-victoriametrics"; legacyVmPort = 19429; + # Grafana, as the module names it. The gateway answers its name over TLS for + # the pods, on a loopback port the SNI stream below leads the bridge's 443 to. + grafanaDir = "/var/lib/nixos-containers/swarm-grafana/var/lib/grafana"; + grafanaGateway = "127.0.0.1:18083"; + gatewayTls = "127.0.0.1:18443"; + stubPort = 1443; + legacyGrafanaUser = "legacy-grafana"; + legacyGrafanaPort = 19430; + # 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 # the variables between. The identity provider's checks are stand-ins that @@ -118,6 +127,8 @@ let # Every location of the vhost but the two that dial the identity # provider, so a location the module adds is served here too. metrics = cfg.services.nginx.virtualHosts."metrics.t.local".locations; + grafana = cfg.services.nginx.virtualHosts."grafana.t.local".locations; + grafanaServed = lib.filter (n: n != "= /__grafana_metrics_authz") (lib.attrNames grafana); metricsServed = lib.filter ( n: !(lib.elem n [ @@ -132,19 +143,32 @@ let events {} http { access_log off; + ssl_certificate ${pkiDir}/svc.pem; + ssl_certificate_key ${pkiDir}/svc-key.pem; ${cfg.services.nginx.appendHttpConfig} server { listen ${vlGateway}; + listen ${gatewayTls} ssl; + server_name logs.t.local; location = /__swarm_logs_ingest_authz { internal; return 200; } location = /__hive_authelia { internal; return 200; } ${lib.concatMapStrings (block logs) logsServed} } server { listen ${vmGateway}; + listen ${gatewayTls} ssl; + server_name metrics.t.local; location = /__metrics_ingest_authz { internal; return 200; } location = /__metrics_authelia { internal; return 200; } ${lib.concatMapStrings (block metrics) metricsServed} } + server { + listen ${grafanaGateway}; + listen ${gatewayTls} ssl; + server_name grafana.t.local; + location = /__grafana_metrics_authz { internal; return 200; } + ${lib.concatMapStrings (block grafana) grafanaServed} + } } ''; requestLog = "/var/log/stub-requests.log"; @@ -227,7 +251,7 @@ let self.send_error(404) - server = http.server.ThreadingHTTPServer(("${bridgeIp}", 443), Handler) + server = http.server.ThreadingHTTPServer(("127.0.0.1", ${toString stubPort}), Handler) context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_cert_chain("${pkiDir}/svc.pem", "${pkiDir}/svc-key.pem") server.socket = context.wrap_socket(server.socket, server_side=True) @@ -275,6 +299,7 @@ pkgs.testers.runNixOSTest { deploy.ci-metrics.enable = true; deploy.victorialogs.enable = true; deploy.victoriametrics.enable = true; + deploy.grafana.enable = true; deploy.hive-controller.hiveName = "h1"; swarm.domain = "t.local"; swarm.forge.domain = forgeName; @@ -327,6 +352,19 @@ pkgs.testers.runNixOSTest { events {} stream { ${config.services.nginx.streamConfig} + # The names the cluster's pods dial on 443 go to the gateway, the + # rest (identity provider, forge, collector) to the stand-in. + map $ssl_preread_server_name $swarm_443_backend { + metrics.t.local ${gatewayTls}; + logs.t.local ${gatewayTls}; + grafana.t.local ${gatewayTls}; + default 127.0.0.1:${toString stubPort}; + } + server { + listen ${bridgeIp}:443; + ssl_preread on; + proxy_pass $swarm_443_backend; + } } ''; in @@ -353,7 +391,7 @@ pkgs.testers.runNixOSTest { -subj "/CN=test-ca" -days 3650 \ -addext basicConstraints=critical,CA:TRUE -addext keyUsage=critical,keyCertSign openssl req -newkey rsa:2048 -nodes -keyout svc-key.pem -out svc.csr -subj "/CN=${natsName}" - printf 'subjectAltName=DNS:${natsName},DNS:${authName},DNS:${forgeName},DNS:${otelName}\n' > svc.ext + printf 'subjectAltName=DNS:${natsName},DNS:${authName},DNS:${forgeName},DNS:${otelName},DNS:metrics.t.local,DNS:logs.t.local,DNS:grafana.t.local\n' > svc.ext openssl x509 -req -in svc.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial \ -days 3650 -extfile svc.ext -out svc.pem chmod 0644 ca.pem svc.pem svc-key.pem @@ -512,6 +550,79 @@ 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. + users.users.${legacyGrafanaUser} = { + isSystemUser = true; + group = legacyGrafanaUser; + }; + users.groups.${legacyGrafanaUser} = { }; + systemd.services.grafana-legacy = { + wantedBy = [ "multi-user.target" ]; + before = [ "k3s.service" ]; + path = [ + pkgs.curl + pkgs.coreutils + pkgs.findutils + pkgs.gnugrep + ]; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + User = legacyGrafanaUser; + # k3s waits for this unit, so an annotation that never shows must + # fail it and not hold the boot. + TimeoutStartSec = 180; + UMask = "0007"; + ExecStartPre = "+${pkgs.writeShellScript "grafana-legacy-dir" '' + mkdir -p ${grafanaDir} + chown ${legacyGrafanaUser}:${legacyGrafanaUser} ${grafanaDir} + chmod 0700 ${grafanaDir} + ''}"; + RuntimeDirectory = "grafana-legacy"; + }; + environment = { + GF_PATHS_DATA = grafanaDir; + GF_PATHS_LOGS = "/run/grafana-legacy"; + GF_PATHS_PLUGINS = "/run/grafana-legacy/plugins"; + GF_PATHS_PROVISIONING = "/run/grafana-legacy/provisioning"; + GF_SERVER_HTTP_ADDR = "127.0.0.1"; + GF_SERVER_HTTP_PORT = toString legacyGrafanaPort; + GF_ANALYTICS_REPORTING_ENABLED = "false"; + GF_ANALYTICS_CHECK_FOR_UPDATES = "false"; + GF_ANALYTICS_CHECK_FOR_PLUGIN_UPDATES = "false"; + GF_PLUGINS_PREINSTALL_DISABLED = "true"; + }; + script = '' + store=http://127.0.0.1:${toString legacyGrafanaPort} + pkg=${config.services.hyperhive.deploy.grafana.package} + ${lib.getExe' config.services.hyperhive.deploy.grafana.package "grafana"} server \ + --homepath $pkg/share/grafana & + pid=$! + until curl -sf $store/api/health; do sleep 1; done + # 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) + found= + for _ in $(seq 60); do + if curl -s -u admin:admin "$store/api/annotations?tags=legacy" | grep -q 'written before the switch'; then + found=1 + break + fi + sleep 1 + done + if [ -z "$found" ]; then + echo "the seeded annotation is not found; the post replied $code; the store holds:" + curl -s -u admin:admin "$store/api/annotations" + exit 1 + fi + kill -TERM "$pid" + wait "$pid" || true + test -s ${grafanaDir}/grafana.db + ''; + }; + # The log and metrics stores' locations, from the active configuration's own text. systemd.services.logs-gateway = { wantedBy = [ "multi-user.target" ]; @@ -630,6 +741,9 @@ pkgs.testers.runNixOSTest { METRICS_AUTH = "swarm-metrics-auth" VM_DIR = "${vmDir}" METRICS_GATEWAY = "http://${vmGateway}" + 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"} @@ -765,6 +879,7 @@ pkgs.testers.runNixOSTest { "swarm-bao-claude-login-policy", "swarm-bao-logs-auth-policy", "swarm-bao-store-auth-policy", + "swarm-bao-grafana-oidc-policy", "swarm-bao-k8s-jwt-policy", ]: settle(f'[ "$(systemctl is-active {unit}.service)" = active ]', 900, [f"{unit}.service"]) @@ -805,6 +920,10 @@ pkgs.testers.runNixOSTest { as_root(f"bao kv put -mount=secret swarm/agents/{name}/observability @/tmp/grant-{name}.json") GRAFANA_BEARER = machine.succeed("openssl rand -hex 32").strip() as_root(f"bao kv put -mount=secret swarm/services/swarm-grafana/metrics/bearer value={GRAFANA_BEARER}") + # The dashboard's OIDC client secret, which the identity provider's mint + # stores in production; the pod's init container reads it. + GRAFANA_OIDC = machine.succeed("openssl rand -hex 16").strip() + as_root(f"bao kv put -mount=secret swarm/services/swarm-grafana/oidc/client value={GRAFANA_OIDC}") with subtest("the queue and the token stub run, and the queue holds the roster the router reads"): machine.wait_for_unit("hive-tls-ca.service") @@ -1599,6 +1718,221 @@ pkgs.testers.runNixOSTest { status = json.loads(kube(machine, f"get pod {name} -o json"))["status"] assert all(c["ready"] for c in status["containerStatuses"]), status + with subtest("the dashboard runs only as a pod: the host has no container, unit, timer or socket directory for it"): + machine.fail("test -e /etc/nixos-containers/swarm-grafana.conf") + assert host_state("container@swarm-grafana.service") == "inactive" + for unit in ( + "swarm-bao-grafana-oidc", + "swarm-bao-grafana-admin", + "swarm-bao-grafana-metrics-bearer", + "swarm-bao-grafana-secret-key", + "swarm-bao-grafana-controller-token", + "swarm-grafana-forwarder-oidc", + ): + machine.fail(f"systemctl cat {unit}.service") + for timer in ("swarm-bao-grafana-oidc", "swarm-bao-grafana-controller-token", "swarm-grafana-forwarder-oidc"): + machine.fail(f"systemctl cat {timer}.timer") + machine.fail("test -e /run/swarm-grafana") + machine.fail("test -e /run/swarm-grafana-secrets") + # The CA publisher is the control that the lookups find a unit of the cluster's that is there. + machine.succeed("systemctl cat hyperhive-k8s-ca-trust.service") + machine.succeed(f"test -L {MANIFESTS}/{GRAFANA}.yaml") + assert machine.execute("machinectl list --no-legend | grep -q swarm-grafana")[0] != 0 + grafana_pod = wait_pod_ready(GRAFANA, timeout=900) + + with subtest("the dashboard's init container fetched its secrets, its sidecar runs, and the pod mounts no store's credential"): + pod = json.loads(kube(machine, f"get pod {grafana_pod} -o json")) + init = pod["status"]["initContainerStatuses"] + assert [c["name"] for c in init] == ["fetch-secrets"] and init[0]["state"]["terminated"]["exitCode"] == 0, init + running = {c["name"]: c for c in pod["status"]["containerStatuses"]} + assert set(running) == {GRAFANA, "controller-token"}, running.keys() + assert all(c["ready"] and "running" in c["state"] for c in running.values()), running + # The pod mounts the one Secret of its own listener's credential and + # none of the two stores', which it reaches through the gateway with + # its bearer; the values it fetched are in no container's log. + secrets = {v["secret"]["secretName"] for v in pod["spec"]["volumes"] if "secret" in v} + assert secrets <= {"swarm-grafana-credentials"}, secrets + stored = as_root("bao kv get -mount=secret -field=value swarm/services/grafana/store-auth").strip() + for name in (GRAFANA, "controller-token"): + logs = machine.succeed(f"kubectl -n {NS} logs {grafana_pod} -c {name} --tail=200 2>&1") + assert stored not in logs and GRAFANA_BEARER not in logs and GRAFANA_OIDC not in logs, name + + with subtest("the dashboard's volume is the old container's directory, whose files keep the user that wrote them and whose tree the pod's group owns"): + pv = json.loads(kube(machine, f"get pv {GRAFANA}-store -o json")) + assert pv["spec"]["local"]["path"] == GRAFANA_DIR and pv["status"]["phase"] == "Bound", pv + pvc = json.loads(kube(machine, f"get pvc {GRAFANA}-store -o json")) + assert pvc["status"]["phase"] == "Bound" and pvc["spec"]["volumeName"] == pv["metadata"]["name"], pvc + assert machine.succeed(f"stat -c %g {GRAFANA_DIR}").strip() == "65532" + assert machine.succeed(f"find {GRAFANA_DIR} -name grafana.db -user ${legacyGrafanaUser} | head -1").strip() != "" + status = json.loads(kube(machine, f"get pod {grafana_pod} -o json")) + main = next(c for c in status["spec"]["containers"] if c["name"] == GRAFANA) + assert main["startupProbe"]["failureThreshold"] == 30, main + + def grafana_request(path: str, *args: str, gateway: bool = True) -> tuple[int, str]: + """One request to the dashboard: through the gateway's locations, or + from the node to the pod's address past the gateway. The status and the + body.""" + base = GRAFANA_GATEWAY if gateway else f"http://{grafana_ip}:3000" + _, out = machine.execute(f"curl -sS --max-time 20 -w '\\n%{{http_code}}' {' '.join(args)} '{base}{path}'") + body, _, code = out.rpartition("\n") + return int(code or 0), body + + def grafana_head(path: str, *args: str) -> tuple[str, str]: + """The status and the redirect target of one request through the gateway.""" + out = machine.succeed(f"curl -sS --max-time 20 -o /dev/null -w '%{{http_code}} %{{redirect_url}}' {' '.join(args)} '{GRAFANA_GATEWAY}{path}'") + code, _, target = out.partition(" ") + return code, target + + 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() + + 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("/") + assert code == "302" and target.endswith("/login"), (code, target) + for path in ("/api/search", "/api/datasources", "/api/user", "/api/datasources/proxy/uid/swarm-victoriametrics/api/v1/query?query=up"): + status, body = grafana_request(path) + assert status == 401, (path, status, body[:200]) + # The login route sends the browser to the identity provider's authorization endpoint with the client the module registers. + code, target = grafana_head("/login/generic_oauth") + assert code == "302" and "/api/oidc/authorization" in target and "client_id=swarm-grafana" in target, (code, target) + # Health is the one unauthenticated route, and says nothing but the version and the database. + status, body = grafana_request("/api/health") + assert status == 200 and json.loads(body)["database"] == "ok", (status, body) + # Anonymous access is off and a made-up bearer is no session. + status, _ = grafana_request("/api/search", "-H 'Authorization: Bearer glsa_made_up'") + assert status == 401, status + + with subtest("the stored administrator password is applied to the database written before the switch, and the default one is refused"): + status, body = grafana_request("/api/user", f"-u admin:{GRAFANA_ADMIN}") + assert status == 200 and json.loads(body)["login"] == "admin", (status, body[:200]) + for wrong in ("admin", "x" * 24): + status, body = grafana_request("/api/user", f"-u admin:{wrong}") + assert status == 401, (wrong, status, body[:200]) + # The annotation the old container's database held is there. + 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 dashboard reads the metrics store through the gateway with its own bearer, and its log datasource is provisioned"): + deadline = time.monotonic() + 300 + while True: + status, body = grafana_request( + "/api/datasources/proxy/uid/swarm-victoriametrics/api/v1/export", + f"-u admin:{GRAFANA_ADMIN}", + "-g --data-urlencode 'match[]=written_before_the_switch' -G", + ) + if status == 200 and "written_before_the_switch" in body: + break + if time.monotonic() >= deadline: + print(machine.execute(f"kubectl -n {NS} logs {grafana_pod} -c {GRAFANA} --tail=100 2>&1")[1]) + metrics_diagnostics(GRAFANA_BEARER) + raise AssertionError((status, body[:300])) + 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) + + GRAFANA_CONF = f"{STORE_AUTH_DIR}/grafana.conf" + GRAFANA_PASSWORD = f"{STORE_AUTH_DIR}/grafana.password" + + with subtest("Grafana's /metrics is refused without the listener credential past the gateway and answered with it, and the gateway puts the credential in place"): + machine.succeed("systemctl restart swarm-bao-store-auth.service") + store_credential_published() + machine.succeed("systemctl reload logs-gateway") + stored = as_root("bao kv get -mount=secret -field=value swarm/services/grafana/store-auth").strip() + assert len(stored) == 64, "the unit stores 64 hex digits" + for other in ("victoriametrics", "victorialogs"): + assert stored != as_root(f"bao kv get -mount=secret -field=value swarm/services/{other}/store-auth").strip() + assert machine.succeed(f"cat {GRAFANA_PASSWORD}").strip() == stored + secret = machine.succeed(f"kubectl -n {NS} get secret swarm-grafana-credentials -o jsonpath='{{.data.store-auth}}' | base64 -d").strip() + assert secret == stored + assert stored not in machine.succeed(f"cat {MANIFESTS}/{GRAFANA}.yaml"), "the manifest holds no credential" + # With no credential, and with a caller's bearer or the administrator's login, the pod answers 401. + for label, args in ( + ("no credential", ()), + ("a caller's bearer", (f"-H 'Authorization: Bearer {AGENT_TOKEN}'",)), + ("the administrator's login", (f"-u admin:{GRAFANA_ADMIN}",)), + ("a wrong password", (f"-u swarm-store:{'0' * 64}",)), + ): + status, body = grafana_request("/metrics", *args, gateway=False) + assert status == 401, (label, status, body[:200]) + status, body = grafana_request("/metrics", f'--user "swarm-store:$(cat {GRAFANA_PASSWORD})"', gateway=False) + assert status == 200 and "grafana_" in body, (status, body[:200]) + # Through the gateway the same request needs no credential of the caller's. + status, body = grafana_request("/metrics") + assert status == 200 and "grafana_" in body, (status, body[:200]) + # A gateway without the credential gets 401 from the pod. + saved = machine.succeed(f"cat {GRAFANA_CONF}") + assert "proxy_set_header Authorization" in saved + machine.succeed(f": > {GRAFANA_CONF} && systemctl reload logs-gateway") + machine.wait_until_succeeds("systemctl is-active logs-gateway", timeout=30) + for _ in range(10): + status, body = grafana_request("/metrics") + if status == 401: + break + time.sleep(1) + assert status == 401, (status, body[:200]) + machine.succeed("systemctl restart swarm-bao-store-auth.service") + store_credential_published() + machine.succeed("systemctl reload logs-gateway") + assert machine.succeed(f"cat {GRAFANA_CONF}") == saved + assert grafana_request("/metrics")[0] == 200 + # The health route and the health check of the kubelet stay open. + assert grafana_request("/api/health", gateway=False)[0] == 200 + + with subtest("the controller's Viewer token is in the store and reads the alert rules and nothing it must not write"): + read_token = f'BAO_TOKEN="$(jq -r .root_token {INIT})" bao kv get -mount=secret -field=value swarm/controller/swarm-controller/grafana/token 2>/dev/null' + token = machine.execute(read_token)[1].strip() + deadline = time.monotonic() + 180 + while not token: + if time.monotonic() >= deadline: + print(machine.execute(f"kubectl -n {NS} logs {grafana_pod} -c controller-token --tail=100 2>&1")[1]) + raise AssertionError("the sidecar stored no token") + time.sleep(3) + token = machine.execute(read_token)[1].strip() + status, body = grafana_request("/api/prometheus/grafana/api/v1/alerts", f"-H 'Authorization: Bearer {token}'") + assert status == 200, (status, body[:200]) + status, body = grafana_request("/api/user", f"-H 'Authorization: Bearer {token}'") + assert status == 200 and json.loads(body)["login"].startswith("sa-"), (status, body[:200]) + status, body = grafana_request( + "/api/annotations", + f"-H 'Authorization: Bearer {token}' -H 'Content-Type: application/json' -X POST -d '{{\"text\":\"a viewer writes\"}}'", + ) + assert status == 403, (status, body[:200]) + + with subtest("a deleted pod comes back with the annotation, the stored password and the same token"): + kube(machine, f"delete pod {grafana_pod} --wait=true", timeout=120) + grafana_pod = wait_pod_ready(GRAFANA, timeout=900) + grafana_ip = kube(machine, f"get pod {grafana_pod} -o jsonpath='{{.status.podIP}}'").strip() + deadline = time.monotonic() + 300 + while True: + status, body = grafana_request("/api/annotations?tags=legacy", f"-u admin:{GRAFANA_ADMIN}") + if status == 200 and "written before the switch" in body: + break + if time.monotonic() >= deadline: + print(machine.execute(f"kubectl -n {NS} logs {grafana_pod} --all-containers --tail=100 2>&1")[1]) + raise AssertionError((status, body[:300])) + time.sleep(3) + 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 + + 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") + machine.succeed(f"timeout 5 bash -c '