Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/nix/vm-tests/k8s-services.nix
atlas 3213bfba7a k8s-services: seed with the stream content type, give the grafana responder its own port name, and print gateway diagnostics on a refusal
the grafana responder's service targeted the port name api, which resolves to the logs responder's container; its port is now grafana-api.

the node-ready wait is raised from 300 to 600 seconds: slow k3s image imports on this test's machine kept the node from registering in vm-nightly 8992 and 8997, so the test never reached the subtests this change fixes.
2026-11-27 18:07:59 +01:00

1244 lines
65 KiB
Nix

# `vmTests.<system>.k8s-services`: the notification router, the speech-to-text
# service, the CI run poller, the review classifier and the claude login minter
# run as pods in the host's cluster, against the real secret store and a real
# queue. The script asserts that:
#
# - each runs once, as a pod or CronJob: the host has no container, unit, timer or
# prune unit for it;
# - each pod is Ready, so it logged in to the store with its ServiceAccount
# token, read its client secret and minted a token with it. The router
# routes an event and a deleted pod exits 0 within its grace period; the
# speech-to-text pod carries its limits and keeps its cache in an emptyDir,
# with no claim and no state gate, in a user namespace, and its NetworkPolicy
# lets a queue request in and only DNS and four host ports out;
# - the log store runs as a pod on the directory its old container kept, which
# a unit of this test filled before the cluster started, as another user: the
# pod reads that record and writes a new one, the gateway's own locations
# (rendered by the module, run in a nginx of their own) reach the store and the
# responders by their Services' names, a bearer is granted or refused by the
# responders with the store's answers, and no other pod reaches the store;
# - the poller's Job completes against a forge that lists one run, pushes it to
# its own route of the swarm collector, holds no Secret, and keeps its cursor
# in a volume, so a second Job pushes nothing, and starts with no state
# gate;
# - the minter's jwt token writes an agent's credentials and the classifier's
# cannot; the daemons' pods have a read-only root, and `claude` writes its
# config under `HOME` in the /tmp volume only, as the real login step does.
#
# The queue is a plain nats-server with TLS, and one stub is the token endpoint,
# the forge and the swarm collector, which records what it is given. The
# speech-to-text model is a placeholder; the hive's CA and leaves come at boot.
{ pkgs, self }:
let
inherit (pkgs) lib;
bridgeIp = "10.42.0.1";
baoName = "bao.t.local";
baoPort = 8200;
podPort = 8208;
natsName = "nats.t.local";
natsPort = 4222;
authName = "auth.t.local";
forgeName = "forge.t.local";
otelName = "otel.t.local";
namespace = "hyperhive";
service = "swarm-notify-router";
clientId = "swarm-notify-router";
stt = "swarm-stt";
sttClientId = "swarm-stt";
ci = "swarm-ci-metrics";
# A fixed value: it is the stub's to check, not a secret.
forgeToken = "test-forge-token";
classifier = "swarm-review-classifier";
login = "swarm-claude-login";
agent = "atlas";
pkiDir = "/var/lib/test-ca";
tlsDir = "/var/lib/hive-tls";
leaf = "swarm/services/${clientId}/oidc/client";
sttLeaf = "swarm/services/${sttClientId}/oidc/client";
ciLeaf = "swarm/services/${ci}/oidc/client";
ciForgeLeaf = "swarm/services/ci-metrics/forge/token";
classifierLeaf = "swarm/services/${classifier}/oidc/client";
loginLeaf = "swarm/services/${login}/oidc/client";
prune = "${service}-k8s-prune";
sttPrune = "${stt}-k8s-prune";
ciPrune = "${ci}-k8s-prune";
classifierPrune = "${classifier}-k8s-prune";
loginPrune = "${login}-k8s-prune";
hostUnit = "container@${service}.service";
sttHostUnit = "container@${stt}.service";
classifierHostUnit = "container@${classifier}.service";
loginHostUnit = "container@${login}.service";
# The model file the service is given: its path is in the pod's image, and
# nothing reads it.
sttModel = pkgs.writeText "ggml-placeholder.bin" "not a model";
tokenLog = "/var/log/stub-token.log";
# The log store, as the module names it.
vlDir = "/var/lib/nixos-containers/swarm-victorialogs/var/lib/victorialogs";
vlGateway = "127.0.0.1:18081";
legacyUser = "legacy-victorialogs";
legacyPort = 19428;
# One nginx with the log store's locations as the module renders them: the
# Services they dial, the responders they check a bearer with and the
# variables between. The identity provider's two checks are stand-ins that
# answer 200, because the VM has no login service; nothing else of the vhost.
gatewayConf =
cfg:
let
locations = cfg.services.nginx.virtualHosts."logs.t.local".locations;
served = [
"= /insert/opentelemetry/v1/logs"
"^~ /select/logsql/"
"= /metrics"
"= /__swarm_logs_auth"
"= /__swarm_logs_agent_auth"
"= /__swarm_logs_grafana_auth"
];
block =
name:
let
l = locations.${name};
in
''
location ${name} {
${lib.optionalString (l.proxyPass != null) "proxy_pass ${l.proxyPass};"}
${l.extraConfig}
}
'';
in
pkgs.writeText "logs-gateway.conf" ''
pid /run/logs-gateway-test/nginx.pid;
error_log stderr;
events {}
http {
access_log off;
${cfg.services.nginx.appendHttpConfig}
server {
listen ${vlGateway};
location = /__swarm_logs_ingest_authz { internal; return 200; }
location = /__hive_authelia { internal; return 200; }
${lib.concatMapStrings block served}
}
}
'';
requestLog = "/var/log/stub-requests.log";
# The identity provider, the forge and the swarm collector, by name, on one
# listener. The token endpoint answers every client-credentials request with
# a token and records the client id and secret of the Basic credentials.
# The forge lists one repo with one finished run. The collector's poller
# route answers 200 and, with the forge, records the request: the route, the
# name asked for, whether the credential is the one this stub issued or
# expects, and the points the body carried.
tokenStub = pkgs.writeText "token-stub.py" ''
import base64
import http.server
import json
import secrets
import ssl
MINTED = set()
RUN = {
"index_in_repo": 1,
"status": "success",
"event": "pull_request",
"prettyref": "#7",
"workflow_id": "ci.yml",
"commit_sha": "d0ab2edd05bcce7a35ea15bbc2ef5a366fc93d18",
"created": "2026-10-16T16:50:38+02:00",
"started": "2026-10-16T16:55:17+02:00",
"stopped": "2026-10-16T17:13:30+02:00",
}
def record(entry):
with open("${requestLog}", "a") as log:
log.write(json.dumps(entry) + "\n")
class Handler(http.server.BaseHTTPRequestHandler):
def reply(self, payload):
body = json.dumps(payload).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("Content-Length", 0)))
auth = self.headers.get("Authorization", "")
path = self.path.split("?")[0]
if path.endswith("/v1/metrics"):
metrics = json.loads(raw)["resourceMetrics"][0]["scopeMetrics"][0]["metrics"]
record({
"host": self.headers.get("Host"),
"path": path,
"bearer_minted": auth.removeprefix("Bearer ") in MINTED,
"points": {m["name"]: len(m["gauge"]["dataPoints"]) for m in metrics},
})
self.reply({})
return
who = base64.b64decode(auth.removeprefix("Basic ")).decode() if auth.startswith("Basic ") else "none"
with open("${tokenLog}", "a") as log:
log.write(f"{self.path} {who}\n")
token = secrets.token_hex(16)
MINTED.add(token)
self.reply({"access_token": token, "token_type": "Bearer", "expires_in": 3600})
def do_GET(self):
path = self.path.split("?")[0]
record({
"host": self.headers.get("Host"),
"path": path,
"forge_token_ok": self.headers.get("Authorization") == "token ${forgeToken}",
})
if path.endswith("/repos/search"):
self.reply({"ok": True, "data": [{"full_name": "o/r", "has_actions": True, "archived": False, "mirror": False}]})
elif path.endswith("/repos/o/r/actions/runs"):
self.reply({"workflow_runs": [RUN], "total_count": 1})
else:
self.send_error(404)
server = http.server.ThreadingHTTPServer(("${bridgeIp}", 443), Handler)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain("${pkiDir}/svc.pem", "${pkiDir}/svc-key.pem")
server.socket = context.wrap_socket(server.socket, server_side=True)
server.serve_forever()
'';
natsConf = pkgs.writeText "nats.conf" ''
listen: "${bridgeIp}:${toString natsPort}"
jetstream { store_dir: "/var/lib/nats-test" }
tls {
cert_file: "${pkiDir}/svc.pem"
key_file: "${pkiDir}/svc-key.pem"
}
'';
in
pkgs.testers.runNixOSTest {
name = "k8s-services";
# The store takes a few minutes to open its raft storage, and the script
# switches the configuration three times. Under the 1 h job bound with room
# for the build before the test starts.
globalTimeout = 3000;
nodes.machine =
{ config, ... }:
{
imports = [ self.nixosModules.default ];
services.hyperhive = {
deploy.k8s.enable = true;
network.enable = true;
network.bridgeIp = bridgeIp;
deploy.bao.enable = true;
deploy.bao.seal = "shamir";
deploy.bao.bootstrapTokenFile = "/var/lib/swarm-bao-bootstrap/grant.token";
deploy.notify-router.enable = true;
deploy.stt.enable = true;
deploy.review-classifier.enable = true;
deploy.claude-login.enable = true;
deploy.stt.settings.modelFile = sttModel;
deploy.ci-metrics.enable = true;
deploy.victorialogs.enable = true;
deploy.hive-controller.hiveName = "h1";
swarm.domain = "t.local";
swarm.forge.domain = forgeName;
swarm.otel.domain = otelName;
swarm.bao.domain = baoName;
swarm.bao.port = baoPort;
swarm.hives.h1.domain = "h1.t.local";
# The queue, the identity provider, the forge and the swarm collector
# are host-run: their names go to the bridge for the cluster's pods, as
# the hive's own do.
gateway.localNames = [
natsName
authName
forgeName
otelName
];
};
system.stateVersion = "25.11";
# The store's TLS passthrough is a stream server of the host's nginx,
# which needs certificates this host does not mint, so a second nginx
# carries the passthrough alone, as `k8s-bao-login` does.
services.nginx.enable = lib.mkForce false;
networking.hosts."${bridgeIp}" = [
baoName
natsName
authName
forgeName
otelName
];
systemd.services.bao-stream = {
wantedBy = [ "multi-user.target" ];
after = [ "network.target" ];
serviceConfig = {
RuntimeDirectory = "bao-stream";
Restart = "always";
RestartSec = 2;
ExecStart =
let
conf = pkgs.writeText "bao-stream.conf" ''
pid /run/bao-stream/nginx.pid;
error_log stderr;
events {}
stream {
${config.services.nginx.streamConfig}
}
'';
in
"${pkgs.nginx}/bin/nginx -c ${conf} -g 'daemon off;'";
};
};
# The hive's CA, and one leaf for the names of the queue, the identity
# provider, the forge and the collector, which this test makes. The trust
# bundle is the unit `hive-tls-ca`'s, and the store's services-root unit
# reloads that unit when it has fetched the store's root, so the test's
# own script is the one the unit runs on every reload.
systemd.services.hive-tls-ca = {
path = [
pkgs.openssl
pkgs.coreutils
];
script = lib.mkForce ''
set -euo pipefail
install -d -m 0755 ${pkiDir} ${tlsDir}
cd ${pkiDir}
if [ ! -s ca.pem ]; then
openssl req -x509 -newkey rsa:2048 -nodes -keyout ca-key.pem -out ca.pem \
-subj "/CN=test-ca" -days 3650 \
-addext basicConstraints=critical,CA:TRUE -addext keyUsage=critical,keyCertSign
openssl req -newkey rsa:2048 -nodes -keyout svc-key.pem -out svc.csr -subj "/CN=${natsName}"
printf 'subjectAltName=DNS:${natsName},DNS:${authName},DNS:${forgeName},DNS:${otelName}\n' > svc.ext
openssl x509 -req -in svc.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial \
-days 3650 -extfile svc.ext -out svc.pem
chmod 0644 ca.pem svc.pem svc-key.pem
fi
cat ca.pem > ${tlsDir}/trust-bundle.pem
chmod 0644 ${tlsDir}/trust-bundle.pem
'';
};
systemd.services.nats-test = {
wantedBy = [ "multi-user.target" ];
after = [ "hive-tls-ca.service" ];
requires = [ "hive-tls-ca.service" ];
serviceConfig = {
ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${natsConf}";
StateDirectory = "nats-test";
Restart = "always";
RestartSec = 2;
};
};
systemd.services.token-stub = {
wantedBy = [ "multi-user.target" ];
after = [ "hive-tls-ca.service" ];
requires = [ "hive-tls-ca.service" ];
serviceConfig = {
ExecStart = "${pkgs.python3}/bin/python3 ${tokenStub}";
Restart = "always";
RestartSec = 2;
};
};
# What the log store's container left on the host before the cluster ran
# the store: its data directory, written by the pinned binary as a user
# of its own with group-writable files, holding one record. A switch from
# the container can't be run here (the container is gone from the
# module), so the directory is what the switch leaves behind.
users.users.${legacyUser} = {
isSystemUser = true;
group = legacyUser;
};
users.groups.${legacyUser} = { };
systemd.services.victorialogs-legacy = {
wantedBy = [ "multi-user.target" ];
before = [ "k3s.service" ];
path = [
pkgs.curl
pkgs.coreutils
pkgs.findutils
];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
User = legacyUser;
# k3s waits for this unit, so a record that never shows must fail it
# and not hold the boot.
TimeoutStartSec = 120;
UMask = "0007";
ExecStartPre = "+${pkgs.writeShellScript "victorialogs-legacy-dir" ''
mkdir -p ${vlDir}
chown ${legacyUser}:${legacyUser} ${vlDir}
chmod 0700 ${vlDir}
''}";
};
script = ''
${config.services.hyperhive.deploy.victorialogs.package}/bin/victoria-logs \
-storageDataPath=${vlDir} -httpListenAddr=127.0.0.1:${toString legacyPort} &
pid=$!
until curl -sf http://127.0.0.1:${toString legacyPort}/health; do sleep 1; done
# One JSON line. Without the stream content type curl sends a form body, which the store reads as form fields and ingests zero rows with a 200.
line=$(printf '{"_msg":"written before the switch","app":"legacy","_time":"%s"}' "$(date -u +%Y-%m-%dT%H:%M:%SZ)")
code=$(printf '%s\n' "$line" | curl -s -o /dev/null -w '%{http_code}' -H 'Content-Type: application/stream+json' --data-binary @- \
'http://127.0.0.1:${toString legacyPort}/insert/jsonline?_stream_fields=app')
# A bare word matches the message field, so the query names a word of it.
found=
for _ in $(seq 60); do
if curl -s --data-urlencode 'query=switch' http://127.0.0.1:${toString legacyPort}/select/logsql/query | grep -q 'written before the switch'; then
found=1
break
fi
sleep 1
done
if [ -z "$found" ]; then
echo "the seeded record is not found; posted $line, insert replied $code; the store's ingest counters:"
curl -s http://127.0.0.1:${toString legacyPort}/metrics | grep -E '^vl_(rows_ingested|rows_dropped|http_errors)'
echo "the store holds:"
curl -s --data-urlencode 'query=*' http://127.0.0.1:${toString legacyPort}/select/logsql/query
exit 1
fi
kill -TERM "$pid"
wait "$pid" || true
test -n "$(find ${vlDir} -type f | head -1)"
'';
};
# The log store's locations, from the active configuration's own text.
systemd.services.logs-gateway = {
wantedBy = [ "multi-user.target" ];
after = [ "network.target" ];
serviceConfig = {
RuntimeDirectory = "logs-gateway-test";
ExecStart = "${pkgs.nginx}/bin/nginx -c ${gatewayConf config} -g 'daemon off;'";
Restart = "on-failure";
RestartSec = 2;
};
};
environment.systemPackages = [
pkgs.kubectl
pkgs.curl
pkgs.jq
pkgs.openssl
pkgs.natscli
pkgs.dig
];
environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml";
# The store paths each daemon's `claude` pulls in, so the script can find
# the bash and coreutils its image holds: the images have no shell of
# their own.
environment.etc."k3s-node/closure-${classifier}".source = "${
pkgs.closureInfo {
rootPaths = [
(builtins.dirOf (
builtins.dirOf config.services.hyperhive.deploy.review-classifier.unit.environment.SWARM_REVIEW_CLASSIFIER_CLAUDE
))
];
}
}/store-paths";
environment.etc."k3s-node/closure-${login}".source = "${
pkgs.closureInfo {
rootPaths = [
(builtins.dirOf (
builtins.dirOf config.services.hyperhive.deploy.claude-login.unit.environment.SWARM_CLAUDE_LOGIN_CLAUDE
))
];
}
}/store-paths";
environment.etc."k3s-node/images".text = lib.concatMapStrings (
i: "${i.imageName}:${i.imageTag}\n"
) config.system.build.k8sImages;
# The store's raft data is on a tmpfs, for the reason `full-setup` gives.
fileSystems."/var/lib/nixos-containers/${config.services.hyperhive.swarm.bao.machine}/var/lib/private" =
{
device = "tmpfs";
fsType = "tmpfs";
options = [
"mode=0700"
"size=1G"
];
};
# The speech-to-text image carries ffmpeg and whisper, the two claude
# images claude-code. The speech-to-text pod's limits (3 GiB, four
# cores) are as large as the node's cores, so it is schedulable only
# because it requests none of them.
virtualisation = {
memorySize = 8192;
cores = 4;
diskSize = 20480;
};
};
testScript = builtins.readFile ./lib/k3s.py + ''
import re
INIT = "/root/bao-init.json"
NS = "${namespace}"
SERVICE = "${service}"
HOST_UNIT = "${hostUnit}"
PRUNE = "${prune}"
STT = "${stt}"
STT_HOST_UNIT = "${sttHostUnit}"
STT_PRUNE = "${sttPrune}"
CI = "${ci}"
CI_PRUNE = "${ciPrune}"
CI_HOST_UNITS = ["${ci}.timer", "${ci}.service"]
OWN_ROUTE = "/${ci}/v1/metrics"
RUN_METRIC = "hyperhive.ci.run.duration"
CERT_METRIC = "bao.client_cert.not_after"
CLASSIFIER = "${classifier}"
LOGIN = "${login}"
CLASSIFIER_HOST_UNIT = "${classifierHostUnit}"
LOGIN_HOST_UNIT = "${loginHostUnit}"
CLASSIFIER_PRUNE = "${classifierPrune}"
LOGIN_PRUNE = "${loginPrune}"
CLAUDE_DAEMONS = {
CLASSIFIER: (CLASSIFIER_HOST_UNIT, CLASSIFIER_PRUNE),
LOGIN: (LOGIN_HOST_UNIT, LOGIN_PRUNE),
}
DAEMON_PODS: dict[str, str] = {}
# The variable of each unit that names its `claude` binary.
CLAUDE_VARS = {
CLASSIFIER: "SWARM_REVIEW_CLASSIFIER_CLAUDE",
LOGIN: "SWARM_CLAUDE_LOGIN_CLAUDE",
}
MANIFESTS = "/var/lib/rancher/k3s/server/manifests"
NATS = "--server tls://${natsName}:${toString natsPort} --tlsca ${pkiDir}/ca.pem"
AGENT = "${agent}"
OTHER_AGENT = "argus"
AGENT_SECRETS: dict[str, str] = {}
VL = "swarm-victorialogs"
LOGS_AUTH = "swarm-logs-auth"
VL_DIR = "${vlDir}"
GATEWAY = "http://${vlGateway}"
SELECTOR = f"--selector app.kubernetes.io/name={SERVICE}"
def as_root(command: str) -> str:
return machine.succeed(f'BAO_TOKEN="$(jq -r .root_token {INIT})" {command}')
def diagnose(units: list[str]) -> None:
for unit in units:
print(f"--- {unit}")
print(machine.execute(f"systemctl status {unit} --no-pager -l; journalctl -u {unit} --no-pager -n 60")[1])
def settle(command: str, timeout: int, units: list[str]) -> None:
try:
machine.wait_until_succeeds(command, timeout=timeout)
except Exception:
diagnose(units)
raise
def service_pods(service: str) -> list[str]:
out = machine.succeed(f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={service} -o name || true")
return out.split()
def router_pods() -> list[str]:
return service_pods(SERVICE)
def host_state(unit: str = HOST_UNIT) -> str:
return machine.execute(f"systemctl is-active {unit}")[1].strip()
def requests() -> list[dict]:
return [json.loads(line) for line in machine.succeed("cat ${requestLog}").splitlines() if line]
def pushes(metric: str) -> list[dict]:
"""The collector requests that carried points of `metric`."""
return [r for r in requests() if r.get("points", {}).get(metric)]
def ci_job(name: str) -> str:
"""Runs one Job from the poller's CronJob, waits for it to complete, and
answers its pod's log."""
kube(machine, f"create job {name} --from=cronjob/{CI}")
try:
kube(machine, f"wait --for=condition=complete job/{name} --timeout=300s", timeout=330)
except Exception:
print(machine.execute(f"kubectl -n {NS} describe job {name}")[1])
print(machine.execute(f"kubectl -n {NS} logs job/{name} --tail=80")[1])
raise
return kube(machine, f"logs job/{name}")
def consumer() -> dict:
return json.loads(machine.succeed(f"nats {NATS} consumer info SWARM_EVENTS notify-router --json"))
def wait_pod_ready(service: str = SERVICE, timeout: int = 600) -> str:
machine.wait_until_succeeds(
f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={service} -o name | grep -q pod/",
timeout=timeout,
)
name = service_pods(service)[0].removeprefix("pod/")
try:
wait_pod(machine, name, phase="Running", ready=True, timeout=timeout)
except Exception:
diagnose(["hyperhive-k8s-ca-trust.service"])
print(machine.execute(f"kubectl -n {NS} describe pod {name}")[1])
print(machine.execute(f"kubectl -n {NS} logs {name} --tail=60")[1])
raise
return name
with subtest("the node is Ready and holds every image"):
wait_node_ready(machine, timeout=600)
wait_images(machine, timeout=300)
kube(machine, f"config set-context --current --namespace={NS}")
with subtest("the store is initialised, unsealed and bootstrapped"):
machine.wait_until_succeeds('[ "$(bao status >/dev/null 2>&1; echo $?)" = 2 ]', timeout=900)
machine.succeed(f"umask 077 && bao operator init -key-shares=1 -key-threshold=1 -format=json > {INIT}")
unseal_bao(machine, INIT)
machine.succeed(
"set -o pipefail; "
f'export BAO_TOKEN="$(jq -r .root_token {INIT})"; '
"bao policy write bao-bootstrap /etc/hyperhive/bao-bootstrap-policy.hcl; "
"bao token create -policy=bao-bootstrap -ttl=24h -orphan -display-name=bao-bootstrap -field=token "
"| install -D -m 0600 /dev/stdin /var/lib/swarm-bao-bootstrap/grant.token; "
"unset BAO_TOKEN; "
"systemctl restart swarm-bao-granter-role"
)
machine.wait_until_succeeds(
"journalctl -u swarm-bao-granter-role --no-pager | grep -F 'Uploaded policy: bao-granter'",
timeout=300,
)
with subtest("the granting units have written the policies and roles of the five services, and the jwt mount"):
machine.succeed("systemctl reset-failed 'swarm-bao-*-policy.service' swarm-bao-agent-pki.service || true")
machine.succeed("systemctl restart --no-block 'swarm-bao-*-policy.service' swarm-bao-agent-pki.service")
settle('[ "$(systemctl is-active swarm-bao-agent-pki.service)" = active ]', 900, ["swarm-bao-agent-pki.service"])
# Under the shamir seal the PKI unit leaves a restart of the store to the
# operator when its listener's client CA changed.
if machine.execute("journalctl -u swarm-bao-agent-pki --no-pager | grep -F 'restart openbao.service'")[0] == 0:
machine.succeed("systemctl --machine=swarm-bao restart openbao.service")
machine.wait_until_succeeds('[ "$(bao status >/dev/null 2>&1; echo $?)" = 2 ]', timeout=900)
unseal_bao(machine, INIT)
for unit in [
"swarm-bao-notify-router-policy",
"swarm-bao-stt-policy",
"swarm-bao-ci-metrics-policy",
"swarm-bao-review-classifier-policy",
"swarm-bao-claude-login-policy",
"swarm-bao-logs-auth-policy",
"swarm-bao-k8s-jwt-policy",
]:
settle(f'[ "$(systemctl is-active {unit}.service)" = active ]', 900, [f"{unit}.service"])
machine.wait_until_succeeds(
"journalctl -u swarm-bao-k8s-jwt-policy --no-pager | grep -F 'Success! Data written to: auth/jwt-k8s/config'",
timeout=300,
)
# The services' queue client secrets, which the identity provider's mint
# stores in production.
SECRET = machine.succeed("openssl rand -hex 16").strip()
as_root(f"bao kv put -mount=secret ${leaf} value={SECRET}")
STT_SECRET = machine.succeed("openssl rand -hex 16").strip()
as_root(f"bao kv put -mount=secret ${sttLeaf} value={STT_SECRET}")
# The poller reads its own client secret and the forge token the
# controller mints in production.
CI_SECRET = machine.succeed("openssl rand -hex 16").strip()
as_root(f"bao kv put -mount=secret ${ciLeaf} value={CI_SECRET}")
as_root("bao kv put -mount=secret ${ciForgeLeaf} value=${forgeToken} name=ci-metrics")
CLASSIFIER_SECRET = machine.succeed("openssl rand -hex 16").strip()
as_root(f"bao kv put -mount=secret ${classifierLeaf} value={CLASSIFIER_SECRET}")
LOGIN_SECRET = machine.succeed("openssl rand -hex 16").strip()
as_root(f"bao kv put -mount=secret ${loginLeaf} value={LOGIN_SECRET}")
# What the log store's responders read: an agent's queue secret and its
# mirrored grant, one agent that holds no grant, and the bearer
# Grafana's host creates. The grant is a JSON object, so it is a file.
for name, grant in ((AGENT, '{"logs": true}'), (OTHER_AGENT, '{"logs": false}')):
AGENT_SECRETS[name] = machine.succeed("openssl rand -hex 16").strip()
as_root(f"bao kv put -mount=secret swarm/agents/{name}/queue value={AGENT_SECRETS[name]} agent={name}")
machine.succeed(f"echo '{grant}' > /tmp/grant-{name}.json")
as_root(f"bao kv put -mount=secret swarm/agents/{name}/observability @/tmp/grant-{name}.json")
GRAFANA_BEARER = machine.succeed("openssl rand -hex 32").strip()
as_root(f"bao kv put -mount=secret swarm/services/swarm-grafana/metrics/bearer value={GRAFANA_BEARER}")
with subtest("the queue and the token stub run, and the queue holds the roster the router reads"):
machine.wait_for_unit("hive-tls-ca.service")
machine.wait_for_unit("nats-test.service")
machine.wait_for_unit("token-stub.service")
machine.wait_until_succeeds(f"nats {NATS} account info", timeout=120)
machine.succeed(f"nats {NATS} kv add agent-status")
machine.succeed(f"nats {NATS} kv put agent-status h1.{AGENT} '{{}}'")
with subtest("the five services run only as pods: the host has no container, unit, timer or prune unit for them"):
for unit in [HOST_UNIT, STT_HOST_UNIT, CLASSIFIER_HOST_UNIT, LOGIN_HOST_UNIT]:
assert host_state(unit) == "inactive", (unit, host_state(unit))
for name in [SERVICE, STT, CLASSIFIER, LOGIN]:
machine.fail(f"test -e /etc/nixos-containers/{name}.conf")
for prune in [PRUNE, STT_PRUNE, CI_PRUNE, CLASSIFIER_PRUNE, LOGIN_PRUNE]:
machine.fail(f"systemctl cat {prune}.service")
for unit in CI_HOST_UNITS:
machine.fail(f"systemctl cat {unit}")
# The CA publisher is the control that the lookups find a unit of the cluster's that is there.
machine.succeed("systemctl cat hyperhive-k8s-ca-trust.service")
for name in [SERVICE, STT, CLASSIFIER, LOGIN, CI]:
machine.succeed(f"test -L {MANIFESTS}/{name}.yaml")
# Suspended as soon as it exists: a scheduled Job at the next five-minute
# mark would push the run before the test's own Job does.
machine.wait_until_succeeds(f"kubectl -n {NS} get cronjob {CI}", timeout=300)
kube(machine, f"patch cronjob {CI} -p '{{\"spec\":{{\"suspend\":true}}}}'")
cron = json.loads(kube(machine, f"get cronjob {CI} -o json"))
assert cron["spec"]["schedule"] == "*/5 * * * *", cron["spec"]
assert cron["spec"]["concurrencyPolicy"] == "Forbid", cron["spec"]
router = wait_pod_ready()
stt_pod = wait_pod_ready(STT)
for daemon in CLAUDE_DAEMONS:
DAEMON_PODS[daemon] = wait_pod_ready(daemon)
for name in [SERVICE, STT, CLASSIFIER, LOGIN]:
assert machine.execute(f"machinectl list --no-legend | grep -q {name}")[0] != 0
with subtest("the host published the CA files, which are the hive's"):
trust = machine.succeed(f"kubectl -n {NS} get configmap hyperhive-ca-trust -o json")
data = json.loads(trust)["data"]
assert data["trust-bundle.pem"] == machine.succeed("cat ${tlsDir}/trust-bundle.pem"), data
assert data["bao-server-ca.pem"] == machine.succeed("cat /var/lib/swarm-bao-pki/ca.pem"), data
assert machine.succeed(f"kubectl -n {NS} get secrets -o name || true").strip() == ""
with subtest("a changed CA file is published again with no manual step"):
machine.succeed("echo '# refreshed' >> ${tlsDir}/trust-bundle.pem")
machine.wait_until_succeeds(
f"kubectl -n {NS} get configmap hyperhive-ca-trust -o jsonpath='{{.data.trust-bundle\\.pem}}' | grep -q refreshed",
timeout=120,
)
with subtest("the pod logged in to the store, read the client secret, and minted a token with it"):
machine.wait_until_succeeds(f"grep -F '/api/oidc/token ${clientId}:{SECRET}' ${tokenLog}", timeout=120)
machine.wait_until_succeeds(f"nats {NATS} consumer info SWARM_EVENTS notify-router >/dev/null", timeout=120)
with subtest("the speech-to-text pod logged in to the store with its token, read its client secret and minted a token with it"):
machine.wait_until_succeeds(f"grep -F '/api/oidc/token ${sttClientId}:{STT_SECRET}' ${tokenLog}", timeout=120)
env = {e["name"]: e.get("value") for e in json.loads(kube(machine, f"get pod {stt_pod} -o json"))["spec"]["containers"][0]["env"]}
assert env["BAO_AUTH"] == "jwt" and env["BAO_JWT_ROLE"] == STT, env
assert "BAO_CLIENT_CERT" not in env and "BAO_CLIENT_KEY" not in env, env
volumes = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["spec"]["volumes"]
assert not any("secret" in v for v in volumes), volumes
with subtest("the speech-to-text pod carries its unit's limits, reserves nothing, and is Burstable"):
# The unit sets MemoryMax=3G and CPUQuota=400% and no MemoryMin or
# MemoryLow. The API server prints 4000m as 4 and accepts the requests
# of 0 the renderer sets.
def pod_field(path: str) -> str:
return kube(machine, f"get pod {stt_pod} -o jsonpath='{{{path}}}'")
assert json.loads(pod_field(".spec.containers[0].resources.limits")) == {"cpu": "4", "memory": "3Gi"}
assert json.loads(pod_field(".spec.containers[0].resources.requests")) == {"cpu": "0", "memory": "0"}
assert pod_field(".status.qosClass") == "Burstable", pod_field(".status.qosClass")
# A pod whose unit sets neither is the control that the field is read
# from the unit: the router's has none.
router_resources = json.loads(kube(machine, f"get pod {router} -o json"))["spec"]["containers"][0]["resources"]
assert router_resources == {}, router_resources
with subtest("the speech-to-text pod runs in a user namespace, and still logs in, writes its state and starts its decoder"):
assert kube(machine, f"get pod {stt_pod} -o jsonpath='{{.spec.hostUsers}}'").strip() == "false"
def id_map(service: str) -> list[str]:
container = machine.succeed(f"k3s crictl ps --name '^{service}$' --state running -q").split()[0]
pid = machine.succeed(f"k3s crictl inspect {container} | jq -r .info.pid").strip()
return machine.succeed(f"cat /proc/{pid}/uid_map").split()
# The router's pod shares the node's ids, which is what reading the map
# shows when there is no namespace.
assert id_map(SERVICE) == ["0", "0", "4294967295"], id_map(SERVICE)
mapping = id_map(STT)
assert mapping[0] == "0" and int(mapping[1]) >= 65536 and mapping[2] == "65536", mapping
# The login read the projected token, and the decode writes a scratch
# directory in the emptyDir; both volumes are idmapped mounts.
machine.wait_until_succeeds(f"grep -F '/api/oidc/token ${sttClientId}:{STT_SECRET}' ${tokenLog}", timeout=120)
out = machine.succeed(f"nats {NATS} req '$SWARM.stt.transcribe.{AGENT}' 'OggS not really audio' --timeout 90s 2>/dev/null")
reply = json.loads([line for line in out.splitlines() if line.startswith("{")][-1])
assert reply == {"status": "failed", "message": "the audio could not be decoded"}, reply
with subtest("the speech-to-text cache is an emptyDir mounted where the unit keeps its state, with no claim and no state gate"):
stt_spec = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["spec"]
assert [v for v in stt_spec["volumes"] if v["name"] == "state"] == [{"name": "state", "emptyDir": {}}], stt_spec["volumes"]
assert "state-gate" not in [c["name"] for c in stt_spec.get("initContainers", [])], stt_spec.get("initContainers")
assert machine.execute(f"kubectl -n {NS} get pvc {STT}-state")[0] != 0
mounts = stt_spec["containers"][0]["volumeMounts"]
assert any(m["name"] == "state" and m["mountPath"] == "/var/lib/swarm-stt" for m in mounts), mounts
def pod_pid(service: str) -> str:
container = machine.succeed(f"k3s crictl ps --name '^{service}$' --state running -q").split()[0]
return machine.succeed(f"k3s crictl inspect {container} | jq -r .info.pid").strip()
def dials(pid: str, address: str, port: int) -> str:
"""A command that opens a TCP connection from the network namespace of
the process `pid`, as the pod in it would."""
return f"nsenter --target {pid} --net -- timeout 5 bash -c '</dev/tcp/{address}/{port}'"
with subtest("the speech-to-text pod answers a request on the queue, the path production uses, with its decoder running"):
assert json.loads(kube(machine, f"get networkpolicy {STT} -o json"))["spec"]["policyTypes"] == ["Ingress", "Egress"]
out = machine.succeed(f"nats {NATS} req '$SWARM.stt.transcribe.{AGENT}' 'OggS not really audio' --timeout 90s 2>/dev/null")
reply = json.loads([line for line in out.splitlines() if line.startswith("{")][-1])
print(f"stt reply: {reply}")
# The audio looks like Ogg, so ffmpeg is started in the pod and refuses it.
assert reply == {"status": "failed", "message": "the audio could not be decoded"}, reply
with subtest("the speech-to-text pod reaches the host ports its policy names and the cluster's DNS, and no other port of the host"):
stt_pid = pod_pid(STT)
router_pid = pod_pid(SERVICE)
# A listener on a port no policy names, on the bridge's address. The
# host and the router's pod, which has no policy, reach it: the control
# that the listener is up and a pod can dial it.
machine.succeed("systemd-run --unit=exfil-standin ${pkgs.socat}/bin/socat TCP-LISTEN:9999,bind=${bridgeIp},reuseaddr,fork /dev/null")
machine.wait_until_succeeds("timeout 5 bash -c '</dev/tcp/${bridgeIp}/9999'", timeout=30)
machine.succeed(dials(router_pid, "${bridgeIp}", 9999))
for port in (${toString podPort}, 443, ${toString natsPort}):
machine.succeed(dials(stt_pid, "${bridgeIp}", port))
cluster_dns = kube(machine, "-n kube-system get service kube-dns -o jsonpath='{.spec.clusterIP}'").strip()
machine.succeed(f"nsenter --target {stt_pid} --net -- dig +short +time=5 +tries=1 @{cluster_dns} ${baoName} | grep -qx ${bridgeIp}")
# The pod's own policy refuses what it names no port for. Waited for
# first: the policy engine syncs a moment after the pod starts.
machine.wait_until_fails(dials(stt_pid, "${bridgeIp}", 9999), timeout=60)
for _ in range(3):
assert machine.execute(dials(stt_pid, "${bridgeIp}", 9999))[0] != 0
classifier_ip = kube(machine, f"get pod {DAEMON_PODS[CLASSIFIER]} -o jsonpath='{{.status.podIP}}'").strip()
machine.succeed(dials(router_pid, classifier_ip, 8080))
assert machine.execute(dials(stt_pid, classifier_ip, 8080))[0] != 0
with subtest("no peer pod reaches the speech-to-text pod, and the kubelet's probes still do"):
stt_ip = kube(machine, f"get pod {stt_pod} -o jsonpath='{{.status.podIP}}'").strip()
# Another pod reaches a pod with no policy on its health port, and
# the node reaches the speech-to-text pod's.
machine.succeed(dials(router_pid, classifier_ip, 8080))
machine.succeed(f"timeout 5 bash -c '</dev/tcp/{stt_ip}/8080'")
machine.wait_until_fails(dials(router_pid, stt_ip, 8080), timeout=60)
status = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["status"]
assert status["containerStatuses"][0]["ready"] and status["containerStatuses"][0]["restartCount"] == 0, status
with subtest("the log store and its responders run only as pods: the host has no container, unit or socket directory for them"):
machine.fail("test -e /etc/nixos-containers/swarm-victorialogs.conf")
assert host_state("container@swarm-victorialogs.service") == "inactive"
for unit in ("swarm-logs-auth", "swarm-logs-grafana-auth"):
machine.fail(f"systemctl cat {unit}.service")
machine.fail("test -e /run/swarm-victorialogs")
# The CA publisher is the control that the lookups find a unit of the cluster's that is there.
machine.succeed("systemctl cat hyperhive-k8s-ca-trust.service")
for name in (VL, LOGS_AUTH):
machine.succeed(f"test -L {MANIFESTS}/{name}.yaml")
vl_pod = wait_pod_ready(VL)
auth_pod = wait_pod_ready(LOGS_AUTH)
assert machine.execute("machinectl list --no-legend | grep -q swarm-victorialogs")[0] != 0
with subtest("the store's volume is the old container's directory, whose files keep the user that wrote them and whose tree the pod's group owns"):
pv = json.loads(kube(machine, f"get pv {VL}-store -o json"))
assert pv["spec"]["local"]["path"] == VL_DIR and pv["status"]["phase"] == "Bound", pv
pvc = json.loads(kube(machine, f"get pvc {VL}-store -o json"))
assert pvc["status"]["phase"] == "Bound" and pvc["spec"]["volumeName"] == pv["metadata"]["name"], pvc
assert machine.succeed(f"stat -c %g {VL_DIR}").strip() == "65532"
assert machine.succeed(f"find {VL_DIR} -type f -user ${legacyUser} | head -1").strip() != ""
assert machine.succeed(f"kubectl -n {NS} get pods {vl_pod} -o jsonpath='{{.status.containerStatuses[0].restartCount}}'").strip() == "0"
def vl_request(path: str, token: str | None, *args: str) -> tuple[int, str]:
"""One request to the gateway's locations: the status and the body."""
auth = f"-H 'Authorization: Bearer {token}' " if token else ""
_, out = machine.execute(f"curl -sS --max-time 20 -w '\\n%{{http_code}}' {auth}{' '.join(args)} {GATEWAY}{path}")
body, _, code = out.rpartition("\n")
return int(code or 0), body
def vl_query(token: str, text: str) -> tuple[int, str]:
return vl_request("/select/logsql/query", token, f"--data-urlencode 'query={text}'")
def gateway_diagnostics(token: str) -> None:
"""What to read when the gateway refuses a bearer for good: the
responders' logs, the gateway's own, the claims of the account token
the responder logs in with, that login and the credential it reads,
and the responder asked directly."""
import base64
def show(title: str, command: str) -> None:
print(f"--- {title}")
print(machine.execute(f"{command} 2>&1")[1])
print("=== gateway diagnostics")
for pod in service_pods(LOGS_AUTH):
show(f"{pod} logs", f"kubectl -n {NS} logs {pod} --all-containers --tail=100")
show(f"{pod} previous logs", f"kubectl -n {NS} logs {pod} --all-containers --previous --tail=100")
show("gateway nginx", "journalctl -u logs-gateway --no-pager -n 100")
sa_token = machine.execute(f"kubectl -n {NS} create token {LOGS_AUTH} --audience bao --duration 10m")[1].strip()
parts = sa_token.split(".")
if len(parts) == 3:
for name, part in zip(("header", "claims"), parts[:2]):
print(f"--- account token {name}")
print(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4)).decode(errors="replace"))
body = json.dumps({"jwt": sa_token, "role": LOGS_AUTH})
show(
"login as the responder's role",
f"curl -sS -m 20 --cacert /var/lib/swarm-bao-pki/ca.pem -X POST -d '{body}' "
f"https://${baoName}:${toString podPort}/v1/auth/jwt-k8s/login | jq -c 'del(.auth.client_token, .auth.accessor)'",
)
else:
print(f"--- account token: {sa_token}")
show("jwt mount config", f"BAO_TOKEN=\"$(jq -r .root_token {INIT})\" bao read -format=json auth/jwt-k8s/config")
show("responder's role", f"BAO_TOKEN=\"$(jq -r .root_token {INIT})\" bao read -format=json auth/jwt-k8s/role/{LOGS_AUTH}")
show("agent's queue credential names", f"BAO_TOKEN=\"$(jq -r .root_token {INIT})\" bao kv get -mount=secret -format=json swarm/agents/{AGENT}/queue | jq -c '.data.data | keys'")
show("responder service", f"kubectl -n {NS} get svc,endpoints {LOGS_AUTH} -o wide")
show("grafana bearer credential names", f"BAO_TOKEN=\"$(jq -r .root_token {INIT})\" bao kv get -mount=secret -format=json swarm/services/swarm-grafana/metrics/bearer | jq -c '.data.data | keys'")
show(
"each responder port asked directly",
f"pod=$(kubectl -n {NS} get pods --selector app.kubernetes.io/name={LOGS_AUTH} -o name | head -1); ip=$(kubectl -n {NS} get $pod -o jsonpath='{{.status.podIP}}'); "
f"for port in $(kubectl -n {NS} get $pod -o jsonpath='{{.spec.containers[*].ports[*].containerPort}}'); do "
f"echo \"port $port\"; curl -sS -m 20 -w '\\nstatus %{{http_code}}\\n' -H 'Authorization: Bearer {token}' http://$ip:$port/; done",
)
def wait_for_record(token: str, text: str, record: str) -> None:
"""Queries until the response holds `record`, for as long as the pod and
the policy engine take to settle."""
deadline = time.monotonic() + 300
while True:
status, body = vl_query(token, text)
if status == 200 and record in body:
return
if time.monotonic() >= deadline:
gateway_diagnostics(token)
raise AssertionError((status, body))
time.sleep(3)
AGENT_TOKEN = f"swarm-agent.{AGENT}.{AGENT_SECRETS[AGENT]}"
with subtest("an agent's bearer reads the record written before the switch through the gateway, and the other bearers are granted or refused as the store says"):
wait_for_record(AGENT_TOKEN, "switch", "written before the switch")
# Each responder's Service reaches its own container: the endpoint port is
# the container's, and the two differ.
for responder, port in ((LOGS_AUTH, "8081"), ("swarm-logs-grafana-auth", "8082")):
assert machine.succeed(f"kubectl -n {NS} get endpoints {responder} -o jsonpath='{{.subsets[0].ports[0].port}}'").strip() == port, responder
# Each refusal has the answer above as its control: the same request with
# a bearer the store grants.
assert vl_query(f"swarm-agent.{OTHER_AGENT}.{AGENT_SECRETS[OTHER_AGENT]}", "switch")[0] == 403
assert vl_query(f"swarm-agent.{AGENT}.{'0' * 32}", "switch")[0] == 401
# Grafana's bearer goes to the second responder of the same pod.
status, body = vl_query(GRAFANA_BEARER, "switch")
if status != 200 or "written before the switch" not in body:
gateway_diagnostics(GRAFANA_BEARER)
raise AssertionError((status, body))
assert vl_query("0" * 64, "switch")[0] == 401
with subtest("a record posted to the ingest route and the store's own metrics come through the gateway, and a restarted pod still holds both records"):
import base64
def varint(n: int) -> bytes:
out = b""
while n > 0x7F:
out += bytes([n & 0x7F | 0x80])
n >>= 7
return out + bytes([n])
def field(number: int, payload: bytes) -> bytes:
return varint(number << 3 | 2) + varint(len(payload)) + payload
# An OTLP logs request with one record: time (field 1, fixed64) and a body
# (field 5) that is a string value.
now_ns = int(machine.succeed("date +%s%N"))
record = varint(1 << 3 | 1) + now_ns.to_bytes(8, "little") + field(5, field(1, b"written through the gateway"))
request = field(1, field(2, field(2, record)))
machine.succeed(f"echo {base64.b64encode(request).decode()} | base64 -d > /tmp/otlp.bin")
status, body = vl_request(
"/insert/opentelemetry/v1/logs", None, "-X POST -H 'Content-Type: application/x-protobuf' --data-binary @/tmp/otlp.bin"
)
assert status == 200, (status, body)
wait_for_record(AGENT_TOKEN, "gateway", "written through the gateway")
status, body = vl_request("/metrics", None)
assert status == 200 and "vl_" in body, (status, body[:200])
kube(machine, f"delete pod {vl_pod} --wait=true", timeout=120)
vl_pod = wait_pod_ready(VL)
wait_for_record(AGENT_TOKEN, "switch", "written before the switch")
wait_for_record(AGENT_TOKEN, "gateway", "written through the gateway")
with subtest("only the node reaches the log store's pods, and the responders' pod reaches the store's pod listener and no other port of the host"):
vl_ip = kube(machine, f"get pod {vl_pod} -o jsonpath='{{.status.podIP}}'").strip()
auth_ip = kube(machine, f"get pod {auth_pod} -o jsonpath='{{.status.podIP}}'").strip()
machine.succeed(f"curl -sf --max-time 5 http://{vl_ip}:9428/health")
# A peer pod reaches the classifier's health port, which has no policy:
# the control that the dial below is refused by the policy.
machine.succeed(dials(router_pid, classifier_ip, 8080))
for ip, port in ((vl_ip, 9428), (auth_ip, 8081), (auth_ip, 8082)):
machine.succeed(f"timeout 5 bash -c '</dev/tcp/{ip}/{port}'")
machine.wait_until_fails(dials(router_pid, ip, port), timeout=60)
for _ in range(3):
assert machine.execute(dials(router_pid, ip, port))[0] != 0
auth_pid = pod_pid(LOGS_AUTH)
machine.succeed(dials(auth_pid, "${bridgeIp}", ${toString podPort}))
machine.wait_until_fails(dials(auth_pid, "${bridgeIp}", 9999), timeout=60)
for name in (vl_pod, auth_pod):
status = json.loads(kube(machine, f"get pod {name} -o json"))["status"]
assert all(c["ready"] for c in status["containerStatuses"]), status
with subtest("the poller's Job completes against the forge and pushes the run to the poller's own route with a token the identity provider minted"):
tokens_before = int(machine.succeed(f"grep -cF '/api/oidc/token ${ci}:{CI_SECRET}' ${tokenLog} || true"))
job_log = ci_job(f"{CI}-first")
assert "pushed=1" in job_log.replace(" ", ""), job_log
runs = pushes(RUN_METRIC)
assert len(runs) == 1, runs
assert runs[0]["path"] == OWN_ROUTE and runs[0]["host"] == "${otelName}", runs[0]
assert runs[0]["bearer_minted"], runs[0]
assert runs[0]["points"] == {RUN_METRIC: 1, "hyperhive.ci.run.queue_wait": 1}, runs[1]
# Every push of the poller went to its own route. The pod holds no client
# certificate, so it reports none; the run's push is the control that
# the lookup finds what is there.
assert {r["path"] for r in requests() if "points" in r} == {OWN_ROUTE}, requests()
assert len(pushes(CERT_METRIC)) == 0, requests()
# The pod read the forge token and its client secret from the store,
# and reached the forge and the identity provider by name. One pass
# makes two forge requests (the repository search and the run list), so
# two is the floor of this one Job.
forge = [r for r in requests() if "forge_token_ok" in r]
assert len(forge) >= 2, forge
assert all(r["forge_token_ok"] and r["host"] == "${forgeName}" for r in forge), forge
tokens = int(machine.succeed(f"grep -cF '/api/oidc/token ${ci}:{CI_SECRET}' ${tokenLog}"))
assert tokens > tokens_before, (tokens, tokens_before)
with subtest("the poller's pod keeps the route its unit names, holds no Secret, and gets the store's CA from the ConfigMap"):
ci_pod = json.loads(kube(machine, f"get pods --selector job-name={CI}-first -o json"))["items"][0]
spec = ci_pod["spec"]
env = {e["name"]: e.get("value") for e in spec["containers"][0]["env"]}
assert env["SWARM_CI_METRICS_OTLP_ENDPOINT"] == "https://${otelName}/${ci}", env
assert "OTEL_EXPORTER_OTLP_ENDPOINT" not in env, env
assert env["BAO_AUTH"] == "jwt" and env["BAO_JWT_ROLE"] == CI, env
assert "BAO_CLIENT_CERT" not in env and "BAO_CLIENT_KEY" not in env, env
creds = next(v for v in spec["volumes"] if v["name"] == "credentials")
sources = creds["projected"]["sources"]
assert [src["configMap"]["name"] for src in sources] == ["hyperhive-ca-trust"], sources
assert [(i["key"], i["path"]) for i in sources[0]["configMap"]["items"]] == [("bao-server-ca.pem", "bao-ca.pem")], sources
assert not any("secret" in v or any("secret" in src for src in v.get("projected", {}).get("sources", [])) for v in spec["volumes"]), spec["volumes"]
assert machine.succeed(f"kubectl -n {NS} get secrets -o name || true").strip() == ""
# The control that the lookup finds the variable: the router's pod sets
# it, and the poller's does not.
router_env = {e["name"]: e.get("value") for e in json.loads(kube(machine, f"get pod {router} -o json"))["spec"]["containers"][0]["env"]}
assert "OTEL_EXPORTER_OTLP_ENDPOINT" in router_env, router_env
with subtest("the poller's cursor volume is bound and mounted where the unit keeps its state, and a second Job pushes nothing"):
claim = json.loads(kube(machine, f"get pvc {CI}-store -o json"))
assert claim["status"]["phase"] == "Bound", claim["status"]
mounts = ci_pod["spec"]["containers"][0]["volumeMounts"]
assert any(m["name"] == "state" and m["mountPath"] == "/var/lib/swarm-ci-metrics" for m in mounts), mounts
seen = len(requests())
job_log = ci_job(f"{CI}-second")
assert "pushed=0" in job_log.replace(" ", ""), job_log
assert len(pushes(RUN_METRIC)) == 1, requests()
# The pass ran: it listed the forge again.
assert len(requests()) > seen, requests()
def claude_of(daemon: str) -> str:
spec = json.loads(kube(machine, f"get deployment {daemon} -o json"))["spec"]["template"]["spec"]
return {e["name"]: e.get("value") for e in spec["containers"][0]["env"]}[CLAUDE_VARS[daemon]]
def probe(daemon: str, name: str, command: str, args: list[str], env: dict[str, str]) -> tuple[str, str]:
"""Runs `command` with `args` and `env` in a pod made from the daemon's
own pod spec (its image, user, read-only root and volumes) and returns
the pod's phase and output. The image has no shell: the commands are
the daemon's `claude`, and the bash and coreutils its closure holds."""
spec = json.loads(kube(machine, f"get deployment {daemon} -o json"))["spec"]["template"]["spec"]
main = spec["containers"][0]
main["command"] = [command]
main["args"] = args
main["env"] = [{"name": k, "value": v} for k, v in env.items()]
for field in ("ports", "readinessProbe", "livenessProbe", "startupProbe"):
main.pop(field, None)
spec["restartPolicy"] = "Never"
pod = {"apiVersion": "v1", "kind": "Pod", "metadata": {"name": name, "namespace": NS}, "spec": spec}
machine.succeed(f"cat > /root/{name}.json <<'EOF'\n{json.dumps(pod)}\nEOF")
kube(machine, f"apply -f /root/{name}.json")
machine.wait_until_succeeds(
f"kubectl -n {NS} get pod {name} -o jsonpath='{{.status.phase}}' | grep -E '^(Succeeded|Failed)$'",
timeout=300,
)
phase = kube(machine, f"get pod {name} -o jsonpath='{{.status.phase}}'")
out = machine.execute(f"kubectl -n {NS} logs {name} 2>&1")[1]
kube(machine, f"delete pod {name} --wait=false")
return phase, out
with subtest("claude runs in each claude daemon's read-only pod as the pod user and writes its config under HOME, in the pod's /tmp volume"):
for daemon, config_dir in [(CLASSIFIER, "/tmp/config"), (LOGIN, "/tmp/.claude")]:
short = daemon.removeprefix("swarm-")
pod_spec = json.loads(kube(machine, f"get pod {DAEMON_PODS[daemon]} -o json"))["spec"]
assert pod_spec["containers"][0]["securityContext"]["runAsNonRoot"] is True, pod_spec["containers"][0]["securityContext"]
assert pod_spec["securityContext"]["runAsUser"] != 0, pod_spec["securityContext"]
env = {"HOME": "/tmp", "CLAUDE_CONFIG_DIR": config_dir}
phase, out = probe(daemon, f"probe-version-{short}", claude_of(daemon), ["--version"], env)
assert phase == "Succeeded" and "Claude Code" in out, (phase, out)
print(f"{daemon}: {out.strip()}")
# `mcp add` writes the user config, which is what the daemons'
# runs of `claude` write first. It names the file it wrote, so the
# path is the presence control for the absence of an EROFS.
phase, out = probe(daemon, f"probe-config-{short}", claude_of(daemon), ["mcp", "add", "--scope", "user", "probe", "--", "/bin/true"], env)
assert phase == "Succeeded", (phase, out)
assert config_dir in out, out
assert "EROFS" not in out and "read-only file system" not in out.lower(), out
with subtest("the pod's root is read-only, a write outside the /tmp volume fails, and claude with HOME on the root writes nothing there"):
for daemon in CLAUDE_DAEMONS:
short = daemon.removeprefix("swarm-")
closure = machine.succeed(f"cat /etc/k3s-node/closure-{daemon}").split()
bash = next(p for p in closure if re.fullmatch(r"/nix/store/\w{32}-bash-[0-9.p]+", p))
coreutils = next(p for p in closure if re.fullmatch(r"/nix/store/\w{32}-coreutils-[0-9.]+", p))
claude = claude_of(daemon)
script = "\n".join([
f"export PATH={coreutils}/bin",
"while read -r dev mp rest; do",
' case "$mp" in /|/tmp|/home) echo "mount $dev $mp $rest";; esac',
"done < /proc/mounts",
"id",
"touch /etc/probe; echo etc-rc=$?",
"touch /tmp/ok; echo tmp-rc=$?",
"mkdir /tmp/scratch",
f"HOME=/tmp/scratch {claude} mcp add --scope user probe -- /bin/true; echo claude-tmp-rc=$?",
"ls -A /tmp/scratch",
f"HOME=/home/probe {claude} mcp add --scope user probe -- /bin/true; echo claude-root-rc=$?",
"ls -A /home/probe; echo home-after-rc=$?",
"ls -A /tmp",
])
phase, out = probe(daemon, f"probe-ro-{short}", f"{bash}/bin/bash", ["-c", script], {})
print(f"--- {daemon}, run in a pod of its own spec:\n{out}")
assert phase == "Succeeded", (phase, out)
# The root is mounted read-only and the /tmp volume is not.
assert re.search(r"^mount \S+ / \S+ ro[, ]", out, re.M), out
assert re.search(r"^mount \S+ /tmp \S+ rw[, ]", out, re.M), out
assert "etc-rc=1" in out and "Read-only file system" in out, out
assert "tmp-rc=0" in out, out
# The control: with HOME in the volume, claude writes its config there.
assert "claude-tmp-rc=0" in out and ".claude.json" in out.split("claude-tmp-rc=0", 1)[1].split("claude-root-rc=")[0], out
# With HOME on the read-only root, nothing appears there.
assert re.search(r"home-after-rc=[1-9]", out), out
with subtest("the minter's real login step runs claude in a scratch directory of the pod's /tmp volume, and removes it"):
uid = kube(machine, f"get pod {DAEMON_PODS[LOGIN]} -o jsonpath='{{.metadata.uid}}'")
volume = machine.succeed(f"find /var/lib -type d -path '*/pods/{uid}/volumes/kubernetes.io~empty-dir/tmp' -print -quit").strip()
assert volume, uid
start = json.dumps({"step": "start", "agent": AGENT, "operator": "test"})
out = machine.succeed(f"nats {NATS} req '$SWARM.claude-login.request' '{start}' --timeout 90s 2>/dev/null")
reply = json.loads([line for line in out.splitlines() if line.startswith("{")][-1])
print(f"login start: {reply}")
assert reply["state"] in ("started", "failed"), reply
assert "EROFS" not in json.dumps(reply) and "read-only file system" not in json.dumps(reply).lower(), reply
if reply["state"] == "started":
scratch = [d for d in machine.succeed(f"ls {volume}").split() if d.startswith(f"{AGENT}-")]
assert scratch, machine.succeed(f"ls -la {volume}")
print(machine.succeed(f"find {volume}/{scratch[0]} | head -20"))
cancel = json.dumps({"step": "cancel", "agent": AGENT})
machine.succeed(f"nats {NATS} req '$SWARM.claude-login.request' '{cancel}' --timeout 30s")
machine.wait_until_succeeds(f"[ -z \"$(ls {volume} | grep '^{AGENT}-')\" ]", timeout=60)
with subtest("the claude daemons' pods logged in to the store with their tokens, read their client secrets and minted tokens with them"):
for daemon, secret in [(CLASSIFIER, CLASSIFIER_SECRET), (LOGIN, LOGIN_SECRET)]:
machine.wait_until_succeeds(f"grep -F '/api/oidc/token {daemon}:{secret}' ${tokenLog}", timeout=120)
pod_spec = json.loads(kube(machine, f"get pod {DAEMON_PODS[daemon]} -o json"))["spec"]
main = pod_spec["containers"][0]
env = {e["name"]: e.get("value") for e in main["env"]}
assert env["BAO_AUTH"] == "jwt" and env["BAO_JWT_ROLE"] == daemon, env
assert "BAO_CLIENT_CERT" not in env and "BAO_CLIENT_KEY" not in env, env
assert not any("secret" in v for v in pod_spec["volumes"]), pod_spec["volumes"]
# The units set no limit, so the pods carry none; the speech-to-text
# pod's limits are the control that the field is read.
assert main["resources"] == {}, main["resources"]
assert main["securityContext"]["readOnlyRootFilesystem"] is True, main["securityContext"]
assert any(m["name"] == "tmp" and m["mountPath"] == "/tmp" for m in main["volumeMounts"]), main["volumeMounts"]
assert not any("persistentVolumeClaim" in v for v in pod_spec["volumes"]), pod_spec["volumes"]
assert json.loads(pod_field(".spec.containers[0].resources.limits")) == {"cpu": "4", "memory": "3Gi"}
with subtest("the claude login minter's token from the pod's account writes an agent's credentials, and the classifier's token reads its keys and cannot"):
BAO_POD = "https://${baoName}:${toString podPort}"
BAO_CA = "/var/lib/swarm-bao-pki/ca.pem"
CREDENTIALS = f"secret/data/swarm/agents/{AGENT}/claude-credentials"
API_KEY = "secret/data/swarm/services/review-classifier/anthropic-api-key"
def jwt_token(role: str) -> str:
sa_token = machine.succeed(f"kubectl -n {NS} create token {role} --audience bao --duration 10m").strip()
body = json.dumps({"jwt": sa_token, "role": role})
out = machine.succeed(f"curl -sS -m 20 --cacert {BAO_CA} -X POST -d '{body}' {BAO_POD}/v1/auth/jwt-k8s/login")
auth = json.loads(out)["auth"]
assert auth["policies"] == ["default", role], auth
return auth["client_token"]
def capabilities(token: str, *paths: str) -> dict:
body = json.dumps({"paths": list(paths)})
out = machine.succeed(
f"curl -sS -m 20 --cacert {BAO_CA} -H 'X-Vault-Token: {token}' -X POST -d '{body}' {BAO_POD}/v1/sys/capabilities-self"
)
result = json.loads(out)
return result.get("data", result)
login_token = jwt_token(LOGIN)
caps = capabilities(login_token, CREDENTIALS, "secret/data/${loginLeaf}", "secret/data/${classifierLeaf}", API_KEY)
assert sorted(caps[CREDENTIALS]) == ["create", "update"], caps
assert "read" in caps["secret/data/${loginLeaf}"], caps
assert caps["secret/data/${classifierLeaf}"] == ["deny"], caps
assert caps[API_KEY] == ["deny"], caps
body = json.dumps({"data": {"value": "written-by-the-minter"}})
status = machine.succeed(
f"curl -sS -m 20 -o /dev/null -w '%{{http_code}}' --cacert {BAO_CA} -H 'X-Vault-Token: {login_token}' -X POST -d '{body}' {BAO_POD}/v1/{CREDENTIALS}"
)
assert status == "200", status
assert as_root(f"bao kv get -mount=secret -field=value swarm/agents/{AGENT}/claude-credentials").strip() == "written-by-the-minter"
# The classifier's account, as the control for the other direction.
classifier_caps = capabilities(jwt_token(CLASSIFIER), CREDENTIALS, API_KEY)
assert classifier_caps[CREDENTIALS] == ["deny"], classifier_caps
assert "read" in classifier_caps[API_KEY], classifier_caps
with subtest("the pod routes a forge event: the agent's todo is queued and the event acknowledged"):
event = json.dumps({
"action": "assigned",
"repository": {"id": 1, "full_name": "o/r"},
"issue": {
"number": 7,
"title": "t",
"html_url": "https://forge.t.local/o/r/7",
"assignees": [{"login": AGENT}],
"user": {"login": "mara"},
},
"sender": {"login": "mara"},
})
machine.succeed(f"nats {NATS} pub '$SWARM.events.forge.issue_assign' '{event}'")
machine.wait_until_succeeds(
f"nats {NATS} stream get ROUTER_TODOS --last-for '$SWARM.router.todo.{AGENT}'",
timeout=180,
)
machine.wait_until_succeeds(
f"nats {NATS} consumer info SWARM_EVENTS notify-router --json | jq -e '.ack_floor.stream_seq == 1'",
timeout=60,
)
with subtest("deleting the pod ends its container with exit code 0 within the grace period, and its replacement is Ready"):
old = router_pods()[0].removeprefix("pod/")
terminated, took = delete_pod(machine, old, timeout=60)
assert terminated["exitCode"] == 0, terminated
print(f"pod deleted in {took:.1f}s, container exit code {terminated['exitCode']}")
assert took < 15 + 5, took
new = wait_pod_ready()
assert new != old, (new, old)
with subtest("deleting the speech-to-text pod ends its container with exit code 0 within the grace period, and its replacement is Ready"):
old_stt = service_pods(STT)[0].removeprefix("pod/")
terminated, took = delete_pod(machine, old_stt, timeout=60)
assert terminated["exitCode"] == 0, terminated
print(f"stt pod deleted in {took:.1f}s, container exit code {terminated['exitCode']}")
assert took < 15 + 5, took
assert wait_pod_ready(STT) != old_stt
with subtest("deleting a claude daemon's pod ends its container with exit code 0 within the grace period, and its replacement is Ready"):
for daemon in CLAUDE_DAEMONS:
old_daemon = service_pods(daemon)[0].removeprefix("pod/")
terminated, took = delete_pod(machine, old_daemon, timeout=60)
assert terminated["exitCode"] == 0, (daemon, terminated)
print(f"{daemon} pod deleted in {took:.1f}s, container exit code {terminated['exitCode']}")
assert took < 15 + 5, took
assert wait_pod_ready(daemon) != old_daemon
'';
}