From dca4720b7b041312a706d2cbe5929af33c5b8a11 Mon Sep 17 00:00:00 2001 From: atlas Date: Thu, 26 Nov 2026 10:17:57 +0100 Subject: [PATCH] run the log store and its auth responders as pods swarm-logs-auth and swarm-metrics-auth take --listen for a TCP address beside --socket. The log store is a Deployment on a static local volume that is its old container's data directory, behind a ClusterIP Service the gateway dials by name. Its two auth_request responders are one unpinned pod with a jwt role. The renderer gains a plain HTTP listener, a probe path, fsGroupChangePolicy, and one policy for a pod with both a listener and egress. --- Cargo.lock | 1 + docs/2-handbook/agents/security.md | 14 +- docs/2-handbook/swarm/services.md | 3 + docs/4-implementation/k8s/manifests.md | 22 +- docs/4-implementation/k8s/node.md | 4 +- docs/4-implementation/k8s/runtime.md | 99 ++- docs/4-implementation/k8s/telemetry.md | 8 +- .../swarm/credentials-reference.md | 2 +- docs/4-implementation/swarm/telemetry.md | 21 +- docs/5-project/process/gotchas.md | 4 +- nix/host-modules/default.nix | 1 - nix/host-modules/deploy.nix | 10 +- .../glue-attic-otel-oidc-client.nix | 2 +- .../glue-victorialogs-otel-oidc-client.nix | 37 -- nix/host-modules/k8s/node.nix | 5 +- nix/host-modules/k8s/render.nix | 102 ++- nix/host-modules/swarm-bao-readers.nix | 17 +- nix/host-modules/swarm-otel-service.nix | 8 +- nix/host-modules/swarm-otel.nix | 4 +- nix/host-modules/swarm-secret-publisher.nix | 7 +- .../swarm-victorialogs-service.nix | 40 +- nix/host-modules/swarm-victorialogs.nix | 621 ++++++++---------- nix/host-modules/swarm-victoriametrics.nix | 5 +- nix/module-eval/bao-grants.nix | 12 +- nix/module-eval/core-toggle.nix | 66 +- nix/module-eval/k8s.nix | 435 +++++++++--- nix/module-eval/nats-authelia.nix | 12 - nix/module-eval/secret-publisher.nix | 1 - nix/module-eval/swarm-otel-identity.nix | 2 +- nix/module-eval/swarm-services-switch.nix | 49 +- nix/vm-tests/k8s-services.nix | 238 +++++++ swarm-logs-auth/src/main.rs | 135 +++- swarm-metrics-auth/Cargo.toml | 2 + swarm-metrics-auth/src/main.rs | 136 +++- 34 files changed, 1382 insertions(+), 743 deletions(-) delete mode 100644 nix/host-modules/glue-victorialogs-otel-oidc-client.nix diff --git a/Cargo.lock b/Cargo.lock index 80b1b5f38..1b6834fd6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5641,6 +5641,7 @@ dependencies = [ "axum", "chrono", "clap", + "futures-util", "hive-log", "mockall", "serde", diff --git a/docs/2-handbook/agents/security.md b/docs/2-handbook/agents/security.md index 8b621bb5f..7e34649a7 100644 --- a/docs/2-handbook/agents/security.md +++ b/docs/2-handbook/agents/security.md @@ -86,13 +86,25 @@ and the store's granter fetches the bao UI's. Three services read **every agent's queue secret** (`swarm/agents//queue`), each under a leaf of its own whose policy reaches that one leaf per agent: the queue's auth callout (`swarm-nats-auth`), -the log store's agent check (`swarm-logs-auth`, on the log store's host), and +the log store's agent check (`swarm-logs-auth`, a pod on the log store's host), and the metrics store's (`swarm-metrics-agent-auth`, under the `swarm-metrics-auth` leaf on the metrics store's host). Any one compromised can present any agent's queue secret, at the queue and at both stores' read routes alike. The two store checks also read the 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 store takes writes and reads from the node + +VictoriaLogs checks no credential: the gateway's vhost does. The 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 log store's host, whatever its user, can therefore read every log line and +write records into the store without a bearer. 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 log store as trusted for logs. The +metrics store still listens on a unix socket that only the gateway's group can +open. + ### Per-hive credentials live under the hive kind `swarm_secret_client::policy` scopes the **hive** stanza narrowly (unlike the diff --git a/docs/2-handbook/swarm/services.md b/docs/2-handbook/swarm/services.md index f3a4663d7..53804f60f 100644 --- a/docs/2-handbook/swarm/services.md +++ b/docs/2-handbook/swarm/services.md @@ -162,6 +162,9 @@ hive's daemons and the harness units in every agent container. To read them, open Grafana, pick **Explore** and choose the `VictoriaLogs` datasource. Agents query it with `swarm-logs`, and need the `logs` permission. +The store runs as a pod in the host's cluster, so `deploy.victorialogs.enable` +turns [the cluster node](../../4-implementation/k8s/node.md) on with it. + | Option | When you'd touch it | | ------------------------------------- | ----------------------------------------------------------------------------------------------------- | | `deploy.victorialogs.retentionPeriod` | Default `30d`, far shorter than the metrics store's. Raise it to answer questions about last quarter. | diff --git a/docs/4-implementation/k8s/manifests.md b/docs/4-implementation/k8s/manifests.md index 180b1f32e..b280afac6 100644 --- a/docs/4-implementation/k8s/manifests.md +++ b/docs/4-implementation/k8s/manifests.md @@ -28,6 +28,8 @@ A service gets manifests on the host whose configuration deploys it: | `swarm-review-classifier` | Deployment | ServiceAccount | | `swarm-claude-login` | Deployment | ServiceAccount | | `swarm-ci-metrics` | CronJob | ServiceAccount, PersistentVolume and Claim | +| `swarm-victorialogs` | Deployment | Service, NetworkPolicy, PersistentVolume and Claim | +| `swarm-logs-auth` | Deployment | ServiceAccount, two Services, NetworkPolicy | `namespace.yaml` holds the Namespace ([Pod Security](#pod-security)). @@ -128,17 +130,23 @@ credential directory. (`collector`). The policy allows its pod on the queue's port too. The node trusts the pod network's interfaces, so without the policy a pod reaches every port of the host. A service without `egress` has no - policy. + policy. A service with a listener and `egress` (`swarm-logs-auth`) has the one + policy: it admits the node to the listener and nothing else, and allows the + egress above. - **Probes:** a service with an opt-in health listener gets its variable set to `0.0.0.0:8080`, with liveness on `/healthz` and readiness on `/readyz` (see [Readiness checks](../swarm/readiness.md)). `swarm-controller` is one of - them, with `SWARM_CONTROLLER_HEALTH_ADDR`. + them, with `SWARM_CONTROLLER_HEALTH_ADDR`. A third-party daemon with no health variable, + `victoria-logs`, names a `probe` path instead (`/health`), which both probes + request on its listener. - **Listener and init container:** a service with a TCP `listener` (`swarm-controller`, with `swarm.controller.tcp.enable`) publishes its port with a ClusterIP Service, admits only the node to it with a NetworkPolicy, and gets an init container and a renewal container that issue its leaf into an `emptyDir` ([runtime](runtime.md#the-controller)). The image of those - containers is part of `system.build.k8sImages`. + containers is part of `system.build.k8sImages`. A listener with no `tlsDir` + (`swarm-victorialogs`, `swarm-logs-auth`) serves plain HTTP: it gets the + Service and the policy and no leaf, init container or renewal container. - **More than the daemon:** a service whose pod holds more than its daemon (the queue, whose server and exporter run beside the responder) names a function in its entry that adds containers, init containers, volumes, host @@ -147,7 +155,13 @@ credential directory. daemon's binary, and the credential directory its unit loads from follows the daemon's name. The pod runs under one ServiceAccount, so a queue that holds two store roles has both bound to it - ([runtime](runtime.md#the-queue)). + ([runtime](runtime.md#the-queue)). The responders' pod of the log store holds a second container the same way + ([runtime](runtime.md#the-log-store)). +- **A unit of the module's own making:** a service that never ran under systemd on the + host (`swarm-victorialogs`, `swarm-logs-auth`) gives the renderer the + `serviceConfig`, `environment` and `path` of one as a plain attribute set, with + the daemon's flags as a list in `ExecStart`. The renderer reads nothing else of + a unit. `fsGroupChangePolicy` in the entry sets the pod's field of that name. - **Config checksum:** a Deployment whose service has a ConfigMap (`etcFiles`) carries `checksum/etc` on its pod template, the hash of that ConfigMap's content, so a changed file rolls the pod. diff --git a/docs/4-implementation/k8s/node.md b/docs/4-implementation/k8s/node.md index 3946c661f..a817a32d2 100644 --- a/docs/4-implementation/k8s/node.md +++ b/docs/4-implementation/k8s/node.md @@ -67,8 +67,8 @@ says so with a label. The module sets the labels (`services.hyperhive.deploy.k8s.nodeLabels`, passed to `services.k3s.nodeLabel`): - `hyperhive.darkest.space/state-=true`, one per service whose data - the cluster keeps. Today that's `nats`, when `deploy.nats.enable` is on, and `ci-metrics`, when - `deploy.ci-metrics.enable` is on. The + the cluster keeps. Today that's `nats`, `ci-metrics` and `victorialogs`, each when its + `deploy..enable` is on. The service's static local volume has a `nodeAffinity` on the label, and its pod a `nodeSelector` on it, so a node without the label can't run the pod and shows as no match instead of a volume that can't bind. One label per service, so diff --git a/docs/4-implementation/k8s/runtime.md b/docs/4-implementation/k8s/runtime.md index 62a30f650..799ae8b33 100644 --- a/docs/4-implementation/k8s/runtime.md +++ b/docs/4-implementation/k8s/runtime.md @@ -2,8 +2,9 @@ The swarm services that have a pod run in the host's cluster and nowhere else: `swarm-notify-router`, `swarm-stt`, `swarm-ci-metrics`, `swarm-review-classifier`, -`swarm-claude-login`, `swarm-controller` and the queue with its auth callout -(`swarm-nats`). Each runs once per swarm, because two copies would share one +`swarm-claude-login`, `swarm-controller`, the queue with its auth callout +(`swarm-nats`) and the log store with its responders (`swarm-victorialogs`, +`swarm-logs-auth`). Each runs once per swarm, because two copies would share one queue consumer and one set of buckets, or two cursors that push every CI run twice. A host that enables one gets [the cluster node](node.md) with it: no option moves a service between the host and the cluster, and the host has no @@ -14,7 +15,7 @@ gateway, `swarm-builder`, `swarm-matrix-ctl` and every hive stay on the host. `services.hyperhive.deploy.k8s.enable` defaults on where the host enables any of `deploy.notify-router`, `stt`, `ci-metrics`, `review-classifier`, -`claude-login`, `nats` or `swarm-controller`. `deploy.singleHostSwarm` and +`claude-login`, `nats`, `swarm-controller` or `victorialogs`. `deploy.singleHostSwarm` and `deploy.allSwarmServices` enable them, so an all-local host gets the node and every service in the cluster with no further option. A host that sets `deploy.k8s.enable = false` while it enables one fails at evaluation, and the @@ -55,6 +56,8 @@ The data stays where it was: ([State](#state)). - The poller's cursor is `/var/lib/private/swarm-ci-metrics`, mounted the same way. +- The log store's pod mounts `/var/lib/nixos-containers/swarm-victorialogs/var/lib/victorialogs`, + the directory the container's store used ([The log store](#the-log-store)). - The other services keep nothing a move has to carry. The pods log in to the store with their ServiceAccount tokens, so the store's @@ -296,6 +299,77 @@ strategy, and the removed container stops before the pod can start. descriptors are the container runtime's, not the 800000 the container's unit sets. The VM test checks the runtime's is at least that. +## The log store + +`swarm-victorialogs` is the swarm's log store: one VictoriaLogs, with the two +`auth_request` responders of its gateway vhost in a second pod. The gateway's +vhost `logs.` stays on the host, and so do the collector that +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 + 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. +- **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 + moves the process and not the bytes. Its `nodeAffinity` and the pod's + `nodeSelector` both name the node label + `hyperhive.darkest.space/state-victorialogs` + ([node labels](node.md#node-labels)), so the pod and the directory stay on the + node that carries it. The files the container wrote belong to a user of its + own, which the pod's user isn't. The pod's `fsGroup` is `65532`, and its + `fsGroupChangePolicy` is `OnRootMismatch`: the first start after the upgrade + gives the pod's group the whole tree, and later starts look at the directory + alone, so a restart doesn't walk a store of many files. The files keep their + user. The module makes the directory on a host that never ran the container, + leaving the owner and mode of an existing one alone. The volume's capacity is + nominal: a local volume's size isn't enforced, and retention + (`deploy.victorialogs.retentionPeriod`, 30 days) is what bounds the store. +- **The gateway's hop.** The host can't reach a unix socket inside a pod, so the + store serves TCP and a ClusterIP Service, + `swarm-victorialogs..svc.`, publishes it. The + vhost's locations dial the Service's name through nginx's `resolver` (the + hive's dnsmasq) and a variable, as [the controller's](#the-controller) do, so + `gateway.dns.enable` has to be on. Each role has a variable of its own, because + the auth subrequests run their own `set`. A `proxy_pass` with a variable and a + URI part sends that URI and not the request's own, so the store's locations + write none, and the request's path and query reach the store as the caller sent + them. The collector's push, Grafana's datasource, the controller's and + hive-c0re's query URLs and the agents' `swarm-logs` all use + `logs.`, which the host serves: none of them changes. +- **The responders' pod.** `swarm-logs-auth`, which checks an agent's bearer and + its `logs` permission, and `swarm-logs-grafana-auth` (the `swarm-metrics-auth` + binary), which checks Grafana's, run as two containers of one Deployment, + `swarm-logs-auth`. Both log in as the cert role `swarm-logs-auth` does, so the + pod has one ServiceAccount and one jwt role of that name, and both read the + store with the pod's token. They hold no state and nothing in the store pod + calls them, so the pod has no node label and runs on any node, and only the + gateway's subrequests (`auth_request`) reach them: each serves TCP + (`--listen`) on 8081 and 8082, behind a Service each. A unix socket couldn't + stay, because the host's nginx can't open a socket inside a pod, and Pod + Security `restricted` refuses a `hostPath` for 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 + 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. +- **The host's part.** The host keeps the vhost, `gateway.localNames` and the + options (`retentionPeriod`, `authRate`, `authBurst`, `authVerdictTtl` and the + store identity files). It runs no container, unit or socket directory for + either pod, and no journal forwarder: the host collector reads the pods' + output from the node like any pod's. + ## Resources and sandbox The pod takes the unit's `MemoryMax` and `CPUQuota` as its container's limits @@ -362,8 +436,9 @@ forwards. ## Validation `module-eval-k8s` checks that the all-local host runs every service as a pod and -none as a container, unit or timer; that the node defaults on through the -all-local mode and through one toggle, and an explicit `false` stays false; that a +none as a container, unit or timer, and that the log store's volume is its +old container's directory and its responders' pod has no node label; that the node +defaults on through the all-local mode and through one toggle, and an explicit `false` stays false; that a host with the node off and a service on fails with a message naming the option and the services; that a controller without the TCP listener, the pod's bind address or the hive's resolver fails the evaluation; that the manifests sit in @@ -409,4 +484,18 @@ listener refuses a client with no leaf. It runs the gateway's own controller location, from the module's text, against the pod: it answers an unsigned webhook 401. A changed rev rolls the Deployment onto a new pod. +The same VM test runs the log store. A unit of the test writes a record into the old +container's data directory as another user before the cluster starts, because the +container is no longer in the module to switch from. It asserts that the host has no +container, unit or socket directory for the store or its responders; that the +volume is that directory and the pod's group owns the tree; that a gateway, run +from the module's own locations in a nginx of its own, returns the record to an +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` +CLI itself isn't run: it needs an agent's store certificate, so the test +presents the `Authorization` header it sends. + `k8s-bao-login` and `k8s-node` check the store's login and the node. diff --git a/docs/4-implementation/k8s/telemetry.md b/docs/4-implementation/k8s/telemetry.md index 870fa2d3e..0cf2880c4 100644 --- a/docs/4-implementation/k8s/telemetry.md +++ b/docs/4-implementation/k8s/telemetry.md @@ -1,8 +1,10 @@ # Pod logs and metrics -The swarm's log and metric stores stay where they are. A pod's output reaches -them through the hive collector that runs on the host -(`opentelemetry-collector`, [Telemetry](../swarm/telemetry.md)), so +The swarm's metric store is a container on the host and its log store is a pod +([the log store](runtime.md#the-log-store)). A pod's output reaches both +through the hive collector that runs on the host +(`opentelemetry-collector`, [Telemetry](../swarm/telemetry.md)), which pushes to +the stores through the gateway, so `swarm-logs query` and `swarm-metrics` show a pod's records next to the ones the same service produced as a host unit. diff --git a/docs/4-implementation/swarm/credentials-reference.md b/docs/4-implementation/swarm/credentials-reference.md index 07ae16716..c059a6d1a 100644 --- a/docs/4-implementation/swarm/credentials-reference.md +++ b/docs/4-implementation/swarm/credentials-reference.md @@ -146,7 +146,7 @@ pieces fit, and the reasoning behind them, is in [`credentials.md`](../../2-hand | an agent's claude login (`.credentials.json`) | `swarm-claude-login.service`, in its container, when an operator completes `claude auth login` from the agent's card in the swarm UI; it stores the file as a new version at `swarm/agents//claude-credentials` under its own leaf, which may create and update that path and read nothing under an agent | the swarm secret store at that path; the agent's `hive-agent` reads it under the agent's own leaf every 30 seconds while it waits for a login and writes it to `~/.claude/.credentials.json` | the same read, co-located or not; nothing for an operator to place beyond the agent's store leaf. When the store's copy and the agent's differ the KV version decides: the agent installs only a version newer than the last it installed (`claude-credentials-version` under the harness dir), because claude rotates the refresh token in its own copy and the stored one goes stale. The agent ignores a stale or equal version, and a relogin writes a newer one — [claude-login.md](../../2-handbook/swarm/claude-login.md) | | the queue responder's copy of its OIDC secret | the responder reads it out of the swarm secret store itself as it starts, under its own leaf, and again when authelia refuses it | the daemon's memory only; never on disk | same read, wherever authelia runs. Nothing for an operator to place beyond the responder's store leaf (`deploy.nats.authBaoClientCertFile`) | | the queue container's journal forwarder's copy of the queue's OIDC secret | `swarm-journal-forwarder-oidc.service` inside the `swarm-nats` container reads it out of the swarm secret store under the responder's store leaf, and again every 10 minutes | `/run/swarm-journal-forwarder-oidc/client-secret` on the container's tmpfs, root `0400`, never on persistent disk; `LoadCredential` hands it to the collector | same unit, same path. After a reboot the fetch fails fast while the store is down and retries with a delay that grows to 5 minutes; the attempt that succeeds starts the collector, which isn't part of the container's boot, and it resumes from its saved journal cursor. Nothing for an operator to place beyond the responder's store leaf (`deploy.nats.authBaoClientCertFile`) | -| the CI runner, Grafana, log store, cache, forge and homeserver containers' journal forwarders' OIDC secrets | `swarm-journal-forwarder-oidc.service` inside each container reads its forwarder client's secret (`swarm..otel.clientId`) out of the swarm secret store under the store leaf the host already holds for that service, handed in as a system credential (bound in read-only, for the homeserver's), and again every 10 minutes | `/run/swarm-journal-forwarder-oidc/client-secret` on the container's tmpfs, root `0400`, never on persistent disk; `LoadCredential` hands it to the collector | same unit, same path. Nothing for an operator to place beyond those leaves (`deploy.bao.ciRunnerClientCertFile`, `deploy.bao.grafanaOidcClientCertFile`, `deploy.victorialogs.authBaoClientCertFile`, `deploy.bao.forgePublisherClientCertFile`, `deploy.bao.atticClientCertFile`, `deploy.matrix.ctlBaoClientCertFile`) | +| the CI runner, Grafana, cache, forge and homeserver containers' journal forwarders' OIDC secrets | `swarm-journal-forwarder-oidc.service` inside each container reads its forwarder client's secret (`swarm..otel.clientId`) out of the swarm secret store under the store leaf the host already holds for that service, handed in as a system credential (bound in read-only, for the homeserver's), and again every 10 minutes | `/run/swarm-journal-forwarder-oidc/client-secret` on the container's tmpfs, root `0400`, never on persistent disk; `LoadCredential` hands it to the collector | same unit, same path. Nothing for an operator to place beyond those leaves (`deploy.bao.ciRunnerClientCertFile`, `deploy.bao.grafanaOidcClientCertFile`, `deploy.bao.forgePublisherClientCertFile`, `deploy.bao.atticClientCertFile`, `deploy.matrix.ctlBaoClientCertFile`) | | the metrics store container's journal forwarder's OIDC secret | `swarm-victoriametrics-forwarder-oidc.service` on the store's host reads its forwarder client's secret (`swarm.victoriametrics.otel.clientId`) out of the swarm secret store under the metrics store responder's leaf, and again every 10 minutes: the container has no network to reach the store | `/run/swarm-victoriametrics-forwarder-oidc/.secret` on the host (tmpfs), root `0400`, never on persistent disk; bound into the container read-only, where `LoadCredential` hands it to the collector | same unit, same path. Nothing for an operator to place beyond that leaf (`deploy.victoriametrics.authBaoClientCertFile`) | | the CI run poller's forge token | `swarm-controller`, with the forge's admin API, for its `ci-metrics` account, at start and in a five-minute pass | the swarm secret store at `swarm/services/ci-metrics/forge/token`; `swarm-ci-metrics` reads it once per pass under its own leaf and holds it in memory for that pass. When the store's token no longer matches the forge's, the controller's next pass mints a new one; until then the poller's forge calls answer 401, the unit fails and no cursor moves | nothing to place beyond the poller's leaf (`deploy.bao.ciMetricsClientCertFile`), on a host without the store | | the CI run poller's copy of its OIDC secret | authelia's mint, which creates it in the swarm secret store | `swarm-ci-metrics` reads `swarm/services//oidc/client` once per pass under its own leaf, and again when authelia refuses it; memory only. While it differs from authelia's, the token request fails, nothing gets pushed and no cursor moves | same leaf, nothing else | diff --git a/docs/4-implementation/swarm/telemetry.md b/docs/4-implementation/swarm/telemetry.md index 09a04f53d..975170fc6 100644 --- a/docs/4-implementation/swarm/telemetry.md +++ b/docs/4-implementation/swarm/telemetry.md @@ -189,19 +189,20 @@ swarm. | `deploy.victorialogs.grafanaAuthPackage` | The `swarm-metrics-auth` build that runs as `swarm-logs-grafana-auth`. Set on its own: `deploy.victoriametrics.authPackage` doesn't reach it. | | `swarm.victorialogs.domain` | Only to rename it. | -It listens on a unix socket in a network namespace of its own, on the hive -bridge so its journal forwarder can reach the swarm collector, and binds no host -port. Only the gateway's nginx can open the socket. It takes no credential of -its own: the gateway vhost is the only way in, and the collector is the only -intended writer. +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). **Who may query.** `/select/logsql/` takes one of three credentials. An agent presents its `swarm-agent..` bearer, checked by `swarm-logs-auth`. The agent must also hold the `logs` permission, which is off by default; without it the answer is a 403 (`docs/5-project/process/conventions.md`, Permissions). Grafana's datasource presents the same bearer as its metrics datasource, which `swarm-bao-grafana-metrics-bearer` creates, and a -second `swarm-metrics-auth` instance (`swarm-logs-grafana-auth`) on the log -store's host checks it against the same store path; the gateway tells it from +second `swarm-metrics-auth` instance (`swarm-logs-grafana-auth`, in the same pod as +`swarm-logs-auth`) checks it against the same store path; the gateway tells it from the others by its shape, 64 hex digits. Anything else needs an operator's authelia session. Because one bearer opens both read APIs, a rotation (see [`credentials.md`](../../2-handbook/swarm/credentials.md)) restarts Grafana once, and the log store @@ -290,16 +291,16 @@ gateway either way. The `swarm-bao`, `swarm-nats`, `swarm-builder`, `swarm-claude-login`, `swarm-notify-router`, `swarm-review-classifier`, `swarm-ci-runner`, `swarm-grafana`, -`swarm-victorialogs`, `swarm-victoriametrics`, `swarm-authelia`, `swarm-attic`, `hive-forge` +`swarm-victoriametrics`, `swarm-authelia`, `swarm-attic`, `hive-forge` and `hive-matrix` containers each run a collector of their own that forwards the container's journal here, on a route and receiver per service (`https:////`), authenticated as an OIDC client of that service's. The queue, builder, login minter, notification router and -classifier reuse the service's own client; the store, CI runner, Grafana, log store, metrics store, +classifier reuse the service's own client; the store, CI runner, Grafana, metrics store, authelia, cache, forge and homeserver have a forwarder client of their own (`swarm..otel.clientId`). Their records carry `service.name` (`bao`, `nats`, `builder`, `claude-login`, `notify-router`, `review-classifier`, `ci-runner`, -`grafana`, `victorialogs`, `victoriametrics`, `authelia`, `attic`, `forgejo`, +`grafana`, `victoriametrics`, `authelia`, `attic`, `forgejo`, `tuwunel`) and the `sender` of its own client id. The forwarder of all but the store's is `nix/container-modules/swarm-journal-forwarder.nix`. diff --git a/docs/5-project/process/gotchas.md b/docs/5-project/process/gotchas.md index 342e4fdad..bb6d82405 100644 --- a/docs/5-project/process/gotchas.md +++ b/docs/5-project/process/gotchas.md @@ -82,8 +82,8 @@ With both set, systemd creates the runtime directory under `/run/private/` `RuntimeDirectoryPreserve=`). No unprivileged user can traverse that, so nginx's `connect()` to a socket in it fails with `EACCES` whatever the directory and socket modes are. A unit serving a socket to another user -runs as a static user instead (`swarm-controller`, `swarm-logs-auth`, -`swarm-metrics-auth`, `swarm-metrics-agent-auth`). +runs as a static user instead (`swarm-controller`, `swarm-metrics-auth`, +`swarm-metrics-agent-auth`). `module-eval-core-toggle` fails on any `unix:` upstream of nginx owned by such a unit. diff --git a/nix/host-modules/default.nix b/nix/host-modules/default.nix index 3efc8e519..09130f588 100644 --- a/nix/host-modules/default.nix +++ b/nix/host-modules/default.nix @@ -66,7 +66,6 @@ ./glue-secret-publisher-bao-identity.nix ./glue-swarm-bao-otel-oidc-client.nix ./glue-swarm-otel-oidc-client.nix - ./glue-victorialogs-otel-oidc-client.nix ./glue-victoriametrics-otel-oidc-client.nix ./swarm-archive.nix ./swarm-attic-options.nix diff --git a/nix/host-modules/deploy.nix b/nix/host-modules/deploy.nix index f89d40ad0..d7223d284 100644 --- a/nix/host-modules/deploy.nix +++ b/nix/host-modules/deploy.nix @@ -104,14 +104,12 @@ in one backfill pass. Remove this definition. '') (lib.mkRemovedOptionModule [ "services" "hyperhive" "swarm" "victorialogs" "port" ] '' - VictoriaLogs listens on a unix socket in a network namespace of its own, - and the gateway reaches it there, so it binds no host port. Remove this - definition. + VictoriaLogs runs as a pod behind a Service the gateway dials, so it + binds no host port. Remove this definition. '') (lib.mkRemovedOptionModule [ "services" "hyperhive" "deploy" "victorialogs" "port" ] '' - VictoriaLogs listens on a unix socket in a network namespace of its own, - and the gateway reaches it there, so it binds no host port. Remove this - definition. + VictoriaLogs runs as a pod behind a Service the gateway dials, so it + binds no host port. Remove this definition. '') (lib.mkRemovedOptionModule [ "services" "hyperhive" "swarm" "victoriametrics" "port" ] '' VictoriaMetrics listens on a unix socket in a network namespace of its diff --git a/nix/host-modules/glue-attic-otel-oidc-client.nix b/nix/host-modules/glue-attic-otel-oidc-client.nix index 1d4de83d7..69efeb822 100644 --- a/nix/host-modules/glue-attic-otel-oidc-client.nix +++ b/nix/host-modules/glue-attic-otel-oidc-client.nix @@ -7,7 +7,7 @@ # # Gated on authelia being HERE, not on this host running the cache: a client is # a row in THIS host's provider config, the split -# ./glue-victorialogs-otel-oidc-client.nix makes for the same reason. +# ./glue-victoriametrics-otel-oidc-client.nix makes for the same reason. { lib, config, diff --git a/nix/host-modules/glue-victorialogs-otel-oidc-client.nix b/nix/host-modules/glue-victorialogs-otel-oidc-client.nix deleted file mode 100644 index fc5c5a3b5..000000000 --- a/nix/host-modules/glue-victorialogs-otel-oidc-client.nix +++ /dev/null @@ -1,37 +0,0 @@ -# Glue: register the log store container's journal forwarder as an OIDC -# client wherever authelia runs. -# -# ONE PAIRING PER FILE: that forwarder ← authelia, and nothing else. -# Without it authelia mints no secret, the publisher has nothing to copy into -# the store, and the forwarder's export is a 401. -# -# Gated on authelia being HERE, not on this host running the log store: a -# client is a row in THIS host's provider config, the split -# ./glue-swarm-bao-otel-oidc-client.nix makes for the same reason. -{ - lib, - config, - ... -}: -let - hyperhiveCfg = config.services.hyperhive; - clientId = hyperhiveCfg.swarm.victorialogs.otel.clientId; -in -{ - config = lib.mkIf hyperhiveCfg.deploy.authelia.enable { - services.hyperhive.swarm.authelia.oidc.clients = [ - { - id = clientId; - description = "HyperHive log store journal forwarder"; - kind = "machine"; - redirectUris = [ ]; - # Its own id as its own permitted audience, the one the swarm - # collector's receiver for this container checks. - audience = [ clientId ]; - # The receiver verifies the token offline against `/jwks.json`; - # authelia's default opaque handle fails there. - accessTokenSignedResponseAlg = "RS256"; - } - ]; - }; -} diff --git a/nix/host-modules/k8s/node.nix b/nix/host-modules/k8s/node.nix index a5981d748..b6f8b54e0 100644 --- a/nix/host-modules/k8s/node.nix +++ b/nix/host-modules/k8s/node.nix @@ -129,13 +129,14 @@ let "claude-login" "nats" "swarm-controller" + "victorialogs" ]; enabledServices = lib.filter (name: deployCfg.${name}.enable) swarmServices; # The services whose data the module keeps in the cluster. Each puts its state # label on this node. stateful = lib.filterAttrs (_: svc: svc.enable) { - inherit (deployCfg) nats ci-metrics; + inherit (deployCfg) nats ci-metrics victorialogs; }; in { @@ -264,7 +265,7 @@ in none of those pods. - `hyperhive.darkest.space/state-` for each service whose data the - cluster keeps: `nats` and `ci-metrics`, each when enabled. A volume's `nodeAffinity` and the pod's `nodeSelector` name it. + cluster keeps: `nats`, `ci-metrics` and `victorialogs`, each when enabled. A volume's `nodeAffinity` and the pod's `nodeSelector` name it. - `hyperhive.darkest.space/entry`: the node the hosts' DNS points at. - `svccontroller.k3s.cattle.io/enablelb`: with it on any node, the service load balancer binds a published port on the labelled nodes diff --git a/nix/host-modules/k8s/render.nix b/nix/host-modules/k8s/render.nix index 5e0dc1b7e..0a0e6ecbc 100644 --- a/nix/host-modules/k8s/render.nix +++ b/nix/host-modules/k8s/render.nix @@ -125,19 +125,21 @@ let ]; }; - # The swarm services that run in the cluster. `unit` is the evaluated - # systemd unit the host runs today; nothing reads it unless `enable` holds. + # The swarm services that run in the cluster. `unit` is an evaluated systemd + # unit, or the `serviceConfig`, `environment` and `path` of one; nothing reads + # it unless `enable` holds. # `healthEnv` names the variable that binds the daemon's /healthz and # /readyz listener. `publicCredentials` maps the ids of the credentials that # hold a public CA file to their key in the CA ConfigMap, and `publicFiles` # the paths the unit names that hold one to theirs. `listener`, where a - # service has one, is the TCP port a Service publishes in the cluster and the - # directory the pod's init container writes the leaf to. + # service has one, is the TCP port a Service publishes and the directory the + # pod's init container writes the leaf to; without a `tlsDir` it is plain HTTP + # and no leaf is issued. `probe` is the path a service without a `healthEnv` is + # probed on, and `fsGroupChangePolicy` the pod's setting of that name. # `ephemeralState` gives a service an `emptyDir` in place of a claim for its # state directory: what it keeps there is re-derived at start. A pod starts on # whatever volume it gets. - # `otlp` is where the pod pushes - # its telemetry: `"hive"` is the hive collector. A swarm-tier producer is + # `otlp` is where the pod pushes its telemetry: `"hive"` is the hive collector. A swarm-tier producer is # `"own"` and keeps the route its unit names, because the hive collector # stamps the `hive` label on what it forwards and a swarm-level series must # not carry one (../swarm-otel.nix, the swarm tier's own pipeline). @@ -255,6 +257,44 @@ let }; otlp = "own"; }; + # The log store: the VictoriaLogs daemon alone, on a static local volume + # that is the old container's data directory. It holds no store identity + # and pushes no telemetry; its own `/metrics` is scraped through the + # gateway. + swarm-victorialogs = { + inherit (deployCfg.victorialogs) enable package unit; + daemon = "victoria-logs"; + kind = "Deployment"; + healthEnv = null; + probe.path = "/health"; + etcFiles = [ ]; + publicCredentials = { }; + listener.port = deployCfg.victorialogs.servicePort; + localState = { + service = "victorialogs"; + hostDir = deployCfg.victorialogs.hostDataDir; + }; + # The first start gives the pod's group the tree the old container wrote; + # a later one looks at the root only. + fsGroupChangePolicy = "OnRootMismatch"; + otlp = "none"; + }; + # The two `auth_request` responders of the log store's gateway vhost, which + # log in to the store under one role. They keep no state, so they run on any + # node. The Grafana responder is the second container of the pod, in `pod`. + swarm-logs-auth = { + inherit (deployCfg.victorialogs) enable; + package = deployCfg.victorialogs.authPackage; + unit = deployCfg.victorialogs.authUnit; + inherit (deployCfg.victorialogs) pod; + kind = "Deployment"; + healthEnv = "SWARM_LOGS_AUTH_HEALTH_ADDR"; + etcFiles = [ ]; + publicCredentials."bao-ca.pem" = baoServerCaKey; + listener.port = deployCfg.victorialogs.authServicePort; + egress = [ "store" ]; + otlp = "none"; + }; }; # Where a pod pushes telemetry. A `"hive"` service pushes to the hive @@ -508,6 +548,9 @@ let sc = unit.serviceConfig; listener = svc.listener or { }; + # A listener with a `tlsDir` serves TLS with a leaf the pod issues; one + # without serves plain HTTP, for a caller that is the node. + listenerTls = listener ? tlsDir; publicFiles = svc.publicFiles or { }; daemon = svc.daemon or name; baoRole = svc.baoRole or name; @@ -594,7 +637,7 @@ let ++ lib.optional (runtimeDir != null) runtimeDir ++ lib.optional (stateDir != null) stateDir ++ lib.attrNames publicFiles - ++ lib.optional (listener != { }) listener.tlsDir + ++ lib.optional listenerTls listener.tlsDir ++ map (f: "/etc/${f}") svc.etcFiles; under = root: v: v == root || lib.hasPrefix "${root}/" v; unmounted = lib.filterAttrs (_: v: lib.hasPrefix "/" v && !(lib.any (r: under r v) mountRoots)) env; @@ -690,7 +733,7 @@ let name = "ca-trust"; configMap.name = caConfigMap; } - ++ lib.optional (listener != { }) { + ++ lib.optional listenerTls { name = "tls"; # In memory: the leaf's key never reaches the node's disk. emptyDir.medium = "Memory"; @@ -745,7 +788,7 @@ let subPath = publicFiles.${path}; readOnly = true; }) (lib.attrNames publicFiles) - ++ lib.optional (listener != { }) tlsMount + ++ lib.optional listenerTls tlsMount ++ lib.optional (runtimeDir != null) { name = "runtime"; mountPath = runtimeDir; @@ -824,6 +867,24 @@ let } // lib.optionalAttrs (lib.tail execWords != [ ]) { args = lib.tail execWords; } // lib.optionalAttrs (ports != [ ]) { inherit ports; } + # A daemon that has no health variable of ours (a third-party one) is + # probed on one path of its listener. + // lib.optionalAttrs (svc ? probe) { + livenessProbe = { + httpGet = { + inherit (svc.probe) path; + port = "api"; + }; + periodSeconds = 10; + }; + readinessProbe = { + httpGet = { + inherit (svc.probe) path; + port = "api"; + }; + periodSeconds = 10; + }; + } // lib.optionalAttrs (svc.healthEnv != null) { livenessProbe = { httpGet = { @@ -906,7 +967,7 @@ let containers = [ container ] - ++ lib.optional (listener != { }) ( + ++ lib.optional listenerTls ( leafContainer // { name = "tls-renew"; @@ -923,15 +984,16 @@ let runAsGroup = serviceUser.gid; fsGroup = serviceUser.gid; seccompProfile.type = "RuntimeDefault"; - }; + } + // lib.optionalAttrs (svc ? fsGroupChangePolicy) { inherit (svc) fsGroupChangePolicy; }; } // lib.optionalAttrs baoLogin { serviceAccountName = name; } // lib.optionalAttrs (svc ? hostUsers && !svc.hostUsers) { hostUsers = false; } // lib.optionalAttrs (localState != null) { nodeSelector = labels.stateSelector localState.service; } - // lib.optionalAttrs (listener != { } || extra.initContainers != [ ]) { - initContainers = lib.optional (listener != { }) leafContainer ++ extra.initContainers; + // lib.optionalAttrs (listenerTls || extra.initContainers != [ ]) { + initContainers = lib.optional listenerTls leafContainer ++ extra.initContainers; } // lib.optionalAttrs (extra.hostAliases != [ ]) { inherit (extra) hostAliases; } // extra.podSpec; @@ -1007,7 +1069,13 @@ let // lib.optionalAttrs (svc ? egress) { "${name}/networkpolicy" = networkPolicyOf name svc.egress; } - // lib.optionalAttrs (listener != { }) (listenerObjects name listener) + // lib.optionalAttrs (listener != { }) ( + # A service with an egress policy has the ingress rule in that one. + if svc ? egress then + removeAttrs (listenerObjects name listener) [ "${name}/networkpolicy" ] + else + listenerObjects name listener + ) // lib.optionalAttrs baoLogin { # Named after the service: the store's jwt role binds this account. "${name}/serviceaccount" = { @@ -1063,10 +1131,10 @@ let fail name "the unit names no OTLP endpoint of its own, which the pod would push to" else if svc.healthEnv != null && unitEnv ? ${svc.healthEnv} then fail name "the unit already sets ${svc.healthEnv}" + else if svc ? probe && (listener == { } || svc.healthEnv != null) then + fail name "has a probe and no listener, or a health variable as well" else if svc ? egress && !(lib.all (r: hostPorts ? ${r}) svc.egress) then fail name "egress names a host service the renderer has no port for (${lib.concatStringsSep ", " (lib.attrNames hostPorts)})" - else if svc ? egress && listener != { } then - fail name "has an egress policy and a listener, which would share one NetworkPolicy" else if lib.head execWords != entrypoint then fail name "ExecStart is not ${entrypoint} with plain arguments" else if lib.any (w: lib.hasInfix "\"" w) execWords then @@ -1079,7 +1147,7 @@ let { inherit objects image; # What the pod's other containers run. - extraImages = lib.optional (listener != { }) leafImage ++ extra.images; + extraImages = lib.optional listenerTls leafImage ++ extra.images; }; enabled = lib.mapAttrs workload (lib.filterAttrs (_: svc: svc.enable) services); diff --git a/nix/host-modules/swarm-bao-readers.nix b/nix/host-modules/swarm-bao-readers.nix index 5756a8537..cc4d1b87b 100644 --- a/nix/host-modules/swarm-bao-readers.nix +++ b/nix/host-modules/swarm-bao-readers.nix @@ -158,11 +158,11 @@ let } ]; - # The log store's auth responders: the agent one checks the secret an agent - # presents against the one stored for it (the same `+` leaf as the queue - # responder's) and reads the agent's mirrored `logs`/`metrics` grant, the other checks the bearer Grafana presents against - # Grafana's metrics bearer; and the store container's journal forwarder - # reads its own client secret under the same leaf. Nothing else. + # The log store's auth responders, which run in one pod under one role: the + # agent one checks the secret an agent presents against the one stored for it + # (the same `+` leaf as the queue responder's) and reads the agent's mirrored + # `logs`/`metrics` grant, the other checks the bearer Grafana presents against + # Grafana's metrics bearer. Nothing else. logsAuthReaders = [ { name = "swarm-logs-auth"; @@ -171,9 +171,7 @@ let policyText = readStanza "${credentialMountPath}/data/swarm/agents/+/queue" + readStanza "${credentialMountPath}/data/swarm/agents/+/observability" - + readStanza "${credentialMountPath}/data/${grafanaMetricsBearerLeaf}" - # The journal forwarder in the store's container, under this same leaf. - + readStanza "${credentialMountPath}/data/swarm/services/${hyperhiveCfg.swarm.victorialogs.otel.clientId}/oidc/client"; + + readStanza "${credentialMountPath}/data/${grafanaMetricsBearerLeaf}"; } ]; @@ -418,6 +416,9 @@ let ++ reviewClassifierReaders ++ claudeLoginWriters ++ ciMetricsReaders + # The log store's two responders hold one role, under the ServiceAccount of + # their pod (./k8s/render.nix, `swarm-logs-auth`). + ++ logsAuthReaders ++ [ { name = controllerPolicyName; } ] # The queue's pod holds both of its roles under one ServiceAccount: the # server's leaf is issued with `swarm-nats`, and the responder reads its diff --git a/nix/host-modules/swarm-otel-service.nix b/nix/host-modules/swarm-otel-service.nix index f389714c7..c3b499eb7 100644 --- a/nix/host-modules/swarm-otel-service.nix +++ b/nix/host-modules/swarm-otel-service.nix @@ -242,9 +242,8 @@ in swarm-stt = { clientId = hyperhiveCfg.swarm.stt.clientId; }; - # The forwarders in ./swarm-attic.nix, ./swarm-ci-runner.nix, - # ./swarm-grafana.nix and ./swarm-victorialogs.nix, each authenticated as a - # client of its own. + # The forwarders in ./swarm-attic.nix, ./swarm-ci-runner.nix and + # ./swarm-grafana.nix, each authenticated as a client of its own. swarm-attic = { clientId = hyperhiveCfg.swarm.attic.otel.clientId; }; @@ -254,9 +253,6 @@ in swarm-grafana = { clientId = hyperhiveCfg.swarm.grafana.otel.clientId; }; - swarm-victorialogs = { - clientId = hyperhiveCfg.swarm.victorialogs.otel.clientId; - }; # The forwarders in ./hive-forge/default.nix and ./hive-matrix.nix, each # authenticated as a client of its own. hive-forge = { diff --git a/nix/host-modules/swarm-otel.nix b/nix/host-modules/swarm-otel.nix index ec90b1f40..092fe21fc 100644 --- a/nix/host-modules/swarm-otel.nix +++ b/nix/host-modules/swarm-otel.nix @@ -250,8 +250,8 @@ let # Every container with a `serviceProducers` entry (`swarm-bao`, `swarm-nats`, # `swarm-builder`, `swarm-claude-login`, `swarm-notify-router`, # `swarm-review-classifier`, `swarm-ci-runner`, `swarm-grafana`, - # `swarm-victorialogs`, `hive-forge`, `hive-matrix`, `swarm-victoriametrics`, - # `swarm-authelia`, `swarm-attic`) forwards its own + # `hive-forge`, `hive-matrix`, `swarm-victoriametrics`, `swarm-authelia`, + # `swarm-attic`) forwards its own # journal from its own collector, so this receiver never sees their units. hostJournalDir = "/var/log/journal"; hostJournalMount = "/run/host-journal"; diff --git a/nix/host-modules/swarm-secret-publisher.nix b/nix/host-modules/swarm-secret-publisher.nix index 3f53e42f3..a23c21374 100644 --- a/nix/host-modules/swarm-secret-publisher.nix +++ b/nix/host-modules/swarm-secret-publisher.nix @@ -55,13 +55,12 @@ let hyperhiveCfg.swarm.notify-router.clientId # The speech-to-text service, which reads it itself inside its container. hyperhiveCfg.swarm.stt.clientId - # The journal forwarders in the CI runner's, Grafana's, the log store's, - # the cache's, the forge's and the homeserver's containers, each reading it - # inside its container. + # The journal forwarders in the CI runner's, Grafana's, the cache's, the + # forge's and the homeserver's containers, each reading it inside its + # container. hyperhiveCfg.swarm.attic.otel.clientId hyperhiveCfg.swarm.ci-runner.otel.clientId hyperhiveCfg.swarm.grafana.otel.clientId - hyperhiveCfg.swarm.victorialogs.otel.clientId hyperhiveCfg.swarm.forge.otel.clientId hyperhiveCfg.swarm.matrix.otel.clientId # The metrics store container's journal forwarder, whose host reads it. diff --git a/nix/host-modules/swarm-victorialogs-service.nix b/nix/host-modules/swarm-victorialogs-service.nix index 59819b9bf..357c0aec1 100644 --- a/nix/host-modules/swarm-victorialogs-service.nix +++ b/nix/host-modules/swarm-victorialogs-service.nix @@ -1,6 +1,6 @@ -# The swarm's log store as every hive sees it: the name it answers on and its -# port, identical on every host. What the host running it decides, and the -# container itself, are in ./swarm-victorialogs.nix. +# The swarm's log store as every hive sees it: the name it answers on, +# identical on every host. What the host running it decides, and its pods, are +# in ./swarm-victorialogs.nix. { lib, config, @@ -16,37 +16,10 @@ let domainBase = if swarmDomain == null then "invalid" else swarmDomain; in { - # What the store IS from any hive's point of view: the name it answers on and - # the port. `enable`, `package` and `retentionPeriod` are decisions of the - # host that runs it and live under `deploy.*`. + # What the store IS from any hive's point of view: the name it answers on. + # `enable`, `package` and `retentionPeriod` are decisions of the host that runs + # it and live under `deploy.*`. options.services.hyperhive.swarm.victorialogs = { - machine = lib.mkOption { - type = lib.types.str; - readOnly = true; - default = "swarm-victorialogs"; - description = '' - Container name. Read-only: the name appears in host paths and in - `machinectl`, so it is a fact other modules may read rather than a - knob. - ''; - }; - - otel.clientId = lib.mkOption { - type = lib.types.str; - readOnly = true; - default = "swarm-victorialogs-collector"; - description = '' - OAuth2 client id the journal forwarder inside the log store's - container authenticates as, and the audience it asks its token for. - - Read-only because three hosts have to agree on it: authelia - registers the client (`glue-victorialogs-otel-oidc-client.nix`), - the swarm collector admits it on the container's receiver - (`swarm.otel.serviceProducers`), and authelia's mint stores - its secret in the store. - ''; - }; - domain = lib.mkOption { type = lib.types.str; default = "logs.${domainBase}"; @@ -61,6 +34,5 @@ in registered for that to actually happen. ''; }; - }; } diff --git a/nix/host-modules/swarm-victorialogs.nix b/nix/host-modules/swarm-victorialogs.nix index 4ef88a29a..dbe758c95 100644 --- a/nix/host-modules/swarm-victorialogs.nix +++ b/nix/host-modules/swarm-victorialogs.nix @@ -1,5 +1,6 @@ -# The swarm's log store: one VictoriaLogs for the whole swarm, in a -# `swarm-victorialogs` nixos-container beside the metrics store it mirrors. +# The swarm's log store: one VictoriaLogs for the whole swarm and the gateway's +# `auth_request` responders for it, each a pod in the host's cluster +# (./k8s/render.nix, docs/4-implementation/k8s/runtime.md). # # Why a store at all rather than reading journals directly: an agent can # verify that a unit was *launched* and never that it is *working*. The @@ -14,13 +15,12 @@ # Gateway vhost is authenticated, unlike the metrics store's: an operator # reaches this at `https://${cfg.domain}/` gated by the same `auth_request` # check against authelia that swarm-ui's own vhost uses (`swarmAuthRequest` -# below, same shape as `swarm-ui.nix`'s) — see that file's copy for the full -# rationale (forceSSL is load-bearing there too: authelia answers a plain-http -# auth subrequest with 400, which `auth_request` cannot interpret as anything -# but a broken check). The store's own listener is a unix socket in a -# netns of its own and is unauthenticated, and the vhost is the ONLY way in: the -# collector pushes through it too, at its own `= /insert/...` location, because -# a swarm has one log store and the collector need not share a host with it. +# 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. # ⚠️ 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. @@ -40,6 +40,8 @@ let networkCfg = config.services.hyperhive.network; hyperhiveCfg = config.services.hyperhive; gatewayCfg = hyperhiveCfg.gateway; + k8sCfg = hyperhiveCfg.k8s; + inherit (import ../images { inherit pkgs lib; }) mkServiceImage; # Copy of `swarm-ui.nix`'s own `swarmAuthRequest` — not shared code because # this vhost needs exactly the two locations that reference it (`/` and the @@ -75,74 +77,192 @@ let proxy_ignore_headers Cache-Control Expires Set-Cookie Vary; ''; - # The agents' `auth_request` responder (`swarm-logs-auth`). Its socket's - # directory holds that socket alone and is traverse-only for others, the - # shape `swarm-controller.nix` gives its own. - logsAuthUnit = "swarm-logs-auth"; - logsAuthSocket = "/run/${logsAuthUnit}/auth.sock"; - logsAuthCredential = id: "/run/credentials/${logsAuthUnit}.service/${id}"; - # Credential id → host path of the responder's store identity. - logsAuthStoreFiles = { - "bao-client.pem" = deployCfg.victorialogs.authBaoClientCertFile; - "bao-client-key.pem" = deployCfg.victorialogs.authBaoClientKeyFile; - } - // lib.optionalAttrs (deployCfg.bao.serverCaFile != null) { - "bao-ca.pem" = deployCfg.bao.serverCaFile; - }; + # The store identity the responders' units name by credential id: the pod + # logs in with its ServiceAccount token instead, and mounts the CA file. + logsAuthStoreIds = [ + "bao-client.pem" + "bao-client-key.pem" + ] + ++ lib.optional (deployCfg.bao.serverCaFile != null) "bao-ca.pem"; baoCfg = hyperhiveCfg.swarm.bao; # Grafana's bearer, checked by a second `swarm-metrics-auth` instance. It # reads the store with the same leaf as `swarm-logs-auth`, which is granted # the one extra path below. The same leaf as `grafanaBearerStorePath` in # ./swarm-victoriametrics.nix and `grafanaMetricsBearerLeaf` in ./swarm-bao.nix. - grafanaAuthUnit = "swarm-logs-grafana-auth"; - grafanaAuthSocket = "/run/${grafanaAuthUnit}/auth.sock"; - grafanaAuthCredential = id: "/run/credentials/${grafanaAuthUnit}.service/${id}"; grafanaBearerStorePath = "swarm/services/${hyperhiveCfg.swarm.grafana.oidc.clientId}/metrics/bearer"; - # A netns of its own on the hive bridge, as the cache's container has - # (./swarm-attic.nix): the forwarder below dials the swarm collector, authelia - # and the store by name, so the container keeps an interface and the bridge's - # resolver. The store listens on a unix socket only, so no host port is - # bound. Grafana reaches the store by its domain through the gateway. - privateNetwork = true; + # 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 + # dials. `legacyContainer` is the name of the container the store ran in + # before it ran in the cluster, whose data directory the volume is. + storeService = "swarm-victorialogs"; + authService = "swarm-logs-auth"; + grafanaAuthService = "swarm-logs-grafana-auth"; + legacyContainer = "swarm-victorialogs"; + storePort = 9428; + authPort = 8081; + grafanaAuthPort = 8082; + # The Grafana responder's own `/healthz` and `/readyz`, beside the logs + # responder's on 8080 in the same pod. + grafanaAuthHealthPort = 8083; + dataDir = "/var/lib/victorialogs"; + hostDataDir = "/var/lib/nixos-containers/${legacyContainer}${dataDir}"; - # The unix socket the gateway's nginx connects to. The directory's mode is - # what keeps it private, so it holds this one socket. - socketDir = "/run/swarm-victorialogs"; - socketPath = "${socketDir}/victorialogs.sock"; - socketGroup = "gateway-nginx"; - # Only the number crosses into the container, which knows the group by name. - nginxGid = config.ids.gids.nginx; - # The upstream every location below forwards to. A location that adds a path - # writes `:`; one with no path leaves the request's own. - upstream = "http://unix:${socketPath}"; + serviceHost = service: "${service}.${k8sCfg.namespace}.svc.${deployCfg.k8s.clusterDomain}"; - # The container's journal forwarder pushes to its own receiver on the swarm - # collector, the route `serviceProducers.swarm-victorialogs` in - # ./swarm-otel-service.nix declares. - forwarderClientId = cfg.otel.clientId; - forwarderEndpoint = "https://${hyperhiveCfg.swarm.otel.domain}/${cfg.machine}"; - forwarderUnit = "swarm-journal-forwarder-oidc"; - # Loopback, in the container's own netns. - forwarderTelemetryPort = 8897; - forwarderCredential = id: "/run/credentials/${forwarderUnit}.service/${id}"; - # The responder's store identity, handed into the container as system - # credentials for the forwarder's fetch unit. The host units keep reading - # the same files. - forwarderStoreFiles = lib.filterAttrs (_: source: source != null) logsAuthStoreFiles; - # nixos-container expands `extraFlags` unquoted, so a source path must be - # one word. - oneWord = path: builtins.match ".*[[:space:]].*" path == null; + # What a location needs to dial a Service: the host's resolver, which hands + # the cluster's domain to CoreDNS, and the name in a variable, so that nginx + # looks it up per request. A name written into `proxy_pass` gets one lookup + # when the configuration loads, which fails the load while the cluster is + # down. A `proxy_pass` with a variable and a URI part sends that URI and not + # the request's own, so the store's locations write none. Each role has a + # variable of its own, so that an auth subrequest's `set` can never change + # where the request it checks is sent. + viaService = variable: service: port: '' + resolver ${networkCfg.bridgeIp} valid=10s ipv6=off; + set ${variable} ${serviceHost service}:${toString port}; + ''; + storeVariable = "$swarm_logs_store_upstream"; + upstream = "http://${storeVariable}"; + agentAuthVariable = "$swarm_logs_agent_auth_upstream"; + grafanaAuthVariable = "$swarm_logs_grafana_auth_upstream"; - rootfsCheck = import ./lib/container-rootfs-check.nix { inherit config; }; - - # The forwarder reaches the swarm collector and authelia by name over TLS; in - # self-signed mode their leaves chain to the hive CA. - caTrust = import ./lib/hive-ca-trust.nix { - inherit lib gatewayCfg; - tlsCfg = deployCfg.hive-controller.tls; + # The store's unit: the daemon, its flags and its state directory, which is + # all the pod is rendered from. Nothing evaluates a systemd unit for it. + storeUnit = { + serviceConfig = { + ExecStart = lib.concatStringsSep " " [ + "${deployCfg.victorialogs.package}/bin/victoria-logs" + "-storageDataPath=${dataDir}" + "-httpListenAddr=:${toString storePort}" + "-retentionPeriod=${deployCfg.victorialogs.retentionPeriod}" + ]; + StateDirectory = "victorialogs"; + }; + environment = { }; + path = [ ]; }; + + # The agents' `auth_request` responder, with the cert and key ids that the + # pod's login drops. + authCredential = id: "/run/credentials/${authService}.service/${id}"; + authUnit = { + serviceConfig = { + ExecStart = lib.concatStringsSep " " [ + "${deployCfg.victorialogs.authPackage}/bin/swarm-logs-auth" + "--listen 0.0.0.0:${toString authPort}" + # The role ./swarm-bao.nix writes on the store's `cert` mount. + "--store-cert-role swarm-logs-auth" + "--surface logs" + "--verdict-ttl ${toString deployCfg.victorialogs.authVerdictTtl}" + ]; + LoadCredential = logsAuthStoreIds; + }; + environment = { + BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; + BAO_CLIENT_CERT = authCredential "bao-client.pem"; + BAO_CLIENT_KEY = authCredential "bao-client-key.pem"; + } + // lib.optionalAttrs (builtins.elem "bao-ca.pem" logsAuthStoreIds) { + BAO_CACERT = authCredential "bao-ca.pem"; + }; + path = [ ]; + }; + + # What the responders' pod holds besides `swarm-logs-auth`: Grafana's + # responder, the metrics store's binary pointed at the bearer Grafana's + # datasources share. It logs in under the pod's one ServiceAccount, with the + # environment and mounts of the first container. + authPod = + { + env, + volumeMounts, + metaFor, + securityContext, + }: + let + image = mkServiceImage { + name = grafanaAuthService; + package = deployCfg.victorialogs.grafanaAuthPackage; + bin = "swarm-metrics-auth"; + }; + probe = path: { + httpGet = { + inherit path; + port = "health"; + }; + periodSeconds = 10; + }; + in + { + containers = [ + { + name = "grafana-auth"; + image = "${image.imageName}:${image.imageTag}"; + imagePullPolicy = "IfNotPresent"; + args = [ + "--listen" + "0.0.0.0:${toString grafanaAuthPort}" + "--store-cert-role" + "swarm-logs-auth" + "--store-path" + grafanaBearerStorePath + ]; + env = lib.mapAttrsToList (name: value: { inherit name value; }) ( + lib.filterAttrs (n: _: lib.hasPrefix "BAO_" n) env + // { + SWARM_METRICS_AUTH_HEALTH_ADDR = "0.0.0.0:${toString grafanaAuthHealthPort}"; + } + ); + ports = [ + { + name = "api"; + containerPort = grafanaAuthPort; + } + { + name = "health"; + containerPort = grafanaAuthHealthPort; + } + ]; + livenessProbe = probe "/healthz"; + readinessProbe = probe "/readyz"; + volumeMounts = lib.filter ( + m: + lib.elem m.name [ + "credentials" + "bao-token" + "tmp" + ] + ) volumeMounts; + inherit securityContext; + } + ]; + + # The pod's policy, from ./k8s/render.nix, covers this port too: only the + # node reaches it. + objects."${grafanaAuthService}/service" = { + apiVersion = "v1"; + kind = "Service"; + metadata = metaFor authService // { + name = grafanaAuthService; + }; + spec = { + type = "ClusterIP"; + selector = (metaFor authService).labels; + ports = [ + { + name = "api"; + protocol = "TCP"; + port = grafanaAuthPort; + targetPort = "api"; + } + ]; + }; + }; + + images = [ image ]; + }; in { # What the store IS from any hive's point of view, the name it answers on, is @@ -151,10 +271,10 @@ in # runs it and live under `deploy.*`. # Retention is a property of the store this host runs, not something the - # swarm has to agree on: it is read only where the container is defined, - # and a hive that is a *client* of the log store never consults it. That - # makes it a `deploy.*` value by the same rule as the seal on the secret - # store — options on the auto-deployed service itself. + # swarm has to agree on: it is read only where the pod is defined, and a hive + # that is a *client* of the log store never consults it. That makes it a + # `deploy.*` value by the same rule as the seal on the secret store — + # options on the auto-deployed service itself. options.services.hyperhive.deploy.victorialogs.package = lib.mkOption { type = lib.types.package; default = pkgs.victorialogs; @@ -271,6 +391,68 @@ in ''; }; + options.services.hyperhive.deploy.victorialogs.unit = lib.mkOption { + type = lib.types.raw; + readOnly = true; + internal = true; + default = storeUnit; + description = '' + The store's unit, the `serviceConfig`, `environment` and `path` that + ../host-modules/k8s/render.nix renders its pod from. + ''; + }; + + options.services.hyperhive.deploy.victorialogs.authUnit = lib.mkOption { + type = lib.types.raw; + readOnly = true; + internal = true; + default = authUnit; + description = '' + The agents' responder's unit, which the first container of the + responders' pod is rendered from. + ''; + }; + + options.services.hyperhive.deploy.victorialogs.pod = lib.mkOption { + type = lib.types.raw; + readOnly = true; + internal = true; + default = authPod; + description = '' + What the responders' pod holds besides the agents' responder: a function + of that container that ../host-modules/k8s/render.nix calls, giving + Grafana's responder, its Service and its image. + ''; + }; + + options.services.hyperhive.deploy.victorialogs.servicePort = lib.mkOption { + type = lib.types.port; + readOnly = true; + internal = true; + default = storePort; + description = "The port the store's Service publishes."; + }; + + options.services.hyperhive.deploy.victorialogs.authServicePort = lib.mkOption { + type = lib.types.port; + readOnly = true; + internal = true; + default = authPort; + description = "The port the agents' responder's Service publishes."; + }; + + options.services.hyperhive.deploy.victorialogs.hostDataDir = lib.mkOption { + type = lib.types.str; + readOnly = true; + internal = true; + default = hostDataDir; + description = '' + The store's data directory on the host, which the pod's volume is: the + directory of the container the store ran in. A host that never ran it gets + the directory made. + ''; + }; + config = lib.mkIf deployCfg.victorialogs.enable { assertions = [ { @@ -289,37 +471,6 @@ in both options. ''; } - { - assertion = lib.all oneWord (lib.attrValues forwarderStoreFiles); - message = '' - The log store responder's store identity paths must not contain - whitespace: nspawn's --load-credential receives them through - nixos-container's unquoted extra flags. - ''; - } - { - assertion = - (hyperhiveCfg.swarm.otel.serviceProducers.${cfg.machine}.clientId or null) == forwarderClientId; - message = '' - services.hyperhive.swarm.otel.serviceProducers has no entry - "${cfg.machine}" with clientId "${forwarderClientId}", so the swarm - collector has no receiver for the log store's journal forwarder. - Declare it in swarm-otel-service.nix. - ''; - } - ]; - - # nspawn fails to start the container when a credential source is - # missing, so where this host mints the leaf the container pulls the - # minting unit in and waits for it, as ./swarm-builder.nix's does. The CA - # ordering keeps the trust bundle's bind source there first. - systemd.services."container@${cfg.machine}" = lib.mkMerge [ - caTrust.containerOrdering - (rootfsCheck.warnOnly cfg.machine) - { - after = [ "swarm-bao-pki.service" ]; - wants = [ "swarm-bao-pki.service" ]; - } ]; # Which check a `/select/logsql/` request gets. `auth_request` takes a @@ -353,14 +504,14 @@ in # `swarm-victoriametrics.nix`). services.hyperhive.gateway.localNames = [ cfg.domain ]; - # This host serves the vhost, and the container behind it resolves + # This host serves the vhost and resolves the cluster's names for it # through the hive's dnsmasq. services.hyperhive.gateway.enable = lib.mkDefault true; services.hyperhive.gateway.dns.enable = lib.mkDefault true; - # Authenticated front door onto the store's socket — see the - # file-top comment for why this is safe to add without touching the - # store's own (still unauthenticated, socket-only) listener at all. + # 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. # `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 @@ -370,8 +521,8 @@ in forceSSL = true; locations = { "/" = { - proxyPass = "${upstream}:/"; - extraConfig = swarmAuthRequest; + proxyPass = upstream; + extraConfig = viaService storeVariable storeService storePort + swarmAuthRequest; }; # The swarm collector's ingest route. `=` so it outranks the `/` @@ -389,8 +540,9 @@ in # note on `swarmAuthRequest` above), so naming it here is required # rather than redundant. "= /insert/opentelemetry/v1/logs" = { - proxyPass = "${upstream}:/insert/opentelemetry/v1/logs"; + proxyPass = upstream; extraConfig = '' + ${viaService storeVariable storeService storePort} auth_request /__swarm_logs_ingest_authz; ''; }; @@ -425,6 +577,7 @@ in # the store as the caller sent them. proxyPass = upstream; extraConfig = '' + ${viaService storeVariable storeService storePort} auth_request /__swarm_logs_auth; ''; }; @@ -440,8 +593,9 @@ in # authelia's rules for this URL admit the collector's client and # deny every other subject (see `metricsRules` in ./swarm-authelia.nix). "= /metrics" = { - proxyPass = "${upstream}:/metrics"; + proxyPass = upstream; extraConfig = '' + ${viaService storeVariable storeService storePort} auth_request /__hive_authelia; ''; }; @@ -463,8 +617,9 @@ in # statuses `auth_request` passes through are 401 and 403, and # `swarm-logs` retries a 401. "= /__swarm_logs_agent_auth" = { - proxyPass = "http://unix:${logsAuthSocket}:/"; + proxyPass = "http://${agentAuthVariable}/"; extraConfig = '' + ${viaService agentAuthVariable authService authPort} internal; limit_req zone=swarm_logs_agent_auth burst=${toString deployCfg.victorialogs.authBurst} nodelay; limit_req_status 403; @@ -477,8 +632,9 @@ in # `swarm-metrics-auth`. The responder reads the store at most once per # its cache TTL whatever the bearers, so no rate limit sits in front. "= /__swarm_logs_grafana_auth" = { - proxyPass = "http://unix:${grafanaAuthSocket}:/"; + proxyPass = "http://${grafanaAuthVariable}/"; extraConfig = '' + ${viaService grafanaAuthVariable grafanaAuthService grafanaAuthPort} internal; proxy_pass_request_body off; proxy_set_header Content-Length ""; @@ -529,241 +685,14 @@ in }; }; - # The agents' check on `/select/logsql/`. On the host rather than in the - # store's container: it needs nothing of the store, only nginx's reach to - # its socket and its own store identity. - users.users.${logsAuthUnit} = { - isSystemUser = true; - group = logsAuthUnit; - description = "swarm log store auth_request responder"; - }; - users.groups.${logsAuthUnit} = { }; + # The store's volume is its old container's data directory, which a host + # that never ran the container does not have. The rule leaves an existing + # directory's owner and mode alone: the pod's group is given the tree when + # it starts. + systemd.tmpfiles.rules = [ "d ${hostDataDir} - - - -" ]; - systemd.services.${logsAuthUnit} = { - description = "swarm log store auth_request responder for agent credentials"; - wantedBy = [ "multi-user.target" ]; - # Where the store's PKI is minted on this host, the leaf is one of its - # files. Ordering only: elsewhere the unit does not exist. - after = [ - "network.target" - "swarm-bao-pki.service" - ]; - serviceConfig = { - ExecStart = lib.concatStringsSep " " [ - "${deployCfg.victorialogs.authPackage}/bin/swarm-logs-auth" - "--socket ${logsAuthSocket}" - # The role ./swarm-bao.nix writes on the store's `cert` mount. - "--store-cert-role swarm-logs-auth" - "--surface logs" - "--verdict-ttl ${toString deployCfg.victorialogs.authVerdictTtl}" - ]; - # Paths only: `argv` is world-readable via /proc//cmdline. - LoadCredential = lib.mapAttrsToList (id: path: "${id}:${path}") logsAuthStoreFiles; - # ⚠️ A static user, never `DynamicUser`: with `RuntimeDirectoryPreserve` - # systemd puts a dynamic user's runtime directory under - # `/run/private/` (0700 root:root), which nginx cannot traverse. - User = logsAuthUnit; - Group = logsAuthUnit; - RuntimeDirectory = logsAuthUnit; - # Traverse-only for others, so nginx reaches the socket path. - RuntimeDirectoryMode = "0751"; - # The path never vanishes from under a running nginx; the responder - # unlinks a stale socket as it starts. - RuntimeDirectoryPreserve = "yes"; - Restart = "on-failure"; - RestartSec = "5s"; - SyslogIdentifier = logsAuthUnit; - ProtectSystem = "strict"; - ProtectHome = true; - PrivateTmp = "disconnected"; - PrivateDevices = true; - NoNewPrivileges = true; - RestrictSUIDSGID = true; - RemoveIPC = true; - }; - environment = { - BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; - BAO_CLIENT_CERT = logsAuthCredential "bao-client.pem"; - BAO_CLIENT_KEY = logsAuthCredential "bao-client-key.pem"; - } - // lib.optionalAttrs (logsAuthStoreFiles ? "bao-ca.pem") { - BAO_CACERT = logsAuthCredential "bao-ca.pem"; - }; - }; - - # Grafana's check on `/select/logsql/`: the metrics store's responder - # binary, pointed at the bearer Grafana's datasources share. - users.users.${grafanaAuthUnit} = { - isSystemUser = true; - group = grafanaAuthUnit; - description = "swarm log store auth_request responder for Grafana's bearer"; - }; - users.groups.${grafanaAuthUnit} = { }; - - systemd.services.${grafanaAuthUnit} = { - description = "swarm log store auth_request responder for Grafana's bearer"; - wantedBy = [ "multi-user.target" ]; - after = [ - "network.target" - "swarm-bao-pki.service" - ]; - serviceConfig = { - ExecStart = lib.concatStringsSep " " [ - "${deployCfg.victorialogs.grafanaAuthPackage}/bin/swarm-metrics-auth" - "--socket ${grafanaAuthSocket}" - "--store-cert-role swarm-logs-auth" - "--store-path ${grafanaBearerStorePath}" - ]; - LoadCredential = lib.mapAttrsToList (id: path: "${id}:${path}") logsAuthStoreFiles; - # ⚠️ A static user, never `DynamicUser`: see the `swarm-logs-auth` unit above. - User = grafanaAuthUnit; - Group = grafanaAuthUnit; - RuntimeDirectory = grafanaAuthUnit; - RuntimeDirectoryMode = "0751"; - RuntimeDirectoryPreserve = "yes"; - Restart = "on-failure"; - RestartSec = "5s"; - SyslogIdentifier = grafanaAuthUnit; - ProtectSystem = "strict"; - ProtectHome = true; - PrivateTmp = "disconnected"; - PrivateDevices = true; - NoNewPrivileges = true; - RestrictSUIDSGID = true; - RemoveIPC = true; - }; - environment = { - BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; - BAO_CLIENT_CERT = grafanaAuthCredential "bao-client.pem"; - BAO_CLIENT_KEY = grafanaAuthCredential "bao-client-key.pem"; - } - // lib.optionalAttrs (logsAuthStoreFiles ? "bao-ca.pem") { - BAO_CACERT = grafanaAuthCredential "bao-ca.pem"; - }; - }; - - # The socket directory is the gateway's way in: its group is nginx's. - systemd.tmpfiles.rules = [ "d ${socketDir} 0770 root ${toString nginxGid} - -" ]; - - # The hive bridge carries the container's DHCP lease and its resolver. + # The pods reach the secret store through the hive bridge. services.hyperhive.network.enable = lib.mkDefault true; - - containers.${cfg.machine} = { - autoStart = true; - ephemeral = false; - # No `--link-journal=host`: the journal stays in the guest, where the - # container's own forwarder reads it (../container-modules/swarm-journal-forwarder.nix). - extraFlags = lib.mapAttrsToList ( - id: source: "--load-credential=${id}:${source}" - ) forwarderStoreFiles; - inherit privateNetwork; - hostBridge = networkCfg.bridgeName; - # A bind mount, not a path both sides know: a container's `/run` is an - # nspawn tmpfs the host cannot see into. Connecting to a socket is a - # write to it. - bindMounts = { - ${socketDir} = { - hostPath = socketDir; - isReadOnly = false; - }; - } - // caTrust.bindMount; - - config = - { pkgs, ... }: - { - imports = [ - ../container-modules/swarm-container.nix - ../container-modules/swarm-journal-forwarder.nix - (import ../container-modules/swarm-container-resolver.nix { - inherit (networkCfg) bridgeIp; - # The forwarder and its secret fetch dial the swarm collector, - # authelia and the store by name too. - dnsConsumers = [ - "victorialogs.service" - "opentelemetry-collector.service" - "${forwarderUnit}.service" - ]; - }) - # Go: `SSL_CERT_FILE` replaces its trust store, for the swarm - # collector's and authelia's names. - (caTrust.trustBundle { - inherit pkgs; - name = cfg.machine; - consumers = [ "opentelemetry-collector" ]; - }) - ]; - - services.hyperhive.swarmContainer = { inherit privateNetwork; }; - - # The bridge address comes from the gateway's DHCP. `swarm-bridge-dns` - # owns resolv.conf, so dhcpcd must not write it over that unit. - networking.interfaces.eth0.useDHCP = true; - networking.dhcpcd.extraConfig = "nohook resolv.conf"; - - # The socket's group is the store's primary group, so that group is - # nginx's gid. A static user, not nixpkgs' DynamicUser: a dynamic - # user's group is allocated per start, and nginx is never in it. - users.groups.${socketGroup}.gid = nginxGid; - users.users.victorialogs = { - isSystemUser = true; - group = socketGroup; - }; - systemd.services.victorialogs = { - serviceConfig = { - DynamicUser = lib.mkForce false; - User = "victorialogs"; - Group = socketGroup; - # The store creates its socket under the process umask, so `0007` - # makes it `0770` and nginx's group can connect. - UMask = "0007"; - }; - # nixpkgs' readiness loop curls a TCP URL, which no `unix:` address - # answers. - postStart = lib.mkForce '' - until ${lib.getExe pkgs.curl} -s -o /dev/null --unix-socket ${socketPath} http://localhost/ping; do - sleep 1; - done - ''; - }; - - # Authenticated as the forwarder's own OIDC client, with the - # responder's store identity: one identity for the whole container. - # It is a system credential, so the fetch unit loads it. - services.hyperhive.swarmJournalForwarder = { - enable = true; - serviceName = "victorialogs"; - endpoint = forwarderEndpoint; - clientId = forwarderClientId; - tokenUrl = "${toString hyperhiveCfg.swarm.authelia.url}/api/oidc/token"; - telemetryPort = forwarderTelemetryPort; - store = { - package = deployCfg.bao.package; - addr = "https://${baoCfg.domain}:${toString baoCfg.port}"; - secretPath = "secret/swarm/services/${forwarderClientId}/oidc/client"; - clientCertFile = forwarderCredential "bao-client.pem"; - clientKeyFile = forwarderCredential "bao-client-key.pem"; - caFile = if forwarderStoreFiles ? "bao-ca.pem" then forwarderCredential "bao-ca.pem" else null; - }; - }; - systemd.services.${forwarderUnit}.serviceConfig.LoadCredential = lib.attrNames forwarderStoreFiles; - - services.victorialogs = { - enable = true; - package = deployCfg.victorialogs.package; - - # ⚠️ A SOCKET, not upstream's default of every interface: this - # endpoint accepts writes as well as reads. Nothing authenticates it - # either — upstream offers one basic-auth pair - # (`-httpAuth.username` / `-httpAuth.password`) and this module sets - # neither. The socket's directory mode is the boundary: only the - # gateway's group can connect. - listenAddress = "unix:${socketPath}"; - - extraOptions = [ "-retentionPeriod=${deployCfg.victorialogs.retentionPeriod}" ]; - }; - }; - }; }; # 🔑 OTLP ingest is served at `/insert/opentelemetry/v1/logs`, measured @@ -780,7 +709,7 @@ in # code is not evidence. # # ⚠️ Like the metrics store's, that endpoint is unauthenticated — which is - # why `listenAddress` above is a socket and why nothing reaches it except - # through the gateway, where the ingest route is authenticated. (This module - # declares a vhost.) + # 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.) } diff --git a/nix/host-modules/swarm-victoriametrics.nix b/nix/host-modules/swarm-victoriametrics.nix index c44cf976a..d31659d96 100644 --- a/nix/host-modules/swarm-victoriametrics.nix +++ b/nix/host-modules/swarm-victoriametrics.nix @@ -133,7 +133,7 @@ let # The `auth_request` responder for Grafana's bearer (`swarm-metrics-auth`). # Its socket's directory holds that socket alone and is traverse-only for - # others, the shape `swarm-logs-auth` in ./swarm-victorialogs.nix has. + # others. metricsAuthUnit = "swarm-metrics-auth"; metricsAuthSocket = "/run/${metricsAuthUnit}/auth.sock"; metricsAuthCredential = id: "/run/credentials/${metricsAuthUnit}.service/${id}"; @@ -152,8 +152,7 @@ let # The agents' check on the read API: a `swarm-logs-auth` binary, logging in # under this host's `swarm-metrics-auth` leaf, whose grant covers every - # agent's queue secret. The log store's host runs `swarm-metrics-auth` under - # its `swarm-logs-auth` leaf the same way. + # agent's queue secret. agentAuthUnit = "swarm-metrics-agent-auth"; agentAuthSocket = "/run/${agentAuthUnit}/auth.sock"; agentAuthCredential = id: "/run/credentials/${agentAuthUnit}.service/${id}"; diff --git a/nix/module-eval/bao-grants.nix b/nix/module-eval/bao-grants.nix index 4e0c1804b..a80766d54 100644 --- a/nix/module-eval/bao-grants.nix +++ b/nix/module-eval/bao-grants.nix @@ -842,10 +842,10 @@ let lib.hasInfix "/nats-auth.pem ]" s && lib.hasInfix "swarm-nats-auth \"\" clientAuth" s; } { - # Every agent's queue secret, Grafana's metrics bearer and the store - # container forwarder's client secret, all read-only, and nothing else: - # this principal checks a presented secret and does nothing with it. - name = "the log store responder's grant is every agent's queue secret and log/metric grant, Grafana's bearer and its container forwarder's client secret, read-only, and nothing else"; + # Every agent's queue secret and Grafana's metrics bearer, all read-only, + # and nothing else: this principal checks a presented secret and does + # nothing with it. + name = "the log store responder's grant is every agent's queue secret and log/metric grant and Grafana's bearer, read-only, and nothing else"; ok = let s = baoGrantHere.systemd.services.swarm-bao-logs-auth-policy.script; @@ -863,10 +863,6 @@ let path = "secret/data/swarm/services/swarm-grafana/metrics/bearer"; caps = [ "read" ]; } - { - path = "secret/data/swarm/services/swarm-victorialogs-collector/oidc/client"; - caps = [ "read" ]; - } ] && lib.hasInfix "auth/cert/certs/swarm-logs-auth" s && lib.hasInfix "allowed_common_names=swarm-logs-auth" s diff --git a/nix/module-eval/core-toggle.nix b/nix/module-eval/core-toggle.nix index b71e4e804..67344e9a5 100644 --- a/nix/module-eval/core-toggle.nix +++ b/nix/module-eval/core-toggle.nix @@ -1276,7 +1276,17 @@ let leaf = "swarm/services/${allLocal.services.hyperhive.swarm.grafana.oidc.clientId}/metrics/bearer"; in logs.secureJsonData.httpHeaderValue1 == metrics.secureJsonData.httpHeaderValue1 - && lib.hasInfix "--store-path ${leaf}" allLocal.systemd.services.swarm-logs-grafana-auth.serviceConfig.ExecStart; + && + (lib.findFirst (c: c.name == "grafana-auth") null ( + allLocal.services.hyperhive.k8s.rendered.services.swarm-logs-auth.objects."swarm-logs-auth/deployment".spec.template.spec.containers + )).args == [ + "--listen" + "0.0.0.0:8082" + "--store-cert-role" + "swarm-logs-auth" + "--store-path" + leaf + ]; } { # The responder reads the store as itself, with the leaf the store's @@ -1359,10 +1369,11 @@ let let l = allLocal.services.nginx.virtualHosts."logs.t.local".locations; http = allLocal.services.nginx.appendHttpConfig; - unit = allLocal.systemd.services.swarm-logs-auth; - grafanaUnit = allLocal.systemd.services.swarm-logs-grafana-auth; logs = allLocal.services.hyperhive.deploy.victorialogs; - metrics = allLocal.services.hyperhive.deploy.victoriametrics; + unit = logs.authUnit; + pod = + allLocal.services.hyperhive.k8s.rendered.services.swarm-logs-auth.objects."swarm-logs-auth/deployment".spec.template.spec; + grafana = lib.findFirst (c: c.name == "grafana-auth") null pod.containers; in lib.hasInfix "map \$http_authorization \$swarm_logs_auth_target" http && lib.hasInfix "\"~^Bearer swarm-agent\\.\" /__swarm_logs_agent_auth;" http @@ -1371,17 +1382,26 @@ let && lib.hasInfix "auth_request /__swarm_logs_auth;" l."^~ /select/logsql/".extraConfig && lib.hasInfix "rewrite ^ \$swarm_logs_auth_target last;" l."= /__swarm_logs_auth".extraConfig && lib.hasInfix "internal;" l."= /__swarm_logs_agent_auth".extraConfig - && l."= /__swarm_logs_agent_auth".proxyPass == "http://unix:/run/swarm-logs-auth/auth.sock:/" - && lib.hasInfix "--socket /run/swarm-logs-auth/auth.sock" unit.serviceConfig.ExecStart + # Each hop dials the Service of its own pod, by the port that pod's + # container listens on, and the variable it writes is the one it dials. + && l."= /__swarm_logs_agent_auth".proxyPass == "http://$swarm_logs_agent_auth_upstream/" + && + lib.hasInfix "set $swarm_logs_agent_auth_upstream swarm-logs-auth.hyperhive.svc.cluster.local:8081;" + l."= /__swarm_logs_agent_auth".extraConfig + && hasStorePath "${logs.authPackage}/bin/swarm-logs-auth " unit.serviceConfig.ExecStart + && lib.hasInfix "--listen 0.0.0.0:8081" unit.serviceConfig.ExecStart + && !(lib.hasInfix "--socket" unit.serviceConfig.ExecStart) && lib.hasInfix "--surface logs" unit.serviceConfig.ExecStart && lib.hasInfix "internal;" l."= /__swarm_logs_grafana_auth".extraConfig + && l."= /__swarm_logs_grafana_auth".proxyPass == "http://$swarm_logs_grafana_auth_upstream/" && - l."= /__swarm_logs_grafana_auth".proxyPass == "http://unix:/run/swarm-logs-grafana-auth/auth.sock:/" - && lib.hasInfix "--socket /run/swarm-logs-grafana-auth/auth.sock" grafanaUnit.serviceConfig.ExecStart - && hasStorePath "${logs.grafanaAuthPackage}/bin/swarm-metrics-auth " grafanaUnit.serviceConfig.ExecStart - && !(hasStorePath "${metrics.authPackage}" grafanaUnit.serviceConfig.ExecStart) - && hasStorePath "${logs.authPackage}/bin/swarm-logs-auth " unit.serviceConfig.ExecStart - && lib.hasInfix "--store-cert-role swarm-logs-auth" grafanaUnit.serviceConfig.ExecStart + lib.hasInfix + "set $swarm_logs_grafana_auth_upstream swarm-logs-grafana-auth.hyperhive.svc.cluster.local:8082;" + l."= /__swarm_logs_grafana_auth".extraConfig + && builtins.elem "--listen" grafana.args + && builtins.elem "0.0.0.0:8082" grafana.args + && builtins.elem "swarm-logs-auth" grafana.args + && pod.serviceAccountName == "swarm-logs-auth" && l ? "= /__hive_authelia"; } { @@ -1389,7 +1409,7 @@ let # `/run/private/` (0700 root:root), which nginx cannot traverse, so a # socket there answers every proxied request with a 502. Each `unix:` # upstream under `/run//` is matched to the units creating ``. - # The first two clauses are the control: the match finds both responders. + # The first clauses are the control: the match finds the metrics store's responders. name = "no unix socket nginx proxies to sits in a DynamicUser's preserved runtime directory"; ok = let @@ -1423,9 +1443,7 @@ let "no" ]); in - owners ? swarm-logs-auth - && owners ? swarm-logs-grafana-auth - && owners ? swarm-metrics-auth + owners ? swarm-metrics-auth && owners ? swarm-metrics-agent-auth && !(lib.any (u: hidden u.serviceConfig) (lib.attrValues owners)); } @@ -1439,8 +1457,8 @@ let let l = allLocal.services.nginx.virtualHosts."logs.t.local".locations; http = allLocal.services.nginx.appendHttpConfig; - unit = allLocal.systemd.services.swarm-logs-auth; v = allLocal.services.hyperhive.deploy.victorialogs; + unit = v.authUnit; in lib.hasInfix "limit_req_zone $binary_remote_addr zone=swarm_logs_agent_auth:1m rate=${v.authRate};" http && @@ -1458,12 +1476,14 @@ let ok = let v = allLocal.services.hyperhive.deploy.victorialogs; - lc = allLocal.systemd.services.swarm-logs-auth.serviceConfig.LoadCredential; + lc = v.authUnit.serviceConfig.LoadCredential; in lib.hasSuffix "/logs-auth.pem" v.authBaoClientCertFile && lib.hasSuffix "/logs-auth-key.pem" v.authBaoClientKeyFile - && builtins.elem "bao-client.pem:${v.authBaoClientCertFile}" lc - && builtins.elem "bao-client-key.pem:${v.authBaoClientKeyFile}" lc; + # The pod's unit names the ids and no host path. + && builtins.elem "bao-client.pem" lc + && builtins.elem "bao-client-key.pem" lc + && !(lib.any (lib.hasInfix ":") lc); } { # The absence arm for the case above, and the option's own rule — a @@ -2471,9 +2491,10 @@ let && h.deploy.nats.otel.telemetryPort == 8891 && h.deploy.swarm-otel.telemetryPort == 8889 && lib.hasInfix ":7777;" (locs h.swarm.nats.domain)."= /metrics".extraConfig + && (locs h.swarm.victorialogs.domain)."= /metrics".proxyPass == "http://$swarm_logs_store_upstream" && - (locs h.swarm.victorialogs.domain)."= /metrics".proxyPass - == "http://unix:/run/swarm-victorialogs/victorialogs.sock:/metrics" + lib.hasInfix "set $swarm_logs_store_upstream swarm-victorialogs.hyperhive.svc.cluster.local:9428;" + (locs h.swarm.victorialogs.domain)."= /metrics".extraConfig && (locs h.swarm.forge.domain)."/".proxyPass == "http://unix:/run/hive-forge/forgejo.sock:/" && !allLocal.containers.hive-matrix.config.services.matrix-tuwunel.settings.global.allow_encryption && env.SWARM_CONTROLLER_MATRIX_ADMIN_SYNC_IGNORE_USERS == "" @@ -2871,7 +2892,6 @@ let "swarm-builder" "swarm-grafana" "swarm-otel" - "swarm-victorialogs" "swarm-victoriametrics" ] && lib.all (carries allLocal) names diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix index 398ebef4a..2fd5d5bda 100644 --- a/nix/module-eval/k8s.nix +++ b/nix/module-eval/k8s.nix @@ -52,6 +52,7 @@ let deploy.claude-login.enable = false; deploy.swarm-controller.enable = false; deploy.nats.enable = false; + deploy.victorialogs.enable = false; } ); @@ -86,6 +87,10 @@ let lib.tail (lib.splitString "\"image\":\"" clusterText) ); occurrences = needle: text: lib.length (lib.splitString needle text) - 1; + # `lib.hasInfix` matches `.*needle.*` as a regular expression, which recurses + # once per character of the text: on the manifests' JSON, thousands of + # characters, it overflows the evaluator's stack. Splitting does not. + hasInfix = needle: text: lib.length (lib.splitString needle text) > 1; # The node on through one toggle alone, which only its option is read from. oneToggle = hive { deploy.notify-router.enable = true; }; @@ -122,7 +127,7 @@ let nodeNoBridge = hive { deploy.k8s.enable = true; }; coreDnsKey = "hyperhive-host-services.override"; refusals = lib.filter (a: !a.assertion) nodeRefused.assertions; - refuses = needle: lib.any (a: lib.hasInfix needle a.message) refusals; + refuses = needle: lib.any (a: hasInfix needle a.message) refusals; render = config: @@ -307,10 +312,10 @@ let name = "the manifests name each credential by id and never the host path it is loaded from"; ok = lib.length credentialSources >= 7 - && !(lib.any (s: lib.hasInfix s rendered) credentialSources) - && lib.all (id: lib.hasInfix "\"${id}\"" rendered) (lib.subtractLists clientCertIds credentialIds) + && !(lib.any (s: hasInfix s rendered) credentialSources) + && lib.all (id: hasInfix "\"${id}\"" rendered) (lib.subtractLists clientCertIds credentialIds) # The units load the client certificates and the pods do not. - && lib.all (id: lib.elem id credentialIds && !(lib.hasInfix "\"${id}\"" rendered)) clientCertIds + && lib.all (id: lib.elem id credentialIds && !(hasInfix "\"${id}\"" rendered)) clientCertIds && !(lib.any (o: o.kind == "Secret") (lib.attrValues objects)) && secretLookupWorks && !(lib.any usesSecret (podSpec "swarm-controller").volumes); @@ -360,28 +365,29 @@ let let start = withNode.systemd.services.k3s.serviceConfig.ExecStart; in - lib.hasInfix "--disable=traefik" start - && lib.hasInfix "--disable=metrics-server" start - && lib.hasInfix "--secrets-encryption" start - && lib.hasInfix "--cluster-cidr=10.200.0.0/16" start - && lib.hasInfix "--service-cidr=10.201.0.0/16" start - && !(lib.hasInfix "--disable=coredns" start) - && !(lib.hasInfix "--disable=local-storage" start); + hasInfix "--disable=traefik" start + && hasInfix "--disable=metrics-server" start + && hasInfix "--secrets-encryption" start + && hasInfix "--cluster-cidr=10.200.0.0/16" start + && hasInfix "--service-cidr=10.201.0.0/16" start + && !(hasInfix "--disable=coredns" start) + && !(hasInfix "--disable=local-storage" start); } { # The images are the ones the manifests run, one per rendered service, the # controller's listener leaf, the queue's three more (server, exporter, - # init): the eleven are the control that the list is not empty. + # init), the log store's and its two responders': the fourteen are the + # control that the list is not empty. name = "the node loads the image of every service the manifests run, and k3s's own"; ok = let loaded = map toString withNode.services.k3s.images; rendered = map toString withNode.system.build.k8sImages; in - lib.length rendered == 11 + lib.length rendered == 14 && lib.all (i: lib.elem i loaded) rendered && lib.elem (toString withNode.services.k3s.package.airgap-images) loaded - && lib.length loaded == 12; + && lib.length loaded == 15; } { # The all-local host's assertions are the control: they all hold. @@ -417,13 +423,13 @@ let && cm.metadata.namespace == "kube-system" && lib.length names >= 6 && lib.elem h.swarm.bao.domain names - && lib.all (n: lib.hasInfix (builtins.replaceStrings [ "." ] [ "[.]" ] n) text) names - && lib.hasInfix "template IN A {" text - && lib.hasInfix "template IN AAAA {" text - && lib.hasInfix "answer \"{{ .Name }} 60 IN A ${h.network.bridgeIp}\"" text - && lib.hasInfix " fallthrough\n}\n" text - && !(lib.hasInfix "127.0.0.1" text) - && !(lib.hasInfix "hosts" text) + && lib.all (n: hasInfix (builtins.replaceStrings [ "." ] [ "[.]" ] n) text) names + && hasInfix "template IN A {" text + && hasInfix "template IN AAAA {" text + && hasInfix "answer \"{{ .Name }} 60 IN A ${h.network.bridgeIp}\"" text + && hasInfix " fallthrough\n}\n" text + && !(hasInfix "127.0.0.1" text) + && !(hasInfix "hosts" text) && lib.attrNames h.deploy.k8s.hostServices == lib.sort lib.lessThan names && lib.all (s: s.address == h.network.bridgeIp) (lib.attrValues h.deploy.k8s.hostServices); } @@ -466,14 +472,14 @@ let && units.swarm-ci-metrics.environment.SWARM_CI_METRICS_OTLP_ENDPOINT == ownRoute && (envOf "swarm-ci-metrics").SWARM_CI_METRICS_OTLP_ENDPOINT == ownRoute && !((envOf "swarm-ci-metrics") ? OTEL_EXPORTER_OTLP_ENDPOINT) - && !(lib.any (e: lib.hasInfix "hive-collector" (e.value or "")) (container "swarm-ci-metrics").env) + && !(lib.any (e: hasInfix "hive-collector" (e.value or "")) (container "swarm-ci-metrics").env) && !(envOf "swarm-notify-router" ? SWARM_CI_METRICS_OTLP_ENDPOINT) && units.swarm-controller.environment.OTEL_EXPORTER_OTLP_ENDPOINT == controllerRoute && (envOf "swarm-controller").OTEL_EXPORTER_OTLP_ENDPOINT == controllerRoute && (envOf "swarm-controller").SWARM_CONTROLLER_OTEL_AUDIENCE == units.swarm-controller.environment.SWARM_CONTROLLER_OTEL_AUDIENCE - && !(lib.any (e: lib.hasInfix "hive-collector" (e.value or "")) (container "swarm-controller").env); + && !(lib.any (e: hasInfix "hive-collector" (e.value or "")) (container "swarm-controller").env); } { # The unchanged host is the control that the render itself succeeds. @@ -503,7 +509,7 @@ let }; }; unit = c: c.systemd.services.opentelemetry-collector.serviceConfig; - collectorAcls = c: lib.filter (lib.hasInfix "u:opentelemetry-collector:") c.systemd.tmpfiles.rules; + collectorAcls = c: lib.filter (hasInfix "u:opentelemetry-collector:") c.systemd.tmpfiles.rules; in !((settings noNode).receivers ? "file_log/pods") && !((settings noNode).service.pipelines ? "logs/pods") @@ -533,13 +539,13 @@ let statements = lib.concatMap ( l: l.statements ) s.processors."transform/pod-service-name".log_statements; - acls = lib.filter (lib.hasInfix "u:opentelemetry-collector:") withNode.systemd.tmpfiles.rules; + acls = lib.filter (hasInfix "u:opentelemetry-collector:") withNode.systemd.tmpfiles.rules; in r.include == [ "/var/log/pods/*/*/*.log" ] && r.include_file_path && r.storage == "file_storage" && (lib.head ops).type == "container" - && lib.all (l: lib.hasInfix l (op "regex_parser").regex) [ + && lib.all (l: hasInfix l (op "regex_parser").regex) [ "WARN" "ERROR" "INFO" @@ -612,8 +618,9 @@ let allRoles = map lib.head ( lib.filter lib.isList (builtins.split "auth/jwt-k8s/role/([a-z-]+)" script) ); - # The queue's two roles share one account: a case of their own. - roles = lib.filter (r: !(lib.hasPrefix "swarm-nats" r)) allRoles; + # The queue's two roles share one account, and the log store's + # responders hold one role of their own: a case each. + roles = lib.filter (r: !(lib.hasPrefix "swarm-nats" r) && r != "swarm-logs-auth") allRoles; ttl = "token_ttl=1h \\\n token_max_ttl=1h"; roleText = name: '' bao write auth/jwt-k8s/role/${name} \ @@ -632,13 +639,13 @@ let == lib.sort lib.lessThan allRoles && lib.all ( name: - lib.hasInfix (lib.removeSuffix "\n" (roleText name)) script - && lib.hasInfix "auth/cert/certs/${name}" certScript.${name} - && lib.hasInfix "token_policies=${name}" certScript.${name} - && lib.hasInfix "token_ttl=1h" certScript.${name} - && lib.hasInfix "token_max_ttl=1h" certScript.${name} + hasInfix (lib.removeSuffix "\n" (roleText name)) script + && hasInfix "auth/cert/certs/${name}" certScript.${name} + && hasInfix "token_policies=${name}" certScript.${name} + && hasInfix "token_ttl=1h" certScript.${name} + && hasInfix "token_max_ttl=1h" certScript.${name} ) roles - && lib.hasInfix "bao write auth/jwt-k8s/config -" script; + && hasInfix "bao write auth/jwt-k8s/config -" script; } { # The two roles are the leaf's and the responder's, each with its cert @@ -658,11 +665,11 @@ let token_policies=${name} \ ''; in - lib.hasInfix (role "swarm-nats") script - && lib.hasInfix (role "swarm-nats-auth") script - && lib.hasInfix "token_type=batch" s.swarm-bao-nats-auth-policy.script - && lib.hasInfix "auth/cert/certs/swarm-nats " s.swarm-bao-nats-tls-policy.script - && lib.hasInfix "auth/cert/certs/swarm-nats-auth" s.swarm-bao-nats-auth-policy.script + hasInfix (role "swarm-nats") script + && hasInfix (role "swarm-nats-auth") script + && hasInfix "token_type=batch" s.swarm-bao-nats-auth-policy.script + && hasInfix "auth/cert/certs/swarm-nats " s.swarm-bao-nats-tls-policy.script + && hasInfix "auth/cert/certs/swarm-nats-auth" s.swarm-bao-nats-auth-policy.script && lib.elem "swarm-nats" withNode.services.hyperhive.deploy.bao.k8sPrincipals && lib.elem "swarm-nats-auth" withNode.services.hyperhive.deploy.bao.k8sPrincipals # The account the pod renders under is the one both roles bind. @@ -678,14 +685,14 @@ let u = withNode.systemd.services.swarm-bao-k8s-jwt-policy; start = withNode.systemd.services.k3s.serviceConfig.ExecStart; in - lib.hasInfix "/var/lib/rancher/k3s/server/tls/service.key" u.script - && lib.hasInfix "/var/lib/rancher/k3s/server/tls/service.current.key" u.script - && lib.hasInfix "openssl pkey -in \"$block\" -pubout" u.script - && lib.hasInfix "jwt_validation_pubkeys" u.script - && lib.hasInfix "https://kubernetes.default.svc.cluster.local" u.script - && lib.hasInfix "\"RS256\", \"ES256\"" u.script - && lib.hasInfix "--data-dir=/var/lib/rancher/k3s" start - && lib.hasInfix "--cluster-domain=cluster.local" start + hasInfix "/var/lib/rancher/k3s/server/tls/service.key" u.script + && hasInfix "/var/lib/rancher/k3s/server/tls/service.current.key" u.script + && hasInfix "openssl pkey -in \"$block\" -pubout" u.script + && hasInfix "jwt_validation_pubkeys" u.script + && hasInfix "https://kubernetes.default.svc.cluster.local" u.script + && hasInfix "\"RS256\", \"ES256\"" u.script + && hasInfix "--data-dir=/var/lib/rancher/k3s" start + && hasInfix "--cluster-domain=cluster.local" start && lib.elem "k3s.service" u.after && lib.elem "k3s.service" u.wants; } @@ -698,12 +705,12 @@ let g = withNode.systemd.services.swarm-bao-granter-role; hcl = builtins.readFile ../host-modules/bao-bootstrap-policy.hcl; in - lib.hasInfix "bao auth enable -path=jwt-k8s jwt" g.script - && lib.hasInfix "path \"auth/jwt-k8s/config\" {\n capabilities = [\"create\", \"update\"]\n}" g.script - && lib.hasInfix "path \"auth/jwt-k8s/role/swarm-*\" {\n capabilities = [\"create\", \"update\"]\n}" g.script - && lib.hasInfix "path \"sys/auth/jwt-k8s\" {\n capabilities = [\"create\", \"update\", \"sudo\"]\n}" hcl - && !(lib.hasInfix "sys/auth/jwt-k8s" g.script) - && lib.hasInfix "swarm-bao-k8s-jwt-policy.service" g.serviceConfig.ExecStartPost; + hasInfix "bao auth enable -path=jwt-k8s jwt" g.script + && hasInfix "path \"auth/jwt-k8s/config\" {\n capabilities = [\"create\", \"update\"]\n}" g.script + && hasInfix "path \"auth/jwt-k8s/role/swarm-*\" {\n capabilities = [\"create\", \"update\"]\n}" g.script + && hasInfix "path \"sys/auth/jwt-k8s\" {\n capabilities = [\"create\", \"update\", \"sudo\"]\n}" hcl + && !(hasInfix "sys/auth/jwt-k8s" g.script) + && hasInfix "swarm-bao-k8s-jwt-policy.service" g.serviceConfig.ExecStartPost; } { # The host with the node on is the control that each lookup finds what @@ -716,14 +723,14 @@ let in (baoSettings withNode).listener ? pod && withNode.systemd.services ? swarm-bao-k8s-jwt-policy - && lib.hasInfix "jwt-k8s" on.script - && lib.hasInfix "swarm-bao-k8s-jwt-policy" on.serviceConfig.ExecStartPost + && hasInfix "jwt-k8s" on.script + && hasInfix "swarm-bao-k8s-jwt-policy" on.serviceConfig.ExecStartPost && withNode.networking.firewall.interfaces ? cni0 && !((baoSettings noNode).listener ? pod) && !(noNode.systemd.services ? swarm-bao-k8s-jwt-policy) - && !(lib.hasInfix "jwt-k8s" off.script) - && !(lib.hasInfix "swarm-bao-k8s-jwt-policy" off.serviceConfig.ExecStartPost) - && lib.hasInfix "swarm-bao-operator-viewer-policy" off.serviceConfig.ExecStartPost + && !(hasInfix "jwt-k8s" off.script) + && !(hasInfix "swarm-bao-k8s-jwt-policy" off.serviceConfig.ExecStartPost) + && hasInfix "swarm-bao-operator-viewer-policy" off.serviceConfig.ExecStartPost && !(noNode.networking.firewall.interfaces ? cni0) && !(noNode.networking.firewall.interfaces ? "flannel.1"); } @@ -789,6 +796,16 @@ let && !(onCluster.systemd.services ? "container@swarm-claude-login") && !(onCluster.containers ? swarm-nats) && !(onCluster.systemd.services ? "container-nats") + # The log store and its responders: no container, no unit, no socket + # directory. The metrics store beside it is the control that the lookups + # find what a host still runs. + && !(onCluster.containers ? swarm-victorialogs) + && !(onCluster.systemd.services ? "container@swarm-victorialogs") + && !(onCluster.systemd.services ? swarm-logs-auth) + && !(onCluster.systemd.services ? swarm-logs-grafana-auth) + && !(lib.any (lib.hasPrefix "d /run/swarm-victorialogs ") onCluster.systemd.tmpfiles.rules) + && onCluster.containers ? swarm-victoriametrics + && onCluster.systemd.services ? swarm-metrics-auth && manifestNames onCluster == [ "coredns-custom" @@ -796,10 +813,12 @@ let "swarm-ci-metrics" "swarm-claude-login" "swarm-controller" + "swarm-logs-auth" "swarm-nats" "swarm-notify-router" "swarm-review-classifier" "swarm-stt" + "swarm-victorialogs" ] && onCluster.services.k3s.manifests.hyperhive-namespace.content.kind == "Namespace" && @@ -821,6 +840,24 @@ let "PersistentVolume" "PersistentVolumeClaim" "ServiceAccount" + ] + && + lib.sort lib.lessThan (map (o: o.kind) onCluster.services.k3s.manifests.swarm-logs-auth.content) + == [ + "Deployment" + "NetworkPolicy" + "Service" + "Service" + "ServiceAccount" + ] + && + lib.sort lib.lessThan (map (o: o.kind) onCluster.services.k3s.manifests.swarm-victorialogs.content) + == [ + "Deployment" + "NetworkPolicy" + "PersistentVolume" + "PersistentVolumeClaim" + "Service" ]; } { @@ -850,10 +887,10 @@ let ] && !(lib.any (v: v ? secret) volumes) && secretLookupWorks - && lib.hasInfix "--from-file=bao-server-ca.pem=${serverCa}" caUnit.script - && lib.hasInfix "--from-file=hive-client-ca.pem=" caUnit.script - && lib.hasInfix "--from-file=swarm-services-root.pem=" caUnit.script - && lib.hasInfix "--from-file=trust-bundle.pem=" caUnit.script + && hasInfix "--from-file=bao-server-ca.pem=${serverCa}" caUnit.script + && hasInfix "--from-file=hive-client-ca.pem=" caUnit.script + && hasInfix "--from-file=swarm-services-root.pem=" caUnit.script + && hasInfix "--from-file=trust-bundle.pem=" caUnit.script && lib.elem "multi-user.target" caUnit.wantedBy # A change to either file publishes again with no manual step, and the # host without the node has no path unit. @@ -917,8 +954,8 @@ let memory = "0"; cpu = "0"; } - && !(lib.hasInfix "TasksMax" rendered) - && !(lib.hasInfix "SystemCallFilter" rendered) + && !(hasInfix "TasksMax" rendered) + && !(hasInfix "SystemCallFilter" rendered) && lib.all (name: !((container name) ? resources)) [ "swarm-controller" "swarm-notify-router" @@ -1000,14 +1037,17 @@ let ports = [ (tcp 4222) ]; } ] - # Only the controller (its listener), the queue and this pod have a policy: - # the others have no egress and no listener. + # Only the controller (its listener), the log store and its responders + # (listeners), the queue and this pod have a policy: the others have no + # egress and no listener. && lib.sort lib.lessThan (lib.filter (n: lib.hasSuffix "/networkpolicy" n) (lib.attrNames objects)) == [ "swarm-controller/networkpolicy" + "swarm-logs-auth/networkpolicy" "swarm-nats/networkpolicy" "swarm-stt/networkpolicy" + "swarm-victorialogs/networkpolicy" ]; } { @@ -1202,13 +1242,13 @@ let } ''; in - lib.hasInfix (lib.removeSuffix "\n" writes) login - && !(lib.hasInfix "claude-credentials" classifier) - && lib.hasInfix "anthropic-api-key" classifier - && lib.hasInfix "token_policies=swarm-claude-login " jwt - && lib.hasInfix "bound_subject=system:serviceaccount:hyperhive:swarm-claude-login" jwt - && lib.hasInfix "bound_subject=system:serviceaccount:hyperhive:swarm-review-classifier" jwt - && lib.hasInfix "token_policies=swarm-claude-login " login; + hasInfix (lib.removeSuffix "\n" writes) login + && !(hasInfix "claude-credentials" classifier) + && hasInfix "anthropic-api-key" classifier + && hasInfix "token_policies=swarm-claude-login " jwt + && hasInfix "bound_subject=system:serviceaccount:hyperhive:swarm-claude-login" jwt + && hasInfix "bound_subject=system:serviceaccount:hyperhive:swarm-review-classifier" jwt + && hasInfix "token_policies=swarm-claude-login " login; } { # `swarmctl setup status` reads this file to tell that the root-only @@ -1228,9 +1268,9 @@ let in lib.length touched == 2 && lib.length cleared == 2 - && lib.hasInfix "rm -f ${marker}" (lib.elemAt touched 1) - && lib.hasInfix "exit 0" between - && lib.hasInfix "bao write auth/jwt-k8s/config" (lib.elemAt cleared 1); + && hasInfix "rm -f ${marker}" (lib.elemAt touched 1) + && hasInfix "exit 0" between + && hasInfix "bao write auth/jwt-k8s/config" (lib.elemAt cleared 1); } { # The poller's one credential in the pod is the store's public CA, from @@ -1263,7 +1303,7 @@ let e: e.name == "BAO_CACERT" && e.value == "/run/credentials/swarm-ci-metrics.service/bao-ca.pem" ) (lib.head spec.containers).env && lib.all (v: lib.all (e: e.name != v) (lib.head spec.containers).env) clientVars - && !(lib.hasInfix "swarm-ci-metrics-credentials" rendered); + && !(hasInfix "swarm-ci-metrics-credentials" rendered); } { # The host with the controller on it is the control for every absence @@ -1329,7 +1369,7 @@ let loc = c: path: c.services.nginx.virtualHosts."t.local".locations.${path}; dials = c: path: needle: - lib.hasInfix needle (loc c path).extraConfig; + hasInfix needle (loc c path).extraConfig; verified = c: path: dials c path "proxy_ssl_name controller.t.local;" @@ -1410,10 +1450,10 @@ let servicesRoot = "${onCluster.services.hyperhive.deploy.hive-controller.tls.stateDir}/swarm-services-root.pem"; mountPath = x: (lib.findFirst (m: m.name == "tls") null x.volumeMounts).mountPath; in - !(lib.hasInfix "install -d" podScript) - && !(lib.hasInfix "chgrp" podScript) - && lib.hasInfix "-checkhost \"$name\"" podScript - && lib.hasInfix "issue/swarm-controller-tls" podScript + !(hasInfix "install -d" podScript) + && !(hasInfix "chgrp" podScript) + && hasInfix "-checkhost \"$name\"" podScript + && hasInfix "issue/swarm-controller-tls" podScript && map (c: c.name) spec.initContainers == [ "tls-issue" ] && init.name == "tls-issue" && renew.name == "tls-renew" @@ -1540,7 +1580,7 @@ let # The per-agent subjects keep their `$`: a pod's arguments are not # unescaped by systemd. && lib.elem "$SWARM.term.{agent}" (named "swarm-nats").args - && !(lib.any (a: lib.hasInfix "$$" a) (named "swarm-nats").args) + && !(lib.any (a: hasInfix "$$" a) (named "swarm-nats").args) # The leaf's key is in memory; the store is a claim; nothing is capped. && (volume "nats-tls").emptyDir.medium == "Memory" && !((volume "tmp").emptyDir ? medium) @@ -1617,7 +1657,7 @@ let && !(objects ? "swarm-stt/persistentvolumeclaim") && (stateVolume "swarm-ci-metrics").persistentVolumeClaim.claimName == "swarm-ci-metrics-store" && objects ? "swarm-ci-metrics/persistentvolumeclaim" - && !(lib.any (n: lib.hasInfix "state-gate" n) (map toString withNode.system.build.k8sImages)) + && !(lib.any (n: hasInfix "state-gate" n) (map toString withNode.system.build.k8sImages)) && objects ? "swarm-nats/persistentvolumeclaim"; } { @@ -1633,14 +1673,14 @@ let && !(onCluster.systemd.services ? "container@swarm-nats") && !(onCluster.systemd.services ? swarm-nats-auth-secrets) && !(onCluster.systemd.services ? swarm-bao-nats-callout-xkey) - && !(lib.hasInfix "nixos-fw-nats" noNode.networking.firewall.extraCommands) - && lib.hasInfix "nixos-fw-nats" onCluster.networking.firewall.extraCommands + && !(hasInfix "nixos-fw-nats" noNode.networking.firewall.extraCommands) + && hasInfix "nixos-fw-nats" onCluster.networking.firewall.extraCommands && !(lib.elem "container@swarm-nats.service" tls.before) && !(lib.elem "container@swarm-nats.service" tls.wantedBy) && onCluster.systemd.services ? swarm-nats-gateway-cert && vhost onCluster == "http://\$swarm_nats_metrics_upstream/metrics" - && lib.hasInfix "resolver 10.42.0.1 valid=10s ipv6=off;" (extra onCluster) - && lib.hasInfix "set \$swarm_nats_metrics_upstream swarm-nats-metrics.hyperhive.svc.cluster.local:7777;" ( + && hasInfix "resolver 10.42.0.1 valid=10s ipv6=off;" (extra onCluster) + && hasInfix "set \$swarm_nats_metrics_upstream swarm-nats-metrics.hyperhive.svc.cluster.local:7777;" ( extra onCluster ) && onCluster.services.hyperhive.network.enable; @@ -1704,7 +1744,7 @@ let }; closed = rules (args // { openClient = false; }); open = rules (args // { openClient = true; }); - has = lib.hasInfix; + has = hasInfix; in has "-p tcp --dport 4222 -i br0 -j RETURN" closed && has "-p tcp --dport 4222 -i cni0 -j RETURN" closed @@ -1773,14 +1813,14 @@ let ) ) ); - idx = c: pat: lib.lists.findFirstIndex (lib.hasInfix pat) 1000 (rules c); + idx = c: pat: lib.lists.findFirstIndex (hasInfix pat) 1000 (rules c); br = onCluster.services.hyperhive.network.bridgeName; published = ''iifname "${br}" oifname != "${br}" meta nfproto ipv4 meta l4proto tcp ct status dnat ct original ip daddr 10.42.0.1 ct original proto-dst { 4222 } accept''; in onCluster.services.hyperhive.deploy.hive-controller.egress.publishedPorts == [ 4222 ] && noNode.services.hyperhive.deploy.hive-controller.egress.publishedPorts == [ ] && lib.elem published (rules onCluster) - && !(lib.any (lib.hasInfix "ct original") (rules noNode)) + && !(lib.any (hasInfix "ct original") (rules noNode)) # After the named SSH connections and before the counter and the log: # a published flow is neither counted nor logged. && idx onCluster "@agent_allow accept" < idx onCluster "ct original" @@ -1864,12 +1904,187 @@ let && ns."pod-security.kubernetes.io/warn" == "restricted" && ns."pod-security.kubernetes.io/audit" == "restricted" && ns."app.kubernetes.io/part-of" == "hyperhive" - && lib.length specs == 7 + && lib.length specs == 9 && lib.all (s: problems s == [ ]) specs && problems withHostPort != [ ] && problems withCaps != [ ] && problems withoutSeccomp != [ ]; } + { + # The data is the container's own directory, so an upgrade moves the + # process and not the bytes. Every arm has a control: the sibling pod + # that has no volume, no selector or no ServiceAccount, and a pod that + # has none of the settings only this one carries. + name = "the log store's pod is the daemon on a static local volume that is its old container's data directory, with no store identity"; + ok = + let + spec = podSpec "swarm-victorialogs"; + c = container "swarm-victorialogs"; + dir = "/var/lib/nixos-containers/swarm-victorialogs/var/lib/victorialogs"; + pv = objects."swarm-victorialogs/persistentvolume"; + pvc = objects."swarm-victorialogs/persistentvolumeclaim"; + dep = objects."swarm-victorialogs/deployment".spec; + label = "hyperhive.darkest.space/state-victorialogs"; + in + c.args == [ + "-storageDataPath=/var/lib/victorialogs" + "-httpListenAddr=:9428" + "-retentionPeriod=30d" + ] + && + c.livenessProbe.httpGet == { + path = "/health"; + port = "api"; + } + && c.readinessProbe.httpGet.path == "/health" + && + c.ports == [ + { + name = "api"; + containerPort = 9428; + } + ] + && dep.replicas == 1 + && dep.strategy.type == "Recreate" + && pv.spec.local.path == dir + && pv.spec.persistentVolumeReclaimPolicy == "Retain" + && pvc.spec.volumeName == pv.metadata.name + && pvc.spec.storageClassName == pv.spec.storageClassName + && + pv.spec.nodeAffinity.required.nodeSelectorTerms == [ + { + matchExpressions = [ + { + key = label; + operator = "In"; + values = [ "true" ]; + } + ]; + } + ] + && spec.nodeSelector == { ${label} = "true"; } + && + (lib.findFirst (v: v.name == "state") null spec.volumes).persistentVolumeClaim.claimName + == pvc.metadata.name + # The first start gives the pod's group the old tree; later ones look at + # the root only. No other pod sets it. + && spec.securityContext.fsGroupChangePolicy == "OnRootMismatch" + && !((podSpec "swarm-nats").securityContext ? fsGroupChangePolicy) + # Plain HTTP: no leaf, no init container, no in-memory volume. The + # controller's pod is the control that those exist where a leaf does. + && !(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. + && !(spec ? serviceAccountName) + && !(objects ? "swarm-victorialogs/serviceaccount") + && !(lib.any (v: v.name == "bao-token" || v.name == "credentials") spec.volumes) + && (podSpec "swarm-stt") ? serviceAccountName + # Its Service is the only way in, and only the node reaches it. + && + objects."swarm-victorialogs/service".spec.ports == [ + { + name = "api"; + protocol = "TCP"; + port = 9428; + targetPort = "api"; + } + ] + && objects."swarm-victorialogs/networkpolicy".spec.policyTypes == [ "Ingress" ] + && !(objects."swarm-victorialogs/networkpolicy".spec ? ingress) + # The directory is made on a host that never ran the container, and an + # existing one is left as it is. + && lib.elem "d ${dir} - - - -" onCluster.systemd.tmpfiles.rules + && !(lib.any (lib.hasPrefix "d ${dir} ") noNode.systemd.tmpfiles.rules); + } + { + # 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. + name = "the log store's responders are one unpinned pod under one account, reached by the node alone, with the store and DNS as its only way out"; + ok = + let + spec = podSpec "swarm-logs-auth"; + named = n: lib.findFirst (c: c.name == n) null spec.containers; + logs = named "swarm-logs-auth"; + grafana = named "grafana-auth"; + policy = objects."swarm-logs-auth/networkpolicy".spec; + s = withNode.systemd.services; + script = s.swarm-bao-k8s-jwt-policy.script; + podLabels = { + "app.kubernetes.io/name" = "swarm-logs-auth"; + "app.kubernetes.io/part-of" = "hyperhive"; + }; + service = n: objects.${n}.spec; + in + map (c: c.name) spec.containers == [ + "swarm-logs-auth" + "grafana-auth" + ] + && + logs.args == [ + "--listen" + "0.0.0.0:8081" + "--store-cert-role" + "swarm-logs-auth" + "--surface" + "logs" + "--verdict-ttl" + "60" + ] + && lib.elem "0.0.0.0:8082" grafana.args + && !(lib.elem "--socket" (logs.args ++ grafana.args)) + # Each container logs in with the pod's token, on the same role. + && + (lib.listToAttrs (map (e: lib.nameValuePair e.name e.value) logs.env)).BAO_JWT_ROLE + == "swarm-logs-auth" + && + (lib.listToAttrs (map (e: lib.nameValuePair e.name e.value) grafana.env)).BAO_JWT_ROLE + == "swarm-logs-auth" + && !(lib.any (e: lib.hasPrefix "BAO_CLIENT" e.name) (logs.env ++ grafana.env)) + && grafana.livenessProbe.httpGet.port == "health" + && spec.serviceAccountName == "swarm-logs-auth" + && objects."swarm-logs-auth/serviceaccount".metadata.name == "swarm-logs-auth" + && hasInfix "bound_subject=system:serviceaccount:hyperhive:swarm-logs-auth" script + && hasInfix "auth/jwt-k8s/role/swarm-logs-auth" script + && hasInfix "token_type=batch" s.swarm-bao-logs-auth-policy.script + && lib.elem "swarm-logs-auth" withNode.services.hyperhive.deploy.bao.k8sPrincipals + # No state label: the store's pod is pinned, this one is not. + && !(spec ? nodeSelector) + && (podSpec "swarm-victorialogs") ? nodeSelector + # One Service per responder, on the pod's labels. + && (service "swarm-logs-auth/service").selector == podLabels + && + (service "swarm-logs-auth/service").ports == [ + { + name = "api"; + protocol = "TCP"; + port = 8081; + targetPort = "api"; + } + ] + && (service "swarm-logs-grafana-auth/service").selector == podLabels + && (lib.head (service "swarm-logs-grafana-auth/service").ports).port == 8082 + # One policy: nothing in but the node, and out to DNS and the store's pod + # listener alone. The sibling's policy has no egress. + && + policy.policyTypes == [ + "Ingress" + "Egress" + ] + && !(policy ? ingress) + && lib.length policy.egress == 2 + && + (lib.elemAt policy.egress 1).ports == [ + { + protocol = "TCP"; + port = 8208; + } + ] + && !(objects."swarm-victorialogs/networkpolicy".spec ? egress) + # No leaf: nothing here serves TLS. + && !(spec ? initContainers) + && !(lib.any (v: v.name == "tls") spec.volumes); + } { # The host without the node is the control: it labels nothing. name = "the node labels itself as the entry node, and with a state label for each service whose data the cluster keeps"; @@ -1886,6 +2101,7 @@ let ++ [ "hyperhive.darkest.space/state-nats=true" "hyperhive.darkest.space/state-ci-metrics=true" + "hyperhive.darkest.space/state-victorialogs=true" ] ) && @@ -1894,6 +2110,7 @@ let "svccontroller.k3s.cattle.io/enablelb" = "true"; "hyperhive.darkest.space/state-nats" = "true"; "hyperhive.darkest.space/state-ci-metrics" = "true"; + "hyperhive.darkest.space/state-victorialogs" = "true"; } && noNode.services.k3s.nodeLabel == [ ]; } @@ -1934,8 +2151,8 @@ let && !(podSpec "swarm-controller" ? nodeSelector) && !(podSpec "swarm-stt" ? nodeSelector) && (podSpec "swarm-nats").nodeSelector == { "hyperhive.darkest.space/state-nats" = "true"; } - && lib.hasInfix "nodeAffinity" text - && !(lib.hasInfix "kubernetes.io/hostname" text) + && hasInfix "nodeAffinity" text + && !(hasInfix "kubernetes.io/hostname" text) && lib.elem rule onCluster.systemd.tmpfiles.rules && !(lib.elem rule noNode.systemd.tmpfiles.rules); } @@ -1957,8 +2174,8 @@ let lib.all (a: a.assertion) withNode.assertions && lib.any ( a: - lib.hasInfix "services.hyperhive.deploy.k8s.enable is false" a.message - && lib.all (n: lib.hasInfix "deploy.${n}.enable" a.message) [ + hasInfix "services.hyperhive.deploy.k8s.enable is false" a.message + && lib.all (n: hasInfix "deploy.${n}.enable" a.message) [ "notify-router" "stt" "ci-metrics" @@ -1975,7 +2192,7 @@ let name = "the controller's TLS listener is on and named from the swarm domain with nothing set, and an explicit value that can't work is refused naming it"; ok = let - refusesWith = needle: lib.any (a: lib.hasInfix needle a.message) nodeOffRefusals; + refusesWith = needle: lib.any (a: hasInfix needle a.message) nodeOffRefusals; in oneToggle.services.hyperhive.swarm.controller.tcp.enable && oneToggle.services.hyperhive.swarm.controller.tcp.domain == "controller.t.local" @@ -1988,7 +2205,7 @@ let && refusesWith "services.hyperhive.gateway.dns.enable" # The same assertion holds on the all-local host: the control that the # needle finds it. - && lib.any (a: a.assertion && lib.hasInfix "tcp.listenAddress" a.message) withNode.assertions; + && lib.any (a: a.assertion && hasInfix "tcp.listenAddress" a.message) withNode.assertions; } { # The registry host is spelled out here, so the module is not compared @@ -2001,7 +2218,7 @@ let in registries == "mirrors:\n registry.hyperhive.invalid:\n" && nodeNoBridge.environment.etc."rancher/k3s/registries.yaml".text == registries - && !(lib.hasInfix "*" registries) + && !(hasInfix "*" registries) && lib.elem "--embedded-registry" onCluster.services.k3s.extraFlags && lib.elem "--embedded-registry" nodeNoBridge.services.k3s.extraFlags && onCluster.services.k3s.nodeIP == "192.168.1.10" @@ -2025,13 +2242,13 @@ let (rule address "udp" "8472") (rule address "tcp" "5001") ]; - nodeLines = lib.filter (l: lib.hasInfix "--dport" l && lib.hasInfix "nixos-fw -s" l) ( + nodeLines = lib.filter (l: hasInfix "--dport" l && hasInfix "nixos-fw -s" l) ( lib.splitString "\n" rules ); in - lib.all (r: lib.hasInfix r rules) (forNodes "192.168.1.11" ++ forNodes "192.168.1.12") + lib.all (r: hasInfix r rules) (forNodes "192.168.1.11" ++ forNodes "192.168.1.12") && lib.length nodeLines == 8 - && !(lib.hasInfix "--dport 6443" nodeNoBridge.networking.firewall.extraCommands) + && !(hasInfix "--dport 6443" nodeNoBridge.networking.firewall.extraCommands) && !(lib.elem 6443 onCluster.networking.firewall.allowedTCPPorts) && !(lib.elem 8472 onCluster.networking.firewall.allowedUDPPorts); } @@ -2051,11 +2268,11 @@ let && joined.environment.etc."rancher/k3s/registries.yaml".text == onCluster.environment.etc."rancher/k3s/registries.yaml".text - && lib.hasInfix "iptables -A nixos-fw -s 192.168.1.10 -p tcp --dport 6443 -j nixos-fw-accept" joined.networking.firewall.extraCommands + && hasInfix "iptables -A nixos-fw -s 192.168.1.10 -p tcp --dport 6443 -j nixos-fw-accept" joined.networking.firewall.extraCommands && joinedUnit.before == [ "k3s.service" ] && joinedUnit.wantedBy == [ "k3s.service" ] - && lib.hasInfix "secret/swarm/services/k8s/agent-token" joinedUnit.script - && lib.hasInfix "/run/k3s-join/token" joinedUnit.script + && hasInfix "secret/swarm/services/k8s/agent-token" joinedUnit.script + && hasInfix "/run/k3s-join/token" joinedUnit.script && !(joined.systemd.services ? k3s-join-token-publish) && withNode.systemd.services ? k3s-join-token-publish && !(withNode.systemd.services ? k3s-join-token) @@ -2074,7 +2291,7 @@ let }; noIdentity = hive { deploy.k8s.join.server = "192.168.1.10"; }; messages = c: map (a: a.message) (lib.filter (a: !a.assertion) c.assertions); - mentions = needle: c: lib.any (lib.hasInfix needle) (messages c); + mentions = needle: c: lib.any (hasInfix needle) (messages c); in mentions "k8s.join as a node of another" both && mentions "baoHiveIdentityCertFile" noIdentity @@ -2108,10 +2325,10 @@ let lib.length imageRefs >= 8 && lib.all (r: lib.hasPrefix registryPrefix r) imageRefs && lib.any (r: lib.hasSuffix "-server" (lib.head (lib.splitString ":" r))) imageRefs - && lib.any (r: lib.hasInfix "-tls:" r) imageRefs + && lib.any (r: hasInfix "-tls:" r) imageRefs && occurrences "\"imagePullPolicy\":\"IfNotPresent\"" clusterText >= 8 - && !(lib.hasInfix "\"imagePullPolicy\":\"Never\"" clusterText) - && !(lib.hasInfix "docker.io" clusterText); + && !(hasInfix "\"imagePullPolicy\":\"Never\"" clusterText) + && !(hasInfix "docker.io" clusterText); } ]; in diff --git a/nix/module-eval/nats-authelia.nix b/nix/module-eval/nats-authelia.nix index ff7055ae7..b8436d37a 100644 --- a/nix/module-eval/nats-authelia.nix +++ b/nix/module-eval/nats-authelia.nix @@ -180,10 +180,6 @@ let machine = "swarm-grafana"; option = "grafana"; } - { - machine = "swarm-victorialogs"; - option = "victorialogs"; - } { machine = "hive-forge"; option = "forge"; @@ -209,14 +205,6 @@ let key = "grafana-bao-key"; port = 8896; } - { - machine = "swarm-victorialogs"; - option = "victorialogs"; - name = "victorialogs"; - cert = "bao-client.pem"; - key = "bao-client-key.pem"; - port = 8897; - } { machine = "hive-forge"; option = "forge"; diff --git a/nix/module-eval/secret-publisher.nix b/nix/module-eval/secret-publisher.nix index 4310e384c..ec44eb382 100644 --- a/nix/module-eval/secret-publisher.nix +++ b/nix/module-eval/secret-publisher.nix @@ -229,7 +229,6 @@ let [ "swarm-ci-runner-collector" "swarm-grafana-collector" - "swarm-victorialogs-collector" "swarm-forge-collector" "swarm-matrix-collector" "swarm-victoriametrics-collector" diff --git a/nix/module-eval/swarm-otel-identity.nix b/nix/module-eval/swarm-otel-identity.nix index ef5c84c50..c522123b7 100644 --- a/nix/module-eval/swarm-otel-identity.nix +++ b/nix/module-eval/swarm-otel-identity.nix @@ -511,7 +511,7 @@ let in h.deploy.victorialogs.enable && locs ? "= /metrics" - && locs."= /metrics".proxyPass == "http://unix:/run/swarm-victorialogs/victorialogs.sock:/metrics" + && locs."= /metrics".proxyPass == "http://$swarm_logs_store_upstream" && checksOf locs."= /metrics" == [ "auth_request /__hive_authelia;" ] && !(lib.hasInfix "error_page" locs."= /metrics".extraConfig) && lib.hasInfix "error_page 401 =302" locs."/".extraConfig diff --git a/nix/module-eval/swarm-services-switch.nix b/nix/module-eval/swarm-services-switch.nix index 0705a25cd..3f0d40475 100644 --- a/nix/module-eval/swarm-services-switch.nix +++ b/nix/module-eval/swarm-services-switch.nix @@ -203,7 +203,6 @@ let "swarm-ci-runner" "swarm-grafana" "swarm-otel" - "swarm-victorialogs" "swarm-victoriametrics" ]; @@ -265,7 +264,6 @@ let "grafana.service" "opentelemetry-collector.service" "tuwunel.service" - "victorialogs.service" "victoriametrics.service" ]; } @@ -772,7 +770,6 @@ let "swarm-authelia" "swarm-bao" "swarm-grafana" - "swarm-victorialogs" "swarm-victoriametrics" "swarm-otel" "hive-matrix" @@ -821,7 +818,7 @@ let # that lost a container can't pass by comparing fewer of them. name = "every service container restates its host-side privateNetwork"; ok = - lib.length (lib.attrNames serviceContainers) == 11 + lib.length (lib.attrNames serviceContainers) == 10 && lib.all ( c: c.privateNetwork == (c.config.services.hyperhive.swarmContainer.privateNetwork or null) ) (lib.attrValues serviceContainers); @@ -1016,50 +1013,6 @@ let && bridge.serviceConfig.Group == "gateway-nginx" && lib.elem dir unit.serviceConfig.ReadWritePaths; } - { - # On the bridge by DHCP, listening on a socket only the gateway's group can - # reach, so the store binds no host port. Every location that forwards to - # it goes through the socket (the authelia subrequests are the `https://` - # upstream); the read, ingest, scrape and catch-all locations are named so - # an empty filter can't pass, and the old loopback port is named nowhere. - name = "the log store runs on a netns of its own and the gateway reaches it over its socket"; - ok = - let - host = serviceContainersWithCi; - net = host.services.hyperhive.network; - c = host.containers.swarm-victorialogs; - dir = "/run/swarm-victorialogs"; - sock = "${dir}/victorialogs.sock"; - viaSock = path: "http://unix:${sock}:${path}"; - locs = - host.services.nginx.virtualHosts.${host.services.hyperhive.swarm.victorialogs.domain}.locations; - toStore = lib.filter ( - p: p != null && !(lib.hasPrefix "https://" p) && !(lib.hasPrefix "http://unix:/run/swarm-logs" p) - ) (map (l: l.proxyPass) (lib.attrValues locs)); - unit = c.config.systemd.services.victorialogs; - nginxGid = host.ids.gids.nginx; - in - c.privateNetwork - && c.hostBridge == net.bridgeName - && c.hostAddress == null - && c.localAddress == null - && c.config.networking.interfaces.eth0.useDHCP - && c.config.services.victorialogs.listenAddress == "unix:${sock}" - && locs."/".proxyPass == viaSock "/" - && locs."= /insert/opentelemetry/v1/logs".proxyPass == viaSock "/insert/opentelemetry/v1/logs" - && locs."^~ /select/logsql/".proxyPass == "http://unix:${sock}" - && locs."= /metrics".proxyPass == viaSock "/metrics" - && toStore != [ ] - && lib.all (lib.hasPrefix "http://unix:${sock}") toStore - && !(lib.any (lib.hasInfix "127.0.0.1") toStore) - && c.bindMounts.${dir}.hostPath == dir - && builtins.elem "d ${dir} 0770 root ${toString nginxGid} - -" host.systemd.tmpfiles.rules - && c.config.users.groups.gateway-nginx.gid == nginxGid - && unit.serviceConfig.Group == "gateway-nginx" - && !unit.serviceConfig.DynamicUser - && unit.serviceConfig.UMask == "0007" - && lib.hasInfix "--unix-socket ${sock}" unit.postStart; - } { # On the bridge by DHCP, listening on a socket (protocol `socket` ignores the # upstream-default `http_port`, which stays in the settings): the diff --git a/nix/vm-tests/k8s-services.nix b/nix/vm-tests/k8s-services.nix index a256cd011..0d6bbbf1c 100644 --- a/nix/vm-tests/k8s-services.nix +++ b/nix/vm-tests/k8s-services.nix @@ -11,6 +11,12 @@ # speech-to-text pod carries its limits and keeps its cache in an emptyDir, # with no claim and no state gate, in a user namespace, and its NetworkPolicy # lets a queue request in and only DNS and four host ports out; +# - the log store runs as a pod on the directory its old container kept, which +# a unit of this test filled before the cluster started, as another user: the +# pod reads that record and writes a new one, the gateway's own locations +# (rendered by the module, run in a nginx of their own) reach the store and the +# responders by their Services' names, a bearer is granted or refused by the +# responders with the store's answers, and no other pod reaches the store; # - the poller's Job completes against a forge that lists one run, pushes it to # its own route of the swarm collector, holds no Secret, and keeps its cursor # in a volume, so a second Job pushes nothing, and starts with no state @@ -67,6 +73,56 @@ let # nothing reads it. sttModel = pkgs.writeText "ggml-placeholder.bin" "not a model"; tokenLog = "/var/log/stub-token.log"; + + # The log store, as the module names it. + vlDir = "/var/lib/nixos-containers/swarm-victorialogs/var/lib/victorialogs"; + vlGateway = "127.0.0.1:18081"; + legacyUser = "legacy-victorialogs"; + legacyPort = 19428; + + # One nginx with the log store's locations as the module renders them: the + # Services they dial, the responders they check a bearer with and the + # variables between. The identity provider's two checks are stand-ins that + # answer 200, because the VM has no login service; nothing else of the vhost. + gatewayConf = + cfg: + let + locations = cfg.services.nginx.virtualHosts."logs.t.local".locations; + served = [ + "= /insert/opentelemetry/v1/logs" + "^~ /select/logsql/" + "= /metrics" + "= /__swarm_logs_auth" + "= /__swarm_logs_agent_auth" + "= /__swarm_logs_grafana_auth" + ]; + block = + name: + let + l = locations.${name}; + in + '' + location ${name} { + ${lib.optionalString (l.proxyPass != null) "proxy_pass ${l.proxyPass};"} + ${l.extraConfig} + } + ''; + in + pkgs.writeText "logs-gateway.conf" '' + pid /run/logs-gateway-test/nginx.pid; + error_log stderr; + events {} + http { + access_log off; + ${cfg.services.nginx.appendHttpConfig} + server { + listen ${vlGateway}; + location = /__swarm_logs_ingest_authz { internal; return 200; } + location = /__hive_authelia { internal; return 200; } + ${lib.concatMapStrings block served} + } + } + ''; requestLog = "/var/log/stub-requests.log"; # The identity provider, the forge and the swarm collector, by name, on one @@ -190,6 +246,7 @@ pkgs.testers.runNixOSTest { deploy.claude-login.enable = true; deploy.stt.settings.modelFile = sttModel; deploy.ci-metrics.enable = true; + deploy.victorialogs.enable = true; deploy.hive-controller.hiveName = "h1"; swarm.domain = "t.local"; swarm.forge.domain = forgeName; @@ -294,6 +351,63 @@ pkgs.testers.runNixOSTest { }; }; + # What the log store's container left on the host before the cluster ran + # the store: its data directory, written by the pinned binary as a user + # of its own with group-writable files, holding one record. A switch from + # the container can't be run here (the container is gone from the + # module), so the directory is what the switch leaves behind. + users.users.${legacyUser} = { + isSystemUser = true; + group = legacyUser; + }; + users.groups.${legacyUser} = { }; + systemd.services.victorialogs-legacy = { + wantedBy = [ "multi-user.target" ]; + before = [ "k3s.service" ]; + path = [ + pkgs.curl + pkgs.coreutils + pkgs.findutils + ]; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + User = legacyUser; + UMask = "0007"; + ExecStartPre = "+${pkgs.writeShellScript "victorialogs-legacy-dir" '' + mkdir -p ${vlDir} + chown ${legacyUser}:${legacyUser} ${vlDir} + chmod 0700 ${vlDir} + ''}"; + }; + script = '' + ${config.services.hyperhive.deploy.victorialogs.package}/bin/victoria-logs \ + -storageDataPath=${vlDir} -httpListenAddr=127.0.0.1:${toString legacyPort} & + pid=$! + until curl -sf http://127.0.0.1:${toString legacyPort}/health; do sleep 1; done + curl -sf --data-binary \ + "{\"_msg\":\"written before the switch\",\"app\":\"legacy\",\"_time\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}" \ + 'http://127.0.0.1:${toString legacyPort}/insert/jsonline?_stream_fields=app' + until curl -s --data-urlencode 'query=legacy' http://127.0.0.1:${toString legacyPort}/select/logsql/query \ + | grep -q 'written before the switch'; do sleep 1; done + kill -TERM "$pid" + wait "$pid" || true + test -n "$(find ${vlDir} -type f | head -1)" + ''; + }; + + # The log store's locations, from the active configuration's own text. + systemd.services.logs-gateway = { + wantedBy = [ "multi-user.target" ]; + after = [ "network.target" ]; + serviceConfig = { + RuntimeDirectory = "logs-gateway-test"; + ExecStart = "${pkgs.nginx}/bin/nginx -c ${gatewayConf config} -g 'daemon off;'"; + Restart = "on-failure"; + RestartSec = 2; + }; + }; + environment.systemPackages = [ pkgs.kubectl pkgs.curl @@ -386,6 +500,12 @@ pkgs.testers.runNixOSTest { MANIFESTS = "/var/lib/rancher/k3s/server/manifests" NATS = "--server tls://${natsName}:${toString natsPort} --tlsca ${pkiDir}/ca.pem" AGENT = "${agent}" + OTHER_AGENT = "argus" + AGENT_SECRETS: dict[str, str] = {} + VL = "swarm-victorialogs" + LOGS_AUTH = "swarm-logs-auth" + VL_DIR = "${vlDir}" + GATEWAY = "http://${vlGateway}" SELECTOR = f"--selector app.kubernetes.io/name={SERVICE}" @@ -501,6 +621,7 @@ pkgs.testers.runNixOSTest { "swarm-bao-ci-metrics-policy", "swarm-bao-review-classifier-policy", "swarm-bao-claude-login-policy", + "swarm-bao-logs-auth-policy", "swarm-bao-k8s-jwt-policy", ]: settle(f'[ "$(systemctl is-active {unit}.service)" = active ]', 900, [f"{unit}.service"]) @@ -523,6 +644,16 @@ pkgs.testers.runNixOSTest { as_root(f"bao kv put -mount=secret ${classifierLeaf} value={CLASSIFIER_SECRET}") LOGIN_SECRET = machine.succeed("openssl rand -hex 16").strip() as_root(f"bao kv put -mount=secret ${loginLeaf} value={LOGIN_SECRET}") + # What the log store's responders read: an agent's queue secret and its + # mirrored grant, one agent that holds no grant, and the bearer + # Grafana's host creates. The grant is a JSON object, so it is a file. + for name, grant in ((AGENT, '{"logs": true}'), (OTHER_AGENT, '{"logs": false}')): + AGENT_SECRETS[name] = machine.succeed("openssl rand -hex 16").strip() + as_root(f"bao kv put -mount=secret swarm/agents/{name}/queue value={AGENT_SECRETS[name]} agent={name}") + machine.succeed(f"echo '{grant}' > /tmp/grant-{name}.json") + as_root(f"bao kv put -mount=secret swarm/agents/{name}/observability @/tmp/grant-{name}.json") + GRAFANA_BEARER = machine.succeed("openssl rand -hex 32").strip() + as_root(f"bao kv put -mount=secret swarm/services/swarm-grafana/metrics/bearer value={GRAFANA_BEARER}") with subtest("the queue and the token stub run, and the queue holds the roster the router reads"): machine.wait_for_unit("hive-tls-ca.service") @@ -676,6 +807,113 @@ pkgs.testers.runNixOSTest { status = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["status"] assert status["containerStatuses"][0]["ready"] and status["containerStatuses"][0]["restartCount"] == 0, status + with subtest("the log store and its responders run only as pods: the host has no container, unit or socket directory for them"): + machine.fail("test -e /etc/nixos-containers/swarm-victorialogs.conf") + assert host_state("container@swarm-victorialogs.service") == "inactive" + for unit in ("swarm-logs-auth", "swarm-logs-grafana-auth"): + machine.fail(f"systemctl cat {unit}.service") + machine.fail("test -e /run/swarm-victorialogs") + # The CA publisher is the control that the lookups find a unit of the cluster's that is there. + machine.succeed("systemctl cat hyperhive-k8s-ca-trust.service") + for name in (VL, LOGS_AUTH): + machine.succeed(f"test -L {MANIFESTS}/{name}.yaml") + 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 + + with subtest("the store's volume is the old container's directory, whose files keep the user that wrote them and whose tree the pod's group owns"): + pv = json.loads(kube(machine, f"get pv {VL}-store -o json")) + assert pv["spec"]["local"]["path"] == VL_DIR and pv["status"]["phase"] == "Bound", pv + pvc = json.loads(kube(machine, f"get pvc {VL}-store -o json")) + assert pvc["status"]["phase"] == "Bound" and pvc["spec"]["volumeName"] == pv["metadata"]["name"], pvc + assert machine.succeed(f"stat -c %g {VL_DIR}").strip() == "65532" + assert machine.succeed(f"find {VL_DIR} -type f -user ${legacyUser} | head -1").strip() != "" + assert machine.succeed(f"kubectl -n {NS} get pods {vl_pod} -o jsonpath='{{.status.containerStatuses[0].restartCount}}'").strip() == "0" + + def vl_request(path: str, token: str | None, *args: str) -> tuple[int, str]: + """One request to the gateway's locations: the status and the body.""" + auth = f"-H 'Authorization: Bearer {token}' " if token else "" + _, out = machine.execute(f"curl -sS --max-time 20 -w '\\n%{{http_code}}' {auth}{' '.join(args)} {GATEWAY}{path}") + body, _, code = out.rpartition("\n") + return int(code or 0), body + + def vl_query(token: str, text: str) -> tuple[int, str]: + return vl_request("/select/logsql/query", token, f"--data-urlencode 'query={text}'") + + def wait_for_record(token: str, text: str, record: str) -> None: + """Queries until the response holds `record`, for as long as the pod and + the policy engine take to settle.""" + deadline = time.monotonic() + 300 + while True: + status, body = vl_query(token, text) + if status == 200 and record in body: + return + assert time.monotonic() < deadline, (status, body) + time.sleep(3) + + AGENT_TOKEN = f"swarm-agent.{AGENT}.{AGENT_SECRETS[AGENT]}" + + with subtest("an agent's bearer reads the record written before the switch through the gateway, and the other bearers are granted or refused as the store says"): + wait_for_record(AGENT_TOKEN, "legacy", "written before the switch") + # Each refusal has the answer above as its control: the same request with + # a bearer the store grants. + assert vl_query(f"swarm-agent.{OTHER_AGENT}.{AGENT_SECRETS[OTHER_AGENT]}", "legacy")[0] == 403 + assert vl_query(f"swarm-agent.{AGENT}.{'0' * 32}", "legacy")[0] == 401 + # Grafana's bearer goes to the second responder of the same pod. + status, body = vl_query(GRAFANA_BEARER, "legacy") + assert status == 200 and "written before the switch" in body, (status, body) + assert vl_query("0" * 64, "legacy")[0] == 401 + + 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 + + def varint(n: int) -> bytes: + out = b"" + while n > 0x7F: + out += bytes([n & 0x7F | 0x80]) + n >>= 7 + return out + bytes([n]) + + def field(number: int, payload: bytes) -> bytes: + return varint(number << 3 | 2) + varint(len(payload)) + payload + + # An OTLP logs request with one record: time (field 1, fixed64) and a body + # (field 5) that is a string value. + now_ns = int(machine.succeed("date +%s%N")) + record = varint(1 << 3 | 1) + now_ns.to_bytes(8, "little") + field(5, field(1, b"written through the gateway")) + request = field(1, field(2, field(2, record))) + machine.succeed(f"echo {base64.b64encode(request).decode()} | base64 -d > /tmp/otlp.bin") + status, body = vl_request( + "/insert/opentelemetry/v1/logs", None, "-X POST -H 'Content-Type: application/x-protobuf' --data-binary @/tmp/otlp.bin" + ) + assert status == 200, (status, body) + wait_for_record(AGENT_TOKEN, "gateway", "written through the gateway") + status, body = vl_request("/metrics", None) + assert status == 200 and "vl_" in body, (status, body[:200]) + kube(machine, f"delete pod {vl_pod} --wait=true", timeout=120) + vl_pod = wait_pod_ready(VL) + wait_for_record(AGENT_TOKEN, "legacy", "written before the switch") + wait_for_record(AGENT_TOKEN, "gateway", "written through the gateway") + + with subtest("only the node reaches the log store's pods, and the responders' pod reaches the store's pod listener and no other port of the host"): + vl_ip = kube(machine, f"get pod {vl_pod} -o jsonpath='{{.status.podIP}}'").strip() + auth_ip = kube(machine, f"get pod {auth_pod} -o jsonpath='{{.status.podIP}}'").strip() + machine.succeed(f"curl -sf --max-time 5 http://{vl_ip}:9428/health") + # A peer pod reaches the classifier's health port, which has no policy: + # the control that the dial below is refused by the policy. + machine.succeed(dials(router_pid, classifier_ip, 8080)) + for ip, port in ((vl_ip, 9428), (auth_ip, 8081), (auth_ip, 8082)): + machine.succeed(f"timeout 5 bash -c ', + /// TCP address to serve on, for a caller that is not on this host's filesystem. + #[arg(long)] + listen: Option, /// Address to serve `/healthz` and `/readyz` on. Nothing listens unless set; /// the environment variable `SWARM_LOGS_AUTH_HEALTH_ADDR` is read when the flag is absent. #[arg(long)] @@ -225,21 +234,7 @@ async fn main() -> anyhow::Result<()> { )), }); - // `RuntimeDirectoryPreserve=yes` can leave the previous run's socket; the - // directory is this unit's alone, so unlinking it is safe. - if let Err(e) = std::fs::remove_file(&args.socket) - && e.kind() != std::io::ErrorKind::NotFound - { - return Err(e) - .with_context(|| format!("clearing stale socket at {}", args.socket.display())); - } - let listener = tokio::net::UnixListener::bind(&args.socket) - .with_context(|| format!("binding {}", args.socket.display()))?; - // nginx is another user and `connect(2)` needs write. The directory is - // the access control, not this mode. - std::fs::set_permissions(&args.socket, std::fs::Permissions::from_mode(0o666)) - .with_context(|| format!("chmod {}", args.socket.display()))?; - tracing::info!(socket = %args.socket.display(), "swarm-logs-auth listening"); + let bound = bind(args.socket.as_deref(), args.listen).await?; // Ready means the store answers: with it down every request is a 401. let probe = Arc::clone(&responder); health.ready_while_checked(move || { @@ -248,16 +243,59 @@ async fn main() -> anyhow::Result<()> { }); let app = axum::Router::new().fallback(handle).with_state(responder); - serve(listener, app, stop).await + match bound { + Bound::Unix(listener) => serve(listener, app, stop).await, + Bound::Tcp(listener) => serve(listener, app, stop).await, + } +} + +/// What the responder answers on. +enum Bound { + Unix(tokio::net::UnixListener), + Tcp(tokio::net::TcpListener), +} + +/// Binds `listen` when given, else `socket`; `Args` requires one of the two. +async fn bind( + socket: Option<&std::path::Path>, + listen: Option, +) -> anyhow::Result { + if let Some(addr) = listen { + let listener = tokio::net::TcpListener::bind(addr) + .await + .with_context(|| format!("binding {addr}"))?; + tracing::info!(%addr, "swarm-logs-auth listening"); + return Ok(Bound::Tcp(listener)); + } + let socket = socket.context("neither --socket nor --listen is set")?; + // `RuntimeDirectoryPreserve=yes` can leave the previous run's socket; the + // directory is this unit's alone, so unlinking it is safe. + if let Err(e) = std::fs::remove_file(socket) + && e.kind() != std::io::ErrorKind::NotFound + { + return Err(e).with_context(|| format!("clearing stale socket at {}", socket.display())); + } + let listener = tokio::net::UnixListener::bind(socket) + .with_context(|| format!("binding {}", socket.display()))?; + // nginx is another user and `connect(2)` needs write. The directory is + // the access control, not this mode. + std::fs::set_permissions(socket, std::fs::Permissions::from_mode(0o666)) + .with_context(|| format!("chmod {}", socket.display()))?; + tracing::info!(socket = %socket.display(), "swarm-logs-auth listening"); + Ok(Bound::Unix(listener)) } /// Answers on `listener` until `stop` resolves, then lets the requests in hand /// finish, for at most the drain, and returns. -async fn serve( - listener: tokio::net::UnixListener, +async fn serve( + listener: L, app: axum::Router, stop: impl Future + Clone + Send + 'static, -) -> anyhow::Result<()> { +) -> anyhow::Result<()> +where + L: axum::serve::Listener, + L::Addr: std::fmt::Debug, +{ let serving = axum::serve(listener, app).with_graceful_shutdown(stop.clone()); swarm_secret_client::serve_bounded(stop, serving.into_future()) .await @@ -559,4 +597,55 @@ mod tests { finished.expect("task").expect("serve is Ok"); let _ = std::fs::remove_file(&socket); } + fn args(extra: &[&str]) -> Result { + Args::try_parse_from( + ["swarm-logs-auth", "--surface", "logs"] + .into_iter() + .chain(extra.iter().copied()), + ) + } + + /// The socket and the TCP address are alternatives, and one is required. + #[test] + fn exactly_one_of_socket_and_listen_is_required() { + assert!(args(&[]).is_err()); + assert!(args(&["--socket", "/x", "--listen", "127.0.0.1:1"]).is_err()); + assert!(args(&["--socket", "/x"]).is_ok()); + assert!(args(&["--listen", "127.0.0.1:1"]).is_ok()); + } + + /// `--listen` answers over TCP, and `serve` returns once the stop arrives. + #[tokio::test] + async fn listen_answers_over_tcp_and_stops() { + let Bound::Tcp(listener) = bind(None, Some("127.0.0.1:0".parse().expect("addr"))) + .await + .expect("bind") + else { + panic!("--listen did not bind a TCP listener"); + }; + let addr = listener.local_addr().expect("addr"); + let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>(); + let stop = async move { + let _ = stop_rx.await; + } + .shared(); + let app = axum::Router::new().fallback(|| async { "answered" }); + let serving = tokio::spawn(serve(listener, app, stop)); + + let mut conn = tokio::net::TcpStream::connect(addr).await.expect("connect"); + conn.write_all(b"GET / HTTP/1.1\r\nhost: x\r\nconnection: close\r\n\r\n") + .await + .expect("send"); + let mut reply = String::new(); + conn.read_to_string(&mut reply).await.expect("reply"); + assert!(reply.starts_with("HTTP/1.1 200"), "{reply}"); + assert!(reply.ends_with("answered"), "{reply}"); + + stop_tx.send(()).expect("stop"); + tokio::time::timeout(Duration::from_secs(5), serving) + .await + .expect("serve returns after the stop") + .expect("task") + .expect("serve is Ok"); + } } diff --git a/swarm-metrics-auth/Cargo.toml b/swarm-metrics-auth/Cargo.toml index 635635f9f..26f12a48d 100644 --- a/swarm-metrics-auth/Cargo.toml +++ b/swarm-metrics-auth/Cargo.toml @@ -27,5 +27,7 @@ workspace = true # `test-util` for `#[tokio::test(start_paused = true)]`: the lookup-timeout # test waits out `LOOKUP_TIMEOUT` on paused time. [dev-dependencies] +# `Shared`, so the injected stop future can be cloned like `shutdown_signal`'s. +futures-util.workspace = true mockall.workspace = true tokio = { workspace = true, features = ["test-util"] } diff --git a/swarm-metrics-auth/src/main.rs b/swarm-metrics-auth/src/main.rs index daecb77a3..2f2057976 100644 --- a/swarm-metrics-auth/src/main.rs +++ b/swarm-metrics-auth/src/main.rs @@ -9,7 +9,9 @@ //! //! It reads the store under its own certificate, whose policy reaches that one //! path. It serves a unix socket whose directory only the gateway's nginx may -//! enter. +//! enter, or, with `--listen`, a TCP address for a gateway that is not on this +//! host's filesystem. The address is not authenticated: whoever reaches it is the +//! gateway. //! //! The stored value is kept for `--cache-ttl` seconds, and no request reaches //! the store within that window: a replaced bearer is refused, and the one it @@ -60,11 +62,17 @@ const LOOKUP_FAILURE_WINDOW: Duration = Duration::from_secs(3); const MAX_KEPT_AGE: Duration = Duration::from_hours(1); #[derive(Parser)] -#[command(about = "auth_request responder: checks Grafana's metrics bearer against the store")] +#[command( + about = "auth_request responder: checks Grafana's metrics bearer against the store", + group(clap::ArgGroup::new("bind").required(true).args(["socket", "listen"])) +)] struct Args { - /// Unix socket to serve on. + /// Unix socket to serve on. Exactly one of `--socket` and `--listen`. #[arg(long)] - socket: PathBuf, + socket: Option, + /// TCP address to serve on, for a caller that is not on this host's filesystem. + #[arg(long)] + listen: Option, /// Address to serve `/healthz` and `/readyz` on. Nothing listens unless set; /// the environment variable `SWARM_METRICS_AUTH_HEALTH_ADDR` is read when the flag is absent. #[arg(long)] @@ -312,21 +320,7 @@ async fn main() -> anyhow::Result<()> { cached: tokio::sync::Mutex::new(Cache::default()), }); - // `RuntimeDirectoryPreserve=yes` can leave the previous run's socket; the - // directory is this unit's alone, so unlinking it is safe. - if let Err(e) = std::fs::remove_file(&args.socket) - && e.kind() != std::io::ErrorKind::NotFound - { - return Err(e) - .with_context(|| format!("clearing stale socket at {}", args.socket.display())); - } - let listener = tokio::net::UnixListener::bind(&args.socket) - .with_context(|| format!("binding {}", args.socket.display()))?; - // nginx is another user and `connect(2)` needs write. The directory is - // the access control, not this mode. - std::fs::set_permissions(&args.socket, std::fs::Permissions::from_mode(0o666)) - .with_context(|| format!("chmod {}", args.socket.display()))?; - tracing::info!(socket = %args.socket.display(), "swarm-metrics-auth listening"); + let bound = bind(args.socket.as_deref(), args.listen).await?; // Ready means the store answers: with it down the bearer can't be checked. let probe = Arc::clone(&responder); health.ready_while_checked(move || { @@ -335,16 +329,59 @@ async fn main() -> anyhow::Result<()> { }); let app = axum::Router::new().fallback(handle).with_state(responder); - serve(listener, app, stop).await + match bound { + Bound::Unix(listener) => serve(listener, app, stop).await, + Bound::Tcp(listener) => serve(listener, app, stop).await, + } +} + +/// What the responder answers on. +enum Bound { + Unix(tokio::net::UnixListener), + Tcp(tokio::net::TcpListener), +} + +/// Binds `listen` when given, else `socket`; `Args` requires one of the two. +async fn bind( + socket: Option<&std::path::Path>, + listen: Option, +) -> anyhow::Result { + if let Some(addr) = listen { + let listener = tokio::net::TcpListener::bind(addr) + .await + .with_context(|| format!("binding {addr}"))?; + tracing::info!(%addr, "swarm-metrics-auth listening"); + return Ok(Bound::Tcp(listener)); + } + let socket = socket.context("neither --socket nor --listen is set")?; + // `RuntimeDirectoryPreserve=yes` can leave the previous run's socket; the + // directory is this unit's alone, so unlinking it is safe. + if let Err(e) = std::fs::remove_file(socket) + && e.kind() != std::io::ErrorKind::NotFound + { + return Err(e).with_context(|| format!("clearing stale socket at {}", socket.display())); + } + let listener = tokio::net::UnixListener::bind(socket) + .with_context(|| format!("binding {}", socket.display()))?; + // nginx is another user and `connect(2)` needs write. The directory is + // the access control, not this mode. + std::fs::set_permissions(socket, std::fs::Permissions::from_mode(0o666)) + .with_context(|| format!("chmod {}", socket.display()))?; + tracing::info!(socket = %socket.display(), "swarm-metrics-auth listening"); + Ok(Bound::Unix(listener)) } /// Answers on `listener` until `stop` resolves, then lets the requests in hand /// finish, for at most the drain, and returns. -async fn serve( - listener: tokio::net::UnixListener, +async fn serve( + listener: L, app: axum::Router, stop: impl Future + Clone + Send + 'static, -) -> anyhow::Result<()> { +) -> anyhow::Result<()> +where + L: axum::serve::Listener, + L::Addr: std::fmt::Debug, +{ let serving = axum::serve(listener, app).with_graceful_shutdown(stop.clone()); swarm_secret_client::serve_bounded(stop, serving.into_future()) .await @@ -356,7 +393,9 @@ async fn serve( #[cfg(test)] mod tests { use super::*; + use futures_util::FutureExt as _; use std::pin::Pin; + use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; type Lookup = Pin>> + Send>>; type Answer = fn() -> Lookup; @@ -727,4 +766,55 @@ mod tests { assert!(cache.stored.is_none()); assert_eq!(cache.expire_kept(t0 + MAX_KEPT_AGE * 2), None); } + fn args(extra: &[&str]) -> Result { + Args::try_parse_from( + ["swarm-metrics-auth", "--store-path", "p"] + .into_iter() + .chain(extra.iter().copied()), + ) + } + + /// The socket and the TCP address are alternatives, and one is required. + #[test] + fn exactly_one_of_socket_and_listen_is_required() { + assert!(args(&[]).is_err()); + assert!(args(&["--socket", "/x", "--listen", "127.0.0.1:1"]).is_err()); + assert!(args(&["--socket", "/x"]).is_ok()); + assert!(args(&["--listen", "127.0.0.1:1"]).is_ok()); + } + + /// `--listen` answers over TCP, and `serve` returns once the stop arrives. + #[tokio::test] + async fn listen_answers_over_tcp_and_stops() { + let Bound::Tcp(listener) = bind(None, Some("127.0.0.1:0".parse().expect("addr"))) + .await + .expect("bind") + else { + panic!("--listen did not bind a TCP listener"); + }; + let addr = listener.local_addr().expect("addr"); + let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>(); + let stop = async move { + let _ = stop_rx.await; + } + .shared(); + let app = axum::Router::new().fallback(|| async { "answered" }); + let serving = tokio::spawn(serve(listener, app, stop)); + + let mut conn = tokio::net::TcpStream::connect(addr).await.expect("connect"); + conn.write_all(b"GET / HTTP/1.1\r\nhost: x\r\nconnection: close\r\n\r\n") + .await + .expect("send"); + let mut reply = String::new(); + conn.read_to_string(&mut reply).await.expect("reply"); + assert!(reply.starts_with("HTTP/1.1 200"), "{reply}"); + assert!(reply.ends_with("answered"), "{reply}"); + + stop_tx.send(()).expect("stop"); + tokio::time::timeout(Duration::from_secs(5), serving) + .await + .expect("serve returns after the stop") + .expect("task") + .expect("serve is Ok"); + } }