Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/nix/module-eval/k8s.nix
atlas 9f62e71dae run grafana as a pod in the cluster
The Deployment swarm-grafana replaces the swarm-grafana container: one
replica on a static local volume that is the container's data directory,
an init container that fetches the OIDC client secret and creates the
administrator password, the datasources' bearer and the encryption key in
the secret store, and a sidecar that keeps the controller's Viewer token.
The datasources reach the stores through the gateway with that bearer, and
Grafana's /metrics asks for the stores' kind of credential, which the vhost
sends. The five host units, the journal forwarder, its client glue and the
unix-socket directory go with the container.
2026-11-28 10:01:39 +01:00

3243 lines
142 KiB
Nix

# `checks.module-eval-k8s` — see ./lib.nix for the shared rationale. The k8s
# manifests ../host-modules/k8s/render.nix builds from the single-host swarm's
# units: each workload carries its unit's environment, no credential source
# reaches the world-readable YAML, and the CronJob follows the timer. And the
# k3s node ../host-modules/k8s/node.nix adds to that host: present with
# `deploy.k8s.enable`, absent and changing nothing without it.
#
# The all-local host with the node on is this cluster's own fixture; the
# rest are shared ones.
{
pkgs,
lib,
self,
nixosSystem,
shared,
}:
let
inherit
(import ./lib.nix {
inherit
pkgs
lib
self
nixosSystem
;
})
runGroup
hive
hiveWith
hiveWithController
baoSettings
bridgePorts
;
allLocal = shared.allLocal;
# The all-local host with the node on, shared with the manifests' schema check.
nodeSettings = shared.k8sNodeSettings;
withNode = shared.k8sNode;
# The all-local host with every service that runs in the cluster, which the
# mode enables, and the cluster, which the services enable by default.
onCluster = withNode;
# The same host with those services off, so it has no node: the control for
# what the node adds.
noNode = hiveWithController (
lib.recursiveUpdate nodeSettings {
deploy.notify-router.enable = false;
deploy.stt.enable = false;
deploy.ci-metrics.enable = false;
deploy.review-classifier.enable = false;
deploy.claude-login.enable = false;
deploy.swarm-controller.enable = false;
deploy.nats.enable = false;
deploy.victorialogs.enable = false;
deploy.victoriametrics.enable = false;
deploy.grafana.enable = false;
}
);
# The node with NetworkManager on, a host that has no node with it on, and
# (below, `joined`) an agent with it on. `allLocal` is the node with it off.
networkManagerOn = {
networking.networkmanager.enable = true;
};
nodeWithNm = hiveWith [ networkManagerOn ] (
lib.recursiveUpdate { deploy.hive-controller.enable = true; } nodeSettings
);
noClusterWithNm = hiveWith [ networkManagerOn ] { deploy.hive-controller.enable = false; };
# Two hives on a store host with the node: the policy of each differs by the
# join token. Shares nothing of `onCluster`'s controller, which lists the
# hives.
twoHives = hive {
deploy.bao.enable = true;
deploy.k8s.enable = true;
swarm.hives.h2.domain = "h2.t.local";
};
# The mesh interface a federated hive runs on the same host (`wg0` on UDP
# 51820, as in the semi-spread example), which the two fixtures below carry:
# a host that is a cluster node and in the mesh is the expected deployment.
semiSpreadWg = {
networking.wireguard.interfaces.wg0 = {
ips = [ "10.77.0.2/24" ];
listenPort = 51820;
privateKeyFile = "/etc/wireguard/wg0.key";
};
};
# A host that joins that cluster: an agent with the store identity its join
# token is read under. The only fixture without `deploy.k8s.enable`, which
# is what it claims about.
joined = hiveWith [ semiSpreadWg networkManagerOn ] {
deploy.k8s.join.server = "192.168.1.10";
deploy.k8s.address = "192.168.1.11";
deploy.hive-controller.tls = {
baoHiveIdentityCertFile = "/var/lib/hive-leaf/leaf.pem";
baoHiveIdentityKeyFile = "/var/lib/hive-leaf/leaf-key.pem";
};
};
joinedUnit = joined.systemd.services.k3s-join-token;
# Every image the cluster's pods name, and where the pull policy is.
registryPrefix = "registry.hyperhive.invalid/";
clusterText =
builtins.toJSON (render onCluster)
+ builtins.toJSON onCluster.services.hyperhive.k8s.rendered.services;
imageRefs = map (s: lib.head (lib.splitString "\"" s)) (
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; };
# A host that turns the node off with the services on, and a controller with
# no TCP listener, a bind address inside the pod that cannot be reached, and
# no resolver for the cluster's names.
nodeOffRefused = hive {
deploy.k8s.enable = false;
deploy.notify-router.enable = true;
deploy.stt.enable = true;
deploy.ci-metrics.enable = true;
deploy.review-classifier.enable = true;
deploy.claude-login.enable = true;
deploy.swarm-controller.enable = true;
swarm.controller.tcp.enable = false;
deploy.swarm-controller.tcp.listenAddress = "10.0.0.5";
deploy.nats.enable = true;
deploy.nats.authPackage = pkgs.emptyDirectory;
gateway.dns.enable = lib.mkForce false;
};
nodeOffRefusals = lib.filter (a: !a.assertion) nodeOffRefused.assertions;
# A node every assertion refuses: no rendering, a pod range containing the
# hive bridge's subnet, and a service range inside the pod range.
nodeRefused = hive {
deploy.k8s.enable = true;
k8s.enable = false;
network.enable = true;
deploy.k8s.podCidr = "10.42.0.0/16";
deploy.k8s.serviceCidr = "10.42.128.0/17";
};
# The node on a host with no hive bridge, so no address to resolve names to.
nodeNoBridge = hiveWith [ semiSpreadWg ] { deploy.k8s.enable = true; };
coreDnsKey = "hyperhive-host-services.override";
refusals = lib.filter (a: !a.assertion) nodeRefused.assertions;
refuses = needle: lib.any (a: hasInfix needle a.message) refusals;
render =
config:
(import ../host-modules/k8s/render.nix {
inherit lib pkgs config;
}).objects;
objects = render allLocal;
unitOf = name: allLocal.services.hyperhive.deploy.${name}.unit;
units = {
swarm-controller = unitOf "swarm-controller";
swarm-notify-router = unitOf "notify-router";
swarm-stt = unitOf "stt";
swarm-review-classifier = unitOf "review-classifier";
swarm-claude-login = unitOf "claude-login";
swarm-ci-metrics = unitOf "ci-metrics";
};
podSpec =
name:
let
o = objects."${name}/deployment" or objects."${name}/cronjob";
in
if o.kind == "CronJob" then o.spec.jobTemplate.spec.template.spec else o.spec.template.spec;
container = name: lib.head (podSpec name).containers;
envOf = name: lib.listToAttrs (map (e: lib.nameValuePair e.name e.value) (container name).env);
# The unit's environment as the pod should see it: no PATH, and `%d`
# spelled out as the credential directory.
unitEnv =
name:
lib.mapAttrs (
_: v: builtins.replaceStrings [ "%d" ] [ "/run/credentials/${name}.service" ] (toString v)
) (removeAttrs units.${name}.environment [ "PATH" ]);
# Where a pod pushes telemetry: the name the hive collector answers to, on
# the port it binds. A literal, so the render and the collector are not
# compared with themselves.
collectorEndpoint = "http://hive-collector.hive:4318";
# What the pod's environment changes about the store login: no client
# certificate or key, and the token login on the listener that asks for no
# certificate. Spelled out here, not read from the module.
storeLogin = name: {
BAO_ADDR = "https://${allLocal.services.hyperhive.swarm.bao.domain}:8208";
BAO_AUTH = "jwt";
BAO_JWT_FILE = "/var/run/secrets/hyperhive/bao/token";
BAO_JWT_ROLE = name;
BAO_JWT_MOUNT = "jwt-k8s";
};
clientVars = [
"BAO_CLIENT_CERT"
"BAO_CLIENT_KEY"
];
# What the pod adds on top of the unit's own environment.
added = {
# No endpoint: the controller keeps the swarm route its unit names.
swarm-controller = {
RUNTIME_DIRECTORY = "/run/swarm-controller";
STATE_DIRECTORY = "/var/lib/swarm-controller";
SWARM_CONTROLLER_HEALTH_ADDR = "127.0.0.1:8080";
};
swarm-notify-router = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_NOTIFY_ROUTER_HEALTH_ADDR = "127.0.0.1:8080";
};
swarm-stt = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_STT_HEALTH_ADDR = "127.0.0.1:8080";
STATE_DIRECTORY = "/var/lib/swarm-stt";
};
swarm-review-classifier = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_REVIEW_CLASSIFIER_HEALTH_ADDR = "127.0.0.1:8080";
};
swarm-claude-login = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_CLAUDE_LOGIN_HEALTH_ADDR = "127.0.0.1:8080";
};
# No endpoint: the poller keeps the route its unit names.
swarm-ci-metrics = {
STATE_DIRECTORY = "/var/lib/swarm-ci-metrics";
};
};
# Host paths the credentials are loaded from: the host units' own
# `LoadCredential=id:source`, and the router container's nspawn flags.
credentialSources =
lib.concatMap
(
e:
let
parts = lib.splitString ":" e;
in
lib.optional (lib.length parts > 1) (lib.last parts)
)
(
units.swarm-controller.serviceConfig.LoadCredential
++ units.swarm-ci-metrics.serviceConfig.LoadCredential
)
# The four daemons' store identity files on the host, which their units name by id only.
++ lib.filter (p: p != null) (
map (n: allLocal.services.hyperhive.deploy.bao.${n}) [
"notifyRouterClientCertFile"
"notifyRouterClientKeyFile"
"sttClientCertFile"
"sttClientKeyFile"
"reviewClassifierClientCertFile"
"reviewClassifierClientKeyFile"
"claudeLoginClientCertFile"
"claudeLoginClientKeyFile"
]
);
credentialIds = lib.concatMap (
u: map (e: lib.head (lib.splitString ":" e)) u.serviceConfig.LoadCredential
) (lib.attrValues units);
rendered = builtins.unsafeDiscardStringContext (builtins.toJSON objects);
# The credentials that hold a client certificate or its key: the pods log in
# with a token instead.
clientCertIds = [
"bao-client.pem"
"bao-client-key.pem"
"notify-router-bao-cert"
"notify-router-bao-key"
"stt-bao-cert"
"stt-bao-key"
"review-classifier-bao-cert"
"review-classifier-bao-key"
"claude-login-bao-cert"
"claude-login-bao-key"
];
ciTimer = allLocal.services.hyperhive.deploy.ci-metrics.timer.timerConfig;
cron = objects."swarm-ci-metrics/cronjob".spec;
# The same host with one more variable on the poller's unit, naming a path
# the pod does not mount.
withStrayPath = lib.recursiveUpdate allLocal {
services.hyperhive.deploy.ci-metrics.unit.environment.SWARM_CI_METRICS_STRAY = "/etc/stray.json";
};
# The same host with the poller's unit naming no endpoint of its own.
withoutOwnEndpoint = lib.recursiveUpdate allLocal {
services.hyperhive.deploy.ci-metrics.unit.environment.SWARM_CI_METRICS_OTLP_ENDPOINT = null;
};
renders =
config: (builtins.tryEval (builtins.deepSeq (builtins.toJSON (render config)) true)).success;
# Whether a volume holds a Secret, plain or among a projected volume's
# sources. The control that the lookup sees one is a literal of each shape,
# since no pod of this host mounts a Secret.
usesSecret = v: v ? secret || lib.any (src: src ? secret) (v.projected.sources or [ ]);
secretLookupWorks =
usesSecret { secret.secretName = "x"; }
&& usesSecret { projected.sources = [ { secret.name = "x"; } ]; }
&& !(usesSecret { projected.sources = [ { configMap.name = "x"; } ]; });
manifestNames = c: lib.sort lib.lessThan (lib.attrNames c.services.k3s.manifests);
clusterRouterSpec = (render onCluster)."swarm-notify-router/deployment".spec.template.spec;
cases = [
{
# Each service's own credential path is the control: the comparison
# reads a non-empty environment.
name = "each workload carries its unit's environment, plus only its directories, its health listener and the token login to the store";
ok =
lib.all (
name: envOf name == removeAttrs (unitEnv name) clientVars // storeLogin name // added.${name}
) (lib.attrNames units)
# The units keep their certificates, and the pods name none.
&&
(unitEnv "swarm-controller").BAO_CLIENT_CERT
== "/run/credentials/swarm-controller.service/bao-client.pem"
&& lib.all (name: lib.all (v: (unitEnv name) ? ${v} && !((envOf name) ? ${v})) clientVars) (
lib.attrNames units
)
&& (envOf "swarm-notify-router") ? SWARM_NOTIFY_ROUTER_NATS_URL;
}
{
# The ids are the control: they are in the same text, so the search
# finds what is there.
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: 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 && !(hasInfix "\"${id}\"" rendered)) clientCertIds
&& !(lib.any (o: o.kind == "Secret") (lib.attrValues objects))
&& secretLookupWorks
&& !(lib.any usesSecret (podSpec "swarm-controller").volumes);
}
{
name = "the poller's CronJob runs on its timer's interval and deadline, never overlapping";
ok =
ciTimer.OnUnitInactiveSec == "5min"
&& cron.schedule == "*/5 * * * *"
&& cron.concurrencyPolicy == "Forbid"
&& cron.jobTemplate.spec.activeDeadlineSeconds == 1800;
}
{
name = "the router's probes reach the listener its variable binds, and every pod outlasts the drain";
ok =
let
c = container "swarm-notify-router";
in
!(c ? ports)
&& lib.last c.readinessProbe.exec.command == "http://127.0.0.1:8080/readyz"
&& lib.last c.livenessProbe.exec.command == "http://127.0.0.1:8080/healthz"
&& lib.all (name: (podSpec name).terminationGracePeriodSeconds > 10) (lib.attrNames units);
}
{
# The presence arms are the controls: the listener's variables, the probes
# and the VictoriaLogs/Metrics `api` probes are found, so an empty list
# cannot pass.
name = "every health listener binds to the pod's loopback and is probed by exec, and no pod declares a port for it";
ok =
let
workloads = lib.filter (o: o.kind == "Deployment" || o.kind == "CronJob") (lib.attrValues objects);
podOf =
o: if o.kind == "CronJob" then o.spec.jobTemplate.spec.template.spec else o.spec.template.spec;
cs = lib.concatMap (o: (podOf o).containers) workloads;
env = c: lib.listToAttrs (map (e: lib.nameValuePair e.name e.value) (c.env or [ ]));
healthAddrs = lib.concatMap (
c: lib.attrValues (lib.filterAttrs (n: _: lib.hasSuffix "_HEALTH_ADDR" n) (env c))
) cs;
probes = lib.concatMap (
c:
lib.filter (p: p != null) [
(c.livenessProbe or null)
(c.readinessProbe or null)
(c.startupProbe or null)
]
) cs;
httpProbes = lib.filter (p: p ? httpGet) probes;
execProbes = lib.filter (p: p ? exec) probes;
in
lib.length healthAddrs == 10
&& lib.all (a: lib.hasPrefix "127.0.0.1:" a) healthAddrs
&& lib.length execProbes >= 20
&& lib.all (p: lib.hasPrefix "http://127.0.0.1:" (lib.last p.exec.command)) execProbes
&& lib.all (p: p.timeoutSeconds == 5) execProbes
&& httpProbes != [ ]
&& lib.all (p: p.httpGet.port == "api") httpProbes
&& !(lib.any (
p:
lib.elem p.name [
"health"
"grafana-health"
]
) (lib.concatMap (c: c.ports or [ ]) cs));
}
{
# The unchanged host is the control that the render itself succeeds.
name = "a unit variable naming a path the pod does not mount fails the render";
ok = renders allLocal && !(renders withStrayPath);
}
{
# The host without the node is the control that the lookups find what
# is there: the same paths on the host with it on.
name = "the node exists only where deploy.k8s.enable is set";
ok =
!noNode.services.k3s.enable
&& !(noNode.systemd.services ? k3s)
&& noNode.services.k3s.images == [ ]
&& !(lib.elem "cni0" noNode.networking.firewall.trustedInterfaces)
&& withNode.services.k3s.enable
&& withNode.services.k3s.role == "server"
&& withNode.systemd.services ? k3s
&& lib.elem "cni0" withNode.networking.firewall.trustedInterfaces
&& lib.elem "flannel-wg" withNode.networking.firewall.trustedInterfaces
&& !(lib.elem "flannel.1" withNode.networking.firewall.trustedInterfaces);
}
{
name = "the node runs k3s with traefik and metrics-server off and its secrets encrypted";
ok =
let
start = withNode.systemd.services.k3s.serviceConfig.ExecStart;
in
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 log store's and its two responders', and the metrics store's and
# its two: the seventeen 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 == 19
&& lib.all (i: lib.elem i loaded) rendered
&& lib.elem (toString withNode.services.k3s.package.airgap-images) loaded
&& lib.length loaded == 20;
}
{
# The all-local host's assertions are the control: they all hold.
name = "the node refuses a host that does not render the manifests it loads";
ok = lib.all (a: a.assertion) withNode.assertions && refuses "deploy.k8s.enable loads the images";
}
{
# The default ranges on the all-local host, whose bridge is up, are the
# control: the same assertions hold there, and the flags carry the ranges.
name = "the node refuses pod and service ranges that overlap the hive bridge or each other";
ok =
withNode.services.hyperhive.network.enable
&& withNode.services.hyperhive.network.networkCidr == "10.42.0.0/24"
&& withNode.services.hyperhive.deploy.k8s.podCidr == "10.200.0.0/16"
&& withNode.services.hyperhive.deploy.k8s.serviceCidr == "10.201.0.0/16"
&& refuses "overlap the hive bridge"
&& refuses "overlap each other";
}
{
# NetworkManager rewrites the routes of the interfaces the CNI makes, so
# it is told to leave `cni0`, flannel's devices and the pods' veth ends
# alone, on the node and on an agent. The literals are spelled here, not
# read from the module. Each absence arm has its presence control: the
# node and the agent have the list, so the lookup finds it where it is.
name = "NetworkManager leaves the pod network's interfaces unmanaged on a node and on an agent, and is untouched where it is off or where there is no cluster";
ok =
let
expected = [
"interface-name:cni0"
"interface-name:flannel*"
"interface-name:veth*"
];
in
nodeWithNm.networking.networkmanager.unmanaged == expected
&& joined.networking.networkmanager.unmanaged == expected
&& !allLocal.networking.networkmanager.enable
&& allLocal.networking.networkmanager.unmanaged == [ ]
&& noClusterWithNm.networking.networkmanager.enable
&& noClusterWithNm.networking.networkmanager.unmanaged == [ ];
}
{
# An agent takes the backend from its server, and `--flannel-backend` is
# a server flag that an agent refuses, so the agent's flags carry none.
# The agent is the control that the lookup reads the flag list.
name = "the server runs flannel's WireGuard backend, and the joined agent sets no backend flag";
ok =
lib.elem "--flannel-backend=wireguard-native" withNode.services.k3s.extraFlags
&& lib.elem "--flannel-backend=wireguard-native" nodeNoBridge.services.k3s.extraFlags
&& !(lib.any (lib.hasPrefix "--flannel-backend") joined.services.k3s.extraFlags)
&& lib.elem "--embedded-registry" withNode.services.k3s.extraFlags
&& joined.services.k3s.role == "agent"
&& lib.elem "flannel-wg" joined.networking.firewall.trustedInterfaces
&& !(lib.elem "flannel.1" joined.networking.firewall.trustedInterfaces);
}
{
# The mesh interface is the control that the fixtures carry what the
# case is about, and its port is what the tunnel must not take.
name = "a cluster node that is also in the semi-spread mesh evaluates, and flannel's tunnel listens on a port other than the mesh's";
ok =
let
port = nodeNoBridge.services.hyperhive.deploy.k8s.flannelWgPort;
# The net-conf spelled out here, so the path (a hash of its text) says
# what the file holds, the tunnel's port among it.
expected = pkgs.writeText "flannel-net-conf.json" (
builtins.toJSON {
Network = "10.200.0.0/16";
EnableIPv4 = true;
EnableIPv6 = false;
IPv6Network = "::/0";
Backend = {
Type = "wireguard";
PersistentKeepaliveInterval = 25;
ListenPort = port;
};
}
);
flag = "--flannel-conf=${expected}";
in
nodeNoBridge.networking.wireguard.interfaces.wg0.listenPort == 51820
&& joined.networking.wireguard.interfaces.wg0.listenPort == 51820
&& lib.all (a: a.assertion) nodeNoBridge.assertions
&& lib.all (a: a.assertion) joined.assertions
&& port != 51820
&& joined.services.hyperhive.deploy.k8s.flannelWgPort == port
&& lib.elem flag nodeNoBridge.services.k3s.extraFlags
&& lib.elem flag withNode.services.k3s.extraFlags
&& lib.elem flag joined.services.k3s.extraFlags;
}
{
# Without an address, the node of the same server is the control: it
# advertises no external IP, and the tunnel follows the default route.
name = "a node with an address advertises it as its external IP so flannel's tunnel runs on it, and the server asks flannel to use external IPs";
ok =
lib.elem "--node-external-ip=192.168.1.10" withNode.services.k3s.extraFlags
&& lib.elem "--flannel-external-ip" withNode.services.k3s.extraFlags
&& lib.elem "--node-external-ip=192.168.1.11" joined.services.k3s.extraFlags
&& !(lib.elem "--flannel-external-ip" joined.services.k3s.extraFlags)
&& lib.elem "--flannel-external-ip" nodeNoBridge.services.k3s.extraFlags
&& !(lib.any (lib.hasPrefix "--node-external-ip") nodeNoBridge.services.k3s.extraFlags);
}
{
# The names are the control that the search finds something: the swarm's
# own bao name and the hive domain are among them, and every one is in the
# A and AAAA templates.
name = "the node's CoreDNS answers every swarm name this host serves with the hive bridge's address";
ok =
let
h = withNode.services.hyperhive;
cm = withNode.services.k3s.manifests.coredns-custom.content;
text = cm.data.${coreDnsKey};
names = lib.unique ([ h.domain ] ++ h.gateway.localNames);
in
cm.kind == "ConfigMap"
&& cm.metadata.name == "coredns-custom"
&& cm.metadata.namespace == "kube-system"
&& lib.length names >= 6
&& lib.elem h.swarm.bao.domain names
&& 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);
}
{
# The host with the node on and a bridge is the control that the manifest
# is there to be absent.
name = "the node applies the CoreDNS override only on a host with the hive bridge";
ok =
withNode.services.hyperhive.network.enable
&& withNode.services.k3s.manifests ? coredns-custom
&& noNode.services.k3s.manifests == { }
&& !nodeNoBridge.services.hyperhive.network.enable
&& nodeNoBridge.services.hyperhive.domain == "h1.t.local"
&& nodeNoBridge.services.hyperhive.deploy.k8s.hostServices == { }
&& !(nodeNoBridge.services.k3s.manifests ? coredns-custom);
}
{
# The units' own endpoints are the control: each differs from the
# collector's, so the override replaces something. The host's units keep
# theirs. The poller and the controller are swarm-tier producers: their
# pods keep the swarm collector's route of their own, spelled out here, and
# name no hive collector in any variable.
name = "every hive-tier pod pushes telemetry to the hive collector, the poller's and the controller's pods keep their swarm routes, and the host units keep their endpoints";
ok =
let
swarmTier = [
"swarm-ci-metrics"
"swarm-controller"
];
hiveTier = lib.filter (n: !(lib.elem n swarmTier)) (lib.attrNames units);
ownRoute = "https://${allLocal.services.hyperhive.swarm.otel.domain}/swarm-ci-metrics";
controllerRoute = "https://${allLocal.services.hyperhive.swarm.otel.domain}/${allLocal.services.hyperhive.swarm.otel.producerName}";
in
lib.length hiveTier == 4
&& lib.all (
name:
(envOf name).OTEL_EXPORTER_OTLP_ENDPOINT == collectorEndpoint
&& (units.${name}.environment.OTEL_EXPORTER_OTLP_ENDPOINT or null) != collectorEndpoint
) hiveTier
&& 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: 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: hasInfix "hive-collector" (e.value or "")) (container "swarm-controller").env);
}
{
# The unchanged host is the control that the render itself succeeds.
name = "a poller whose unit names no endpoint of its own fails the render, as the pod would have nowhere to push";
ok = renders allLocal && !(renders withoutOwnEndpoint);
}
{
# Off, the collector's configuration holds nothing of the pod logs, and
# on, taking that out leaves the configuration it has off. The host with
# the node on is the control that the lookups find what is there.
name = "the collector reads pod logs only where deploy.k8s.enable is set";
ok =
let
mine = {
receivers = [ "file_log/pods" ];
processors = [ "transform/pod-service-name" ];
};
settings = c: c.services.opentelemetry-collector.settings;
bare =
s:
s
// {
receivers = removeAttrs s.receivers mine.receivers;
processors = removeAttrs s.processors mine.processors;
service = s.service // {
pipelines = removeAttrs s.service.pipelines [ "logs/pods" ];
};
};
unit = c: c.systemd.services.opentelemetry-collector.serviceConfig;
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")
&& (settings withNode).receivers ? "file_log/pods"
&& (settings withNode).service.pipelines ? "logs/pods"
&& bare (settings withNode) == settings noNode
&& (unit noNode).DynamicUser
&& !(unit noNode ? User)
&& !(noNode.users.users ? opentelemetry-collector)
&& collectorAcls noNode == [ ]
&& !(unit withNode).DynamicUser
&& (unit withNode).User == "opentelemetry-collector"
&& withNode.users.users.opentelemetry-collector.isSystemUser;
}
{
# The receiver reads the files kubelet's runtime writes, the parser reads
# the CRI framing and then hive-log's level, and the service name is the
# container's without `swarm-`. The ACL is on /var/log/pods alone, access
# and default, for the collector's user.
name = "the pod logs receiver parses CRI and the text level, names the service, and the ACL covers /var/log/pods only";
ok =
let
s = withNode.services.opentelemetry-collector.settings;
r = s.receivers."file_log/pods";
ops = r.operators;
op = t: lib.findFirst (o: o.type == t) null ops;
statements = lib.concatMap (
l: l.statements
) s.processors."transform/pod-service-name".log_statements;
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: hasInfix l (op "regex_parser").regex) [
"WARN"
"ERROR"
"INFO"
"DEBUG"
"TRACE"
]
&& (op "severity_parser").parse_from == "attributes.level"
&& (op "severity_parser").overwrite_text
&& lib.elem ''set(attributes["service.name"], attributes["k8s.container.name"])'' statements
&& lib.elem ''replace_pattern(attributes["service.name"], "^swarm-", "")'' statements
&&
s.service.pipelines."logs/pods" == {
receivers = [ "file_log/pods" ];
processors = [ "transform/pod-service-name" ];
exporters = [ "otlphttp/swarm" ];
}
&& s.exporters ? "otlphttp/swarm"
&& lib.elem "file_storage" s.service.extensions
&&
acls == [ "A+ /var/log/pods - - - - u:opentelemetry-collector:rX,d:u:opentelemetry-collector:rX" ];
}
{
# The projected token is the pod's only credential from its account, and
# the roles in the store bind exactly this account and audience.
name = "each in-cluster service runs under its own ServiceAccount, with a token projected for the store's audience";
ok =
lib.all (
name:
let
sa = objects."${name}/serviceaccount";
vol = lib.findFirst (v: v.name == "bao-token") null (podSpec name).volumes;
mount = lib.findFirst (m: m.name == "bao-token") null (container name).volumeMounts;
source = (lib.head vol.projected.sources).serviceAccountToken;
in
sa.kind == "ServiceAccount"
&& sa.metadata.name == name
&& sa.metadata.namespace == "hyperhive"
&& !sa.automountServiceAccountToken
&& (podSpec name).serviceAccountName == name
&& !(podSpec name).automountServiceAccountToken
&& vol != null
&& lib.attrNames (lib.head vol.projected.sources) == [ "serviceAccountToken" ]
&& source.audience == "bao"
&& source.expirationSeconds >= 600
&& mount.mountPath == "/var/run/secrets/hyperhive/bao"
&& mount.readOnly
&& (envOf name).BAO_JWT_FILE == "${mount.mountPath}/${source.path}"
) (lib.attrNames units)
# The control: the credentials volume is still there beside it.
&& lib.any (v: v.name == "credentials") (podSpec "swarm-controller").volumes
&& lib.length (lib.filter (v: v.name == "bao-token") (podSpec "swarm-controller").volumes) == 1;
}
{
# The off arm and the on arm read the same unit, so what differs is the
# node alone. Roles are written one to one with the principals' cert
# roles: the same name, policy and token lifetimes.
name = "the store writes one jwt role per in-cluster service, binding its account and audience, with its cert role's policy and lifetimes";
ok =
let
s = withNode.systemd.services;
script = s.swarm-bao-k8s-jwt-policy.script;
certScript = {
swarm-notify-router = s.swarm-bao-notify-router-policy.script;
swarm-stt = s.swarm-bao-stt-policy.script;
swarm-review-classifier = s.swarm-bao-review-classifier-policy.script;
swarm-claude-login = s.swarm-bao-claude-login-policy.script;
swarm-ci-metrics = s.swarm-bao-ci-metrics-policy.script;
swarm-controller = s.swarm-bao-controller-policy.script;
};
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, and the log and metrics stores'
# responders and Grafana hold one role each of their own: a case each.
roles = lib.filter (
r:
!(lib.hasPrefix "swarm-nats" r)
&& !(lib.elem r [
"swarm-logs-auth"
"swarm-metrics-auth"
"swarm-grafana-oidc"
])
) allRoles;
ttl = "token_ttl=1h \\\n token_max_ttl=1h";
roleText = name: ''
bao write auth/jwt-k8s/role/${name} \
role_type=jwt \
user_claim=sub \
bound_subject=system:serviceaccount:hyperhive:${name} \
bound_audiences=bao \
token_policies=${name} \
${ttl}
'';
in
lib.length roles == 6
&& lib.sort lib.lessThan roles == lib.sort lib.lessThan (lib.attrNames units)
&&
lib.sort lib.lessThan withNode.services.hyperhive.deploy.bao.k8sPrincipals
== lib.sort lib.lessThan allRoles
&& lib.all (
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
&& hasInfix "bao write auth/jwt-k8s/config -" script;
}
{
# The two roles are the leaf's and the responder's, each with its cert
# role's policy, and both bind the one account the pod runs under. The
# responder's lifetimes are its cert role's batch token.
name = "the store writes the queue's two jwt roles, each with its cert role's policy and both bound to the pod's one account";
ok =
let
s = withNode.systemd.services;
script = s.swarm-bao-k8s-jwt-policy.script;
role = name: ''
bao write auth/jwt-k8s/role/${name} \
role_type=jwt \
user_claim=sub \
bound_subject=system:serviceaccount:hyperhive:swarm-nats \
bound_audiences=bao \
token_policies=${name} \
'';
in
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.
&& (podSpec "swarm-nats").serviceAccountName == "swarm-nats"
&& objects."swarm-nats/serviceaccount".metadata.name == "swarm-nats";
}
{
# The keys come from the node's own files, and the issuer is the one the
# node's flags give its API server.
name = "the jwt config is the public half of k3s's ServiceAccount keys and its issuer, derived by a unit ordered after k3s";
ok =
let
u = withNode.systemd.services.swarm-bao-k8s-jwt-policy;
start = withNode.systemd.services.k3s.serviceConfig.ExecStart;
in
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;
}
{
# The mount is a bootstrap-token act, like the oidc one, and the granter
# may then write its config and roles only.
name = "the granter's role unit enables the jwt mount, the bootstrap policy carries it and the granter writes its config and roles";
ok =
let
g = withNode.systemd.services.swarm-bao-granter-role;
hcl = builtins.readFile ../host-modules/bao-bootstrap-policy.hcl;
in
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
# the host without it lacks.
name = "without the node the store has no pod listener, jwt mount, jwt unit or firewall rule for pods";
ok =
let
off = noNode.systemd.services.swarm-bao-granter-role;
on = withNode.systemd.services.swarm-bao-granter-role;
in
(baoSettings withNode).listener ? pod
&& withNode.systemd.services ? swarm-bao-k8s-jwt-policy
&& 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)
&& !(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-wg");
}
{
# Pods log in on a listener that asks for no client certificate, and no
# other listener has lost the requirement.
name = "the pods' listener asks for no client certificate and every other API listener still does";
ok =
let
l = (baoSettings withNode).listener;
others = removeAttrs l [
"metrics"
"ui"
"pod"
];
in
l.pod.type == "tcp"
&& l.pod.address == "${withNode.services.hyperhive.network.bridgeIp}:8208"
&& l.pod.cluster_address == "127.0.0.1:8209"
&& l.pod ? tls_cert_file
&& l.pod.tls_client_ca_file == l.loopback.tls_client_ca_file
&& !(l.pod ? tls_require_and_verify_client_cert)
&& others ? loopback
&& lib.all (x: (x.tls_require_and_verify_client_cert or false) == true) (lib.attrValues others);
}
{
# An agent on the hive bridge reaches a port only if the bridge's own
# firewall lists it, so the port's absence there is the whole of its
# isolation. The bridge's listed ports are the control: they hold the
# store's other port.
name = "the pods' port is open on the pod network's interfaces and on no other, and not on the hive bridge";
ok =
let
fw = withNode.networking.firewall;
portsOn = i: fw.interfaces.${i}.allowedTCPPorts or [ ];
cni = withNode.services.hyperhive.deploy.k8s.cniInterfaces;
in
cni == [
"cni0"
"flannel-wg"
]
&& lib.all (i: lib.elem 8208 (portsOn i)) cni
&& lib.all (i: lib.elem i cni || !(lib.elem 8208 (portsOn i))) (lib.attrNames fw.interfaces)
&& lib.elem 8200 (bridgePorts withNode)
&& lib.elem 443 (bridgePorts withNode)
&& !(lib.elem 8208 (bridgePorts withNode))
&& !(lib.elem 8208 fw.allowedTCPPorts)
&& !(lib.elem 8208 withNode.services.hyperhive.network.exposeHostPorts);
}
{
name = "a daemon or the poller runs only in the cluster: the host has no container, service or timer, and applies the namespace and its objects";
ok =
!(onCluster.containers ? swarm-notify-router)
&& !(onCluster.systemd.services ? "container@swarm-notify-router")
&& !(onCluster.containers ? swarm-stt)
&& !(onCluster.systemd.services ? "container@swarm-stt")
&& !(onCluster.systemd.services ? swarm-ci-metrics)
&& !(onCluster.systemd.timers ? swarm-ci-metrics)
&& !(onCluster.systemd.services ? swarm-ci-metrics-ca-bundle)
&& !(onCluster.containers ? swarm-review-classifier)
&& !(onCluster.systemd.services ? "container@swarm-review-classifier")
&& !(onCluster.containers ? swarm-claude-login)
&& !(onCluster.systemd.services ? "container@swarm-claude-login")
&& !(onCluster.containers ? swarm-nats)
&& !(onCluster.systemd.services ? "container-nats")
# The log and metrics stores, Grafana and their responders: no container,
# no unit, no socket directory. The swarm collector's container, the CA
# publisher and a runtime directory of the host's own are the controls
# that the lookups find what a host still runs.
# that the lookups find what a host still runs.
&& !(onCluster.containers ? swarm-victorialogs)
&& !(onCluster.systemd.services ? "container@swarm-victorialogs")
&& !(onCluster.systemd.services ? swarm-logs-auth)
&& !(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 ? "container@swarm-victoriametrics")
&& !(onCluster.systemd.services ? swarm-metrics-auth)
&& !(onCluster.systemd.services ? swarm-metrics-agent-auth)
&& !(onCluster.systemd.services ? swarm-victoriametrics-forwarder-oidc)
&& !(onCluster.systemd.timers ? swarm-victoriametrics-forwarder-oidc)
&& !(lib.any (lib.hasPrefix "d /run/swarm-victoriametrics") onCluster.systemd.tmpfiles.rules)
&& !(onCluster.containers ? swarm-grafana)
&& !(onCluster.systemd.services ? "container@swarm-grafana")
&& !(onCluster.systemd.services ? swarm-bao-grafana-oidc)
&& !(onCluster.systemd.services ? swarm-bao-grafana-admin)
&& !(onCluster.systemd.services ? swarm-bao-grafana-metrics-bearer)
&& !(onCluster.systemd.services ? swarm-bao-grafana-secret-key)
&& !(onCluster.systemd.services ? swarm-bao-grafana-controller-token)
&& !(onCluster.systemd.timers ? swarm-bao-grafana-oidc)
&& !(lib.any (lib.hasPrefix "d /run/swarm-grafana") onCluster.systemd.tmpfiles.rules)
&& onCluster.containers ? swarm-otel
&& onCluster.systemd.services ? "container@swarm-otel"
&& onCluster.systemd.services ? hyperhive-k8s-ca-trust
&& lib.any (lib.hasPrefix "d /run/swarm-") onCluster.systemd.tmpfiles.rules
&&
manifestNames onCluster == [
"coredns-custom"
"hyperhive-namespace"
"swarm-ci-metrics"
"swarm-claude-login"
"swarm-controller"
"swarm-grafana"
"swarm-logs-auth"
"swarm-metrics-auth"
"swarm-nats"
"swarm-notify-router"
"swarm-review-classifier"
"swarm-stt"
"swarm-victorialogs"
"swarm-victoriametrics"
]
&&
map (o: o.kind) onCluster.services.k3s.manifests.hyperhive-namespace.content == [
"Namespace"
"NetworkPolicy"
]
&&
lib.sort lib.lessThan (map (o: o.kind) onCluster.services.k3s.manifests.swarm-notify-router.content)
== [
"Deployment"
"ServiceAccount"
]
&&
lib.sort lib.lessThan (map (o: o.kind) onCluster.services.k3s.manifests.swarm-stt.content) == [
"Deployment"
"NetworkPolicy"
"ServiceAccount"
]
&&
lib.sort lib.lessThan (map (o: o.kind) onCluster.services.k3s.manifests.swarm-ci-metrics.content)
== [
"CronJob"
"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-metrics-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"
]
&&
lib.sort lib.lessThan (
map (o: o.kind) onCluster.services.k3s.manifests.swarm-victoriametrics.content
) == [
"Deployment"
"NetworkPolicy"
"PersistentVolume"
"PersistentVolumeClaim"
"Service"
];
}
{
# The controller's pod is the control for the Secret lookup: its
# credentials still come from one.
name = "the router's CA file comes from the ConfigMap the host publishes, and the pod mounts no Secret";
ok =
let
volumes = clusterRouterSpec.volumes;
credentials = lib.findFirst (v: v.name == "credentials") null volumes;
sources = credentials.projected.sources;
caUnit = onCluster.systemd.services.hyperhive-k8s-ca-trust;
serverCa = onCluster.services.hyperhive.deploy.bao.serverCaFile;
in
credentials != null
&& lib.length sources == 1
&& (lib.head sources).configMap.name == "hyperhive-ca-trust"
&&
map (i: [
i.key
i.path
]) (lib.head sources).configMap.items == [
[
"bao-server-ca.pem"
"notify-router-bao-server-ca"
]
]
&& !(lib.any (v: v ? secret) volumes)
&& secretLookupWorks
&& 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
# Not a oneshot: its start job would last until the script ends, and the
# script waits for files the setup writes after boot.
&& caUnit.serviceConfig.Type == "simple"
# A change to either file publishes again with no manual step, and the
# host without the node has no path unit.
&&
lib.sort lib.lessThan onCluster.systemd.paths.hyperhive-k8s-ca-trust.pathConfig.PathChanged
== lib.sort lib.lessThan [
serverCa
"${onCluster.services.hyperhive.deploy.hive-controller.tls.stateDir}/trust-bundle.pem"
"${onCluster.services.hyperhive.deploy.hive-controller.tls.stateDir}/swarm-services-root.pem"
]
&& !(caUnit.serviceConfig ? RemainAfterExit)
&& !(noNode.systemd.paths ? hyperhive-k8s-ca-trust);
}
{
# Only the speech-to-text pod is in a user namespace: every other pod is
# the control that the field is not rendered for a service without it.
# With the service on the host nothing asks for one, so the kernel
# assertion is absent; with it on the cluster the assertion is there and
# holds for the fixture's kernel.
name = "only the speech-to-text pod runs in a user namespace, and a host that runs it asserts a kernel of 6.3 or later";
ok =
let
# The assertions defined in runtime.nix, found by where their message
# is written: reading every host's messages evaluates NixOS's own,
# which throw when their condition holds.
userns =
c:
lib.filter (
a: lib.hasSuffix "/k8s/runtime.nix" (builtins.unsafeGetAttrPos "message" a).file
) c.assertions;
in
(podSpec "swarm-stt").hostUsers == false
&& lib.all (n: !((podSpec n) ? hostUsers)) (lib.filter (n: n != "swarm-stt") (lib.attrNames units))
&& withNode.services.hyperhive.k8s.rendered.userNamespaces == [ "swarm-stt" ]
&& userns noNode == [ ]
&& lib.length (userns withNode) == 1
&& (lib.head (userns withNode)).assertion
&& lib.versionAtLeast withNode.boot.kernelPackages.kernel.version "6.3";
}
{
# The unit's ceilings are the pod's limits and reserve nothing, and the
# limits the pod has no field for are not rendered. The controller's pod,
# whose unit sets none, is the control that nothing is added to a pod
# without them.
name = "the speech-to-text pod carries its unit's memory and CPU ceilings as limits and reserves nothing, and a pod whose unit sets none carries none";
ok =
let
unit = units.swarm-stt.serviceConfig;
limits = (container "swarm-stt").resources.limits;
in
unit.MemoryMax == "3G"
&& unit.CPUQuota == "400%"
&& unit.TasksMax == 256
&&
limits == {
memory = "3Gi";
cpu = "4000m";
}
&&
(container "swarm-stt").resources.requests == {
memory = "0";
cpu = "0";
}
&& !(hasInfix "TasksMax" rendered)
&& !(hasInfix "SystemCallFilter" rendered)
&& lib.all (name: !((container name) ? resources)) [
"swarm-controller"
"swarm-notify-router"
"swarm-ci-metrics"
];
}
{
# The policy is pinned by value: an empty selector is the property, since
# a `matchLabels` would leave every pod it does not name open, and a rule
# would admit someone. The pods the lists name have no ingress policy of
# their own and rely on it; the speech-to-text pod and the controller are
# the controls that the lookup finds a pod's own policy.
name = "the namespace has a default-deny ingress policy that selects every pod and admits nobody, and the pods without an ingress policy of their own rely on it";
ok =
let
policy = objects."default-deny-ingress/networkpolicy";
manifest = onCluster.services.k3s.manifests.hyperhive-namespace.content;
ownPolicy = name: objects ? "${name}/networkpolicy";
in
policy.kind == "NetworkPolicy"
&& policy.metadata.namespace == "hyperhive"
&&
policy.spec == {
podSelector = { };
policyTypes = [ "Ingress" ];
}
&& lib.elem policy manifest
&& lib.all (name: !(ownPolicy name)) [
"swarm-notify-router"
"swarm-review-classifier"
"swarm-claude-login"
"swarm-ci-metrics"
]
&& lib.all ownPolicy [
"swarm-stt"
"swarm-controller"
"swarm-nats"
];
}
{
# The policy is pinned by value: the ports are literals, not the options
# the render reads. The router's pod is the control that a service
# without `egress` has no policy, and the host without the queue in the
# cluster the control that the queue's pod rule follows the queue.
name = "the speech-to-text pod's NetworkPolicy admits no ingress and allows DNS and four host ports, and a pod without egress has none";
ok =
let
bridge = "${withNode.services.hyperhive.network.bridgeIp}/32";
policyOf = o: o."swarm-stt/networkpolicy";
policy = policyOf objects;
withoutQueue = policyOf (
render (lib.recursiveUpdate allLocal { services.hyperhive.deploy.nats.enable = false; })
);
tcp = port: {
protocol = "TCP";
inherit port;
};
dns = {
to = [
{
namespaceSelector.matchLabels."kubernetes.io/metadata.name" = "kube-system";
podSelector.matchLabels.k8s-app = "kube-dns";
}
];
ports = [
{
protocol = "UDP";
port = 53;
}
(tcp 53)
];
};
host = {
to = [ { ipBlock.cidr = bridge; } ];
ports = map tcp [
8208
443
4222
4318
];
};
in
policy.kind == "NetworkPolicy"
&& policy.metadata.namespace == "hyperhive"
&& policy.metadata.labels."app.kubernetes.io/name" == "swarm-stt"
&& policy.spec.podSelector.matchLabels == objects."swarm-stt/deployment".spec.selector.matchLabels
&&
policy.spec.policyTypes == [
"Ingress"
"Egress"
]
&& !(policy.spec ? ingress)
&&
withoutQueue.spec.egress == [
dns
host
]
&&
policy.spec.egress == [
dns
host
{
to = [
{
namespaceSelector.matchLabels."kubernetes.io/metadata.name" = "kube-system";
podSelector.matchLabels = {
"svccontroller.k3s.cattle.io/svcname" = "swarm-nats";
"svccontroller.k3s.cattle.io/svcnamespace" = "hyperhive";
};
}
];
ports = [ (tcp 4222) ];
}
]
# The namespace's default, the controller (its listener), the log and metrics
# stores and their responders (listeners), the queue and this pod have a
# policy: the others have no egress and no listener, and rely on the default.
&&
lib.sort lib.lessThan (lib.filter (n: lib.hasSuffix "/networkpolicy" n) (lib.attrNames objects))
== [
"default-deny-ingress/networkpolicy"
"swarm-controller/networkpolicy"
"swarm-grafana/networkpolicy"
"swarm-logs-auth/networkpolicy"
"swarm-metrics-auth/networkpolicy"
"swarm-nats/networkpolicy"
"swarm-stt/networkpolicy"
"swarm-victorialogs/networkpolicy"
"swarm-victoriametrics/networkpolicy"
];
}
{
# Other spellings of a ceiling: bytes, megabytes, a fractional core, no
# memory limit. A setting render cannot read fails the evaluation, the
# unchanged host being the control that the render itself succeeds.
name = "the unit's limits translate by systemd's units, and one render cannot read fails the evaluation";
ok =
let
withLimits =
sc: lib.recursiveUpdate allLocal { services.hyperhive.deploy.stt.unit.serviceConfig = sc; };
containersOf = sc: ((render (withLimits sc))."swarm-stt/deployment".spec.template.spec.containers);
first = sc: lib.head (containersOf sc);
in
renders allLocal
&&
(first {
MemoryMax = "512M";
CPUQuota = "150%";
}).resources.limits == {
memory = "512Mi";
cpu = "1500m";
}
&&
(first { MemoryMax = "1048576"; }).resources.limits == {
memory = "1048576";
cpu = "4000m";
}
&&
(first { MemoryMax = "infinity"; }).resources.limits == {
cpu = "4000m";
}
&& !(renders (withLimits {
MemoryMax = "50%";
}))
&& !(renders (withLimits {
MemoryMax = "3 G";
}))
&& !(renders (withLimits {
CPUQuota = "4";
}));
}
{
# `MemoryMin` wins over `MemoryLow`, either is the memory the pod asks
# for, and the cpu request stays 0. A unit with neither is the control.
name = "a unit's MemoryMin, else its MemoryLow, is the pod's memory request, and one the renderer cannot read fails the evaluation";
ok =
let
withSc =
sc: lib.recursiveUpdate allLocal { services.hyperhive.deploy.stt.unit.serviceConfig = sc; };
resourcesOf =
sc: (lib.head (render (withSc sc))."swarm-stt/deployment".spec.template.spec.containers).resources;
in
(resourcesOf { }).requests.memory == "0"
&&
(resourcesOf { MemoryLow = "256M"; }).requests == {
memory = "256Mi";
cpu = "0";
}
&&
(resourcesOf {
MemoryMin = "1G";
MemoryLow = "256M";
}).requests.memory == "1Gi"
&&
(resourcesOf { MemoryLow = "256M"; }).limits == {
memory = "3Gi";
cpu = "4000m";
}
&& !(renders (withSc {
MemoryLow = "10%";
}))
&& !(renders (withSc {
MemoryMin = "infinity";
}));
}
{
name = "the speech-to-text pod has probes on its health listener, keeps its cache in an emptyDir with no claim, mounts no Secret, and runs as every pod does";
ok =
let
c = container "swarm-stt";
spec = podSpec "swarm-stt";
cred = lib.findFirst (v: v.name == "credentials") null spec.volumes;
in
!(c ? ports)
&& lib.last c.readinessProbe.exec.command == "http://127.0.0.1:8080/readyz"
&& lib.last c.livenessProbe.exec.command == "http://127.0.0.1:8080/healthz"
&& lib.any (m: m.name == "state" && m.mountPath == "/var/lib/swarm-stt") c.volumeMounts
# The cache needs no claim, and is no state to gate. The poller beside
# it, whose cursor is kept, is the control that a claim renders.
&&
(lib.findFirst (v: v.name == "state") null spec.volumes) == {
name = "state";
emptyDir = { };
}
&& !(objects ? "swarm-stt/persistentvolumeclaim")
&& objects ? "swarm-ci-metrics/persistentvolumeclaim"
# The one credential the pod holds is the store's public CA, from the
# ConfigMap. The controller's pod is the control for the lookup.
&& cred != null
&& !(cred ? secret)
&&
map (s: s.configMap.items) cred.projected.sources == [
[
{
key = "bao-server-ca.pem";
path = "stt-bao-server-ca";
}
]
]
&& secretLookupWorks
&& c.securityContext.readOnlyRootFilesystem
&& c.securityContext.runAsNonRoot
&& c.securityContext.capabilities.drop == [ "ALL" ]
&& spec.securityContext.seccompProfile.type == "RuntimeDefault";
}
{
# Neither unit sets a limit, so the pods carry none. The stt pod, whose
# unit does, is the control that the lookup finds a limit where there is
# one. Neither keeps state, so their objects are a Deployment and an
# account, and the pod's `/tmp` volume is where the scratch directories
# and the `HOME` the daemons give `claude` land.
name = "the review classifier's and the claude login minter's pods carry no limits, keep no volume of state, probe their health listener and keep their scratch in the pod's /tmp volume";
ok =
let
check =
{ name, prefix }:
let
c = container name;
spec = podSpec name;
cred = lib.findFirst (v: v.name == "credentials") null spec.volumes;
kinds = lib.sort lib.lessThan (map (o: o.kind) onCluster.services.k3s.manifests.${name}.content);
in
!(c ? resources)
&&
kinds == [
"Deployment"
"ServiceAccount"
]
&& !(c ? ports)
&& lib.last c.readinessProbe.exec.command == "http://127.0.0.1:8080/readyz"
&& lib.last c.livenessProbe.exec.command == "http://127.0.0.1:8080/healthz"
&& (envOf name)."${prefix}_HEALTH_ADDR" == "127.0.0.1:8080"
&& lib.any (m: m.name == "tmp" && m.mountPath == "/tmp") c.volumeMounts
&& (lib.findFirst (v: v.name == "tmp") null spec.volumes).emptyDir == { }
&& !(lib.any (v: v ? persistentVolumeClaim) spec.volumes)
&& !((envOf name) ? TMPDIR)
&& !((envOf name) ? HOME)
&& c.securityContext.readOnlyRootFilesystem
&& c.securityContext.runAsNonRoot
&& c.securityContext.capabilities.drop == [ "ALL" ]
&& spec.securityContext.seccompProfile.type == "RuntimeDefault"
&& (envOf name).BAO_AUTH == "jwt"
&& (envOf name).BAO_JWT_ROLE == name
&& !((envOf name) ? BAO_CLIENT_CERT)
&& !(cred ? secret)
&&
map (s: s.configMap.items) cred.projected.sources == [
[
{
key = "bao-server-ca.pem";
path = lib.removePrefix "swarm-" name + "-bao-server-ca";
}
]
];
in
check {
name = "swarm-review-classifier";
prefix = "SWARM_REVIEW_CLASSIFIER";
}
&& check {
name = "swarm-claude-login";
prefix = "SWARM_CLAUDE_LOGIN";
}
&& (container "swarm-stt") ? resources;
}
{
# The minter's jwt login must be able to write what its certificate
# writes: the cert role's policy is the jwt role's, and it grants create
# and update on every agent's credentials. The classifier's policy is the
# control that the search for them finds only what is there.
name = "the claude login minter's jwt role has the policy that writes agents' credentials, and the classifier's reads its keys";
ok =
let
s = withNode.systemd.services;
login = s.swarm-bao-claude-login-policy.script;
classifier = s.swarm-bao-review-classifier-policy.script;
jwt = s.swarm-bao-k8s-jwt-policy.script;
writes = ''
path "secret/data/swarm/agents/+/claude-credentials" {
capabilities = ["create", "update"]
}
'';
in
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
# grant-bootstrap re-run is pending (`PENDING_MARKER` in
# swarmctl/src/setup.rs). The unit must create it on the stay-off path and
# remove it before it writes the mount's config, or the check goes quiet
# or never clears.
name = "the pods' login unit keeps the marker file `swarmctl setup status` reads while it waits for the root step";
ok =
let
jwt = withNode.systemd.services.swarm-bao-k8s-jwt-policy.script;
marker = "/run/swarm-bao-k8s-jwt-pending";
touched = lib.splitString "touch ${marker}" jwt;
cleared = lib.splitString "rm -f ${marker}" jwt;
# What follows the one `touch`, up to and after the one `rm`.
between = lib.head (lib.splitString "rm -f ${marker}" (lib.elemAt touched 1));
in
lib.length touched == 2
&& lib.length cleared == 2
&& 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
# the ConfigMap the host publishes, and no volume of it names a Secret,
# which nothing creates. The controller's pod is the control that the
# lookup finds a Secret where there is one.
name = "the poller's pod gets the store's CA from the ConfigMap, drops its client certificate and key, and mounts no Secret";
ok =
let
spec = (render onCluster)."swarm-ci-metrics/cronjob".spec.jobTemplate.spec.template.spec;
volumesOf = s: s.volumes;
cred = lib.findFirst (v: v.name == "credentials") null spec.volumes;
serverCa = onCluster.services.hyperhive.deploy.bao.serverCaFile;
in
serverCa != null
&& cred != null
&&
map (s: s.configMap.items) cred.projected.sources == [
[
{
key = "bao-server-ca.pem";
path = "bao-ca.pem";
}
]
]
&& !(lib.any usesSecret (volumesOf spec))
&& secretLookupWorks
&& (lib.head spec.containers).env != [ ]
&& lib.any (
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
&& !(hasInfix "swarm-ci-metrics-credentials" rendered);
}
{
# The host with the controller on it is the control for every absence
# below: it holds the unit, its listener's leaf unit and timer, and the
# prune unit that runs before the unit.
# The gateway's client leaf unit is the control that the lookups find a
# unit of the listener's that is there.
name = "the controller runs only as a pod: the host has no unit, listener leaf unit, timer or prune unit, and keeps the gateway's client leaf";
ok =
let
s = withNode.systemd;
in
s.services ? swarm-controller-gateway-client
&& !s.services.swarm-controller.enable
&& !(s.services ? swarm-controller-tls)
&& !(s.timers ? swarm-controller-tls)
&& !(s.services ? swarm-controller-k8s-prune)
&&
lib.sort lib.lessThan (map (o: o.kind) onCluster.services.k3s.manifests.swarm-controller.content)
== [
"ConfigMap"
"Deployment"
"NetworkPolicy"
"Service"
"ServiceAccount"
];
}
{
name = "the controller's listener is a ClusterIP Service that only the node reaches, with the cluster's DNS handed the cluster's domain by the host's resolver";
ok =
let
cluster = render onCluster;
svc = cluster."swarm-controller/service";
policy = cluster."swarm-controller/networkpolicy";
h = withNode.services.hyperhive;
in
svc.kind == "Service"
&& svc.spec.type == "ClusterIP"
&& svc.spec.selector == policy.spec.podSelector.matchLabels
&& !(svc.spec ? clusterIP)
&&
svc.spec.ports == [
{
name = "api";
protocol = "TCP";
port = 9443;
targetPort = "api";
}
]
&& policy.spec.policyTypes == [ "Ingress" ]
&& !(policy.spec ? ingress)
&& !(policy.spec ? egress)
&& h.swarm.controller.tcp.enable
&& h.deploy.swarm-controller.tcp.serviceHost == "swarm-controller.hyperhive.svc.cluster.local"
&& lib.elem "/cluster.local/10.201.0.10" withNode.services.dnsmasq.settings.server
&& lib.elem "--cluster-dns=10.201.0.10" withNode.services.k3s.extraFlags
&& !(lib.elem "/cluster.local/10.201.0.10" (noNode.services.dnsmasq.settings.server or [ ]));
}
{
name = "the gateway dials the controller's Service by name, resolved per request, and verifies its certificate as the listener's name";
ok =
let
loc = c: path: c.services.nginx.virtualHosts."t.local".locations.${path};
dials =
c: path: needle:
hasInfix needle (loc c path).extraConfig;
verified =
c: path:
dials c path "proxy_ssl_name controller.t.local;"
&& dials c path "proxy_ssl_verify on;"
&& dials c path "proxy_ssl_certificate ";
in
(loc onCluster "/webhook/forge/").proxyPass == "https://\$swarm_controller_upstream"
&& (loc onCluster "/api/").proxyPass == "https://\$swarm_controller_upstream"
&&
lib.all
(
p:
dials onCluster p "resolver 10.42.0.1 valid=10s ipv6=off;"
&&
dials onCluster p
"set \$swarm_controller_upstream swarm-controller.hyperhive.svc.cluster.local:9443;"
)
[
"/webhook/forge/"
"/api/"
]
&& verified onCluster "/webhook/forge/"
&& verified onCluster "/api/";
}
{
name = "the controller's pod serves its listener on a named port with no hostPort, is probed on the health listener, and rolls with its rev file";
ok =
let
cluster = render onCluster;
deployment = cluster."swarm-controller/deployment";
pod = deployment.spec.template;
c = lib.head pod.spec.containers;
byName = n: lib.findFirst (x: x.name == n) null;
api = byName "api" c.ports;
rolled = lib.recursiveUpdate onCluster {
environment.etc."hyperhive/swarm-controller.json".text = ''{"hyperhive_rev":"other"}'';
};
annotationOf =
o: (render o)."swarm-controller/deployment".spec.template.metadata.annotations."checksum/etc";
in
lib.last c.readinessProbe.exec.command == "http://127.0.0.1:8080/readyz"
&& lib.last c.livenessProbe.exec.command == "http://127.0.0.1:8080/healthz"
&& byName "health" c.ports == null
&& api.containerPort == 9443
&& !(api ? hostPort)
&& !(api ? hostIP)
&& deployment.spec.replicas == 1
&& deployment.spec.strategy.type == "Recreate"
# The checksum is of the ConfigMap's content, and a changed rev changes it.
&&
annotationOf onCluster
== builtins.hashString "sha256" (builtins.toJSON cluster."swarm-controller/configmap".data)
&& annotationOf rolled != annotationOf onCluster
# A pod with no ConfigMap carries no annotation: the router is the control.
&& !((cluster."swarm-notify-router/deployment".spec.template.metadata) ? annotations);
}
{
# The pod issues its own listener leaf with the unit's script, logging in
# with its ServiceAccount token. The host's is the control: the shared
# script with the certificate login and the key's group.
name = "the controller's pod issues its listener leaf before the daemon starts and renews it beside it";
ok =
let
shared = import ../host-modules/lib/swarm-controller-tls-issue.nix {
inherit lib;
config = withNode;
};
podScript = shared.script {
login = "L";
credential = "c";
};
spec = (render onCluster)."swarm-controller/deployment".spec.template.spec;
init = lib.head spec.initContainers;
renew = lib.last spec.containers;
main = lib.head spec.containers;
mountsOf = x: map (m: m.name) x.volumeMounts;
tlsDir = "/var/lib/swarm-controller-tls";
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
!(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"
&& renew.command == [ "/bin/swarm-controller-tls-renew" ]
&& init.image == renew.image
&& init.image != main.image
&& lib.all (x: mountPath x == tlsDir) [
init
renew
main
]
&& lib.all (x: lib.elem "bao-token" (mountsOf x)) [
init
renew
]
&& lib.elem "bao-token" (mountsOf main)
&&
# In memory, so the leaf's key never reaches the node's disk. The
# `tmp` volume beside it is the control that the lookup finds a
# plain one.
(lib.findFirst (v: v.name == "tls") null spec.volumes) == {
name = "tls";
emptyDir.medium = "Memory";
}
&&
(lib.findFirst (v: v.name == "tmp") null spec.volumes) == {
name = "tmp";
emptyDir = { };
}
&& lib.any (e: e.name == "BAO_ADDR") init.env
&& !(lib.any (e: e.name == "BAO_CLIENT_CERT") init.env)
&& !(lib.any (v: v ? secret) spec.volumes)
# The root the listener trusts the gateway's client leaf by comes from
# the CA ConfigMap, at the path the daemon is told.
&& lib.any (
m: m.name == "ca-trust" && m.subPath == "swarm-services-root.pem" && m.mountPath == servicesRoot
) main.volumeMounts
&& lib.any (e: e.name == "SWARM_CONTROLLER_TCP_CLIENT_CA" && e.value == servicesRoot) main.env;
}
{
# Everything of the pod is read off the manifest the module renders. The
# `tmp` volume is the control that the lookup of a volume's medium finds
# a plain one.
name = "the queue's pod is one replaced copy of the responder, the server and the exporter, started after the leaf and the callout config, on the host unit's own store directory";
ok =
let
o = objects."swarm-nats/deployment";
spec = o.spec.template.spec;
named = n: lib.findFirst (c: c.name == n) { } spec.containers;
volume = n: lib.findFirst (v: v.name == n) null spec.volumes;
pvc = objects."swarm-nats/persistentvolumeclaim";
pv = objects."swarm-nats/persistentvolume";
hostStore = "/var/lib/nixos-containers/swarm-nats/var/lib/nats";
env = envOf "swarm-nats";
in
o.spec.replicas == 1
&& o.spec.strategy.type == "Recreate"
&&
map (c: c.name) spec.containers == [
"swarm-nats"
"nats"
"tls-renew"
"exporter"
]
# The renewal signals the server, so the two share their processes, and
# it writes the volume the server only reads.
&& spec.shareProcessNamespace
&& (named "tls-renew").command == [ "/bin/swarm-nats-tls-renew" ]
&& lib.any (m: m.name == "nats-tls" && !(m.readOnly or false)) (named "tls-renew").volumeMounts
&& lib.all (m: m.readOnly or false) (
lib.filter (m: m.name == "nats-tls") (named "nats").volumeMounts
)
&&
map (c: c.name) spec.initContainers == [
"tls-issue"
"callout-config"
]
# The responder and the server dial the queue's name on the pod's own
# loopback, where the leaf's name is checked.
&&
spec.hostAliases == [
{
ip = "127.0.0.1";
hostnames = [ "nats.t.local" ];
}
]
&& lib.elem "tls://nats.t.local:4222" (named "swarm-nats").args
&&
(named "nats").args == [
"-c"
"/var/lib/nats-callout/nats.conf"
]
# Both ports are named for their Services, and neither has a `hostPort`:
# the load balancer publishes the client port on the node.
&&
(named "nats").ports == [
{
name = "client";
containerPort = 4222;
}
]
&&
(named "exporter").ports == [
{
name = "metrics";
containerPort = 7777;
}
]
&& lib.elem "0.0.0.0" (named "exporter").args
&&
(named "nats").readinessProbe.exec.command == [
"/bin/wget"
"-q"
"-O"
"/dev/null"
"http://127.0.0.1:8222/healthz?js-enabled-only=true"
]
# The responder's own probes, on an address of the pod's own.
&& env.SWARM_NATS_AUTH_HEALTH_ADDR == "127.0.0.1:8080"
&& lib.last (named "swarm-nats").readinessProbe.exec.command == "http://127.0.0.1:8080/readyz"
&& env.BAO_JWT_ROLE == "swarm-nats-auth"
&& !(env ? BAO_CLIENT_CERT)
# 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: 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)
&& (volume "nats-data").persistentVolumeClaim.claimName == pvc.metadata.name
&& pvc.spec.accessModes == [ "ReadWriteOnce" ]
# The claim binds by name the static local volume on the container's
# store directory, and only that: its class is its own.
&& pvc.spec.volumeName == pv.metadata.name
&& pvc.spec.storageClassName == pv.spec.storageClassName
&& pv.spec.storageClassName != ""
&& pv.spec.local.path == hostStore
&& pv.spec.persistentVolumeReclaimPolicy == "Retain"
&& !(pv.metadata ? namespace)
# It binds on the node with the queue's state label, and the pod runs
# only there.
&&
pv.spec.nodeAffinity.required.nodeSelectorTerms == [
{
matchExpressions = [
{
key = "hyperhive.darkest.space/state-nats";
operator = "In";
values = [ "true" ];
}
];
}
]
&& spec.nodeSelector == { "hyperhive.darkest.space/state-nats" = "true"; }
# A pod on a host that never ran the container gets the directory made;
# a host without the queue needs no rule.
&& lib.any (lib.hasPrefix "d ${hostStore} ") onCluster.systemd.tmpfiles.rules
&& !(lib.any (lib.hasPrefix "d ${hostStore} ") noNode.systemd.tmpfiles.rules)
&& !(lib.any (c: c ? resources) spec.containers)
&& !(lib.any (v: v ? secret) spec.volumes);
}
{
# No pod starts on a gate: its first init container is the leaf's or
# none. Each pod's state directory is read off the manifest: an emptyDir
# where the service re-derives what it keeps, a claim where it does not
# (the poller's cursor), and the queue's claim is its own, bound to the
# host's directory. The claims are the control for the emptyDirs.
name = "no pod starts on a state gate, and the state directories are emptyDirs except the poller's claim and the queue's volume";
ok =
let
specOf =
name:
let
o = objects."${name}/deployment" or objects."${name}/cronjob";
in
if o.kind == "CronJob" then o.spec.jobTemplate.spec.template.spec else o.spec.template.spec;
stateVolume = name: lib.findFirst (v: v.name == "state") null (specOf name).volumes;
services = [
"swarm-controller"
"swarm-nats"
"swarm-notify-router"
"swarm-stt"
"swarm-review-classifier"
"swarm-claude-login"
"swarm-ci-metrics"
];
in
lib.all (n: !(lib.any (i: i.name == "state-gate") ((specOf n).initContainers or [ ]))) services
&&
stateVolume "swarm-controller" == {
name = "state";
emptyDir = { };
}
&&
stateVolume "swarm-stt" == {
name = "state";
emptyDir = { };
}
&& !(objects ? "swarm-controller/persistentvolumeclaim")
&& !(objects ? "swarm-stt/persistentvolumeclaim")
&& (stateVolume "swarm-ci-metrics").persistentVolumeClaim.claimName == "swarm-ci-metrics-store"
&& objects ? "swarm-ci-metrics/persistentvolumeclaim"
&& !(lib.any (n: hasInfix "state-gate" n) (map toString withNode.system.build.k8sImages))
&& objects ? "swarm-nats/persistentvolumeclaim";
}
{
# The host with no queue is the control for the rule in the raw table.
name = "the queue runs only as a pod: the host has no container, delivery or callout-key unit, keeps the leaf for the gateway's vhost, and points the vhost at the exporter's Service by name";
ok =
let
vhost = c: c.services.nginx.virtualHosts."nats.t.local".locations."= /metrics".proxyPass;
extra = c: c.services.nginx.virtualHosts."nats.t.local".locations."= /metrics".extraConfig;
tls = onCluster.systemd.services.swarm-bao-nats-tls;
in
!(onCluster.containers ? swarm-nats)
&& !(onCluster.systemd.services ? "container@swarm-nats")
&& !(onCluster.systemd.services ? swarm-nats-auth-secrets)
&& !(onCluster.systemd.services ? swarm-bao-nats-callout-xkey)
&& !(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"
&& 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;
}
{
name = "the queue's exporter is a ClusterIP Service only the node reaches, and the pod admits the client port from anywhere and nothing else";
ok =
let
cluster = render onCluster;
svc = cluster."swarm-nats/service";
policy = cluster."swarm-nats/networkpolicy";
pod = cluster."swarm-nats/deployment".spec.template.metadata.labels;
in
svc.kind == "Service"
&& svc.metadata.name == "swarm-nats-metrics"
&& svc.metadata.labels."app.kubernetes.io/name" == "swarm-nats"
&& svc.spec.type == "ClusterIP"
&& !(svc.spec ? clusterIP)
&& svc.spec.selector == pod
&&
svc.spec.ports == [
{
name = "metrics";
protocol = "TCP";
port = 7777;
targetPort = "metrics";
}
]
&& policy.spec.podSelector.matchLabels == pod
&& policy.spec.policyTypes == [ "Ingress" ]
&&
policy.spec.ingress == [
{
ports = [
{
protocol = "TCP";
port = 4222;
}
];
}
]
&& !(policy.spec ? egress)
&& (render withNode)."swarm-nats/service" == svc
&& (render withNode)."swarm-nats/networkpolicy" == policy;
}
{
# Both arms of `openFirewall`, from the function the module calls, and
# the module's own text for the default.
name = "the pod's raw-table rules close the client port as the container's INPUT rules do, and name no other port";
ok =
let
rules = import ../host-modules/lib/swarm-nats-raw-rules.nix { inherit lib; };
args = {
chain = "c";
clientPort = 4222;
trusted = [
"lo"
"br0"
"cni0"
];
firewallInterfaces = { };
};
closed = rules (args // { openClient = false; });
open = rules (args // { openClient = true; });
# An interface the firewall opens the port on, by the port or by a
# range, is let through; one that opens other ports is not.
viaInterfaces = rules (
args
// {
openClient = false;
firewallInterfaces = {
wg0 = {
allowedTCPPorts = [ 4222 ];
allowedTCPPortRanges = [ ];
};
wg1 = {
allowedTCPPorts = [ ];
allowedTCPPortRanges = [
{
from = 4000;
to = 4300;
}
];
};
eth1 = {
allowedTCPPorts = [ 80 ];
allowedTCPPortRanges = [
{
from = 5000;
to = 5100;
}
];
};
};
}
);
has = hasInfix;
in
has "-p tcp --dport 4222 -i wg0 -j RETURN" viaInterfaces
&& has "-p tcp --dport 4222 -i wg1 -j RETURN" viaInterfaces
&& !(has "-i eth1" viaInterfaces)
&& !(has "-i wg0" closed)
&& has "-p tcp --dport 4222 -i br0 -j RETURN" closed
&& has "-p tcp --dport 4222 -i cni0 -j RETURN" closed
&& has "-p tcp --dport 4222 -m addrtype --dst-type LOCAL -j DROP" closed
# Open, the client port has no rule. The exporter's port, behind a
# Service, has none in either.
&& !(has "--dport 4222" open)
&& !(has "7777" closed)
&& !(has "7777" onCluster.networking.firewall.extraCommands)
&& has "-t raw -I PREROUTING -j c" closed
&& has "-t raw -A nixos-fw-nats -p tcp --dport 4222 -i cni0 -j RETURN" onCluster.networking.firewall.extraCommands
&& has "-t raw -A nixos-fw-nats -p tcp --dport 4222 -m addrtype --dst-type LOCAL -j DROP" onCluster.networking.firewall.extraCommands
&& has "-t raw -F nixos-fw-nats" onCluster.networking.firewall.extraStopCommands;
}
{
name = "the queue's client port is a LoadBalancer Service with no node port, and the pod has no hostPort";
ok =
let
cluster = render onCluster;
svc = cluster."swarm-nats/loadbalancer";
pod = cluster."swarm-nats/deployment".spec.template;
ports = lib.concatMap (c: c.ports or [ ]) pod.spec.containers;
in
svc.kind == "Service"
&& svc.metadata.name == "swarm-nats"
&& svc.metadata.labels."app.kubernetes.io/name" == "swarm-nats"
&& svc.spec.type == "LoadBalancer"
&& svc.spec.allocateLoadBalancerNodePorts == false
&& svc.spec.selector == pod.metadata.labels
&&
svc.spec.ports == [
{
name = "client";
protocol = "TCP";
port = 4222;
targetPort = "client";
}
]
&& !(svc.spec ? loadBalancerClass)
&& !(svc.spec ? externalTrafficPolicy)
&& !(lib.any (p: p ? hostPort || p ? hostIP) ports)
&&
lib.sort lib.lessThan (map (p: p.name) ports) == [
"client"
"metrics"
]
&& (render withNode)."swarm-nats/loadbalancer" == svc;
}
{
# The host with the queue on it is the control: it publishes no port, and
# its chain has no rule of the kind.
name = "the egress forward chain accepts the flows the host publishes for the agents, from the bridge's address at the queue's port, and none on a host without the queue in the cluster";
ok =
let
rules =
c:
lib.filter (l: l != "") (
map lib.trim (
lib.splitString "\n" (
lib.last (
lib.splitString "chain forward" (
lib.head (lib.splitString "table bridge hive_egress {" c.services.hyperhive.network.egress.ruleset)
)
)
)
)
);
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 (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"
&& idx onCluster "ct original" < idx onCluster "counter"
&& idx onCluster "@direct_mac accept" < idx onCluster "ct original";
}
{
# The checker is the control that it finds a violation: the same pod with
# a host port, a kept capability or a missing seccomp profile is flagged,
# and the workloads it reads are all eleven.
name = "the namespace enforces Pod Security restricted, and no pod the module renders breaks it";
ok =
let
ns = (render allLocal).namespace.metadata.labels;
workloads = lib.filterAttrs (_: o: o.kind == "Deployment" || o.kind == "CronJob") (
render onCluster
);
specOf =
o: if o.kind == "CronJob" then o.spec.jobTemplate.spec.template.spec else o.spec.template.spec;
specs = map specOf (lib.attrValues workloads);
containersOf = s: s.containers ++ (s.initContainers or [ ]);
problems =
s:
lib.concatMap (k: lib.optional (s.${k} or false) k) [
"hostNetwork"
"hostPID"
"hostIPC"
]
++ lib.optional (lib.any (v: v ? hostPath) s.volumes) "hostPath"
++ lib.optional (
!(lib.elem (s.securityContext.seccompProfile.type or "") [
"RuntimeDefault"
"Localhost"
])
) "seccomp"
++ lib.concatMap (
c:
let
sc = c.securityContext or { };
in
lib.optional ((sc.allowPrivilegeEscalation or null) != false) "escalation ${c.name}"
++ lib.optional ((sc.capabilities.drop or [ ]) != [ "ALL" ]) "drop ${c.name}"
++ lib.optional (sc.capabilities ? add) "add ${c.name}"
++ lib.optional (sc.privileged or false) "privileged ${c.name}"
++ lib.optional (!(sc.runAsNonRoot or s.securityContext.runAsNonRoot or false)) "root ${c.name}"
++ lib.concatMap (p: lib.optional (p ? hostPort) "hostPort ${c.name}") (c.ports or [ ])
) (containersOf s);
first = lib.head specs;
withHostPort = first // {
containers = [
(
(lib.head first.containers)
// {
ports = [
{
containerPort = 1;
hostPort = 1;
}
];
}
)
];
};
withCaps = first // {
containers = [
(
(lib.head first.containers)
// {
securityContext = (lib.head first.containers).securityContext // {
capabilities.add = [ "NET_ADMIN" ];
};
}
)
];
};
withoutSeccomp = first // {
securityContext = removeAttrs first.securityContext [ "seccompProfile" ];
};
in
ns."pod-security.kubernetes.io/enforce" == "restricted"
&& ns."pod-security.kubernetes.io/warn" == "restricted"
&& ns."pod-security.kubernetes.io/audit" == "restricted"
&& ns."app.kubernetes.io/part-of" == "hyperhive"
&& lib.length specs == 12
&& 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"
"-httpAuth.username=swarm-store"
"-httpAuth.password=file:///run/credentials/victoria-logs.service/store-auth"
]
&&
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 and no token. Its one
# credential is the Secret the host publishes, mounted where the
# password flag names it.
&& !(spec ? serviceAccountName)
&& !(objects ? "swarm-victorialogs/serviceaccount")
&& !(lib.any (v: v.name == "bao-token") spec.volumes)
&&
(lib.findFirst (v: v.name == "credentials") null spec.volumes).secret == {
secretName = "swarm-victorialogs-credentials";
defaultMode = 288;
items = [
{
key = "store-auth";
path = "store-auth";
}
];
}
&& lib.any (
m: m.name == "credentials" && m.mountPath == "/run/credentials/victoria-logs.service" && m.readOnly
) c.volumeMounts
&& (podSpec "swarm-stt") ? serviceAccountName
# Its Service is the only way in, and only the node reaches it.
&&
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 credential has three ends that must agree: the unit that creates
# it, the file the gateway's store locations include, and the Secret the
# pod loads. Each absence arm has a presence control beside it.
name = "the stores' listener credentials are created and published by one unit and sent by every location that dials the store, and by no other";
ok =
let
h = allLocal.services.hyperhive;
unit = allLocal.systemd.services.swarm-bao-store-auth;
rule = store: "f /var/lib/swarm-store-auth/${store}.conf 0640 root nginx -";
# One store's vhost: every location that dials it includes the file,
# and no other location does.
vhost =
{
domain,
variable,
store,
}:
let
locations = allLocal.services.nginx.virtualHosts.${domain}.locations;
dialsStore = l: hasInfix variable (l.proxyPass or "");
storeLocations = lib.filterAttrs (_: dialsStore) locations;
otherLocations = lib.filterAttrs (_: l: !(dialsStore l)) locations;
include = "include /var/lib/swarm-store-auth/${store}.conf;";
in
{
inherit storeLocations otherLocations;
sent =
storeLocations != { }
&& lib.all (l: hasInfix include l.extraConfig) (lib.attrValues storeLocations)
&& lib.all (l: !(hasInfix "/var/lib/swarm-store-auth" (l.extraConfig or ""))) (
lib.attrValues otherLocations
);
# The credential of the other store is not this one's.
notTheOther = lib.all (
l:
!(hasInfix "/var/lib/swarm-store-auth/${if store == "victorialogs" then "victoriametrics" else "victorialogs"}" l.extraConfig)
) (lib.attrValues storeLocations);
};
logs = vhost {
domain = h.swarm.victorialogs.domain;
variable = "$swarm_logs_store_upstream";
store = "victorialogs";
};
metrics = vhost {
domain = h.swarm.victoriametrics.domain;
variable = "$swarm_metrics_store_upstream";
store = "victoriametrics";
};
grafanaLocations = allLocal.services.nginx.virtualHosts.${h.swarm.grafana.domain}.locations;
grafanaSent = lib.filterAttrs (
_: l: hasInfix "/var/lib/swarm-store-auth/grafana.conf" (l.extraConfig or "")
) grafanaLocations;
in
# The log store's four: the operator's `/`, the collector's ingest, the
# query API and the store's own metrics.
lib.attrNames logs.storeLocations == [
"/"
"= /insert/opentelemetry/v1/logs"
"= /metrics"
"^~ /select/logsql/"
]
# The metrics store's: the read API, vmui, the push and its metrics, and
# none of its import and admin routes, which have no location at all.
&& lib.all (n: metrics.storeLocations ? ${n}) [
"= /api/v1/query"
"= /api/v1/export"
"^~ /api/v1/label/"
"= /vmui"
"^~ /vmui/"
"= /opentelemetry/api/v1/push"
"= /metrics"
]
&& !(lib.any (n: hasInfix "import" n || hasInfix "admin" n || hasInfix "snapshot" n) (
lib.attrNames metrics.storeLocations
))
&& logs.sent
&& metrics.sent
&& logs.notTheOther
&& metrics.notTheOther
# The control for the absence arms of `sent`: the responders' and the
# identity provider's subrequests exist, are not the store's, and
# carry no credential.
&& lib.length (lib.attrNames logs.otherLocations) >= 5
&& lib.any (n: hasInfix "agent_auth" n) (lib.attrNames logs.otherLocations)
&& lib.any (n: hasInfix "agent_auth" n) (lib.attrNames metrics.otherLocations)
# The unit creates the leaves the policy names, writes the files those
# locations include, and publishes the Secrets the pods load.
&& lib.all (store: hasInfix "secret/swarm/services/${store}/store-auth" unit.script) [
"victorialogs"
"victoriametrics"
"grafana"
]
&& lib.all (store: hasInfix "/var/lib/swarm-store-auth/${store}.conf" unit.script) [
"victorialogs"
"victoriametrics"
"grafana"
]
&& lib.all (store: hasInfix "swarm-${store}-credentials" unit.script) [
"victorialogs"
"victoriametrics"
"grafana"
]
&& hasInfix "--from-file=store-auth=/var/lib/swarm-store-auth/victoriametrics.password" unit.script
&& unit.environment.BAO_CLIENT_CERT == h.deploy.bao.storeAuthClientCertFile
&& hasInfix "store-auth.pem" h.deploy.bao.storeAuthClientCertFile
&& lib.elem (rule "victorialogs") allLocal.systemd.tmpfiles.rules
&& lib.elem (rule "victoriametrics") allLocal.systemd.tmpfiles.rules
&& lib.elem (rule "grafana") allLocal.systemd.tmpfiles.rules
# nginx runs as `User=nginx`: the directory and the nginx files are its
# group's to read, written that way and fixed when they already hold the
# value, and the passwords stay root's.
&& lib.elem "d /var/lib/swarm-store-auth 0750 root nginx - -" allLocal.systemd.tmpfiles.rules
&& hasInfix "install -d -m 0750 -o root -g nginx /var/lib/swarm-store-auth" unit.script
&& hasInfix ''atomic_write_secret 0640 root:nginx "$nginx_file" "$directive"'' unit.script
&& hasInfix ''chown root:nginx "$nginx_file"'' unit.script
&& hasInfix ''chmod 0640 "$nginx_file"'' unit.script
&& hasInfix ''atomic_write_secret 0600 root:root "$password_file" "$password"'' unit.script
# Without either store there is no unit, no file and no location.
&& !(noNode.systemd.services ? swarm-bao-store-auth)
&& !(lib.elem (rule "victorialogs") noNode.systemd.tmpfiles.rules)
&& !(lib.elem (rule "victoriametrics") noNode.systemd.tmpfiles.rules)
&& !(lib.elem (rule "grafana") noNode.systemd.tmpfiles.rules)
&& !(lib.elem "d /var/lib/swarm-store-auth 0750 root nginx - -" noNode.systemd.tmpfiles.rules)
&& !(noNode.services.nginx.virtualHosts ? ${h.swarm.victorialogs.domain})
&& !(noNode.services.nginx.virtualHosts ? ${h.swarm.victoriametrics.domain})
# Grafana's vhost sends it on `/metrics` alone, after the identity
# provider's check; `/` dials the same Service and carries none, which
# is Grafana's own login's. The Service's variable is the control that
# the lookup finds the location.
&& lib.attrNames grafanaSent == [ "= /metrics" ]
&& hasInfix "auth_request /__grafana_metrics_authz;" grafanaLocations."= /metrics".extraConfig
&& hasInfix "$swarm_grafana_upstream" grafanaLocations."/".proxyPass
&& !(hasInfix "swarm-store-auth" grafanaLocations."/".extraConfig)
&& !(noNode.services.nginx.virtualHosts ? ${h.swarm.grafana.domain});
}
{
# The exporter's login has the same three ends as the stores', with the
# hash in place of the password in the pod. The literals are spelled here,
# not read from the module.
name = "the queue's exporter asks every request for a login whose bcrypt hash a Secret supplies, the gateway's location sends the password, and the unit creates, hashes and publishes it";
ok =
let
h = allLocal.services.hyperhive;
unit = allLocal.systemd.services.swarm-bao-store-auth;
exporter = lib.findFirst (c: c.name == "exporter") null (podSpec "swarm-nats").containers;
after =
flag: lib.elemAt exporter.args ((lib.lists.findFirstIndex (a: a == flag) (-1) exporter.args) + 1);
locations = allLocal.services.nginx.virtualHosts.${h.swarm.nats.domain}.locations;
include = "include /var/lib/swarm-store-auth/nats.conf;";
rule = "f /var/lib/swarm-store-auth/nats.conf 0640 root nginx -";
in
after "-http_user" == "swarm-exporter"
# The argument is the variable Kubernetes substitutes, and the Secret it
# names holds the hash only, never the password.
&& after "-http_pass" == "$(EXPORTER_HASH)"
&&
exporter.env == [
{
name = "EXPORTER_HASH";
valueFrom.secretKeyRef = {
name = "swarm-nats-exporter-auth";
key = "hash";
};
}
]
# The gateway's `/metrics` location sends the password; the
# authorization subrequest and the catch-all do not. The location is
# the control that the lookup finds one.
&& hasInfix include locations."= /metrics".extraConfig
&& lib.all (n: !(hasInfix "/var/lib/swarm-store-auth" (locations.${n}.extraConfig or ""))) (
lib.filter (n: n != "= /metrics") (lib.attrNames locations)
)
&& lib.length (lib.attrNames locations) >= 3
# The unit mints the password, hashes it as `$2a$` at NATS's own cost
# from stdin, and gives the cluster the hash alone.
&& hasInfix "secret/swarm/services/nats/exporter-auth" unit.script
&& hasInfix "/var/lib/swarm-store-auth/nats.conf" unit.script
&& hasInfix "htpasswd -niBC 11 x" unit.script
&& hasInfix "[$]2y[$]/$2a$/" unit.script
&& hasInfix "--from-literal=hash=" unit.script
&& hasInfix "swarm-nats-exporter-auth" unit.script
&& !(hasInfix "--from-file=hash" unit.script)
&& lib.elem rule allLocal.systemd.tmpfiles.rules
# Without the queue there is no file for it.
&& !(lib.elem rule noNode.systemd.tmpfiles.rules);
}
{
# A oneshot's start job stays pending through its restarts, so while the
# secret store is sealed a boot and a switch waited on the unit for its
# whole retry budget. The start job of a `simple` unit is done at fork.
name = "the stores' credential unit starts at fork, so a sealed secret store holds neither multi-user.target nor a switch, and its retries go on";
ok =
let
services = allLocal.systemd.services;
unit = services.swarm-bao-store-auth;
orderedAfter =
name:
lib.filterAttrs (
_: s: lib.elem name (s.after or [ ]) || lib.elem name (s.requires or [ ])
) services;
in
unit.serviceConfig.Type == "simple"
# It is still started at boot, and still restarts on failure for as
# long as the store is down: the retry budget is the shared one.
&& unit.wantedBy == [ "multi-user.target" ]
&& unit.serviceConfig.Restart == "on-failure"
&& unit.startLimitBurst == 2880
# `active (exited)` after the publish, so `SubState=exited` says the
# credential is out.
&& unit.serviceConfig.RemainAfterExit
# A start timeout would be a second, unrelated budget on a unit whose
# start job is done at fork.
&& !(unit.serviceConfig ? TimeoutStartSec)
# Nothing orders after it, so none of the units that depend on the
# credential is delayed by it: the gateway reads the file it writes at
# its next reload and the pods wait in `ContainerCreating` for the
# Secret. The control: the lookup finds the units ordered after k3s.
&& orderedAfter "swarm-bao-store-auth.service" == { }
&& orderedAfter "k3s.service" != { };
}
{
# 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))
&& lib.last grafana.livenessProbe.exec.command == "http://127.0.0.1:8083/healthz"
&& !(lib.any (p: p.name == "health") grafana.ports)
&& 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
&& (lib.head (service "swarm-logs-grafana-auth/service").ports).targetPort == "grafana-api"
# 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 data is the container's own directory, so an upgrade moves the
# process and not the bytes. The path is the plain one, never the
# DynamicUser layout's `private/` directory. Every arm has a control: the
# log store's pod, which has no startup probe, and the pods that have no
# volume, no selector or no ServiceAccount.
name = "the metrics store's pod is the daemon on a static local volume that is its old container's data directory, with a startup probe and no store identity";
ok =
let
spec = podSpec "swarm-victoriametrics";
c = container "swarm-victoriametrics";
dir = "/var/lib/nixos-containers/swarm-victoriametrics/var/lib/victoriametrics";
pv = objects."swarm-victoriametrics/persistentvolume";
pvc = objects."swarm-victoriametrics/persistentvolumeclaim";
dep = objects."swarm-victoriametrics/deployment".spec;
label = "hyperhive.darkest.space/state-victoriametrics";
probe = {
path = "/health";
port = "api";
};
in
c.args == [
"-storageDataPath=/var/lib/victoriametrics"
"-httpListenAddr=:8428"
"-retentionPeriod=5y"
"-httpAuth.username=swarm-store"
"-httpAuth.password=file:///run/credentials/victoria-metrics.service/store-auth"
]
&& c.livenessProbe.httpGet == probe
&& c.readinessProbe.httpGet == probe
# The store opens its storage before it serves HTTP: liveness waits for
# ten minutes of tries.
&& c.startupProbe.httpGet == probe
&& c.startupProbe.failureThreshold == 60
&& !((container "swarm-victorialogs") ? startupProbe)
&&
c.ports == [
{
name = "api";
containerPort = 8428;
}
]
&& dep.replicas == 1
&& dep.strategy.type == "Recreate"
&& pv.spec.local.path == dir
&& !(lib.hasInfix "/private/" pv.spec.local.path)
&& pv.spec.persistentVolumeReclaimPolicy == "Retain"
&& pvc.spec.volumeName == pv.metadata.name
&&
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
&& spec.securityContext.fsGroupChangePolicy == "OnRootMismatch"
&& !(spec ? initContainers)
&& !(lib.any (v: v.name == "tls") spec.volumes)
&& lib.any (v: v.name == "tls") (podSpec "swarm-controller").volumes
&& !(spec ? serviceAccountName)
&& !(objects ? "swarm-victoriametrics/serviceaccount")
&& !(lib.any (v: v.name == "bao-token") spec.volumes)
&&
(lib.findFirst (v: v.name == "credentials") null spec.volumes).secret == {
secretName = "swarm-victoriametrics-credentials";
defaultMode = 288;
items = [
{
key = "store-auth";
path = "store-auth";
}
];
}
&& lib.any (
m:
m.name == "credentials" && m.mountPath == "/run/credentials/victoria-metrics.service" && m.readOnly
) c.volumeMounts
&& (podSpec "swarm-stt") ? serviceAccountName
&&
objects."swarm-victoriametrics/service".spec.ports == [
{
name = "api";
protocol = "TCP";
port = 8428;
targetPort = "api";
}
]
&& objects."swarm-victoriametrics/networkpolicy".spec.policyTypes == [ "Ingress" ]
&& !(objects."swarm-victoriametrics/networkpolicy".spec ? ingress)
&& lib.elem "d ${dir} - - - -" onCluster.systemd.tmpfiles.rules
&& !(lib.any (lib.hasPrefix "d ${dir} ") noNode.systemd.tmpfiles.rules);
}
{
# The metrics store's responders: one unpinned pod, one account, two
# containers whose Services each reach their own. The log store's pod is
# the control for the shape; a `--socket` would be a listener no Service
# reaches.
name = "the metrics 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-metrics-auth";
named = n: lib.findFirst (c: c.name == n) null spec.containers;
agents = named "swarm-metrics-auth";
grafana = named "grafana-auth";
policy = objects."swarm-metrics-auth/networkpolicy".spec;
s = withNode.systemd.services;
script = s.swarm-bao-k8s-jwt-policy.script;
podLabels = {
"app.kubernetes.io/name" = "swarm-metrics-auth";
"app.kubernetes.io/part-of" = "hyperhive";
};
service = n: objects.${n}.spec;
envOfC = c: lib.listToAttrs (map (e: lib.nameValuePair e.name e.value) c.env);
in
map (c: c.name) spec.containers == [
"swarm-metrics-auth"
"grafana-auth"
]
&&
agents.args == [
"--listen"
"0.0.0.0:8083"
"--store-cert-role"
"swarm-metrics-auth"
"--surface"
"metrics"
"--verdict-ttl"
"60"
]
&&
grafana.args == [
"--listen"
"0.0.0.0:8084"
"--store-cert-role"
"swarm-metrics-auth"
"--store-path"
"swarm/services/swarm-grafana/metrics/bearer"
]
&& !(lib.elem "--socket" (agents.args ++ grafana.args))
# Each container logs in with the pod's token, on the same role.
&& (envOfC agents).BAO_JWT_ROLE == "swarm-metrics-auth"
&& (envOfC grafana).BAO_JWT_ROLE == "swarm-metrics-auth"
&& !(lib.any (e: lib.hasPrefix "BAO_CLIENT" e.name) (agents.env ++ grafana.env))
&& lib.last grafana.livenessProbe.exec.command == "http://127.0.0.1:8085/healthz"
&& !(lib.any (p: p.name == "grafana-health") grafana.ports)
&& spec.serviceAccountName == "swarm-metrics-auth"
&& objects."swarm-metrics-auth/serviceaccount".metadata.name == "swarm-metrics-auth"
&& hasInfix "bound_subject=system:serviceaccount:hyperhive:swarm-metrics-auth" script
&& hasInfix "auth/jwt-k8s/role/swarm-metrics-auth" script
&& hasInfix "token_type=batch" s.swarm-bao-metrics-auth-policy.script
&& lib.elem "swarm-metrics-auth" withNode.services.hyperhive.deploy.bao.k8sPrincipals
# No state label: the store's pod is pinned, this one is not.
&& !(spec ? nodeSelector)
&& (podSpec "swarm-victoriametrics") ? nodeSelector
&& (service "swarm-metrics-auth/service").selector == podLabels
&&
(service "swarm-metrics-auth/service").ports == [
{
name = "api";
protocol = "TCP";
port = 8083;
targetPort = "api";
}
]
&& (service "swarm-metrics-grafana-auth/service").selector == podLabels
&&
(service "swarm-metrics-grafana-auth/service").ports == [
{
name = "api";
protocol = "TCP";
port = 8084;
targetPort = "grafana-api";
}
]
&&
policy.policyTypes == [
"Ingress"
"Egress"
]
&& !(policy ? ingress)
&& lib.length policy.egress == 2
&&
(lib.elemAt policy.egress 1).ports == [
{
protocol = "TCP";
port = 8208;
}
]
&& !(objects."swarm-victoriametrics/networkpolicy".spec ? egress)
&& !(spec ? initContainers)
&& !(lib.any (v: v.name == "tls") spec.volumes);
}
{
# Grafana's pod: the server on a static local volume that is its data
# directory, an init container that fetches its secrets into memory
# before it starts, and a sidecar that keeps the controller's token. The
# server's is the only port, and the pod logs in with its account's token.
# The metrics store's pod, which has neither container, is the control
# for the lookups that name them.
name = "Grafana's pod is the server on a static local volume that is its data directory, with an init container that fetches its secrets into memory and a sidecar that keeps the controller's token";
ok =
let
spec = podSpec "swarm-grafana";
named = n: lib.findFirst (c: c.name == n) null spec.containers;
main = named "swarm-grafana";
side = named "controller-token";
init = lib.head spec.initContainers;
dir = "/var/lib/nixos-containers/swarm-grafana/var/lib/grafana";
pv = objects."swarm-grafana/persistentvolume";
label = "hyperhive.darkest.space/state-grafana";
probe = {
path = "/api/health";
port = "api";
};
envOfC = c: lib.listToAttrs (map (e: lib.nameValuePair e.name e.value) c.env);
mountsOf = c: map (m: m.name) c.volumeMounts;
script = withNode.systemd.services.swarm-bao-k8s-jwt-policy.script;
credentials = lib.findFirst (v: v.name == "credentials") null spec.volumes;
policy = objects."swarm-grafana/networkpolicy".spec;
in
map (c: c.name) spec.containers == [
"swarm-grafana"
"controller-token"
]
&& map (c: c.name) spec.initContainers == [ "fetch-secrets" ]
&& !((podSpec "swarm-victoriametrics") ? initContainers)
&& main.livenessProbe.httpGet == probe
&& main.readinessProbe.httpGet == probe
&& main.startupProbe.httpGet == probe
&& main.startupProbe.failureThreshold == 30
# One port, named once: the init container and the sidecar declare none.
&&
main.ports == [
{
name = "api";
containerPort = 3000;
}
]
&& !(init ? ports)
&& !(side ? ports)
&& objects."swarm-grafana/deployment".spec.strategy.type == "Recreate"
&& pv.spec.local.path == dir
&& !(lib.hasInfix "/private/" pv.spec.local.path)
&& spec.nodeSelector == { ${label} = "true"; }
&& spec.securityContext.fsGroupChangePolicy == "OnRootMismatch"
# The secrets are in memory, and all three containers mount them where
# the settings name them. The `tmp` volume is the control that the
# lookup finds a plain one.
&&
(lib.findFirst (v: v.name == "runtime") null spec.volumes) == {
name = "runtime";
emptyDir.medium = "Memory";
}
&&
(lib.findFirst (v: v.name == "tmp") null spec.volumes) == {
name = "tmp";
emptyDir = { };
}
&& lib.all (c: lib.elem "runtime" (mountsOf c)) [
main
init
side
]
&&
(lib.findFirst (m: m.name == "runtime") null main.volumeMounts).mountPath == "/run/grafana-secrets"
# It logs in with its account's token, under the role its certificate has.
&& spec.serviceAccountName == "swarm-grafana"
&& objects."swarm-grafana/serviceaccount".metadata.name == "swarm-grafana"
&& lib.all (c: (envOfC c).BAO_JWT_ROLE == "swarm-grafana-oidc") [
main
init
side
]
&& !(lib.any (e: lib.hasPrefix "BAO_CLIENT" e.name) (init.env ++ side.env))
&& hasInfix "auth/jwt-k8s/role/swarm-grafana-oidc" script
&& hasInfix "bound_subject=system:serviceaccount:hyperhive:swarm-grafana" script
&& lib.elem "swarm-grafana-oidc" withNode.services.hyperhive.deploy.bao.k8sPrincipals
# The listener credential comes from the Secret the host publishes.
&& lib.any (s: (s.secret.name or null) == "swarm-grafana-credentials") credentials.projected.sources
# The Service and the policy: only the node in, and out to DNS, the
# store and the gateway.
&&
objects."swarm-grafana/service".spec.ports == [
{
name = "api";
protocol = "TCP";
port = 3000;
targetPort = "api";
}
]
&&
policy.policyTypes == [
"Ingress"
"Egress"
]
&& !(policy ? ingress)
&& lib.length policy.egress == 2
&&
(lib.elemAt policy.egress 1).ports == [
{
protocol = "TCP";
port = 8208;
}
{
protocol = "TCP";
port = 443;
}
]
&& lib.elem "d ${dir} - - - -" onCluster.systemd.tmpfiles.rules
&& !(lib.any (lib.hasPrefix "d ${dir} ") noNode.systemd.tmpfiles.rules);
}
{
# A named `targetPort` resolves to the first container of the pod that
# declares the name, so a second container declaring it too is reached by
# the wrong Service. The first clauses are the control: the lookup finds
# the Services whose pods hold two containers, and the store's, and
# finds the name once in each.
name = "every Service that targets a port by name reaches a name that exactly one container of its pod declares";
ok =
let
all = lib.attrValues objects;
services = lib.filter (o: o.kind == "Service") all;
deployments = lib.filter (o: o.kind == "Deployment") all;
named = lib.filter (svc: lib.any (p: builtins.isString p.targetPort) svc.spec.ports) services;
podOf =
svc: lib.findFirst (d: d.spec.template.metadata.labels == svc.spec.selector) null deployments;
declared =
pod: port:
lib.length (
lib.filter (p: p.name == port) (lib.concatMap (c: c.ports or [ ]) pod.spec.template.spec.containers)
);
reached = lib.concatMap (
svc:
map (p: {
service = svc.metadata.name;
count = declared (podOf svc) p.targetPort;
}) (lib.filter (p: builtins.isString p.targetPort) svc.spec.ports)
) named;
countOf = n: (lib.findFirst (r: r.service == n) { count = 0; } reached).count;
in
lib.length (lib.filter (svc: lib.length (podOf svc).spec.template.spec.containers > 1) named) >= 4
&& countOf "swarm-metrics-grafana-auth" == 1
&& countOf "swarm-logs-grafana-auth" == 1
&& countOf "swarm-victoriametrics" == 1
&& lib.all (r: r.count == 1) reached;
}
{
# 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";
ok =
let
entry = [
"hyperhive.darkest.space/entry=true"
"svccontroller.k3s.cattle.io/enablelb=true"
];
sorted = lib.sort lib.lessThan;
in
sorted onCluster.services.k3s.nodeLabel == sorted (
entry
++ [
"hyperhive.darkest.space/state-nats=true"
"hyperhive.darkest.space/state-ci-metrics=true"
"hyperhive.darkest.space/state-victorialogs=true"
"hyperhive.darkest.space/state-victoriametrics=true"
"hyperhive.darkest.space/state-grafana=true"
]
)
&&
onCluster.services.hyperhive.deploy.k8s.nodeLabels == {
"hyperhive.darkest.space/entry" = "true";
"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";
"hyperhive.darkest.space/state-victoriametrics" = "true";
"hyperhive.darkest.space/state-grafana" = "true";
}
&& noNode.services.k3s.nodeLabel == [ ];
}
{
# The queue's pod is the control for the poller's lookups, and the
# stateless pods for the absence of a selector. `nodeAffinity` is in the
# text the hostname is searched in.
name = "the poller's claim is a static local volume on the service's directory, and the volumes and pods of the queue and the poller name their state label, with no hostname in any object";
ok =
let
pv = objects."swarm-ci-metrics/persistentvolume";
pvc = objects."swarm-ci-metrics/persistentvolumeclaim";
spec = podSpec "swarm-ci-metrics";
state = lib.findFirst (v: v.name == "state") null spec.volumes;
text = builtins.toJSON objects + builtins.toJSON onCluster.services.hyperhive.k8s.rendered.services;
hostDir = "/var/lib/private/swarm-ci-metrics";
rule = "d ${hostDir} 0700 root root -";
in
pv.spec.nodeAffinity.required.nodeSelectorTerms == [
{
matchExpressions = [
{
key = "hyperhive.darkest.space/state-ci-metrics";
operator = "In";
values = [ "true" ];
}
];
}
]
&& spec.nodeSelector == { "hyperhive.darkest.space/state-ci-metrics" = "true"; }
&& pv.spec.local.path == hostDir
&& pv.spec.persistentVolumeReclaimPolicy == "Retain"
&& !(pv.metadata ? namespace)
&& pvc.spec.volumeName == pv.metadata.name
&& pvc.spec.storageClassName == pv.spec.storageClassName
&& pv.spec.storageClassName != ""
&& state.persistentVolumeClaim.claimName == pvc.metadata.name
&& !(podSpec "swarm-controller" ? nodeSelector)
&& !(podSpec "swarm-stt" ? nodeSelector)
&& (podSpec "swarm-nats").nodeSelector == { "hyperhive.darkest.space/state-nats" = "true"; }
&& hasInfix "nodeAffinity" text
&& !(hasInfix "kubernetes.io/hostname" text)
&& lib.elem rule onCluster.systemd.tmpfiles.rules
&& !(lib.elem rule noNode.systemd.tmpfiles.rules);
}
{
# `noNode` is the control that the lookup reads false where no service is
# enabled; `nodeOffRefused` sets it false itself, and the assertion below
# is what tells that host.
name = "the node is on wherever the host enables a swarm service, through the all-local mode or through one toggle, and an explicit false stays false";
ok =
withNode.services.hyperhive.deploy.k8s.enable
&& oneToggle.services.hyperhive.deploy.k8s.enable
&& !noNode.services.hyperhive.deploy.k8s.enable
&& !nodeOffRefused.services.hyperhive.deploy.k8s.enable;
}
{
# The all-local host's assertions are the control: they all hold.
name = "a host that enables a swarm service with the node off fails at evaluation, and the message names the option and the services";
ok =
lib.all (a: a.assertion) withNode.assertions
&& lib.any (
a:
hasInfix "services.hyperhive.deploy.k8s.enable is false" a.message
&& lib.all (n: hasInfix "deploy.${n}.enable" a.message) [
"notify-router"
"stt"
"ci-metrics"
"review-classifier"
"claude-login"
"swarm-controller"
"nats"
]
) nodeOffRefusals;
}
{
# A host that sets nothing gets the listener on, named from the swarm domain
# and bound on every address: `oneToggle` sets none of them.
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: hasInfix needle a.message) nodeOffRefusals;
in
oneToggle.services.hyperhive.swarm.controller.tcp.enable
&& oneToggle.services.hyperhive.swarm.controller.tcp.domain == "controller.t.local"
&& oneToggle.services.hyperhive.swarm.controller.tcp.clientName == "gateway-client.t.local"
&& oneToggle.services.hyperhive.deploy.swarm-controller.tcp.listenAddress == "0.0.0.0"
&& withNode.services.hyperhive.swarm.controller.tcp.enable
&& !nodeOffRefused.services.hyperhive.swarm.controller.tcp.enable
&& refusesWith "services.hyperhive.swarm.controller.tcp.enable is false"
&& refusesWith "services.hyperhive.deploy.swarm-controller.tcp.listenAddress"
&& 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 && hasInfix "tcp.listenAddress" a.message) withNode.assertions;
}
{
# The registry host is spelled out here, so the module is not compared
# with itself. `withNode` is the control for the flags that follow an
# address: it sets none, and k3s keeps its own default.
name = "the server serves the embedded registry and mirrors the images' host alone, and follows the node's address when it has one";
ok =
let
registries = onCluster.environment.etc."rancher/k3s/registries.yaml".text;
in
registries == "mirrors:\n registry.hyperhive.invalid:\n"
&& nodeNoBridge.environment.etc."rancher/k3s/registries.yaml".text == 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"
&& lib.elem "--tls-san=192.168.1.10" onCluster.services.k3s.extraFlags
&& nodeNoBridge.services.k3s.nodeIP == null
&& !(lib.any (lib.hasPrefix "--tls-san") nodeNoBridge.services.k3s.extraFlags);
}
{
# `withNode` lists no node: the control that the ports are not open
# for everyone, and the `-s` on every rule that they are for the nodes.
name = "the nodes' ports are open to the listed node addresses and to no other source";
ok =
let
rules = onCluster.networking.firewall.extraCommands;
rule =
address: proto: port:
"iptables -A nixos-fw -s ${address} -p ${proto} --dport ${port} -j nixos-fw-accept\n";
forNodes = address: [
(rule address "tcp" "6443")
(rule address "tcp" "10250")
(rule address "udp" (toString onCluster.services.hyperhive.deploy.k8s.flannelWgPort))
(rule address "tcp" "5001")
];
nodeLines = lib.filter (l: hasInfix "--dport" l && hasInfix "nixos-fw -s" l) (
lib.splitString "\n" rules
);
in
lib.all (r: hasInfix r rules) (forNodes "192.168.1.11" ++ forNodes "192.168.1.12")
&& lib.length nodeLines == 8
&& !(hasInfix "--dport 6443" nodeNoBridge.networking.firewall.extraCommands)
&& !(lib.elem 6443 onCluster.networking.firewall.allowedTCPPorts)
&& !(lib.elem onCluster.services.hyperhive.deploy.k8s.flannelWgPort onCluster.networking.firewall.allowedUDPPorts)
&& !(hasInfix "8472" rules)
&& !(hasInfix "8472" joined.networking.firewall.extraCommands)
&& hasInfix (rule "192.168.1.10" "udp" (
toString joined.services.hyperhive.deploy.k8s.flannelWgPort
)) joined.networking.firewall.extraCommands;
}
{
# The main node is the control for each absence.
name = "a host that joins runs a k3s agent with the token the store gave it, none of the server's units or labels, and the same mirror";
ok =
joined.services.k3s.enable
&& joined.services.k3s.role == "agent"
&& joined.services.k3s.serverAddr == "https://192.168.1.10:6443"
&& joined.services.k3s.tokenFile == "/run/k3s-join/token"
&& joined.services.k3s.agentTokenFile == null
&& joined.services.k3s.nodeIP == "192.168.1.11"
&& joined.services.k3s.nodeLabel == [ ]
&& joined.services.k3s.manifests == { }
&& !(lib.elem "--embedded-registry" joined.services.k3s.extraFlags)
&&
joined.environment.etc."rancher/k3s/registries.yaml".text
== onCluster.environment.etc."rancher/k3s/registries.yaml".text
&& 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" ]
&& 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)
&& withNode.services.k3s.role == "server"
&& withNode.services.k3s.nodeLabel != [ ]
&& !(joined.systemd.services ? hyperhive-k8s-ca-trust)
&& withNode.systemd.services ? hyperhive-k8s-ca-trust;
}
{
name = "a host that is both the main node and a joined node is refused, and so is a join with no store identity";
ok =
let
both = hive {
deploy.k8s.enable = true;
deploy.k8s.join.server = "192.168.1.10";
};
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 (hasInfix needle) (messages c);
in
mentions "k8s.join as a node of another" both
&& mentions "baoHiveIdentityCertFile" noIdentity
&& !(mentions "k8s.join as a node of another" joined)
&& !(mentions "baoHiveIdentityCertFile" joined);
}
{
# The main hive writes and h2 only reads. A count, not a match: the
# same path is in both policies, so a stanza in the wrong one still
# leaves the other in the text.
name = "every hive's identity may read the join token, and the main node's hive alone may write it";
ok =
let
script = twoHives.systemd.services.swarm-bao-hive-leaf-policy.script;
path = "path \"secret/data/swarm/services/k8s/agent-token\" {\n capabilities = ";
in
occurrences "${path}[\"create\", \"read\", \"update\"]" script == 1
&& occurrences "${path}[\"read\"]" script == 1
&&
occurrences "agent-token\" {\n capabilities = [\"create\"" noNode.systemd.services.swarm-bao-hive-leaf-policy.script
== 0
&&
occurrences "agent-token\" {\n capabilities = [\"read\"]" noNode.systemd.services.swarm-bao-hive-leaf-policy.script
== 1;
}
{
# Presence controls: the lists are not empty, and the queue's three images
# and a leaf's are among them.
name = "every image the pods name carries the registry host that resolves nowhere, and none is pulled from a registry or never";
ok =
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: hasInfix "-tls:" r) imageRefs
&& occurrences "\"imagePullPolicy\":\"IfNotPresent\"" clusterText >= 8
&& !(hasInfix "\"imagePullPolicy\":\"Never\"" clusterText)
&& !(hasInfix "docker.io" clusterText);
}
{
# The literals are the controls that the lookup sees each place a name is
# written (an object key, a name, the app label) and lets `swarm-` and an
# inner `hive-` through. The hosts hold many objects, so the empty result
# is not an empty input.
name = "no workload, Service, volume claim or label in the cluster starts with the legacy hive- prefix";
ok =
let
legacy =
(import ../host-modules/k8s/render.nix {
inherit lib pkgs;
config = onCluster;
}).legacyPrefixed;
obj = name: labels: { metadata = { inherit name labels; }; };
named = n: l: legacy { x = obj n l; };
in
legacy { "hive-forge/deployment" = obj "x" { }; } == [ "hive-forge/deployment" ]
&& named "hive-matrix" { } == [ "hive-matrix" ]
&& named "x" { "app.kubernetes.io/name" = "hive-forge"; } == [ "hive-forge" ]
&& named "swarm-hive-forge" { "app.kubernetes.io/name" = "swarm-x"; } == [ ]
&& lib.length (lib.attrNames objects) >= 15
&& lib.length (lib.attrNames (render onCluster)) >= 30
&& legacy objects == [ ]
&& legacy (render onCluster) == [ ];
}
];
in
runGroup "k8s" cases