Watch
0
0
Fork
You've already forked hyperhive
0

the log and metrics stores ask every request for a credential the gateway supplies

Each store runs with -httpAuth.* and a credential from the secret store, published to the namespace as a Secret by the host. The gateway's locations send it after auth_request has passed, and the collector's scrape and push take the same one, so a process on the node that bypasses the gateway is refused.
This commit is contained in:
atlas 2026-11-27 17:24:08 +01:00 • committed by maia
commit f54aae7927
21 changed files with 808 additions and 72 deletions

View file

@ -92,17 +92,12 @@ queue secret, at the queue and at both stores' read routes alike. The two store
agent's `swarm/agents/<agent>/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

View file

@ -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 `<service>-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

View file

@ -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.

View file

@ -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/<hive>/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/<hive>/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/<clientId>/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/<hive>/oidc/client`, `swarm/controller/swarm-controller/oidc/client` or `swarm/services/<client id>/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/<id>.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/<id>.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/<id>.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/<id>.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/<grafana client id>/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/<grafana client id>/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/<grafana client id>/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/<grafana client id>/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 <value>`: 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/<poller client id>/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/<forge client id>/oidc/client` and `swarm/services/<forge forwarder client id>/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.<pair>`; the common names, what a missing leaf
costs and how to place a leaf by hand are in

View file

@ -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.<swarm-domain>` 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.<swarm-domain>` 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.<agent>.<secret>` bearer, checked by

View file

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

View file

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

View file

@ -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.

View file

@ -27,6 +27,7 @@ in
./node.nix
./pod-logs.nix
./runtime.nix
./store-credentials.nix
];
options.services.hyperhive.k8s = {

View file

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

View file

@ -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
}
# <store> <leaf> <password file> <nginx file> <secret>. 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}
'';
};
})
]
);
}

View file

@ -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 `<service>-credentials`).
secretName = store: "swarm-${store}-credentials";
}

View file

@ -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;

View file

@ -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`;

View file

@ -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;

View file

@ -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.
}

View file

@ -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.
}

View file

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

View file

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

View file

@ -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 == [

Some files were not shown because too many files have changed in this diff Show more