diff --git a/docs/2-handbook/agents/security.md b/docs/2-handbook/agents/security.md index b64258452..7022778a8 100644 --- a/docs/2-handbook/agents/security.md +++ b/docs/2-handbook/agents/security.md @@ -92,17 +92,12 @@ queue secret, at the queue and at both stores' read routes alike. The two store agent's `swarm/agents//observability` leaf, which only the controller writes, and let the agent through only with the `logs` or `metrics` permission it names. -### The log and metrics stores take writes and reads from the node +### The log and metrics stores check a credential of their own -VictoriaLogs and VictoriaMetrics check no credential: the gateway's vhost does. -Each store listens on its pod's address behind a ClusterIP Service, and the -Service's NetworkPolicy admits traffic from the node and from nothing else. A -process on the host that runs a store, whatever its user, can therefore read -every record in it and write records into it without a bearer. The metrics store -also serves its import and admin routes on that listener, so the same process -can delete series from it. An agent can't: its traffic doesn't come from the -node, and the hive's egress rules don't forward it to the pod network. Treat the -host that runs the stores as trusted for logs and metrics. +Each store asks every request for a credential of its own, beside the gateway's +per-agent checks, so a process on the host that goes around the gateway gets a 401. Root can read the credentials, so treat the host as trusted for what root +can do. The implementation notes say how the credential gets made and delivered: +[the stores' listener credential](../../4-implementation/k8s/runtime.md#the-stores-listener-credential). ### Per-hive credentials live under the hive kind diff --git a/docs/4-implementation/k8s/manifests.md b/docs/4-implementation/k8s/manifests.md index 8d041afbf..67f513c2e 100644 --- a/docs/4-implementation/k8s/manifests.md +++ b/docs/4-implementation/k8s/manifests.md @@ -42,7 +42,7 @@ A service gets manifests on the host whose configuration deploys it: The renderer reads the service's evaluated unit, not a copy of its settings: - **Environment:** the unit's `environment`, including what other modules - merge into it, minus `PATH`. A systemd `%d` becomes the credential + merge into it, minus `PATH`. A systemd `%d`, here and in `ExecStart`'s arguments, becomes the credential directory it stands for. On a host with a hive collector, the OTLP endpoint variables of a hive-tier service point at it ([Pod logs and metrics](telemetry.md)) instead; a swarm-tier producer, `swarm-ci-metrics`, keeps its own. The @@ -80,7 +80,8 @@ commit. The YAML lands in the world-readable nix store, so it holds no credential. It names the Secret `-credentials` and the credential ids as keys. It never names the host path the unit loads a credential from, and never its -contents. Nothing here creates the Secret. +contents. Nothing here creates the Secret: the unit `swarm-bao-store-auth` publishes +the stores' ([the log store](runtime.md#the-log-store)). A credential that holds a public CA file isn't a secret. `swarm-notify-router`'s `notify-router-bao-server-ca` and `swarm-ci-metrics`'s `bao-ca.pem` come from diff --git a/docs/4-implementation/k8s/runtime.md b/docs/4-implementation/k8s/runtime.md index d0227ef45..c37653fbe 100644 --- a/docs/4-implementation/k8s/runtime.md +++ b/docs/4-implementation/k8s/runtime.md @@ -320,14 +320,41 @@ writes to the store and Grafana that reads it. - **The store's pod.** The first service rendered without a unit of the module's own: the module defines the daemon's `ExecStart`, with its flags - (`-storageDataPath`, `-httpListenAddr`, `-retentionPeriod`) as a list, and its - `StateDirectory`, and the renderer reads the pod from those. The image holds + (`-storageDataPath`, `-httpListenAddr`, `-retentionPeriod`, `-httpAuth.username` and + `-httpAuth.password`) as a list, and its `StateDirectory` and `LoadCredential`, + and the renderer reads the pod from those. The image holds the nixpkgs build of `victoria-logs` and nothing else. The pod serves plain HTTP on port 9428, probed on `/health`, logs in to nothing and pushes no telemetry: its output is the pod's log, which the host collector reads like any pod's ([logs](telemetry.md#logs)), and the collector scrapes the store's own metrics through the gateway. Its Deployment has one replica and the `Recreate` strategy, and the removed container stops before the pod can start. +- **The store's credential.** Every route of the store's listener asks for HTTP + Basic credentials, `-httpAuth.password=file://` the credential `store-auth` of + the pod's Secret `swarm-victorialogs-credentials`. The built-in routes that + answer a fixed text (`/health`, `/ping`, `/-/healthy`, `/-/ready`, + `/robots.txt`) stay open, and the kubelet's probes use `/health`: the other + routes, the insert, select, delete and admin ones and `/metrics`, answer 401 + without it. The module sets none of the store's `-*AuthKey` flags: each of those + routes falls back to the Basic credentials when its key is empty. The unit + `swarm-bao-store-auth` ([`store-credentials.nix`](../../../nix/host-modules/k8s/store-credentials.nix)) + creates the password in the swarm secret store at + `swarm/services/victorialogs/store-auth` when the store holds none, as the host's + `swarm-store-auth` principal, whose one grant is create and read on this leaf + and the metrics store's. It writes the `Authorization` header to + `/var/lib/swarm-store-auth/victorialogs.conf` (`root:root`, `0600`, in a root-only directory; + nginx's main process reads its configuration as root, so the file needs no + other reader, and it's never in the nix store), which the vhost's store + locations `include`, then reloads nginx, and publishes the password as the + Secret the way the host publishes the CA ConfigMap. The files stay on disk, as the cluster keeps the Secret on disk, so a reboot with + the secret store still sealed leaves the gateway sending the credential the pod + expects. Nothing rotates the value + by itself: to rotate it, delete the leaf's metadata with a token that may and + restart the unit, which stores a new password, rewrites the file, reloads + nginx and updates the Secret; the store re-reads the file within seconds. A pod waits in `ContainerCreating` + until the Secret exists, and the store re-reads the file every two seconds. A + gateway whose file is still empty sends the caller's own `Authorization`, which + the store refuses. The responders' locations never include the file. - **State.** The store's data directory is the container's own on the host, `/var/lib/nixos-containers/swarm-victorialogs/var/lib/victorialogs`: the claim `swarm-victorialogs-store` binds a static local volume on it, so an upgrade @@ -370,9 +397,9 @@ writes to the store and Grafana that reads it. - **Who reaches what.** Both pods have a NetworkPolicy that selects them for ingress and allows none, so only the node's own traffic reaches them: the host's nginx, which dials the Services, and the kubelet's probes. The policy - refuses a pod of the cluster. The store takes writes and reads with no credential, so a - process on the host can read and write it: see - [Agent security](../../2-handbook/agents/security.md). The responders' policy + refuses a pod of the cluster. The log store asks for its credential on every route, so a + process on the host that dials the Service gets 401: see + [the stores' listener credential](#the-stores-listener-credential). The responders' policy also lets the pod reach cluster DNS and the store's pod listener on the bridge's address (`egress = [ "store" ]`), the one host port the pod needs until the store moves into the cluster. @@ -391,14 +418,24 @@ shape of [the log store](#the-log-store). The gateway's vhost pushes to the store and Grafana that reads it. - **The store's pod.** The module defines the daemon's `ExecStart`, with its flags - (`-storageDataPath`, `-httpListenAddr`, `-retentionPeriod`) as a list, and its - `StateDirectory`, and the renderer reads the pod from those. The image holds + (`-storageDataPath`, `-httpListenAddr`, `-retentionPeriod`, `-httpAuth.username` and + `-httpAuth.password`) as a list, and its `StateDirectory` and `LoadCredential`, + and the renderer reads the pod from those. The image holds the nixpkgs build of `victoria-metrics` and nothing else. The pod serves plain HTTP on port 8428, logs in to nothing and pushes no telemetry: its output is the pod's log, which the host collector reads like any pod's ([logs](telemetry.md#logs)), and the collector scrapes the store's own metrics through the gateway. Its Deployment has one replica and the `Recreate` strategy. +- **The store's credential.** As the log store's ([above](#the-log-store)): + `-httpAuth.password=file://` the credential `store-auth` of the Secret + `swarm-victoriametrics-credentials`, created and published by the same unit at + `swarm/services/victoriametrics/store-auth`, and sent by the vhost from + `/var/lib/swarm-store-auth/victoriametrics.conf`. Every route answers 401 without + it but `/health` and the built-in routes that answer a fixed text, the import, + snapshot, delete and `-*AuthKey` admin routes and `/metrics` included, and the module sets no + `-*AuthKey` flag: each falls back to the Basic credentials when its key + is empty. - **Probes.** The store opens its storage before it serves HTTP, so it answers nothing while a large store opens. The pod's startup probe requests `/health` every ten seconds for up to ten minutes, and the liveness and readiness probes @@ -450,8 +487,8 @@ pushes to the store and Grafana that reads it. - **Who reaches what.** Both pods have a NetworkPolicy that selects them for ingress and allows none, so only the node's own traffic reaches them: the host's nginx, which dials the Services, and the kubelet's probes. The store - takes writes, deletes and reads with no credential, so a process on the host - can use all three: see [Agent security](../../2-handbook/agents/security.md). + asks for its credential on every route, so a process on the host that dials the + Service gets 401: see [the stores' listener credential](#the-stores-listener-credential). The responders' policy also lets the pod reach cluster DNS and the secret store's pod listener (`egress = [ "store" ]`). - **The host's part.** The host keeps the vhost, `gateway.localNames` and the @@ -459,6 +496,25 @@ 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 stores' listener credential + +Each store listens on its pod's address behind a ClusterIP Service, and the +Service's NetworkPolicy admits traffic from the node and from nothing else. An +agent can't reach the pod: its traffic doesn't come from the node, and the +hive's egress rules don't forward it to the pod network. + +VictoriaLogs and VictoriaMetrics each check a credential of their own on every +route, beside the gateway's vhost, which checks the caller's bearer. They run +with `-httpAuth.username` and `-httpAuth.password`. Each password is a random +value that `swarm-bao-store-auth` creates in the swarm secret store, hands to +the gateway's nginx and publishes to the cluster as a Secret the pod loads. +After its own check passes, the vhost replaces the caller's `Authorization` +with that credential, so the caller's bearer never reaches the store. A process +on the host that reaches a store without going through the vhost gets 401 from +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. + ## Resources and sandbox The pod takes the unit's `MemoryMax` and `CPUQuota` as its container's limits @@ -583,7 +639,9 @@ agent's bearer, refuses an agent without the grant and a wrong secret, and checks Grafana's bearer with the second responder; that the store keeps a record posted to the ingest route and both records across a pod delete; and that the policy refuses a peer pod the Services while it admits the node and the -kubelet. The `swarm-logs` +kubelet. From the node itself, not through the gateway, the store answers 401 to +an insert, a select and a delete without the credential and 200 with it, and +`/health` answers without; a gateway whose include file is empty gets 401. The `swarm-logs` CLI itself isn't run: it needs an agent's store certificate, so the test presents the `Authorization` header it sends. diff --git a/docs/4-implementation/swarm/credentials-reference.md b/docs/4-implementation/swarm/credentials-reference.md index d3fccbb42..36fc9c932 100644 --- a/docs/4-implementation/swarm/credentials-reference.md +++ b/docs/4-implementation/swarm/credentials-reference.md @@ -42,6 +42,8 @@ the rest of the cell says how. | `ssh-agents/sign/swarm-agent` (a signing call, nothing is stored) | the store's SSH CA mount (`ssh-agents`), when the agent's `hive-agent-ssh-cert` unit asks it to sign, which the operator's per-agent `ssh` switch allows the public key the unit generated in its own `/run`; the CA key is generated inside the store by `swarm-bao-agent-ssh-policy` | the agent, which keeps the key and the signed certificate in `/run` only; a target machine trusts the CA's public key by value | ✅ the certificate lasts 60 minutes; the CA is never replaced, and a target that holds a different CA key refuses every certificate | ✅ the agent signs again every 20 minutes | | `swarm/hives//squid-selfcheck` | `swarm-controller`, in the same pass as the agents' credentials | the hive: `hive-c0re` and `squid-selfcheck-credential` (root) | ❌ never replaced: written only while the path holds nothing | ✅ `hive-c0re` every 30 seconds, the root unit every 10 minutes | | `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/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 | @@ -127,6 +129,8 @@ pieces fit, and the reasoning behind them, is in [`credentials.md`](../../2-hand | OIDC client secret, plaintext half | `authelia crypto hash generate --random` | the swarm secret store, at the path its reader fetches: `swarm/hives//oidc/client`, `swarm/controller/swarm-controller/oidc/client` or `swarm/services//oidc/client`. The bridge reads its own into `/run/swarm-authelia-bridge/client-secret` before each start. A container with no secret publisher identity keeps it in `/var/lib/authelia-swarm/oidc-clients/.secret`; a file an earlier release left seeds the store once when it holds no value, and stays unused | nothing to place: readers fetch it from the store ([how](../../2-handbook/swarm/credentials.md#hive-level-secrets)) | | OIDC client secret, digest half | the same mint | `oidc-clients/.digest` | authelia's own half; merged at runtime via `settingsFiles` | | 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, `0600`, in a directory of `0700`): the `Authorization` header the vhost's store locations send, and `/var/lib/swarm-store-auth/victorialogs.password` (the same), 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, `0600`, in a directory of `0700`): the `Authorization` header the vhost's store locations send, and `/var/lib/swarm-store-auth/victoriametrics.password` (the same), 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 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 | @@ -198,6 +202,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` and `swarm/services/victoriametrics/store-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 d51651196..dd99a9b41 100644 --- a/docs/4-implementation/swarm/telemetry.md +++ b/docs/4-implementation/swarm/telemetry.md @@ -105,8 +105,9 @@ 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 authenticates nothing -itself; the `metrics.` vhost does it: +that admits 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 @@ -186,11 +187,12 @@ swarm. | `swarm.victorialogs.domain` | Only to rename it. | It runs as a pod in the host's cluster ([the log store](../k8s/runtime.md#the-log-store)) -and binds no host port. Its Service takes no credential of its own, so a -NetworkPolicy lets only the host's own traffic reach it. The gateway vhost, which -dials the Service by name, is the only way in for a hive, an agent or a -browser, and the collector is the only intended writer. A process on this host -can also reach the Service; see [Agent security](../../2-handbook/agents/security.md). +and binds no host port. A NetworkPolicy lets only the host's own traffic reach its +Service, and the store asks every request for a credential of its own +([the stores' listener credential](../k8s/runtime.md#the-stores-listener-credential)). +The gateway vhost, which dials the Service by name and supplies that credential +after its own checks, is the way in for a hive, an agent or a browser, and the +collector is the only intended writer. **Who may query.** `/select/logsql/` takes one of three credentials. An agent presents its `swarm-agent..` bearer, checked by diff --git a/docs/examples/semi-spread/swarm-services.nix b/docs/examples/semi-spread/swarm-services.nix index 45e25513d..a73024002 100644 --- a/docs/examples/semi-spread/swarm-services.nix +++ b/docs/examples/semi-spread/swarm-services.nix @@ -52,6 +52,7 @@ in (pair "stt" "stt") (pair "claudeLogin" "claude-login") (pair "ciMetrics" "ci-metrics") + (pair "storeAuth" "store-auth") ]; deploy.matrix = { ctlBaoClientCertFile = "${pki}/matrix-ctl.pem"; diff --git a/nix/host-modules/glue-bao-readers-policy-order.nix b/nix/host-modules/glue-bao-readers-policy-order.nix index 3b985257c..06e27d3e4 100644 --- a/nix/host-modules/glue-bao-readers-policy-order.nix +++ b/nix/host-modules/glue-bao-readers-policy-order.nix @@ -44,6 +44,12 @@ let swarm-bao-nats-tls = deployCfg.nats.enable; # ./swarm-ci-runner.nix swarm-bao-ci-runner = deployCfg.ci-runner.enable; + # ./k8s/store-credentials.nix + swarm-bao-store-auth = + (deployCfg.victorialogs.enable || deployCfg.victoriametrics.enable) + && deployCfg.k8s.enable + && hyperhiveCfg.k8s.enable + && havePair baoDeploy.storeAuthClientCertFile baoDeploy.storeAuthClientKeyFile; }; # Readers that log in under another unit's principal: reader unit → the diff --git a/nix/host-modules/glue-bao-tls.nix b/nix/host-modules/glue-bao-tls.nix index f9aec2f72..20a5dad9d 100644 --- a/nix/host-modules/glue-bao-tls.nix +++ b/nix/host-modules/glue-bao-tls.nix @@ -130,6 +130,8 @@ in atticClientKeyFile = lib.mkDefault "${pkiDir}/attic-key.pem"; archiveClientCertFile = lib.mkDefault "${pkiDir}/archive.pem"; archiveClientKeyFile = lib.mkDefault "${pkiDir}/archive-key.pem"; + storeAuthClientCertFile = lib.mkDefault "${pkiDir}/store-auth.pem"; + storeAuthClientKeyFile = lib.mkDefault "${pkiDir}/store-auth-key.pem"; forgePublisherClientCertFile = lib.mkDefault "${pkiDir}/forge-publisher.pem"; forgePublisherClientKeyFile = lib.mkDefault "${pkiDir}/forge-publisher-key.pem"; servicesIssuerClientCertFile = lib.mkDefault "${pkiDir}/services-issuer.pem"; @@ -358,6 +360,13 @@ in [ -s ${pkiDir}/archive.pem ] || ${signLeaf} ${pkiDir} archive \ ${lib.escapeShellArg deployCfg.bao.archiveCommonName} "" clientAuth + # The unit that publishes the log store's and the metrics store's listener + # credentials. Minted here for the matrix-ctl leaf's reason: each store is a + # swarm singleton, so on a store host without the secret store this is the + # file an operator copies. + [ -s ${pkiDir}/store-auth.pem ] || ${signLeaf} ${pkiDir} store-auth \ + ${lib.escapeShellArg deployCfg.bao.storeAuthCommonName} "" clientAuth + # The forge's token publisher. Minted here for the matrix-ctl leaf's # reason: the forge is a swarm singleton, so on a forge host without the # store this is the file an operator copies. diff --git a/nix/host-modules/k8s/default.nix b/nix/host-modules/k8s/default.nix index 9a68bfd74..d85b30406 100644 --- a/nix/host-modules/k8s/default.nix +++ b/nix/host-modules/k8s/default.nix @@ -27,6 +27,7 @@ in ./node.nix ./pod-logs.nix ./runtime.nix + ./store-credentials.nix ]; options.services.hyperhive.k8s = { diff --git a/nix/host-modules/k8s/render.nix b/nix/host-modules/k8s/render.nix index 6ebfcfda3..8a64ca978 100644 --- a/nix/host-modules/k8s/render.nix +++ b/nix/host-modules/k8s/render.nix @@ -718,7 +718,11 @@ let ); }; - execWords = splitExec name (toString sc.ExecStart); + # A systemd `%d` in an argument is the credential directory, as in the + # environment. + execWords = map (builtins.replaceStrings [ "%d" ] [ credDir ]) ( + splitExec name (toString sc.ExecStart) + ); entrypoint = "${svc.package}/bin/${daemon}"; # The credentials that are public CA files come from the CA ConfigMap, the diff --git a/nix/host-modules/k8s/store-credentials.nix b/nix/host-modules/k8s/store-credentials.nix new file mode 100644 index 000000000..1b1cf69cd --- /dev/null +++ b/nix/host-modules/k8s/store-credentials.nix @@ -0,0 +1,180 @@ +# The listener credential of the Victoria stores the cluster runs: the unit that +# creates it in the swarm secret store when the store holds none, hands it to +# the gateway's nginx and publishes it to the cluster as the Secret the store's +# pod loads its password from. The store's flags and the locations that send it +# are in ../swarm-victorialogs.nix and ../swarm-victoriametrics.nix; ../lib/store-auth.nix names what they +# share. docs/4-implementation/k8s/runtime.md has the design. +{ + pkgs, + lib, + config, + ... +}: +let + hyperhiveCfg = config.services.hyperhive; + deployCfg = hyperhiveCfg.deploy; + k8sCfg = hyperhiveCfg.k8s; + node = deployCfg.k8s; + baoCfg = hyperhiveCfg.swarm.bao; + baoDeploy = deployCfg.bao; + + storeAuth = import ../lib/store-auth.nix; + storeRetry = import ../lib/store-retry.nix { }; + + # The stores this host runs, by the name `store-auth.nix` takes. + stores = + lib.optional deployCfg.victorialogs.enable "victorialogs" + ++ lib.optional deployCfg.victoriametrics.enable "victoriametrics"; + + haveIdentity = + baoDeploy.storeAuthClientCertFile != null && baoDeploy.storeAuthClientKeyFile != null; + + # Where the store runs on this host, the first login waits for its container. + # No `wants`: a pull would start the container mid-switch on the old closure. + storeContainer = lib.optional baoDeploy.enable "container@${baoCfg.machine}.service"; + + kubeconfig = "/etc/rancher/k3s/k3s.yaml"; + + publish = store: '' + publish ${ + lib.escapeShellArgs [ + store + "secret/${storeAuth.leaf store}" + (storeAuth.passwordFile store) + (storeAuth.nginxFile store) + (storeAuth.secretName store) + ] + } + ''; +in +{ + config = lib.mkIf (stores != [ ]) ( + lib.mkMerge [ + { + # The files exist before nginx first reads its configuration, because + # an `include` of a missing file is a fatal error there. `f` creates + # a file and never overwrites one, and an empty file sets no header: + # the store then refuses the request, which is the only thing a + # gateway without the credential can get from it. + systemd.tmpfiles.rules = [ + "d ${storeAuth.dir} 0700 root root - -" + ] + ++ map (store: "f ${storeAuth.nginxFile store} 0600 root root -") stores; + } + + (lib.mkIf (node.enable && k8sCfg.enable) { + assertions = [ + { + assertion = haveIdentity; + message = '' + The ${lib.concatStringsSep " and " stores} the cluster runs takes a credential, which a unit + creates in the swarm secret store and publishes under the identity + services.hyperhive.deploy.bao.storeAuthClientCertFile and + storeAuthClientKeyFile name (the leaf the store mints where + services.hyperhive.deploy.bao.enable is set on this host). + ''; + } + ]; + + systemd.services.swarm-bao-store-auth = lib.mkIf haveIdentity { + description = "create the Victoria stores' listener credential in the swarm secret store if absent, and publish it"; + wantedBy = [ "multi-user.target" ]; + wants = [ "network-online.target" ]; + after = [ + "k3s.service" + "network-online.target" + ] + ++ storeContainer; + path = [ + baoDeploy.package + pkgs.coreutils + pkgs.gnugrep + pkgs.kubectl + pkgs.openssl + pkgs.systemd + ]; + # ./lib/store-retry.nix: the login fails for as long as the store is + # sealed or down. + inherit (storeRetry) startLimitBurst startLimitIntervalSec; + serviceConfig = storeRetry.serviceConfig // { + Type = "oneshot"; + RemainAfterExit = true; + UMask = "0077"; + SyslogIdentifier = "swarm-bao-store-auth"; + TimeoutStartSec = "15min"; + }; + environment = { + BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; + BAO_CLIENT_CERT = baoDeploy.storeAuthClientCertFile; + BAO_CLIENT_KEY = baoDeploy.storeAuthClientKeyFile; + KUBECONFIG = kubeconfig; + } + // lib.optionalAttrs (baoDeploy.serverCaFile != null) { + BAO_CACERT = baoDeploy.serverCaFile; + }; + script = '' + set -euo pipefail + ${import ../lib/store-seeded-secret.nix { }} + ${import ../lib/atomic-write-secret.nix { }} + ${import ../lib/refresh-consumer.nix { }} + + install -d -m 0700 ${storeAuth.dir} + + # A password of 64 hex digits, as Grafana's bearer is. + mint_password() { + openssl rand -hex 32 + } + + # . The store's + # value wins and a leaf that holds none is created, so the first + # password stored is the one every later run reads. The nginx file + # is written first: it is what the gateway needs before the store + # answers anyone, and it needs nothing of the cluster. + reload=0 + publish() { + local store="$1" leaf="$2" password_file="$3" nginx_file="$4" secret="$5" + local password directive + password="$(store_seeded "$leaf" /nonexistent mint_password)" || return 1 + directive="proxy_set_header Authorization \"Basic $(printf '%s:%s' ${lib.escapeShellArg storeAuth.user} "$password" | base64 -w0)\";" + + if secret_differs "$nginx_file" "$directive"; then + atomic_write_secret 0600 root:root "$nginx_file" "$directive" + reload=1 + elif written_after_start nginx.service "$nginx_file"; then + reload=1 + fi + if secret_differs "$password_file" "$password"; then + atomic_write_secret 0600 root:root "$password_file" "$password" + fi + echo "the credential of $store is at $nginx_file and $password_file; the Secret $secret follows." + } + + 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 + exit 1 + fi + ${lib.concatMapStrings publish stores} + + # A running nginx reads its files at a reload; one that is not + # running reads them as it starts. + if [ "$reload" = 1 ] && systemctl is-active --quiet nginx.service; then + systemctl reload nginx.service + fi + + # A pod that loads the Secret waits in ContainerCreating until this + # has run. + timeout 600 ${pkgs.bash}/bin/bash -c ${lib.escapeShellArg "until kubectl get namespace ${k8sCfg.namespace} >/dev/null 2>&1; do sleep 2; done"} + ${lib.concatMapStrings (store: '' + kubectl --namespace ${k8sCfg.namespace} create secret generic ${storeAuth.secretName store} \ + --from-file=${storeAuth.credentialId}=${storeAuth.passwordFile store} \ + --dry-run=client --output=yaml \ + | kubectl --namespace ${k8sCfg.namespace} apply --server-side --force-conflicts --filename=- + '') stores} + ''; + }; + }) + ] + ); +} diff --git a/nix/host-modules/lib/store-auth.nix b/nix/host-modules/lib/store-auth.nix new file mode 100644 index 000000000..77d3831c9 --- /dev/null +++ b/nix/host-modules/lib/store-auth.nix @@ -0,0 +1,31 @@ +# What the Victoria stores' listener credential 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. +# +# The credential is the HTTP Basic login every route of the store's listener +# asks for (`-httpAuth.username` and `-httpAuth.password`). The password is a +# 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. +rec { + # The Basic login's user name, the same for every store. + user = "swarm-store"; + + # The credential id the store's unit loads and the key of the Secret that + # holds the password. + credentialId = "store-auth"; + + # Under KV v2's `secret/` mount, as `bao kv` takes it. `store` is + # `victorialogs` or `victoriametrics`. + leaf = store: "swarm/services/${store}/store-auth"; + + # On the host, a directory only root reads: the password the Secret is made from, + # and the nginx file the gateway's locations include. + dir = "/var/lib/swarm-store-auth"; + passwordFile = store: "${dir}/${store}.password"; + nginxFile = store: "${dir}/${store}.conf"; + + # The Secret the store's pod loads its credentials from + # (../k8s/render.nix names it `-credentials`). + secretName = store: "swarm-${store}-credentials"; +} diff --git a/nix/host-modules/swarm-bao-agent-pki.nix b/nix/host-modules/swarm-bao-agent-pki.nix index c9e393d35..4eb4698dd 100644 --- a/nix/host-modules/swarm-bao-agent-pki.nix +++ b/nix/host-modules/swarm-bao-agent-pki.nix @@ -151,6 +151,7 @@ in "swarm-bao-ci-runner-policy.service" "swarm-bao-logs-auth-policy.service" "swarm-bao-metrics-auth-policy.service" + "swarm-bao-store-auth-policy.service" "swarm-bao-forge-publisher-policy.service" ] ++ granterAfter; diff --git a/nix/host-modules/swarm-bao-readers.nix b/nix/host-modules/swarm-bao-readers.nix index a81f93904..1d1b416ea 100644 --- a/nix/host-modules/swarm-bao-readers.nix +++ b/nix/host-modules/swarm-bao-readers.nix @@ -20,6 +20,8 @@ let k8sNode = deployCfg.k8s; podAuth = import ./lib/bao-pod-auth.nix; + storeAuth = import ./lib/store-auth.nix; + shared = import ./lib/swarm-bao-shared.nix { inherit config lib pkgs; }; inherit (shared) atticFactLeaves @@ -360,6 +362,24 @@ let } ]; + # The unit that publishes the stores' 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, a leaf each. + storeAuthWriters = [ + { + name = "swarm-store-auth"; + cn = baoDeploy.storeAuthCommonName; + policyText = + lib.concatMapStrings (store: createReadStanza "${credentialMountPath}/data/${storeAuth.leaf store}") + [ + "victorialogs" + "victoriametrics" + ]; + } + ]; + # The role name IS the policy name, as for the three service principals # above: the role attaches the policy by spelling it identically, and one # string for both objects removes the way they drift apart. @@ -511,6 +531,8 @@ in systemd.services.swarm-bao-forge-publisher-policy = readerPolicyUnit "write the forge's controller-token-publisher bao policy and cert-auth role" forgePublisherWriters; + systemd.services.swarm-bao-store-auth-policy = readerPolicyUnit "write the Victoria stores' credential publisher's bao policy and cert-auth role" storeAuthWriters; + # The pods' login: the `jwt` auth mount's config and one role per # in-cluster service. The mount exists once `swarm-bao-granter-role` has # run with a bootstrap token that carries `sys/auth/jwt-k8s`; diff --git a/nix/host-modules/swarm-bao.nix b/nix/host-modules/swarm-bao.nix index 8016c5343..3e9a7930a 100644 --- a/nix/host-modules/swarm-bao.nix +++ b/nix/host-modules/swarm-bao.nix @@ -2046,6 +2046,20 @@ in ''; }; + storeAuthCommonName = lib.mkOption { + type = lib.types.str; + 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 and the metrics store's + listener credentials presents from the host (./k8s/store-credentials.nix). + Its grant is create and read on `swarm/services/victorialogs/store-auth` + and `swarm/services/victoriametrics/store-auth`, and nothing else. + + ⚠️ Reserved as a hive name by ./swarm.nix, like its siblings. + ''; + }; + atticCommonName = lib.mkOption { type = lib.types.str; default = "swarm-attic"; @@ -2195,6 +2209,32 @@ in ''; }; + storeAuthClientCertFile = lib.mkOption { + type = lib.types.nullOr lib.types.str; + default = null; + example = "/var/lib/swarm-bao-pki/store-auth.pem"; + description = '' + Certificate the host presents to the store to create and read the log + store's and the metrics store's listener credentials. Its + subject must be {option}`services.hyperhive.deploy.bao.storeAuthCommonName`. + + ./glue-bao-tls.nix points it at the leaf it mints on the store's host. + On a host that runs either store without the secret store, it is a file + the operator copies from the store's host. A path, never a value. + ''; + }; + + storeAuthClientKeyFile = lib.mkOption { + type = lib.types.nullOr lib.types.str; + default = null; + example = "/var/lib/swarm-bao-pki/store-auth-key.pem"; + description = '' + Private key for + {option}`services.hyperhive.deploy.bao.storeAuthClientCertFile`. + A path, never a value. + ''; + }; + forgePublisherClientCertFile = lib.mkOption { type = lib.types.nullOr lib.types.str; default = null; diff --git a/nix/host-modules/swarm-victorialogs.nix b/nix/host-modules/swarm-victorialogs.nix index 2651fe28a..2d38db6e8 100644 --- a/nix/host-modules/swarm-victorialogs.nix +++ b/nix/host-modules/swarm-victorialogs.nix @@ -16,11 +16,11 @@ # reaches this at `https://${cfg.domain}/` gated by the same `auth_request` # check against authelia that swarm-ui's own vhost uses (`swarmAuthRequest` # below; `swarm-ui.nix` says why forceSSL is load-bearing: authelia answers a -# plain-http auth subrequest with 400). The store's own listener is unauthenticated and takes -# writes as well as reads. Its Service admits only the node's own traffic, and -# the vhost, which dials it by name, is the ONLY way in: the collector pushes -# through it too, at its own `= /insert/...` location, because the collector -# need not share a host with the store. +# plain-http auth subrequest with 400). The store's own listener asks every +# request for the credential in ./lib/store-auth.nix: each location below that +# dials it replaces the caller's `Authorization` with it once its own check has +# passed. The collector pushes through the vhost too, at its own +# `= /insert/...` location, because it need not share a host with the store. # ⚠️ That ingest location deliberately does not carry `swarmAuthRequest` — a # pusher handed its `error_page 401 =302` follows the redirect and POSTs at a # login page, which answers 200. See the location itself. @@ -42,6 +42,7 @@ let gatewayCfg = hyperhiveCfg.gateway; k8sCfg = hyperhiveCfg.k8s; inherit (import ../images { inherit pkgs lib; }) mkServiceImage; + storeAuth = import ./lib/store-auth.nix; # Copy of `swarm-ui.nix`'s own `swarmAuthRequest` — not shared code because # this vhost needs exactly the two locations that reference it (`/` and the @@ -125,6 +126,13 @@ let ''; storeVariable = "$swarm_logs_store_upstream"; upstream = "http://${storeVariable}"; + # The store's locations dial it with the store's credential in place of the + # caller's `Authorization`. The file is empty until the unit that mints the + # credential has run (./k8s/store-credentials.nix), and the + # store then refuses the request. The responders' locations never include it. + viaStore = + viaService storeVariable storeService storePort + + "include ${storeAuth.nginxFile "victorialogs"};\n"; agentAuthVariable = "$swarm_logs_agent_auth_upstream"; grafanaAuthVariable = "$swarm_logs_grafana_auth_upstream"; @@ -137,7 +145,12 @@ let "-storageDataPath=${dataDir}" "-httpListenAddr=:${toString storePort}" "-retentionPeriod=${deployCfg.victorialogs.retentionPeriod}" + # Every route but `/health` and the few built-in ones that answer a + # fixed text asks for it (docs/4-implementation/k8s/runtime.md). + "-httpAuth.username=${storeAuth.user}" + "-httpAuth.password=file://%d/${storeAuth.credentialId}" ]; + LoadCredential = [ storeAuth.credentialId ]; StateDirectory = "victorialogs"; }; environment = { }; @@ -512,8 +525,7 @@ in services.hyperhive.gateway.dns.enable = lib.mkDefault true; # Authenticated front door onto the store's Service — see the file-top - # comment for why the store's own unauthenticated listener is reached - # through this vhost alone. + # comment for the credential each location sends the store. # `forceSSL`: same asymmetry `swarm-ui.nix` documents — # authelia answers a plain-http auth subrequest with 400, which # `auth_request` cannot read as anything but a broken check, so this @@ -524,7 +536,7 @@ in locations = { "/" = { proxyPass = upstream; - extraConfig = viaService storeVariable storeService storePort + swarmAuthRequest; + extraConfig = viaStore + swarmAuthRequest; }; # The swarm collector's ingest route. `=` so it outranks the `/` @@ -544,7 +556,7 @@ in "= /insert/opentelemetry/v1/logs" = { proxyPass = upstream; extraConfig = '' - ${viaService storeVariable storeService storePort} + ${viaStore} auth_request /__swarm_logs_ingest_authz; ''; }; @@ -579,7 +591,7 @@ in # the store as the caller sent them. proxyPass = upstream; extraConfig = '' - ${viaService storeVariable storeService storePort} + ${viaStore} auth_request /__swarm_logs_auth; ''; }; @@ -597,7 +609,7 @@ in "= /metrics" = { proxyPass = upstream; extraConfig = '' - ${viaService storeVariable storeService storePort} + ${viaStore} auth_request /__hive_authelia; ''; }; @@ -710,8 +722,7 @@ in # nonsense-path control, because a probe where every arm returns the same # code is not evidence. # - # ⚠️ Like the metrics store's, that endpoint is unauthenticated — which is - # why the Service's policy admits only the node and why nothing reaches it - # except through the gateway, where the ingest route is authenticated. (This - # module declares a vhost.) + # ⚠️ The endpoint asks for the store's credential like every other route: the + # ingest location replaces the caller's `Authorization` with it once the + # collector's own check has passed. } diff --git a/nix/host-modules/swarm-victoriametrics.nix b/nix/host-modules/swarm-victoriametrics.nix index 70c6a5a97..141474ba3 100644 --- a/nix/host-modules/swarm-victoriametrics.nix +++ b/nix/host-modules/swarm-victoriametrics.nix @@ -11,10 +11,12 @@ # It is the collector that feeds this (the gateway OTEL collector), not the # agents directly: one ingest point per swarm, authenticated there. # -# The store's own listener authenticates nothing and takes writes and admin -# calls beside its queries. Its Service admits only the node's own traffic, and -# the vhost below, which dials it by name, is the way in for everything the -# swarm does. +# The store's own listener takes writes and admin calls beside its queries, and +# asks every request for the credential in ./lib/store-auth.nix: each location +# below that dials it replaces the caller's `Authorization` with that credential +# once its own check has passed, so a caller's bearer never reaches the store. +# Its Service admits only the node's own traffic, and the vhost below, which +# dials it by name, is the way in for everything the swarm does. { pkgs, lib, @@ -30,6 +32,7 @@ let k8sCfg = hyperhiveCfg.k8s; baoCfg = hyperhiveCfg.swarm.bao; inherit (import ../images { inherit pkgs lib; }) mkServiceImage; + storeAuth = import ./lib/store-auth.nix; # The workloads, as the cluster names them: the store, and the one pod that # holds both responders. Each has a Service of its name, which the gateway @@ -61,7 +64,13 @@ let storeVariable = "$swarm_metrics_store_upstream"; agentAuthVariable = "$swarm_metrics_agent_auth_upstream"; grafanaAuthVariable = "$swarm_metrics_grafana_auth_upstream"; - viaStore = viaService storeVariable storeService storePort; + # The store's locations dial it with the store's credential in place of the + # caller's `Authorization`. The file is empty until the unit that mints the + # credential has run (./k8s/store-credentials.nix), and the store then refuses + # the request. The responders' locations never include it. + viaStore = + viaService storeVariable storeService storePort + + "include ${storeAuth.nginxFile "victoriametrics"};\n"; # The store's read API, which the vhost forwards to a caller holding # Grafana's bearer, an agent's own bearer, or an operator's session. @@ -177,7 +186,12 @@ let "-storageDataPath=${dataDir}" "-httpListenAddr=:${toString storePort}" "-retentionPeriod=${deployCfg.victoriametrics.retentionPeriod}" + # Every route but `/health` and the few built-in ones that answer a + # fixed text asks for it (docs/4-implementation/k8s/runtime.md). + "-httpAuth.username=${storeAuth.user}" + "-httpAuth.password=file://%d/${storeAuth.credentialId}" ]; + LoadCredential = [ storeAuth.credentialId ]; StateDirectory = "victoriametrics"; }; environment = { }; @@ -581,7 +595,7 @@ in # Nothing reaches the store unless a location here names it. The # store serves writes and admin calls (`/api/v1/import`, # `/api/v1/admin/tsdb/delete_series`, ...) on the same listener as - # its queries, and authenticates none of them. + # its queries, and asks for its credential on all of them. "/".return = "403"; # The swarm UI's quick link opens the bare domain. The store's own @@ -721,9 +735,9 @@ in # 400, so that 200 means the route exists). The `-opentelemetry.*` flags # only tune naming and limits. # - # ⚠️ That endpoint is unauthenticated, which is why the Service admits only - # the node: the only route to it is the vhost's ingest location, which - # authenticates. The collector is still the only writer, but it arrives by the - # swarm name rather than over loopback, because it need not share a host with - # this store. + # ⚠️ That endpoint asks for the store's credential like every other route: the + # vhost's ingest location authenticates the collector and then replaces its + # `Authorization` with it. The collector is still the only writer, but it + # arrives by the swarm name rather than over loopback, because it need not + # share a host with this store. } diff --git a/nix/host-modules/swarm.nix b/nix/host-modules/swarm.nix index 56a3d3b97..424bcd329 100644 --- a/nix/host-modules/swarm.nix +++ b/nix/host-modules/swarm.nix @@ -85,6 +85,7 @@ let deployCfg.bao.claudeLoginCommonName deployCfg.bao.notifyRouterCommonName deployCfg.bao.sttCommonName + deployCfg.bao.storeAuthCommonName deployCfg.bao.atticCommonName deployCfg.bao.archiveCommonName deployCfg.bao.forgePublisherCommonName diff --git a/nix/module-eval/bao-grants.nix b/nix/module-eval/bao-grants.nix index dd36feb96..9042b23c5 100644 --- a/nix/module-eval/bao-grants.nix +++ b/nix/module-eval/bao-grants.nix @@ -170,7 +170,7 @@ let _: u: (u.environment.BAO_CLIENT_CERT or null) == granterCertFile ) baoGrantWithConsumers.systemd.services; - # The twenty-two units that write a `swarm-*` grant, by name, for the + # The twenty-three units that write a `swarm-*` grant, by name, for the # discovery control below. grantingUnitNames = [ "swarm-bao-controller-policy" @@ -198,6 +198,7 @@ let "swarm-bao-stt-policy" "swarm-bao-attic-policy" "swarm-bao-archive-policy" + "swarm-bao-store-auth-policy" ]; # Comment lines dropped first: both the HCL and the scripts explain @@ -1146,24 +1147,24 @@ let } { # A store host without the granter's pair writes its grants some other - # way, so none of the twenty-two units may exist. Without this arm + # way, so none of the twenty-three units may exist. Without this arm # `lib.mkIf haveGranter` could be dropped from any of them and every other # case here would still pass. - name = "without the granter's pair none of the twenty-two granting units render"; + name = "without the granter's pair none of the twenty-three granting units render"; ok = let s = baoGranterOptOut.systemd.services; in lib.all (unit: !(s ? ${unit})) (grantingUnitNames ++ [ "swarm-bao-granter-role" ]) - # The control: the same store with the pair renders all twenty-two. + # The control: the same store with the pair renders all twenty-three. && lib.all (unit: baoGrantHere.systemd.services ? ${unit}) grantingUnitNames; } { - # 🩸 What replaced the silent skip. With no bootstrap token the twenty-two + # 🩸 What replaced the silent skip. With no bootstrap token the twenty-three # still render, and a refused granter fails them with the step that fixes it. # A store host that never named a token is told to name one, since the # unit that sets the granter up renders only where it has. - name = "a store host without a bootstrap token renders the twenty-two, each failing loudly with the one-time step"; + name = "a store host without a bootstrap token renders the twenty-three, each failing loudly with the one-time step"; ok = let s = baoGranterNoToken.systemd.services; @@ -2242,6 +2243,38 @@ let in lib.hasInfix "/stt.pem ]" s && lib.hasInfix "swarm-stt \"\" clientAuth" s; } + { + # Create without update: the first value stored is the one every later + # run reads, and no run replaces it. The two leaves are the stores'. + name = "the store credential publisher's grant is create and read on the two stores' credentials and nothing else, and the PKI unit signs its leaf"; + ok = + let + s = baoGrantHere.systemd.services.swarm-bao-store-auth-policy.script; + grants = grantsIn s; + pki = baoGrantHere.systemd.services.swarm-bao-pki.script; + in + (grantFor grants "secret/data/swarm/services/victorialogs/store-auth").caps == [ + "create" + "read" + ] + && + (grantFor grants "secret/data/swarm/services/victoriametrics/store-auth").caps == [ + "create" + "read" + ] + && lib.length grants == 2 + && 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 + && lib.hasInfix "/store-auth.pem ]" pki + && lib.hasInfix "swarm-store-auth \"\" clientAuth" pki + # Nothing else names either leaf, and the list is not empty for want of + # a match: the publisher's own unit is the one it finds. + && + lib.filter ( + u: lib.hasInfix "/store-auth" baoGrantHere.systemd.services.${u}.script + ) grantingUnitNames == [ "swarm-bao-store-auth-policy" ]; + } { name = "the PKI unit signs the notification router's leaf under its own subject"; ok = @@ -2677,8 +2710,8 @@ let } { # What makes the case above mean something: discovery by the granter's - # certificate reaches all twenty-two units, and each yields calls. - name = "the granter-policy check sees all twenty-two granting units, and parses calls from each"; + # certificate reaches all twenty-three units, and each yields calls. + name = "the granter-policy check sees all twenty-three granting units, and parses calls from each"; ok = lib.sort lib.lessThan (lib.attrNames granterUnits) == lib.sort lib.lessThan grantingUnitNames && lib.all (u: baoCalls u.script != [ ]) (lib.attrValues granterUnits) diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix index 52af8b6cb..6ca7f3816 100644 --- a/nix/module-eval/k8s.nix +++ b/nix/module-eval/k8s.nix @@ -2049,6 +2049,8 @@ let "-storageDataPath=/var/lib/victorialogs" "-httpListenAddr=:9428" "-retentionPeriod=30d" + "-httpAuth.username=swarm-store" + "-httpAuth.password=file:///run/credentials/victoria-logs.service/store-auth" ] && c.livenessProbe.httpGet == { @@ -2094,10 +2096,26 @@ let && !(spec ? initContainers) && !(lib.any (v: v.name == "tls") spec.volumes) && lib.any (v: v.name == "tls") (podSpec "swarm-controller").volumes - # It logs in to nothing, so it has no account, no token and no secret. + # It logs in to nothing, so it has no account and no token. Its one + # credential is the Secret the host publishes, mounted where the + # password flag names it. && !(spec ? serviceAccountName) && !(objects ? "swarm-victorialogs/serviceaccount") - && !(lib.any (v: v.name == "bao-token" || v.name == "credentials") spec.volumes) + && !(lib.any (v: v.name == "bao-token") spec.volumes) + && + (lib.findFirst (v: v.name == "credentials") null spec.volumes).secret == { + secretName = "swarm-victorialogs-credentials"; + defaultMode = 288; + items = [ + { + key = "store-auth"; + path = "store-auth"; + } + ]; + } + && lib.any ( + m: m.name == "credentials" && m.mountPath == "/run/credentials/victoria-logs.service" && m.readOnly + ) c.volumeMounts && (podSpec "swarm-stt") ? serviceAccountName # Its Service is the only way in, and only the node reaches it. && @@ -2116,6 +2134,114 @@ let && lib.elem "d ${dir} - - - -" onCluster.systemd.tmpfiles.rules && !(lib.any (lib.hasPrefix "d ${dir} ") noNode.systemd.tmpfiles.rules); } + { + # The credential has three ends that must agree: the unit that creates + # it, the file the gateway's store locations include, and the Secret the + # pod loads. Each absence arm has a presence control beside it. + name = "the stores' listener credentials are created and published by one unit and sent by every location that dials the store, and by no other"; + ok = + let + h = allLocal.services.hyperhive; + unit = allLocal.systemd.services.swarm-bao-store-auth; + rule = store: "f /var/lib/swarm-store-auth/${store}.conf 0600 root root -"; + # One store's vhost: every location that dials it includes the file, + # and no other location does. + vhost = + { + domain, + variable, + store, + }: + let + locations = allLocal.services.nginx.virtualHosts.${domain}.locations; + dialsStore = l: hasInfix variable (l.proxyPass or ""); + storeLocations = lib.filterAttrs (_: dialsStore) locations; + otherLocations = lib.filterAttrs (_: l: !(dialsStore l)) locations; + include = "include /var/lib/swarm-store-auth/${store}.conf;"; + in + { + inherit storeLocations otherLocations; + sent = + storeLocations != { } + && lib.all (l: hasInfix include l.extraConfig) (lib.attrValues storeLocations) + && lib.all (l: !(hasInfix "/var/lib/swarm-store-auth" (l.extraConfig or ""))) ( + lib.attrValues otherLocations + ); + # The credential of the other store is not this one's. + notTheOther = lib.all ( + l: + !(hasInfix "/var/lib/swarm-store-auth/${if store == "victorialogs" then "victoriametrics" else "victorialogs"}" l.extraConfig) + ) (lib.attrValues storeLocations); + }; + logs = vhost { + domain = h.swarm.victorialogs.domain; + variable = "$swarm_logs_store_upstream"; + store = "victorialogs"; + }; + metrics = vhost { + domain = h.swarm.victoriametrics.domain; + variable = "$swarm_metrics_store_upstream"; + store = "victoriametrics"; + }; + in + # The log store's four: the operator's `/`, the collector's ingest, the + # query API and the store's own metrics. + lib.attrNames logs.storeLocations == [ + "/" + "= /insert/opentelemetry/v1/logs" + "= /metrics" + "^~ /select/logsql/" + ] + # The metrics store's: the read API, vmui, the push and its metrics, and + # none of its import and admin routes, which have no location at all. + && lib.all (n: metrics.storeLocations ? ${n}) [ + "= /api/v1/query" + "= /api/v1/export" + "^~ /api/v1/label/" + "= /vmui" + "^~ /vmui/" + "= /opentelemetry/api/v1/push" + "= /metrics" + ] + && !(lib.any (n: hasInfix "import" n || hasInfix "admin" n || hasInfix "snapshot" n) ( + lib.attrNames metrics.storeLocations + )) + && logs.sent + && metrics.sent + && logs.notTheOther + && metrics.notTheOther + # The control for the absence arms of `sent`: the responders' and the + # identity provider's subrequests exist, are not the store's, and + # carry no credential. + && lib.length (lib.attrNames logs.otherLocations) >= 5 + && lib.any (n: hasInfix "agent_auth" n) (lib.attrNames logs.otherLocations) + && lib.any (n: hasInfix "agent_auth" n) (lib.attrNames metrics.otherLocations) + # The unit creates the leaves the policy names, writes the files those + # locations include, and publishes the Secrets the pods load. + && lib.all (store: hasInfix "secret/swarm/services/${store}/store-auth" unit.script) [ + "victorialogs" + "victoriametrics" + ] + && lib.all (store: hasInfix "/var/lib/swarm-store-auth/${store}.conf" unit.script) [ + "victorialogs" + "victoriametrics" + ] + && lib.all (store: hasInfix "swarm-${store}-credentials" unit.script) [ + "victorialogs" + "victoriametrics" + ] + && 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 + # Without either store there is no unit, no file and no location. + && !(noNode.systemd.services ? swarm-bao-store-auth) + && !(lib.elem (rule "victorialogs") noNode.systemd.tmpfiles.rules) + && !(lib.elem (rule "victoriametrics") noNode.systemd.tmpfiles.rules) + && !(noNode.services.nginx.virtualHosts ? ${h.swarm.victorialogs.domain}) + && !(noNode.services.nginx.virtualHosts ? ${h.swarm.victoriametrics.domain}); + } { # The two `auth_request` responders hold no state and log in under one # role, so they are one pod with one account that may run on any node. @@ -2230,6 +2356,8 @@ let "-storageDataPath=/var/lib/victoriametrics" "-httpListenAddr=:8428" "-retentionPeriod=5y" + "-httpAuth.username=swarm-store" + "-httpAuth.password=file:///run/credentials/victoria-metrics.service/store-auth" ] && c.livenessProbe.httpGet == probe && c.readinessProbe.httpGet == probe @@ -2273,7 +2401,22 @@ let && lib.any (v: v.name == "tls") (podSpec "swarm-controller").volumes && !(spec ? serviceAccountName) && !(objects ? "swarm-victoriametrics/serviceaccount") - && !(lib.any (v: v.name == "bao-token" || v.name == "credentials") spec.volumes) + && !(lib.any (v: v.name == "bao-token") spec.volumes) + && + (lib.findFirst (v: v.name == "credentials") null spec.volumes).secret == { + secretName = "swarm-victoriametrics-credentials"; + defaultMode = 288; + items = [ + { + key = "store-auth"; + path = "store-auth"; + } + ]; + } + && lib.any ( + m: + m.name == "credentials" && m.mountPath == "/run/credentials/victoria-metrics.service" && m.readOnly + ) c.volumeMounts && (podSpec "swarm-stt") ? serviceAccountName && objects."swarm-victoriametrics/service".spec.ports == [ diff --git a/nix/vm-tests/k8s-services.nix b/nix/vm-tests/k8s-services.nix index bf909e89e..e7a6fac51 100644 --- a/nix/vm-tests/k8s-services.nix +++ b/nix/vm-tests/k8s-services.nix @@ -512,6 +512,7 @@ pkgs.testers.runNixOSTest { serviceConfig = { RuntimeDirectory = "logs-gateway-test"; ExecStart = "${pkgs.nginx}/bin/nginx -c ${gatewayConf config} -g 'daemon off;'"; + ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID"; Restart = "on-failure"; RestartSec = 2; }; @@ -620,6 +621,13 @@ pkgs.testers.runNixOSTest { METRICS_AUTH = "swarm-metrics-auth" VM_DIR = "${vmDir}" METRICS_GATEWAY = "http://${vmGateway}" + # 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"} + + def other_secrets() -> set[str]: + names = machine.succeed(f"kubectl -n {NS} get secrets -o name || true").split() + return set(names) - STORE_SECRETS SELECTOR = f"--selector app.kubernetes.io/name={SERVICE}" @@ -736,9 +744,13 @@ pkgs.testers.runNixOSTest { "swarm-bao-review-classifier-policy", "swarm-bao-claude-login-policy", "swarm-bao-logs-auth-policy", + "swarm-bao-store-auth-policy", "swarm-bao-k8s-jwt-policy", ]: settle(f'[ "$(systemctl is-active {unit}.service)" = active ]', 900, [f"{unit}.service"]) + # The credential's unit retries until the store has its policy. + machine.succeed("systemctl reset-failed swarm-bao-store-auth.service || true") + machine.succeed("systemctl restart --no-block swarm-bao-store-auth.service") machine.wait_until_succeeds( "journalctl -u swarm-bao-k8s-jwt-policy --no-pager | grep -F 'Success! Data written to: auth/jwt-k8s/config'", timeout=300, @@ -814,7 +826,7 @@ pkgs.testers.runNixOSTest { data = json.loads(trust)["data"] assert data["trust-bundle.pem"] == machine.succeed("cat ${tlsDir}/trust-bundle.pem"), data assert data["bao-server-ca.pem"] == machine.succeed("cat /var/lib/swarm-bao-pki/ca.pem"), data - assert machine.succeed(f"kubectl -n {NS} get secrets -o name || true").strip() == "" + assert other_secrets() == set(), other_secrets() with subtest("a changed CA file is published again with no manual step"): # `swarm-services-cert` rewrites the trust bundle once, when the store first @@ -945,6 +957,10 @@ pkgs.testers.runNixOSTest { machine.succeed("systemctl cat hyperhive-k8s-ca-trust.service") for name in (VL, LOGS_AUTH): machine.succeed(f"test -L {MANIFESTS}/{name}.yaml") + # The pod waits for the Secret the unit publishes; the gateway reads its + # include file as it reloads. + settle('[ "$(systemctl is-active swarm-bao-store-auth.service)" = active ]', 900, ["swarm-bao-store-auth.service"]) + machine.succeed("systemctl reload logs-gateway") vl_pod = wait_pod_ready(VL) auth_pod = wait_pod_ready(LOGS_AUTH) assert machine.execute("machinectl list --no-legend | grep -q swarm-victorialogs")[0] != 0 @@ -1042,6 +1058,89 @@ pkgs.testers.runNixOSTest { raise AssertionError((status, body)) assert vl_query("0" * 64, "switch")[0] == 401 + STORE_AUTH_DIR = "/var/lib/swarm-store-auth" + STORE_PASSWORD = f"{STORE_AUTH_DIR}/victorialogs.password" + STORE_CONF = f"{STORE_AUTH_DIR}/victorialogs.conf" + + def store_direct(path: str, *args: str, credential: bool = True) -> tuple[int, str]: + """One request from the node to the store's pod address, past the gateway.""" + vl_ip = kube(machine, f"get pod {vl_pod} -o jsonpath='{{.status.podIP}}'").strip() + auth = f'--user "swarm-store:$(cat {STORE_PASSWORD})" ' if credential else "" + _, out = machine.execute(f"curl -sS --max-time 20 -w '\\n%{{http_code}}' {auth}{' '.join(args)} 'http://{vl_ip}:9428{path}'") + body, _, code = out.rpartition("\n") + return int(code or 0), body + + with subtest("the log store refuses every route without its credential from the node itself, past the gateway, and takes the credential the host keeps in the secret store"): + stored = as_root("bao kv get -mount=secret -field=value swarm/services/victorialogs/store-auth").strip() + assert len(stored) == 64, "the unit stores 64 hex digits" + # The three ends agree: the secret store's value, the file the unit + # keeps for the Secret, and the Secret itself. The files are root's + # and nobody else's. + assert machine.succeed(f"cat {STORE_PASSWORD}").strip() == stored + secret = machine.succeed(f"kubectl -n {NS} get secret swarm-victorialogs-credentials -o jsonpath='{{.data.store-auth}}' | base64 -d").strip() + assert secret == stored + assert machine.succeed(f"stat -c '%a %U %G' {STORE_PASSWORD} {STORE_CONF} {STORE_AUTH_DIR}").split("\n")[:3] == ["600 root root", "600 root root", "700 root root"] + assert stored not in machine.succeed(f"cat {MANIFESTS}/{VL}.yaml"), "the manifest holds no credential" + # Insert, select, a delete route, the admin routes, the store's own + # metrics and the UI answer 401 with no credential and with a caller's + # bearer, which is all a node process without the credential has. + refused = [ + ("POST", "/insert/opentelemetry/v1/logs"), + ("POST", "/insert/jsonline"), + ("POST", "/select/logsql/query"), + ("GET", "/select/logsql/tail"), + ("POST", "/delete/run_task"), + ("POST", "/delete/active_tasks"), + ("POST", "/internal/force_merge"), + ("POST", "/internal/partition/list"), + ("GET", "/metrics"), + ("GET", "/flags"), + ("GET", "/select/vmui/"), + ("GET", "/"), + ] + for method, path in refused: + for label, args in (("no credential", ()), ("a caller's bearer", (f"-H 'Authorization: Bearer {AGENT_TOKEN}'",))): + status, body = store_direct(path, f"-X {method}", *args, credential=False) + assert status == 401, (method, path, label, status, body[:200]) + # The same routes with the credential are answered by the store: its + # select and metrics routes answer 200, the insert accepts a record and + # the delete route is reached (the store runs without `-delete.enable`, + # so it says so) instead of being refused with 401. + status, body = store_direct("/select/logsql/query", "-X POST --data-urlencode 'query=switch'") + assert status == 200 and "written before the switch" in body, (status, body[:200]) + status, body = store_direct("/metrics") + assert status == 200 and "vl_" in body, (status, body[:200]) + status, body = store_direct("/insert/jsonline?_stream_fields=app", "-X POST --data-binary '{\"_msg\":\"written to the store directly\",\"app\":\"vm-test\"}'") + assert status == 200, (status, body[:200]) + status, body = store_direct("/delete/run_task", "-X POST") + assert status != 401 and "disabled" in body, (status, body[:200]) + # What stays open: the probes' route. + assert store_direct("/health", credential=False)[0] == 200 + # A wrong password is refused like none. + vl_ip = kube(machine, f"get pod {vl_pod} -o jsonpath='{{.status.podIP}}'").strip() + status = machine.execute(f"curl -sS -o /dev/null -w '%{{http_code}}' --user swarm-store:{'0' * 64} -X POST --data-urlencode 'query=switch' http://{vl_ip}:9428/select/logsql/query")[1] + assert status.strip() == "401", status + + with subtest("the gateway sends the store's credential in place of the caller's bearer, and a gateway without it gets 401 from the store"): + # The bearer cases above went through the gateway with the credential in + # place. With the include file emptied, the caller's own bearer reaches + # the store, which refuses it, although the responders still grant it. + saved = machine.succeed(f"cat {STORE_CONF}") + assert "proxy_set_header Authorization" in saved + machine.succeed(f": > {STORE_CONF} && systemctl reload logs-gateway") + machine.wait_until_succeeds("systemctl is-active logs-gateway", timeout=30) + for _ in range(10): + status, body = vl_query(AGENT_TOKEN, "switch") + if status == 401: + break + time.sleep(1) + assert status == 401, (status, body[:200]) + # The unit writes the file again, and the same request is granted: the + # control that the 401 is the missing credential. + machine.succeed("systemctl restart swarm-bao-store-auth.service && systemctl reload logs-gateway") + assert machine.succeed(f"cat {STORE_CONF}") == saved + wait_for_record(AGENT_TOKEN, "switch", "written before the switch") + with subtest("a record posted to the ingest route and the store's own metrics come through the gateway, and a restarted pod still holds both records"): import base64 @@ -1311,8 +1410,8 @@ pkgs.testers.runNixOSTest { import base64 import struct - # The store serves these on the listener its queries use and - # authenticates none of them; only the locations the module names reach it. + # The store serves these on the listener its queries use; only the + # locations the module names reach it. for path in ("/api/v1/admin/tsdb/delete_series", "/api/v1/import/prometheus"): metrics_expect(path, vm_request(path, GRAFANA_BEARER, "-X POST --data-binary 'x 1'")[0], 403) metrics_expect("the store's export route, as the control for the refusals above", vm_export(GRAFANA_BEARER, "written_before_the_switch")[0], 200) @@ -1347,6 +1446,85 @@ pkgs.testers.runNixOSTest { wait_for_series(AGENT_TOKEN, "written_before_the_switch") wait_for_series(AGENT_TOKEN, "written_through_the_gateway") + VM_PASSWORD = f"{STORE_AUTH_DIR}/victoriametrics.password" + VM_CONF = f"{STORE_AUTH_DIR}/victoriametrics.conf" + + def vm_direct(path: str, *args: str, credential: bool = True) -> tuple[int, str]: + """One request from the node to the metrics store's pod address, past the gateway.""" + vm_ip = kube(machine, f"get pod {vm_pod} -o jsonpath='{{.status.podIP}}'").strip() + auth = f'--user "swarm-store:$(cat {VM_PASSWORD})" ' if credential else "" + _, out = machine.execute(f"curl -sS --max-time 20 -w '\\n%{{http_code}}' {auth}{' '.join(args)} 'http://{vm_ip}:8428{path}'") + body, _, code = out.rpartition("\n") + return int(code or 0), body + + with subtest("the metrics store refuses every route without its credential from the node itself, past the gateway, and takes the credential the host keeps in the secret store"): + stored = as_root("bao kv get -mount=secret -field=value swarm/services/victoriametrics/store-auth").strip() + assert len(stored) == 64, "the unit stores 64 hex digits" + # Each store has a credential of its own. + assert stored != as_root("bao kv get -mount=secret -field=value swarm/services/victorialogs/store-auth").strip() + assert machine.succeed(f"cat {VM_PASSWORD}").strip() == stored + secret = machine.succeed(f"kubectl -n {NS} get secret swarm-victoriametrics-credentials -o jsonpath='{{.data.store-auth}}' | base64 -d").strip() + assert secret == stored + assert machine.succeed(f"stat -c '%a %U %G' {VM_PASSWORD} {VM_CONF}").split("\n")[:2] == ["600 root root", "600 root root"] + assert stored not in machine.succeed(f"cat {MANIFESTS}/{VM}.yaml"), "the manifest holds no credential" + # Writes, imports, queries, exports, the routes that delete and + # snapshot, the config and reload routes, the store's own metrics and + # the UI answer 401 with no credential and with a caller's bearer. + refused = [ + ("POST", "/api/v1/write"), + ("POST", "/api/v1/import"), + ("POST", "/api/v1/import/prometheus"), + ("POST", "/opentelemetry/api/v1/push"), + ("POST", "/influx/write"), + ("GET", "/api/v1/query?query=up"), + ("GET", "/api/v1/export?match[]={__name__!=\"\"}"), + ("POST", "/api/v1/admin/tsdb/delete_series?match[]={__name__!=\"\"}"), + ("POST", "/api/v1/admin/tsdb/snapshot"), + ("GET", "/snapshot/create"), + ("POST", "/internal/force_merge"), + ("POST", "/internal/resetRollupResultCache"), + ("GET", "/config"), + ("GET", "/-/reload"), + ("GET", "/metrics"), + ("GET", "/flags"), + ("GET", "/vmui/"), + ("GET", "/"), + ] + for method, path in refused: + for label, args in (("no credential", ()), ("a caller's bearer", (f"-H 'Authorization: Bearer {AGENT_TOKEN}'",))): + status, body = vm_direct(path, f"-g -X {method}", *args, credential=False) + assert status == 401, (method, path, label, status, body[:200]) + # With the credential the store answers: a query and an export read the + # sample written before the switch, the store's metrics come back, and + # a delete that matches nothing is accepted (204) instead of refused. + status, body = vm_direct("/api/v1/export", "-g --data-urlencode 'match[]={__name__=\"written_before_the_switch\"}'") + assert status == 200 and "written_before_the_switch" in body, (status, body[:200]) + status, body = vm_direct("/api/v1/query?query=vm_app_version") + assert status == 200 and "success" in body, (status, body[:200]) + status, body = vm_direct("/metrics") + assert status == 200 and "vm_" in body, (status, body[:200]) + status, body = vm_direct("/api/v1/admin/tsdb/delete_series", "-g -X POST --data-urlencode 'match[]={__name__=\"no_such_series_in_this_store\"}'") + assert status == 204, (status, body[:200]) + assert vm_direct("/health", credential=False)[0] == 200 + vm_ip = kube(machine, f"get pod {vm_pod} -o jsonpath='{{.status.podIP}}'").strip() + status = machine.execute(f"curl -sS -o /dev/null -w '%{{http_code}}' --user swarm-store:{'0' * 64} 'http://{vm_ip}:8428/api/v1/query?query=up'")[1] + assert status.strip() == "401", status + + with subtest("the gateway sends the metrics store's credential in place of the caller's bearer, and a gateway without it gets 401 from the store"): + saved = machine.succeed(f"cat {VM_CONF}") + assert "proxy_set_header Authorization" in saved and saved != machine.succeed(f"cat {STORE_CONF}") + machine.succeed(f": > {VM_CONF} && systemctl reload logs-gateway") + machine.wait_until_succeeds("systemctl is-active logs-gateway", timeout=30) + for _ in range(10): + status, body = vm_export(AGENT_TOKEN, "written_before_the_switch") + if status == 401: + break + time.sleep(1) + assert status == 401, (status, body[:200]) + machine.succeed("systemctl restart swarm-bao-store-auth.service && systemctl reload logs-gateway") + assert machine.succeed(f"cat {VM_CONF}") == saved + wait_for_series(AGENT_TOKEN, "written_before_the_switch") + with subtest("only the node reaches the metrics store's pods, and the responders' pod reaches the store's pod listener and no other port of the host"): vm_ip = kube(machine, f"get pod {vm_pod} -o jsonpath='{{.status.podIP}}'").strip() metrics_auth_ip = kube(machine, f"get pod {metrics_auth_pod} -o jsonpath='{{.status.podIP}}'").strip() @@ -1403,7 +1581,7 @@ pkgs.testers.runNixOSTest { assert [src["configMap"]["name"] for src in sources] == ["hyperhive-ca-trust"], sources assert [(i["key"], i["path"]) for i in sources[0]["configMap"]["items"]] == [("bao-server-ca.pem", "bao-ca.pem")], sources assert not any("secret" in v or any("secret" in src for src in v.get("projected", {}).get("sources", [])) for v in spec["volumes"]), spec["volumes"] - assert machine.succeed(f"kubectl -n {NS} get secrets -o name || true").strip() == "" + assert other_secrets() == set(), other_secrets() # The control that the lookup finds the variable: the router's pod sets # it, and the poller's does not. router_env = {e["name"]: e.get("value") for e in json.loads(kube(machine, f"get pod {router} -o json"))["spec"]["containers"][0]["env"]}