Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/nix/module-eval/k8s.nix
atlas 3cf89f25f1 k8s: the controller's listener is a ClusterIP service the host dials by name
The controller's api port was a hostPort on the node, which Pod Security baseline and restricted forbid. It is a ClusterIP Service now, behind a NetworkPolicy that admits only the node. The host's resolver (the hive's dnsmasq) forwards cluster.local to CoreDNS, and the gateway dials the Service by name through nginx's resolver. tcp.hostAddress goes.
2026-11-27 11:46:56 +01:00

2033 lines
91 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
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 same host with the router, the speech-to-text service, the review
# classifier, the claude login minter and the CI run poller in the cluster,
# so it has none of their containers, nor the poller's unit or timer. A
# second full host, because the claim is about what the configuration drops;
# the other cases of this group read `withNode`.
onCluster = hiveWithController (
lib.recursiveUpdate nodeSettings {
deploy.notify-router.runtime = "k8s";
deploy.stt.runtime = "k8s";
deploy.ci-metrics.runtime = "k8s";
deploy.review-classifier.runtime = "k8s";
deploy.claude-login.runtime = "k8s";
deploy.swarm-controller.runtime = "k8s";
deploy.nats.runtime = "k8s";
}
);
# A host that asks for the cluster with no node, and a controller in it with
# no TCP listener.
runtimeRefused = hive {
deploy.notify-router.runtime = "k8s";
deploy.stt.runtime = "k8s";
deploy.ci-metrics.runtime = "k8s";
deploy.review-classifier.runtime = "k8s";
deploy.claude-login.runtime = "k8s";
deploy.swarm-controller.enable = true;
deploy.swarm-controller.runtime = "k8s";
deploy.swarm-controller.tcp.listenAddress = "10.0.0.5";
deploy.nats.runtime = "k8s";
};
runtimeRefusals = lib.filter (a: !a.assertion) runtimeRefused.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 = hive { deploy.k8s.enable = true; };
coreDnsKey = "hyperhive-host-services.override";
refusals = lib.filter (a: !a.assertion) nodeRefused.assertions;
refuses = needle: lib.any (a: lib.hasInfix needle a.message) refusals;
render =
config:
(import ../host-modules/k8s/render.nix {
inherit lib pkgs config;
}).objects;
objects = render allLocal;
# The queue's pod reads the settings of the system it runs from, which differ
# in the path of the server's key: what a switch must leave alone is the rest.
# The speech-to-text policy names the queue's pod only where the queue runs in
# the cluster, so it follows the queue; its own case reads it.
notQueue = lib.filterAttrs (
n: _: !(lib.hasPrefix "swarm-nats/" n) && n != "swarm-stt/networkpolicy"
);
units = {
swarm-controller = allLocal.systemd.services.swarm-controller;
swarm-notify-router =
allLocal.containers.swarm-notify-router.config.systemd.services.swarm-notify-router;
swarm-stt = allLocal.containers.swarm-stt.config.systemd.services.swarm-stt;
swarm-review-classifier =
allLocal.containers.swarm-review-classifier.config.systemd.services.swarm-review-classifier;
swarm-claude-login =
allLocal.containers.swarm-claude-login.config.systemd.services.swarm-claude-login;
swarm-ci-metrics = allLocal.systemd.services.swarm-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 = "0.0.0.0:8080";
};
swarm-notify-router = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_NOTIFY_ROUTER_HEALTH_ADDR = "0.0.0.0:8080";
};
swarm-stt = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_STT_HEALTH_ADDR = "0.0.0.0:8080";
STATE_DIRECTORY = "/var/lib/swarm-stt";
};
swarm-review-classifier = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_REVIEW_CLASSIFIER_HEALTH_ADDR = "0.0.0.0:8080";
};
swarm-claude-login = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_CLAUDE_LOGIN_HEALTH_ADDR = "0.0.0.0: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
)
++ map (f: lib.last (lib.splitString ":" f)) (
allLocal.containers.swarm-notify-router.extraFlags
++ allLocal.containers.swarm-stt.extraFlags
++ allLocal.containers.swarm-review-classifier.extraFlags
++ allLocal.containers.swarm-claude-login.extraFlags
);
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.systemd.timers.swarm-ci-metrics.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"; } ]; });
migrateOf = c: builtins.fromJSON c.environment.etc."hyperhive/migrate.json".text;
routerUnit = c: c.services.hyperhive.deploy.notify-router.unit;
manifestNames = c: lib.sort lib.lessThan (lib.attrNames c.services.k3s.manifests);
routerPrune = withNode.systemd.services.swarm-notify-router-k8s-prune;
sttPrune = withNode.systemd.services.swarm-stt-k8s-prune;
ciPrune = withNode.systemd.services.swarm-ci-metrics-k8s-prune;
classifierPrune = withNode.systemd.services.swarm-review-classifier-k8s-prune;
loginPrune = withNode.systemd.services.swarm-claude-login-k8s-prune;
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: lib.hasInfix s rendered) credentialSources)
&& lib.all (id: lib.hasInfix "\"${id}\"" rendered) (lib.subtractLists clientCertIds credentialIds)
# The units load the client certificates and the pods do not.
&& lib.all (id: lib.elem id credentialIds && !(lib.hasInfix "\"${id}\"" rendered)) clientCertIds
&& !(lib.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
(lib.head c.ports).containerPort == 8080
&& c.readinessProbe.httpGet.path == "/readyz"
&& c.livenessProbe.httpGet.path == "/healthz"
&& lib.all (name: (podSpec name).terminationGracePeriodSeconds > 10) (lib.attrNames units);
}
{
# 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 =
!allLocal.services.k3s.enable
&& !(allLocal.systemd.services ? k3s)
&& allLocal.services.k3s.images == [ ]
&& !(lib.elem "cni0" allLocal.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.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
lib.hasInfix "--disable=traefik" start
&& lib.hasInfix "--disable=metrics-server" start
&& lib.hasInfix "--secrets-encryption" start
&& lib.hasInfix "--cluster-cidr=10.200.0.0/16" start
&& lib.hasInfix "--service-cidr=10.201.0.0/16" start
&& !(lib.hasInfix "--disable=coredns" start)
&& !(lib.hasInfix "--disable=local-storage" start);
}
{
# The images are the ones the manifests run, one per rendered service, the
# controller's listener leaf, the queue's three more (server, exporter,
# init): the eleven are the control that the list is not empty.
name = "the node loads the image of every service the manifests run, and k3s's own";
ok =
let
loaded = map toString withNode.services.k3s.images;
rendered = map toString withNode.system.build.k8sImages;
in
lib.length rendered == 11
&& lib.all (i: lib.elem i loaded) rendered
&& lib.elem (toString withNode.services.k3s.package.airgap-images) loaded
&& lib.length loaded == 12;
}
{
# Nothing the host already runs differs but the store's side of the pods'
# login: every unit, timer and container is still there, the only new
# units are k3s's and the one that writes the pods' login, every unit but
# the firewall (whose rules carry the pod network's interfaces), the
# resolver (which hands the cluster's domain to its DNS) and the
# granter's role unit (which enables the login's auth mount) starts the
# same command, and the manifests are the same as without the node. The
# fixture has the controller's TCP listener on, which `allLocal` has off:
# its units, its roles and grants, and the gateway's locations are the
# one difference, and the controller's pod differs by the listener.
name = "the node adds only k3s, the jwt unit and the prune units of the controller, the four daemons and the CI run poller to the all-local host, and changes no container, timer or manifest";
ok =
let
# The listener's own units, which `withNode` has on and `allLocal` off.
tcpUnit =
n: lib.hasPrefix "swarm-controller-tls" n || lib.hasPrefix "swarm-controller-gateway-client" n;
names = a: lib.filter (n: !tcpUnit n) (lib.attrNames a);
added = lib.subtractLists (names allLocal.systemd.services) (names withNode.systemd.services);
in
names allLocal.systemd.timers == names withNode.systemd.timers
&& names allLocal.containers == names withNode.containers
&& lib.subtractLists (names withNode.systemd.services) (names allLocal.systemd.services) == [ ]
&& lib.elem "k3s" added
&& lib.all (
n:
lib.hasPrefix "k3s" n
|| n == "swarm-bao-k8s-jwt-policy"
|| n == "swarm-notify-router-k8s-prune"
|| n == "swarm-stt-k8s-prune"
|| n == "swarm-ci-metrics-k8s-prune"
|| n == "swarm-review-classifier-k8s-prune"
|| n == "swarm-claude-login-k8s-prune"
|| n == "swarm-controller-k8s-prune"
|| n == "swarm-nats-k8s-prune"
) added
&& lib.elem "swarm-bao-k8s-jwt-policy" added
&& lib.elem "swarm-notify-router-k8s-prune" added
&& lib.elem "swarm-stt-k8s-prune" added
&& lib.elem "swarm-ci-metrics-k8s-prune" added
&& lib.elem "swarm-review-classifier-k8s-prune" added
&& lib.elem "swarm-claude-login-k8s-prune" added
&& lib.elem "swarm-controller-k8s-prune" added
&& lib.elem "swarm-nats-k8s-prune" added
&&
lib.all
(
n:
withNode.systemd.services.${n}.serviceConfig.ExecStart or null
== allLocal.systemd.services.${n}.serviceConfig.ExecStart or null
)
(
lib.subtractLists [
"firewall"
"dnsmasq"
"nginx"
"opentelemetry-collector"
"swarm-bao-controller-policy"
"swarm-bao-granter-role"
"swarm-bao-services-issuer-policy"
] (names allLocal.systemd.services)
)
&& (
let
others = lib.filterAttrs (n: _: !(lib.hasPrefix "swarm-controller/" n));
in
others (render withNode) == others (render allLocal)
)
# `withNode` has the controller's listener on, which `allLocal` has
# off: the pod differs by it, its other objects do not.
&& (render withNode)."swarm-controller/configmap" == (render allLocal)."swarm-controller/configmap";
}
{
# 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";
}
{
# 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: lib.hasInfix (builtins.replaceStrings [ "." ] [ "[.]" ] n) text) names
&& lib.hasInfix "template IN A {" text
&& lib.hasInfix "template IN AAAA {" text
&& lib.hasInfix "answer \"{{ .Name }} 60 IN A ${h.network.bridgeIp}\"" text
&& lib.hasInfix " fallthrough\n}\n" text
&& !(lib.hasInfix "127.0.0.1" text)
&& !(lib.hasInfix "hosts" text)
&& lib.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
&& allLocal.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: lib.hasInfix "hive-collector" (e.value or "")) (container "swarm-ci-metrics").env)
&& !(envOf "swarm-notify-router" ? SWARM_CI_METRICS_OTLP_ENDPOINT)
&& units.swarm-controller.environment.OTEL_EXPORTER_OTLP_ENDPOINT == controllerRoute
&& (envOf "swarm-controller").OTEL_EXPORTER_OTLP_ENDPOINT == controllerRoute
&&
(envOf "swarm-controller").SWARM_CONTROLLER_OTEL_AUDIENCE
== units.swarm-controller.environment.SWARM_CONTROLLER_OTEL_AUDIENCE
&& !(lib.any (e: lib.hasInfix "hive-collector" (e.value or "")) (container "swarm-controller").env);
}
{
# 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 (lib.hasInfix "u:opentelemetry-collector:") c.systemd.tmpfiles.rules;
in
!((settings allLocal).receivers ? "file_log/pods")
&& !((settings allLocal).service.pipelines ? "logs/pods")
&& (settings withNode).receivers ? "file_log/pods"
&& (settings withNode).service.pipelines ? "logs/pods"
&& bare (settings withNode) == settings allLocal
&& (unit allLocal).DynamicUser
&& !(unit allLocal ? User)
&& !(allLocal.users.users ? opentelemetry-collector)
&& collectorAcls allLocal == [ ]
&& !(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 (lib.hasInfix "u:opentelemetry-collector:") withNode.systemd.tmpfiles.rules;
in
r.include == [ "/var/log/pods/*/*/*.log" ]
&& r.include_file_path
&& r.storage == "file_storage"
&& (lib.head ops).type == "container"
&& lib.all (l: lib.hasInfix l (op "regex_parser").regex) [
"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: a case of their own.
roles = lib.filter (r: !(lib.hasPrefix "swarm-nats" r)) 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:
lib.hasInfix (lib.removeSuffix "\n" (roleText name)) script
&& lib.hasInfix "auth/cert/certs/${name}" certScript.${name}
&& lib.hasInfix "token_policies=${name}" certScript.${name}
&& lib.hasInfix "token_ttl=1h" certScript.${name}
&& lib.hasInfix "token_max_ttl=1h" certScript.${name}
) roles
&& lib.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
lib.hasInfix (role "swarm-nats") script
&& lib.hasInfix (role "swarm-nats-auth") script
&& lib.hasInfix "token_type=batch" s.swarm-bao-nats-auth-policy.script
&& lib.hasInfix "auth/cert/certs/swarm-nats " s.swarm-bao-nats-tls-policy.script
&& lib.hasInfix "auth/cert/certs/swarm-nats-auth" s.swarm-bao-nats-auth-policy.script
&& 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
lib.hasInfix "/var/lib/rancher/k3s/server/tls/service.key" u.script
&& lib.hasInfix "/var/lib/rancher/k3s/server/tls/service.current.key" u.script
&& lib.hasInfix "openssl pkey -in \"$block\" -pubout" u.script
&& lib.hasInfix "jwt_validation_pubkeys" u.script
&& lib.hasInfix "https://kubernetes.default.svc.cluster.local" u.script
&& lib.hasInfix "\"RS256\", \"ES256\"" u.script
&& lib.hasInfix "--data-dir=/var/lib/rancher/k3s" start
&& lib.hasInfix "--cluster-domain=cluster.local" start
&& 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
lib.hasInfix "bao auth enable -path=jwt-k8s jwt" g.script
&& lib.hasInfix "path \"auth/jwt-k8s/config\" {\n capabilities = [\"create\", \"update\"]\n}" g.script
&& lib.hasInfix "path \"auth/jwt-k8s/role/swarm-*\" {\n capabilities = [\"create\", \"update\"]\n}" g.script
&& lib.hasInfix "path \"sys/auth/jwt-k8s\" {\n capabilities = [\"create\", \"update\", \"sudo\"]\n}" hcl
&& !(lib.hasInfix "sys/auth/jwt-k8s" g.script)
&& lib.hasInfix "swarm-bao-k8s-jwt-policy.service" g.serviceConfig.ExecStartPost;
}
{
# 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 = allLocal.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
&& lib.hasInfix "jwt-k8s" on.script
&& lib.hasInfix "swarm-bao-k8s-jwt-policy" on.serviceConfig.ExecStartPost
&& withNode.networking.firewall.interfaces ? cni0
&& !((baoSettings allLocal).listener ? pod)
&& !(allLocal.systemd.services ? swarm-bao-k8s-jwt-policy)
&& !(lib.hasInfix "jwt-k8s" off.script)
&& !(lib.hasInfix "swarm-bao-k8s-jwt-policy" off.serviceConfig.ExecStartPost)
&& lib.hasInfix "swarm-bao-operator-viewer-policy" off.serviceConfig.ExecStartPost
&& !(allLocal.networking.firewall.interfaces ? cni0)
&& !(allLocal.networking.firewall.interfaces ? "flannel.1");
}
{
# 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.1"
]
&& 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);
}
{
# The host with the router on it is the control for every absence below:
# it holds the container, the prune unit and the pieces the cluster
# case lacks.
name = "a router on the host keeps its container, the node adds no manifest and no CA unit, and its prune unit runs before the container";
ok =
withNode.containers ? swarm-notify-router
&& withNode.systemd.services ? "container@swarm-notify-router"
&& manifestNames withNode == [ "coredns-custom" ]
&& !(withNode.systemd.services ? hyperhive-k8s-ca-trust)
&& routerPrune.before == [ "container@swarm-notify-router.service" ]
&& routerPrune.requiredBy == [ "container@swarm-notify-router.service" ]
&& lib.hasInfix "swarm-notify-router.yaml" routerPrune.script
&& allLocal.services.k3s.manifests == { }
&& !(allLocal.systemd.services ? swarm-notify-router-k8s-prune)
&& !(allLocal.systemd.services ? hyperhive-k8s-ca-trust);
}
{
name = "a daemon or the poller in the cluster leaves the host no container, service, timer or prune unit, and applies the namespace and its objects";
ok =
!(onCluster.containers ? swarm-notify-router)
&& !(onCluster.systemd.services ? "container@swarm-notify-router")
&& !(onCluster.systemd.services ? swarm-notify-router-k8s-prune)
&& !(onCluster.containers ? swarm-stt)
&& !(onCluster.systemd.services ? "container@swarm-stt")
&& !(onCluster.systemd.services ? swarm-stt-k8s-prune)
&& !(onCluster.systemd.services ? swarm-ci-metrics)
&& !(onCluster.systemd.timers ? swarm-ci-metrics)
&& !(onCluster.systemd.services ? swarm-ci-metrics-k8s-prune)
&& !(onCluster.systemd.services ? swarm-ci-metrics-ca-bundle)
&& !(onCluster.containers ? swarm-review-classifier)
&& !(onCluster.systemd.services ? "container@swarm-review-classifier")
&& !(onCluster.systemd.services ? swarm-review-classifier-k8s-prune)
&& !(onCluster.containers ? swarm-claude-login)
&& !(onCluster.systemd.services ? "container@swarm-claude-login")
&& !(onCluster.systemd.services ? swarm-claude-login-k8s-prune)
&& !(onCluster.containers ? swarm-nats)
&& !(onCluster.systemd.services ? "container-nats")
&& !(onCluster.systemd.services ? swarm-nats-k8s-prune)
&&
manifestNames onCluster == [
"coredns-custom"
"hyperhive-namespace"
"swarm-ci-metrics"
"swarm-claude-login"
"swarm-controller"
"swarm-nats"
"swarm-notify-router"
"swarm-review-classifier"
"swarm-stt"
]
&& onCluster.services.k3s.manifests.hyperhive-namespace.content.kind == "Namespace"
&&
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"
"PersistentVolumeClaim"
"ServiceAccount"
];
}
{
name = "the router's manifests and its unit are the same whether the container or the stand-alone evaluation supplies the unit";
ok =
(routerUnit withNode).environment ? SWARM_NOTIFY_ROUTER_NATS_URL
&& (routerUnit onCluster).environment == (routerUnit withNode).environment
&& (routerUnit onCluster).serviceConfig.ExecStart == (routerUnit withNode).serviceConfig.ExecStart
&&
(routerUnit onCluster).serviceConfig.LoadCredential == (routerUnit withNode)
.serviceConfig.LoadCredential
&& notQueue (render onCluster) == notQueue (render withNode);
}
{
# 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
&& lib.hasInfix "--from-file=bao-server-ca.pem=${serverCa}" caUnit.script
&& lib.hasInfix "--from-file=hive-client-ca.pem=" caUnit.script
&& lib.hasInfix "--from-file=swarm-services-root.pem=" caUnit.script
&& lib.hasInfix "--from-file=trust-bundle.pem=" caUnit.script
&& lib.elem "multi-user.target" caUnit.wantedBy
# A change to either file publishes again with no manual step, and the
# host with the router on its container 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)
&& !(withNode.systemd.paths ? hyperhive-k8s-ca-trust);
}
{
# The container's whole unit is compared, sandbox included, so the
# stand-alone evaluation cannot drift from what the host runs.
name = "the speech-to-text service's unit, and so its manifests, are the same whether the container or the stand-alone evaluation supplies it";
ok =
let
unitOf = c: c.services.hyperhive.deploy.stt.unit;
in
(unitOf withNode).serviceConfig.SystemCallFilter == [
"@system-service"
"~@privileged"
"~@resources"
]
&& (unitOf onCluster).serviceConfig == (unitOf withNode).serviceConfig
&& (unitOf onCluster).environment == (unitOf withNode).environment
&& notQueue (render onCluster) == notQueue (render withNode);
}
{
# The host-mode container is pinned by value: the module moved into a
# let binding, and nothing about the container it defines may change.
name = "with the speech-to-text service on the host, its container, credential flags and sandbox are as the module defines them";
ok =
let
c = withNode.containers.swarm-stt;
sc = (unitOf withNode).serviceConfig;
unitOf = x: x.services.hyperhive.deploy.stt.unit;
flags = c.extraFlags;
in
c.autoStart
&& !c.ephemeral
&& c.privateNetwork
&& c.hostBridge == withNode.services.hyperhive.network.bridgeName
&& lib.all (f: lib.hasPrefix "--load-credential=stt-bao-" f) flags
&& lib.any (lib.hasPrefix "--load-credential=stt-bao-cert:") flags
&& lib.any (lib.hasPrefix "--load-credential=stt-bao-key:") flags
&& sc.User == "swarm-stt"
&& sc.StateDirectory == "swarm-stt"
&& sc.NoNewPrivileges
&& sc.MemoryDenyWriteExecute
&& sc.PrivateUsers
&& sc.CapabilityBoundingSet == ""
&& sc.MemoryMax == "3G"
&& sc.CPUQuota == "400%"
&& sc.TasksMax == 256
&& withNode.systemd.services ? "container@swarm-stt"
&& sttPrune.before == [ "container@swarm-stt.service" ]
&& sttPrune.requiredBy == [ "container@swarm-stt.service" ]
&& lib.hasInfix "swarm-stt.yaml" sttPrune.script;
}
{
# 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 with it on the cluster 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 withNode == [ ]
&& lib.length (userns onCluster) == 1
&& (lib.head (userns onCluster)).assertion
&& lib.versionAtLeast onCluster.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";
}
&& !(lib.hasInfix "TasksMax" rendered)
&& !(lib.hasInfix "SystemCallFilter" rendered)
&& lib.all (name: !((container name) ? resources)) [
"swarm-controller"
"swarm-notify-router"
"swarm-ci-metrics"
];
}
{
# 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;
clusterPolicy = policyOf (render onCluster);
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)
&&
policy.spec.egress == [
dns
host
]
&&
clusterPolicy.spec.egress == [
dns
host
{
to = [
{
podSelector.matchLabels = objects."swarm-stt/deployment".spec.selector.matchLabels // {
"app.kubernetes.io/name" = "swarm-nats";
};
}
];
ports = [ (tcp 4222) ];
}
]
&& !(lib.any (n: lib.hasSuffix "/networkpolicy" n) (
lib.attrNames (removeAttrs objects [ "swarm-stt/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
(lib.head c.ports).containerPort == 8080
&& c.readinessProbe.httpGet.path == "/readyz"
&& c.livenessProbe.httpGet.path == "/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";
}
{
# The unit is the container's whole unit, so the stand-alone evaluation
# cannot drift from what the host runs. The claude binary is the control
# that the unfree package is in the pod's unit: the stand-alone
# evaluation allows `claude-code` by its own predicate and nothing else.
name = "the review classifier's and the claude login minter's units, and so their manifests, are the same whether the container or the stand-alone evaluation supplies them";
ok =
let
classifier = c: c.services.hyperhive.deploy.review-classifier.unit;
login = c: c.services.hyperhive.deploy.claude-login.unit;
in
lib.hasSuffix "/bin/claude" (classifier onCluster).environment.SWARM_REVIEW_CLASSIFIER_CLAUDE
&& lib.hasInfix "claude-code" (classifier onCluster).environment.SWARM_REVIEW_CLASSIFIER_CLAUDE
&& lib.hasSuffix "/bin/opencode" (classifier onCluster).environment.SWARM_REVIEW_CLASSIFIER_OPENCODE
&& lib.hasInfix "claude-code" (login onCluster).environment.SWARM_CLAUDE_LOGIN_CLAUDE
&& (classifier onCluster).serviceConfig == (classifier withNode).serviceConfig
&& (classifier onCluster).environment == (classifier withNode).environment
&& (login onCluster).serviceConfig == (login withNode).serviceConfig
&& (login onCluster).environment == (login withNode).environment
&& notQueue (render onCluster) == notQueue (render withNode);
}
{
# The host-mode containers are pinned by value: both modules moved into
# let bindings, and nothing about the containers they define may change.
name = "with the review classifier and the claude login minter on the host, their containers, credential flags and units are as the modules define them";
ok =
let
check =
{
name,
id,
prune,
}:
let
c = withNode.containers.${name};
flags = c.extraFlags;
in
c.autoStart
&& !c.ephemeral
&& c.privateNetwork
&& c.hostBridge == withNode.services.hyperhive.network.bridgeName
&& lib.all (f: lib.hasPrefix "--load-credential=${id}-bao-" f) flags
&& lib.any (lib.hasPrefix "--load-credential=${id}-bao-cert:") flags
&& lib.any (lib.hasPrefix "--load-credential=${id}-bao-key:") flags
&& withNode.systemd.services ? "container@${name}"
&& prune.before == [ "container@${name}.service" ]
&& prune.requiredBy == [ "container@${name}.service" ]
&& lib.hasInfix "${name}.yaml" prune.script;
sc = name: units.${name}.serviceConfig;
in
check {
name = "swarm-review-classifier";
id = "review-classifier";
prune = classifierPrune;
}
&& check {
name = "swarm-claude-login";
id = "claude-login";
prune = loginPrune;
}
&& (sc "swarm-review-classifier").DynamicUser
&& (sc "swarm-review-classifier").PrivateTmp
&& (sc "swarm-claude-login").User == "swarm-claude-login"
&& (sc "swarm-claude-login").PrivateTmp
&& (sc "swarm-claude-login").UMask == "0077"
# The control: a host with them in the cluster has no such container.
&& !(onCluster.containers ? swarm-review-classifier)
&& !(onCluster.containers ? swarm-claude-login);
}
{
# 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"
]
&& (lib.head c.ports).containerPort == 8080
&& c.readinessProbe.httpGet.path == "/readyz"
&& c.livenessProbe.httpGet.path == "/healthz"
&& (envOf name)."${prefix}_HEALTH_ADDR" == "0.0.0.0: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
lib.hasInfix (lib.removeSuffix "\n" writes) login
&& !(lib.hasInfix "claude-credentials" classifier)
&& lib.hasInfix "anthropic-api-key" classifier
&& lib.hasInfix "token_policies=swarm-claude-login " jwt
&& lib.hasInfix "bound_subject=system:serviceaccount:hyperhive:swarm-claude-login" jwt
&& lib.hasInfix "bound_subject=system:serviceaccount:hyperhive:swarm-review-classifier" jwt
&& lib.hasInfix "token_policies=swarm-claude-login " login;
}
{
name = "the four daemons' and the poller's runtime \"k8s\" needs the node";
ok =
lib.any (a: lib.hasInfix "notify-router.runtime = \"k8s\" needs the" a.message) runtimeRefusals
&& lib.any (a: lib.hasInfix "stt.runtime = \"k8s\" needs the" a.message) runtimeRefusals
&& lib.any (
a: lib.hasInfix "review-classifier.runtime = \"k8s\" needs the" a.message
) runtimeRefusals
&& lib.any (a: lib.hasInfix "claude-login.runtime = \"k8s\" needs the" a.message) runtimeRefusals
&& lib.any (a: lib.hasInfix "ci-metrics.runtime = \"k8s\" needs the" a.message) runtimeRefusals
&& lib.any (
a: lib.hasInfix "swarm-controller.runtime = \"k8s\" needs the" a.message
) runtimeRefusals
&& lib.any (a: lib.hasInfix "nats.runtime = \"k8s\" needs the cluster" a.message) runtimeRefusals
&& lib.any (
a: lib.hasInfix "controller.tcp.enable: the host cannot reach" a.message
) runtimeRefusals
&& lib.any (
a: lib.hasInfix "tcp.listenAddress is" a.message && lib.hasInfix "\"10.0.0.5\"" a.message
) runtimeRefusals
&& lib.any (a: lib.hasInfix "gateway.dns.enable: the gateway dials" a.message) runtimeRefusals
# The all-local host binds the default, which the refusal lets through.
&& onCluster.services.hyperhive.deploy.swarm-controller.tcp.listenAddress == "0.0.0.0"
&& lib.all (a: a.assertion) onCluster.assertions;
}
{
# The host with the poller on it is the control for the stand-alone
# evaluation: the unit and timer read there are what the host runs.
name = "the poller's unit and timer, and so its CronJob, are the same whether the host or the stand-alone evaluation supplies them";
ok =
let
unitOf = c: c.services.hyperhive.deploy.ci-metrics.unit;
timerOf = c: c.services.hyperhive.deploy.ci-metrics.timer;
in
(unitOf withNode).serviceConfig.Type == "oneshot"
&& (unitOf withNode).environment ? SWARM_CI_METRICS_OTLP_ENDPOINT
&& (unitOf onCluster).serviceConfig == (unitOf withNode).serviceConfig
&& (unitOf onCluster).environment == (unitOf withNode).environment
&& (timerOf withNode).timerConfig.OnUnitInactiveSec == "5min"
&& (timerOf onCluster).timerConfig == (timerOf withNode).timerConfig
&& (render onCluster)."swarm-ci-metrics/cronjob" == (render withNode)."swarm-ci-metrics/cronjob";
}
{
# The host's own unit and timer are pinned by value, and both are held
# back by the prune unit. The host with the poller in the cluster is the
# control that the lookups find what is there.
name = "with the poller on the host, its service, timer and CA bundle are as the module defines them, and its prune unit runs before both";
ok =
let
sc = withNode.systemd.services.swarm-ci-metrics.serviceConfig;
timer = withNode.systemd.timers.swarm-ci-metrics;
in
sc.Type == "oneshot"
&& sc.DynamicUser
&& sc.StateDirectory == "swarm-ci-metrics"
&& sc.TimeoutStartSec == "30min"
&& lib.any (e: lib.hasPrefix "bao-client.pem:" e) sc.LoadCredential
&& timer.timerConfig.OnUnitInactiveSec == "5min"
&& lib.elem "timers.target" timer.wantedBy
&& withNode.systemd.services.swarm-ci-metrics.environment ? SSL_CERT_FILE
&& withNode.systemd.services ? swarm-ci-metrics-ca-bundle
&&
ciPrune.before == [
"swarm-ci-metrics.timer"
"swarm-ci-metrics.service"
]
&&
ciPrune.requiredBy == [
"swarm-ci-metrics.timer"
"swarm-ci-metrics.service"
]
&& lib.hasInfix "swarm-ci-metrics.yaml" ciPrune.script
&& lib.hasInfix "delete deployment,cronjob,serviceaccount" ciPrune.script
&& !(allLocal.systemd.services ? swarm-ci-metrics-k8s-prune);
}
{
# 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
&& !(lib.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.
name = "the controller in the cluster leaves the host no unit, listener leaf unit or prune unit, and a controller on the host keeps all three";
ok =
let
s = withNode.systemd;
c = onCluster.systemd;
in
s.services.swarm-controller.enable
&& s.services ? swarm-controller-tls
&& s.timers ? swarm-controller-tls
&& s.services.swarm-controller-k8s-prune.before == [ "swarm-controller.service" ]
&& s.services.swarm-controller-k8s-prune.requiredBy == [ "swarm-controller.service" ]
&& lib.hasInfix "swarm-controller.yaml" s.services.swarm-controller-k8s-prune.script
&& !c.services.swarm-controller.enable
&& !(c.services ? swarm-controller-tls)
&& !(c.timers ? swarm-controller-tls)
&& !(c.services ? swarm-controller-k8s-prune)
&& !(allLocal.systemd.services ? swarm-controller-k8s-prune)
&& notQueue (render onCluster) == notQueue (render withNode)
&&
lib.sort lib.lessThan (map (o: o.kind) onCluster.services.k3s.manifests.swarm-controller.content)
== [
"ConfigMap"
"Deployment"
"NetworkPolicy"
"Service"
"ServiceAccount"
];
}
{
# The host with no listener is the control: the controller has no Service
# or policy there, and the policy admits nothing but the node.
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;
prune = withNode.systemd.services.swarm-controller-k8s-prune.script;
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)
&& !(objects ? "swarm-controller/service")
&& !(objects ? "swarm-controller/networkpolicy")
&& 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" (allLocal.services.dnsmasq.settings.server or [ ]))
&& lib.hasInfix "networkpolicy,service \\" prune;
}
{
# The host with the controller on it dials the name, as it always did.
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:
lib.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/"
]
# The host with the controller on it names no variable and no resolver.
&& !(dials withNode "/api/" "resolver")
&& !(dials withNode "/api/" "swarm_controller_upstream")
&& (loc withNode "/webhook/forge/").proxyPass == "https://controller.t.local:9443"
&& (loc withNode "/api/").proxyPass == "https://controller.t.local:9443"
&& verified onCluster "/webhook/forge/"
&& verified onCluster "/api/"
&& verified withNode "/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
c.readinessProbe.httpGet.path == "/readyz"
&& c.livenessProbe.httpGet.path == "/healthz"
&& (byName "health" c.ports).containerPort == 8080
&& 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)
&& !((podSpec "swarm-controller") ? initContainers);
}
{
# 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, with the host unit's script";
ok =
let
shared = import ../host-modules/lib/swarm-controller-tls-issue.nix {
inherit lib;
config = withNode;
};
hostScript = withNode.systemd.services.swarm-controller-tls.script;
podScript = shared.script {
login = "L";
credential = "c";
group = null;
createDir = false;
};
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
hostScript == shared.script {
login = "bao login -method=cert -token-only";
credential = "certificate";
group = "swarm-controller";
}
&& lib.hasInfix "chgrp swarm-controller" hostScript
&& lib.hasInfix "install -d -m 0750" hostScript
&& !(lib.hasInfix "install -d" podScript)
&& !(lib.hasInfix "chgrp" podScript)
&& lib.hasInfix "-checkhost \"$name\"" podScript
&& lib.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
# runtime 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 == "runtime") null spec.volumes) == {
name = "runtime";
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"
]
# The client port is published on every address of the node, and the
# exporter's on the bridge's.
&&
(named "nats").ports == [
{
name = "client";
containerPort = 4222;
hostPort = 4222;
hostIP = "0.0.0.0";
}
]
&&
(named "exporter").ports == [
{
name = "metrics";
containerPort = 7777;
hostPort = 7777;
hostIP = "10.42.0.1";
}
]
&& 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 == "0.0.0.0:8080"
&& (named "swarm-nats").readinessProbe.httpGet.path == "/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: lib.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, on this node, and only that: its class is its own.
# The poller's claim is the control that a claim does not.
&& pvc.spec.volumeName == pv.metadata.name
&& pvc.spec.storageClassName == pv.spec.storageClassName
&& pv.spec.storageClassName != ""
&& !(objects."swarm-ci-metrics/persistentvolumeclaim".spec ? volumeName)
&& pv.spec.local.path == hostStore
&& pv.spec.persistentVolumeReclaimPolicy == "Retain"
&& !(pv.metadata ? namespace)
&&
pv.spec.nodeAffinity.required.nodeSelectorTerms == [
{
matchExpressions = [
{
key = "kubernetes.io/hostname";
operator = "In";
values = [ (lib.toLower allLocal.networking.hostName) ];
}
];
}
]
# A pod on a host that never ran the container gets the directory made;
# a host with the container needs no rule.
&& lib.any (lib.hasPrefix "d ${hostStore} ") onCluster.systemd.tmpfiles.rules
&& !(lib.any (lib.hasPrefix "d ${hostStore} ") withNode.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-state"
&& objects ? "swarm-ci-metrics/persistentvolumeclaim"
&& !(lib.any (n: lib.hasInfix "state-gate" n) (map toString withNode.system.build.k8sImages))
&& objects ? "swarm-nats/persistentvolumeclaim";
}
{
# The responder's unit is the container's on the host and the
# stand-alone evaluation's in the cluster; its arguments and its
# environment are one text.
name = "the responder's unit is the same whether the container or the stand-alone evaluation supplies it";
ok =
let
u = c: c.services.hyperhive.deploy.nats.unit;
in
(u withNode).serviceConfig.ExecStart != null
&& lib.hasInfix "--nats-url tls://nats.t.local:4222" (u withNode).serviceConfig.ExecStart
&& (u onCluster).serviceConfig.ExecStart == (u withNode).serviceConfig.ExecStart
&& (u onCluster).environment == (u withNode).environment
&& (u onCluster).serviceConfig.LoadCredential == (u withNode).serviceConfig.LoadCredential;
}
{
# The host with the queue on it is the control for each absence: it has
# the container, both delivery units and no rule in the raw table.
name = "the queue in the cluster leaves the host no container and no delivery unit, keeps the leaf for the gateway's vhost, and points the vhost at the exporter's published port";
ok =
let
vhost = c: c.services.nginx.virtualHosts."nats.t.local".locations."= /metrics".proxyPass;
tls = onCluster.systemd.services.swarm-bao-nats-tls;
in
withNode.containers ? swarm-nats
&& withNode.systemd.services ? "container@swarm-nats"
&& withNode.systemd.services.swarm-nats-auth-secrets.enable
&& withNode.systemd.services.swarm-bao-nats-callout-xkey.enable
&& withNode.systemd.services.swarm-nats-k8s-prune.before == [ "container@swarm-nats.service" ]
&& withNode.systemd.services.swarm-nats-k8s-prune.requiredBy == [ "container@swarm-nats.service" ]
&& lib.hasInfix "swarm-nats.yaml" withNode.systemd.services.swarm-nats-k8s-prune.script
&& lib.elem "container@swarm-nats.service" withNode.systemd.services.swarm-bao-nats-tls.before
&& !(lib.hasInfix "nixos-fw-nats" withNode.networking.firewall.extraCommands)
&& vhost withNode == "http://127.0.0.1:7777/metrics"
# In the cluster: nothing to start the server or deliver to it, a leaf
# that restarts nothing, the exporter on the bridge, the bridge up.
&& !(onCluster.containers ? swarm-nats)
&& !(onCluster.systemd.services ? "container@swarm-nats")
&& !onCluster.systemd.services.swarm-nats-auth-secrets.enable
&& !onCluster.systemd.services.swarm-bao-nats-callout-xkey.enable
&& !(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://10.42.0.1:7777/metrics"
&& onCluster.services.hyperhive.network.enable;
}
{
# 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 the exporter's port to all but the host's loopback";
ok =
let
rules = import ../host-modules/lib/swarm-nats-raw-rules.nix { inherit lib; };
args = {
chain = "c";
clientPort = 4222;
metricsPort = 7777;
trusted = [
"lo"
"br0"
"cni0"
];
};
closed = rules (args // { openClient = false; });
open = rules (args // { openClient = true; });
has = lib.hasInfix;
in
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 still has.
&& !(has "--dport 4222" open)
&& has "-p tcp --dport 7777 -i lo -j RETURN" open
&& has "-p tcp --dport 7777 -m addrtype --dst-type LOCAL -j DROP" open
# The exporter's port is not returned for the bridge or the pods.
&& !(has "--dport 7777 -i br0" closed)
&& !(has "--dport 7777 -i cni0" closed)
&& 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;
}
{
# The file names the runtime and the host units of every service and no
# state: nothing is copied. The units of the poller (timer and service)
# are the control for a list of more than one.
name = "migrate.json names every service with its option, host units and the runtime the configuration wants, and no state";
ok =
let
host = (migrateOf withNode).services;
cluster = (migrateOf onCluster).services;
in
(migrateOf withNode).namespace == "hyperhive"
&&
lib.sort lib.lessThan (lib.attrNames host) == [
"swarm-ci-metrics"
"swarm-claude-login"
"swarm-controller"
"swarm-nats"
"swarm-notify-router"
"swarm-review-classifier"
"swarm-stt"
]
&& lib.all (s: !(s ? state)) (lib.attrValues host)
&& lib.all (n: lib.hasPrefix "services.hyperhive.deploy." host.${n}.option) (lib.attrNames host)
&&
host.swarm-ci-metrics.hostUnits == [
"swarm-ci-metrics.timer"
"swarm-ci-metrics.service"
]
&& host.swarm-nats.hostUnits == [ "container@swarm-nats.service" ]
&& host.swarm-ci-metrics.option == "services.hyperhive.deploy.ci-metrics.runtime"
&& lib.all (s: s.runtime == "host") (lib.attrValues host)
# The runtime follows the option: the cluster fixture has every one on k8s.
&& lib.all (s: s.runtime == "k8s") (lib.attrValues cluster);
}
{
name = "swarmctl is wrapped with kubectl and the cluster's kubeconfig, by one wrapper per host";
ok =
let
env = c: c.services.hyperhive.deploy.swarm-controller.swarmctlEnvironment;
wrappers =
c:
map lib.getName (
lib.filter (p: lib.hasPrefix "swarmctl-" (lib.getName p)) c.environment.systemPackages
);
in
(env withNode).SWARMCTL_KUBECTL == "${pkgs.kubectl}/bin/kubectl"
&& (env withNode).SWARMCTL_KUBECONFIG == "/etc/rancher/k3s/k3s.yaml"
# The controller's own wrapper carries them where the controller is
# enabled; elsewhere the k8s module installs one.
&& wrappers withNode == [ "swarmctl-configured" ]
&& wrappers nodeNoBridge == [ "swarmctl-kube" ]
# Without the node there is no cluster to name, though the manifests render.
&& allLocal.services.hyperhive.k8s.enable
&& !(env allLocal ? SWARMCTL_KUBECTL)
&& !(allLocal.environment.etc ? "hyperhive/migrate.json")
&& wrappers allLocal == [ "swarmctl-configured" ];
}
];
in
runGroup "k8s" cases