Watch
0
0
Fork
You've already forked hyperhive
0

vm-tests: k8s-runtime-switch moves the review classifier and the claude login minter with the router

This commit is contained in:
atlas 2026-11-22 02:41:24 +01:00 • committed by maia
commit 931ce8c016

View file

@ -1,11 +1,11 @@
# `vmTests.<system>.k8s-runtime-switch`: the notification router, the # `vmTests.<system>.k8s-runtime-switch`: the notification router, the
# speech-to-text service and the CI run poller move between their host units # speech-to-text service, the CI run poller, the review classifier and the
# and the host's cluster (`services.hyperhive.deploy.<service>.runtime`), # claude login minter move between their host units or containers and the host's
# against the real secret store and a real queue. The host boots with all three # cluster (`services.hyperhive.deploy.<service>.runtime`), against the real
# on the host; the `k8s` specialisation has all three in the cluster. One test # secret store and a real queue. The host boots with all five on the host; the
# holds them because the switch is one activation and a second VM would pay the # `k8s` specialisation has them in the cluster. One test holds them because the
# store's start-up again. The script switches to it, back, and to it again, and # switch is one activation and a second VM would pay the store's start-up
# asserts that: # again. The script switches to it, back, and to it again, and asserts that:
# #
# - exactly one copy of each service runs at each step, by the order of the # - exactly one copy of each service runs at each step, by the order of the
# switch's own timestamps and by a sampler that looks every 200 ms. The # switch's own timestamps and by a sampler that looks every 200 ms. The
@ -15,9 +15,11 @@
# routes an event and a deleted pod exits 0 within its grace period; the # routes an event and a deleted pod exits 0 within its grace period; the
# speech-to-text pod carries its limits and has its cache volume bound; # speech-to-text pod carries its limits and has its cache volume bound;
# - the poller's Job completes against a forge that lists one run, pushes it to # - the poller's Job completes against a forge that lists one run, pushes it to
# the poller's own route of the swarm collector with a bearer the stub # the poller's own route of the swarm collector, holds no Secret, and keeps
# minted, holds no Secret, and keeps its cursor in a volume, so a second Job # its cursor in a volume, so a second Job pushes nothing;
# pushes nothing; # - 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 switch back leaves no pod, Deployment, CronJob or AddOn, and the # - the switch back leaves no pod, Deployment, CronJob or AddOn, and the
# router's consumer is the queue's, unchanged. # router's consumer is the queue's, unchanged.
# #
@ -25,8 +27,7 @@
# endpoint, the forge and the swarm collector: it records the client # endpoint, the forge and the swarm collector: it records the client
# credentials it is given and each push's route. They replace services that # credentials it is given and each push's route. They replace services that
# stay host-run and unchanged. The speech-to-text service gets a placeholder # stay host-run and unchanged. The speech-to-text service gets a placeholder
# model file, which it never loads. The test makes the hive's CA and the leaf of # model file. The test makes the hive's CA and the leaf of every name at boot.
# every name at boot.
{ pkgs, self }: { pkgs, self }:
let let
inherit (pkgs) lib; inherit (pkgs) lib;
@ -48,6 +49,8 @@ let
ci = "swarm-ci-metrics"; ci = "swarm-ci-metrics";
# A fixed value: it is the stub's to check, not a secret. # A fixed value: it is the stub's to check, not a secret.
forgeToken = "test-forge-token"; forgeToken = "test-forge-token";
classifier = "swarm-review-classifier";
login = "swarm-claude-login";
agent = "atlas"; agent = "atlas";
pkiDir = "/var/lib/test-ca"; pkiDir = "/var/lib/test-ca";
tlsDir = "/var/lib/hive-tls"; tlsDir = "/var/lib/hive-tls";
@ -55,11 +58,17 @@ let
sttLeaf = "swarm/services/${sttClientId}/oidc/client"; sttLeaf = "swarm/services/${sttClientId}/oidc/client";
ciLeaf = "swarm/services/${ci}/oidc/client"; ciLeaf = "swarm/services/${ci}/oidc/client";
ciForgeLeaf = "swarm/services/ci-metrics/forge/token"; ciForgeLeaf = "swarm/services/ci-metrics/forge/token";
classifierLeaf = "swarm/services/${classifier}/oidc/client";
loginLeaf = "swarm/services/${login}/oidc/client";
prune = "${service}-k8s-prune"; prune = "${service}-k8s-prune";
sttPrune = "${stt}-k8s-prune"; sttPrune = "${stt}-k8s-prune";
ciPrune = "${ci}-k8s-prune"; ciPrune = "${ci}-k8s-prune";
classifierPrune = "${classifier}-k8s-prune";
loginPrune = "${login}-k8s-prune";
hostUnit = "container@${service}.service"; hostUnit = "container@${service}.service";
sttHostUnit = "container@${stt}.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 # The model file the service is given: its path is in the pod's image, and
# nothing reads it. # nothing reads it.
sttModel = pkgs.writeText "ggml-placeholder.bin" "not a model"; sttModel = pkgs.writeText "ggml-placeholder.bin" "not a model";
@ -167,7 +176,7 @@ let
# cluster while its CronJob, a Job or a pod exists. # cluster while its CronJob, a Job or a pod exists.
sampler = pkgs.writeShellScript "overlap-sampler" '' sampler = pkgs.writeShellScript "overlap-sampler" ''
while true; do while true; do
for svc in ${service} ${stt}; do for svc in ${service} ${stt} ${classifier} ${login}; do
state="$(systemctl is-active container@$svc.service || true)" state="$(systemctl is-active container@$svc.service || true)"
pods="$(kubectl --namespace ${namespace} get pods --selector app.kubernetes.io/name=$svc --no-headers 2>/dev/null | wc -l)" pods="$(kubectl --namespace ${namespace} get pods --selector app.kubernetes.io/name=$svc --no-headers 2>/dev/null | wc -l)"
echo "$(date +%s.%N) $svc host=$state pods=$pods" >> ${overlapLog} echo "$(date +%s.%N) $svc host=$state pods=$pods" >> ${overlapLog}
@ -207,6 +216,8 @@ pkgs.testers.runNixOSTest {
deploy.bao.bootstrapTokenFile = "/var/lib/swarm-bao-bootstrap/grant.token"; deploy.bao.bootstrapTokenFile = "/var/lib/swarm-bao-bootstrap/grant.token";
deploy.notify-router.enable = true; deploy.notify-router.enable = true;
deploy.stt.enable = true; deploy.stt.enable = true;
deploy.review-classifier.enable = true;
deploy.claude-login.enable = true;
deploy.stt.settings.modelFile = sttModel; deploy.stt.settings.modelFile = sttModel;
deploy.ci-metrics.enable = true; deploy.ci-metrics.enable = true;
deploy.hive-controller.hiveName = "h1"; deploy.hive-controller.hiveName = "h1";
@ -232,6 +243,8 @@ pkgs.testers.runNixOSTest {
notify-router.runtime = "k8s"; notify-router.runtime = "k8s";
stt.runtime = "k8s"; stt.runtime = "k8s";
ci-metrics.runtime = "k8s"; ci-metrics.runtime = "k8s";
review-classifier.runtime = "k8s";
claude-login.runtime = "k8s";
}; };
# The store's TLS passthrough is a stream server of the host's nginx, # The store's TLS passthrough is a stream server of the host's nginx,
@ -337,6 +350,27 @@ pkgs.testers.runNixOSTest {
pkgs.natscli pkgs.natscli
]; ];
environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml"; 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 ( environment.etc."k3s-node/images".text = lib.concatMapStrings (
i: "${i.imageName}:${i.imageTag}\n" i: "${i.imageName}:${i.imageTag}\n"
) config.system.build.k8sImages; ) config.system.build.k8sImages;
@ -352,17 +386,20 @@ pkgs.testers.runNixOSTest {
]; ];
}; };
# The speech-to-text image carries ffmpeg and whisper. The pod's limits # The speech-to-text image carries ffmpeg and whisper, the two claude
# (3 GiB, four cores) are as large as the node's cores, so it is # images claude-code. The speech-to-text pod's limits (3 GiB, four
# schedulable only because it requests none of them. # cores) are as large as the node's cores, so it is schedulable only
# because it requests none of them.
virtualisation = { virtualisation = {
memorySize = 8192; memorySize = 8192;
cores = 4; cores = 4;
diskSize = 12288; diskSize = 20480;
}; };
}; };
testScript = builtins.readFile ./lib/k3s.py + '' testScript = builtins.readFile ./lib/k3s.py + ''
import re
INIT = "/root/bao-init.json" INIT = "/root/bao-init.json"
NS = "${namespace}" NS = "${namespace}"
SERVICE = "${service}" SERVICE = "${service}"
@ -377,6 +414,22 @@ pkgs.testers.runNixOSTest {
OWN_ROUTE = "/${ci}/v1/metrics" OWN_ROUTE = "/${ci}/v1/metrics"
RUN_METRIC = "hyperhive.ci.run.duration" RUN_METRIC = "hyperhive.ci.run.duration"
CERT_METRIC = "bao.client_cert.not_after" 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" MANIFESTS = "/var/lib/rancher/k3s/server/manifests"
NATS = "--server tls://${natsName}:${toString natsPort} --tlsca ${pkiDir}/ca.pem" NATS = "--server tls://${natsName}:${toString natsPort} --tlsca ${pkiDir}/ca.pem"
AGENT = "${agent}" AGENT = "${agent}"
@ -480,7 +533,7 @@ pkgs.testers.runNixOSTest {
print(out) print(out)
assert status in (0, 4), out assert status in (0, 4), out
failed = next((line for line in out.splitlines() if "the following units failed" in line), "") failed = next((line for line in out.splitlines() if "the following units failed" in line), "")
ours = [HOST_UNIT, STT_HOST_UNIT, *CI_HOST_UNITS, f"{PRUNE}.service", f"{STT_PRUNE}.service", f"{CI_PRUNE}.service", "hyperhive-k8s-ca-trust.service", "k3s.service"] ours = [HOST_UNIT, STT_HOST_UNIT, CLASSIFIER_HOST_UNIT, LOGIN_HOST_UNIT, *CI_HOST_UNITS, f"{PRUNE}.service", f"{STT_PRUNE}.service", f"{CLASSIFIER_PRUNE}.service", f"{LOGIN_PRUNE}.service", f"{CI_PRUNE}.service", "hyperhive-k8s-ca-trust.service", "k3s.service"]
assert not any(unit in failed for unit in ours), failed assert not any(unit in failed for unit in ours), failed
return out return out
@ -510,7 +563,7 @@ pkgs.testers.runNixOSTest {
timeout=300, timeout=300,
) )
with subtest("the granting units have written the policies and roles of the router, the speech-to-text service and the poller, and the jwt mount"): 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 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") 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"]) settle('[ "$(systemctl is-active swarm-bao-agent-pki.service)" = active ]', 900, ["swarm-bao-agent-pki.service"])
@ -521,7 +574,14 @@ pkgs.testers.runNixOSTest {
machine.wait_until_succeeds('[ "$(bao status >/dev/null 2>&1; echo $?)" = 2 ]', timeout=900) machine.wait_until_succeeds('[ "$(bao status >/dev/null 2>&1; echo $?)" = 2 ]', timeout=900)
machine.succeed(f"bao operator unseal \"$(jq -r '.unseal_keys_b64[0]' {INIT})\"") machine.succeed(f"bao operator unseal \"$(jq -r '.unseal_keys_b64[0]' {INIT})\"")
machine.wait_until_succeeds("bao status", timeout=120) machine.wait_until_succeeds("bao status", timeout=120)
for unit in ["swarm-bao-notify-router-policy", "swarm-bao-stt-policy", "swarm-bao-ci-metrics-policy", "swarm-bao-k8s-jwt-policy"]: 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-k8s-jwt-policy",
]:
settle(f'[ "$(systemctl is-active {unit}.service)" = active ]', 900, [f"{unit}.service"]) settle(f'[ "$(systemctl is-active {unit}.service)" = active ]', 900, [f"{unit}.service"])
machine.wait_until_succeeds( machine.wait_until_succeeds(
"journalctl -u swarm-bao-k8s-jwt-policy --no-pager | grep -F 'Success! Data written to: auth/jwt-k8s/config'", "journalctl -u swarm-bao-k8s-jwt-policy --no-pager | grep -F 'Success! Data written to: auth/jwt-k8s/config'",
@ -538,6 +598,10 @@ pkgs.testers.runNixOSTest {
CI_SECRET = machine.succeed("openssl rand -hex 16").strip() CI_SECRET = machine.succeed("openssl rand -hex 16").strip()
as_root(f"bao kv put -mount=secret ${ciLeaf} value={CI_SECRET}") 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") 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}")
with subtest("the queue and the token stub run, and the queue holds the roster the router reads"): 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("hive-tls-ca.service")
@ -548,7 +612,7 @@ pkgs.testers.runNixOSTest {
machine.succeed(f"nats {NATS} kv put agent-status h1.{AGENT} '{{}}'") machine.succeed(f"nats {NATS} kv put agent-status h1.{AGENT} '{{}}'")
machine.succeed("systemctl start overlap-sampler.service") machine.succeed("systemctl start overlap-sampler.service")
with subtest("on the host, the containers run and the cluster holds no router or speech-to-text service"): with subtest("on the host, the containers run and the cluster holds none of the four services"):
machine.wait_until_succeeds(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", timeout=300) machine.wait_until_succeeds(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", timeout=300)
machine.wait_until_succeeds(f"[ \"$(systemctl is-active {STT_HOST_UNIT})\" = active ]", timeout=300) machine.wait_until_succeeds(f"[ \"$(systemctl is-active {STT_HOST_UNIT})\" = active ]", timeout=300)
assert router_pods() == [], router_pods() assert router_pods() == [], router_pods()
@ -562,6 +626,12 @@ pkgs.testers.runNixOSTest {
# The prune unit ran with the container, found no link, and needed # The prune unit ran with the container, found no link, and needed
# nothing from the cluster. # nothing from the cluster.
assert machine.succeed(f"systemctl is-active {PRUNE}.service").strip() == "active" assert machine.succeed(f"systemctl is-active {PRUNE}.service").strip() == "active"
for daemon, (daemon_unit, daemon_prune) in CLAUDE_DAEMONS.items():
machine.wait_until_succeeds(f"[ \"$(systemctl is-active {daemon_unit})\" = active ]", timeout=300)
assert service_pods(daemon) == [], service_pods(daemon)
assert machine.execute(f"test -e {MANIFESTS}/{daemon}.yaml")[0] != 0
assert machine.execute(f"kubectl -n {NS} get deployment {daemon}")[0] != 0
assert machine.succeed(f"systemctl is-active {daemon_prune}.service").strip() == "active"
with subtest("on the host, the poller's timer runs, one pass pushes the run to the poller's own route, and the cluster holds none of it"): with subtest("on the host, the poller's timer runs, one pass pushes the run to the poller's own route, and the cluster holds none of it"):
assert host_state(f"{CI}.timer") == "active", host_state(f"{CI}.timer") assert host_state(f"{CI}.timer") == "active", host_state(f"{CI}.timer")
@ -586,11 +656,14 @@ pkgs.testers.runNixOSTest {
with subtest("the switch to the cluster stops the container before it applies the pod"): with subtest("the switch to the cluster stops the container before it applies the pod"):
out = switch("/run/booted-system/specialisation/k8s") out = switch("/run/booted-system/specialisation/k8s")
assert HOST_UNIT in out and STT_HOST_UNIT in out and "stopping the following units" in out, out assert all(u in out for u in [HOST_UNIT, STT_HOST_UNIT, CLASSIFIER_HOST_UNIT, LOGIN_HOST_UNIT]) and "stopping the following units" in out, out
assert host_state() == "inactive", host_state() assert host_state() == "inactive", host_state()
assert host_state(STT_HOST_UNIT) == "inactive", host_state(STT_HOST_UNIT) assert host_state(STT_HOST_UNIT) == "inactive", host_state(STT_HOST_UNIT)
machine.succeed(f"test -L {MANIFESTS}/{SERVICE}.yaml") machine.succeed(f"test -L {MANIFESTS}/{SERVICE}.yaml")
machine.succeed(f"test -L {MANIFESTS}/{STT}.yaml") machine.succeed(f"test -L {MANIFESTS}/{STT}.yaml")
for daemon, (daemon_unit, _) in CLAUDE_DAEMONS.items():
assert host_state(daemon_unit) == "inactive", host_state(daemon_unit)
machine.succeed(f"test -L {MANIFESTS}/{daemon}.yaml")
router = wait_pod_ready() router = wait_pod_ready()
assert stopped_at(HOST_UNIT) <= created_at_of(router) assert stopped_at(HOST_UNIT) <= created_at_of(router)
assert machine.execute("machinectl list --no-legend | grep -q swarm-notify-router")[0] != 0 assert machine.execute("machinectl list --no-legend | grep -q swarm-notify-router")[0] != 0
@ -611,6 +684,11 @@ pkgs.testers.runNixOSTest {
assert cron["spec"]["concurrencyPolicy"] == "Forbid", cron["spec"] assert cron["spec"]["concurrencyPolicy"] == "Forbid", cron["spec"]
# A scheduled Job would run beside the ones this test makes. # A scheduled Job would run beside the ones this test makes.
kube(machine, f"patch cronjob {CI} -p '{{\"spec\":{{\"suspend\":true}}}}'") kube(machine, f"patch cronjob {CI} -p '{{\"spec\":{{\"suspend\":true}}}}'")
with subtest("the review classifier and the claude login pods are Ready after their containers stopped, and the containers are gone"):
for daemon, (daemon_unit, _) in CLAUDE_DAEMONS.items():
DAEMON_PODS[daemon] = wait_pod_ready(daemon)
assert stopped_at(daemon_unit) <= created_at_of(DAEMON_PODS[daemon])
assert machine.execute(f"machinectl list --no-legend | grep -q {daemon}")[0] != 0
with subtest("the host published the CA files, which are the hive's"): 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") trust = machine.succeed(f"kubectl -n {NS} get configmap hyperhive-ca-trust -o json")
@ -714,6 +792,160 @@ pkgs.testers.runNixOSTest {
assert len(pushes(RUN_METRIC)) == 2, requests() assert len(pushes(RUN_METRIC)) == 2, requests()
# The pass ran: it listed the forge again. # The pass ran: it listed the forge again.
assert len(requests()) > seen, requests() 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"): with subtest("the pod routes a forge event: the agent's todo is queued and the event acknowledged"):
event = json.dumps({ event = json.dumps({
@ -756,6 +988,15 @@ pkgs.testers.runNixOSTest {
assert took < 15 + 5, took assert took < 15 + 5, took
assert wait_pod_ready(STT) != old_stt 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
with subtest("the switch back removes the pods and their objects before the containers start, and keeps the cache volume"): with subtest("the switch back removes the pods and their objects before the containers start, and keeps the cache volume"):
out = switch("/run/booted-system") out = switch("/run/booted-system")
print(out) print(out)
@ -779,6 +1020,16 @@ pkgs.testers.runNixOSTest {
pruned = int(machine.succeed(f"systemctl show -p ExecMainExitTimestampMonotonic --value {PRUNE}.service")) pruned = int(machine.succeed(f"systemctl show -p ExecMainExitTimestampMonotonic --value {PRUNE}.service"))
started = int(machine.succeed(f"systemctl show -p InactiveExitTimestampMonotonic --value {HOST_UNIT}")) started = int(machine.succeed(f"systemctl show -p InactiveExitTimestampMonotonic --value {HOST_UNIT}"))
assert 0 < pruned <= started, (pruned, started) assert 0 < pruned <= started, (pruned, started)
for daemon, (daemon_unit, daemon_prune) in CLAUDE_DAEMONS.items():
machine.wait_until_succeeds(f"[ \"$(systemctl is-active {daemon_unit})\" = active ]", timeout=300)
assert service_pods(daemon) == [], service_pods(daemon)
assert machine.execute(f"kubectl -n {NS} get deployment {daemon}")[0] != 0
assert machine.execute(f"kubectl -n kube-system get addons.k3s.cattle.io {daemon}")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{daemon}.yaml")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{daemon}.yaml.pruning")[0] != 0
pruned_daemon = int(machine.succeed(f"systemctl show -p ExecMainExitTimestampMonotonic --value {daemon_prune}.service"))
started_daemon = int(machine.succeed(f"systemctl show -p InactiveExitTimestampMonotonic --value {daemon_unit}"))
assert 0 < pruned_daemon <= started_daemon, (daemon, pruned_daemon, started_daemon)
with subtest("the switch back removes the poller's CronJob, Jobs and pods before its timer starts, and keeps the cursor volume"): with subtest("the switch back removes the poller's CronJob, Jobs and pods before its timer starts, and keeps the cursor volume"):
machine.wait_until_succeeds(f"[ \"$(systemctl is-active {CI}.timer)\" = active ]", timeout=300) machine.wait_until_succeeds(f"[ \"$(systemctl is-active {CI}.timer)\" = active ]", timeout=300)
@ -819,6 +1070,9 @@ pkgs.testers.runNixOSTest {
assert host_state(STT_HOST_UNIT) == "inactive", host_state(STT_HOST_UNIT) assert host_state(STT_HOST_UNIT) == "inactive", host_state(STT_HOST_UNIT)
wait_pod_ready() wait_pod_ready()
wait_pod_ready(STT) wait_pod_ready(STT)
for daemon, (daemon_unit, _) in CLAUDE_DAEMONS.items():
assert host_state(daemon_unit) == "inactive", host_state(daemon_unit)
wait_pod_ready(daemon)
claim = json.loads(kube(machine, f"get pvc {STT}-state -o json")) claim = json.loads(kube(machine, f"get pvc {STT}-state -o json"))
assert claim["status"]["phase"] == "Bound" and claim["metadata"]["uid"] == CACHE_VOLUME, claim assert claim["status"]["phase"] == "Bound" and claim["metadata"]["uid"] == CACHE_VOLUME, claim
assert ci_host_state() == "inactive", [host_state(u) for u in CI_HOST_UNITS] assert ci_host_state() == "inactive", [host_state(u) for u in CI_HOST_UNITS]
@ -834,7 +1088,7 @@ pkgs.testers.runNixOSTest {
machine.succeed("systemctl stop overlap-sampler.service") machine.succeed("systemctl stop overlap-sampler.service")
lines = machine.succeed("cat ${overlapLog}").splitlines() lines = machine.succeed("cat ${overlapLog}").splitlines()
host_up = {"active", "activating", "deactivating", "reloading"} host_up = {"active", "activating", "deactivating", "reloading"}
for svc in (SERVICE, STT, CI): for svc in (SERVICE, STT, CI, CLASSIFIER, LOGIN):
samples = [ samples = [
(fields[2].removeprefix("host="), int(fields[3].removeprefix("pods="))) (fields[2].removeprefix("host="), int(fields[3].removeprefix("pods=")))
for fields in (line.split() for line in lines) for fields in (line.split() for line in lines)