# `vmTests..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 and metrics stores run as pods on the directories their old # containers kept, which units of this test filled as other users: each pod # reads that record and writes a new one, the gateway's own locations # (rendered by the modules) reach the stores and the responders, bearers are # granted or refused as the store says, the metrics gateway refuses the # store's write and admin routes, and no other pod reaches either 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"; agentIp = "10.42.0.200"; 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; # The metrics store, as the module names it. vmDir = "/var/lib/nixos-containers/swarm-victoriametrics/var/lib/victoriametrics"; vmGateway = "127.0.0.1:18082"; legacyVmUser = "legacy-victoriametrics"; legacyVmPort = 19429; # One nginx with the log and metrics stores' locations as the modules render # them: the Services they dial, the responders they check a bearer with and # the variables between. The identity provider's checks are stand-ins that # answer 200, because the VM has no login service; nothing else of the vhosts. gatewayConf = cfg: let block = locations: name: let l = locations.${name}; in '' location ${name} { ${lib.optionalString (l.proxyPass != null) "proxy_pass ${l.proxyPass};"} ${lib.optionalString (l.return != null) "return ${l.return};"} ${l.extraConfig} } ''; logs = cfg.services.nginx.virtualHosts."logs.t.local".locations; logsServed = [ "= /insert/opentelemetry/v1/logs" "^~ /select/logsql/" "= /metrics" "= /__swarm_logs_auth" "= /__swarm_logs_agent_auth" "= /__swarm_logs_grafana_auth" ]; # Every location of the vhost but the two that dial the identity # provider, so a location the module adds is served here too. metrics = cfg.services.nginx.virtualHosts."metrics.t.local".locations; metricsServed = lib.filter ( n: !(lib.elem n [ "= /__metrics_authelia" "= /__metrics_ingest_authz" ]) ) (lib.attrNames metrics); in pkgs.writeText "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 logs) logsServed} } server { listen ${vmGateway}; location = /__metrics_ingest_authz { internal; return 200; } location = /__metrics_authelia { internal; return 200; } ${lib.concatMapStrings (block metrics) metricsServed} } } ''; 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 ./lib/agent-netns.nix ]; 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.victoriametrics.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)" ''; }; # What the metrics store's container left on the host: the directory the # same way, holding one sample. users.users.${legacyVmUser} = { isSystemUser = true; group = legacyVmUser; }; users.groups.${legacyVmUser} = { }; systemd.services.victoriametrics-legacy = { wantedBy = [ "multi-user.target" ]; before = [ "k3s.service" ]; path = [ pkgs.curl pkgs.coreutils pkgs.findutils pkgs.gnugrep ]; serviceConfig = { Type = "oneshot"; RemainAfterExit = true; User = legacyVmUser; # k3s waits for this unit, so a sample that never shows must fail it # and not hold the boot. TimeoutStartSec = 120; UMask = "0007"; ExecStartPre = "+${pkgs.writeShellScript "victoriametrics-legacy-dir" '' mkdir -p ${vmDir} chown ${legacyVmUser}:${legacyVmUser} ${vmDir} chmod 0700 ${vmDir} ''}"; }; script = '' store=http://127.0.0.1:${toString legacyVmPort} ${config.services.hyperhive.deploy.victoriametrics.package}/bin/victoria-metrics \ -storageDataPath=${vmDir} -httpListenAddr=127.0.0.1:${toString legacyVmPort} -retentionPeriod=5y & pid=$! until curl -sf $store/health; do sleep 1; done # One line of the text exposition format. Without a content type curl # sends a form body, which a route may read as form fields and ingest # nothing with a 200. code=$(printf '%s\n' 'written_before_the_switch{app="legacy"} 42' | curl -s -o /dev/null -w '%{http_code}' \ -H 'Content-Type: text/plain' --data-binary @- $store/api/v1/import/prometheus) curl -s -o /dev/null $store/internal/force_flush found= for _ in $(seq 60); do if curl -s $store/api/v1/export --data-urlencode 'match[]=written_before_the_switch' | grep -q written_before_the_switch; then found=1 break fi sleep 1 done if [ -z "$found" ]; then echo "the seeded sample is not found; the import replied $code; the store's ingest counters:" curl -s $store/metrics | grep -E '^vm_(rows_inserted_total|rows_ignored_total|http_request_errors_total)' echo "the store holds:" curl -s $store/api/v1/export --data-urlencode 'match[]={__name__!=""}' exit 1 fi kill -TERM "$pid" wait "$pid" || true test -n "$(find ${vmDir} -type f | head -1)" ''; }; # The log and metrics stores' 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;'"; ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID"; 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" LOGS_ONLY_AGENT = "scout" AGENT_SECRETS: dict[str, str] = {} VL = "swarm-victorialogs" LOGS_AUTH = "swarm-logs-auth" VL_DIR = "${vlDir}" GATEWAY = "http://${vlGateway}" VM = "swarm-victoriametrics" METRICS_AUTH = "swarm-metrics-auth" VM_DIR = "${vmDir}" METRICS_GATEWAY = "http://${vmGateway}" # The only Secrets the cluster holds: the two the host publishes for the # stores' passwords. STORE_SECRETS = {f"secret/{VL}-credentials", f"secret/{VM}-credentials"} def other_secrets() -> set[str]: names = machine.succeed(f"kubectl -n {NS} get secrets -o name || true").split() return set(names) - STORE_SECRETS 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 store_credential_published() -> None: # The unit is `Type=simple`: `is-active` is true while its script is still # running and `systemctl restart` returns at fork, so `SubState=exited` # is what says the files and the Secrets are out. settle( '[ "$(systemctl show --property=SubState --value swarm-bao-store-auth.service)" = exited ]', 900, ["swarm-bao-store-auth.service"], ) 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-store-auth-policy", "swarm-bao-k8s-jwt-policy", ]: settle(f'[ "$(systemctl is-active {unit}.service)" = active ]', 900, [f"{unit}.service"]) # The credential's unit retries until the store has its policy. machine.succeed("systemctl reset-failed swarm-bao-store-auth.service || true") machine.succeed("systemctl restart --no-block swarm-bao-store-auth.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 and metrics stores' responders read: an agent's queue # secret and its mirrored grant, one agent that holds no grant, one that # holds the logs grant alone, 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, "metrics": true}'), (OTHER_AGENT, '{"logs": false, "metrics": false}'), (LOGS_ONLY_AGENT, '{"logs": true, "metrics": 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 other_secrets() == set(), other_secrets() with subtest("a changed CA file is published again with no manual step"): # `swarm-services-cert` rewrites the trust bundle once, when the store first # answers it, and that can fall inside this wait. A line the rewrite drops # is appended again, each time with a marker of its own. deadline = time.monotonic() + 120 attempt = 0 while True: attempt += 1 machine.succeed(f"echo '# refreshed {attempt}' >> ${tlsDir}/trust-bundle.pem") published, _ = machine.execute( f"for _ in $(seq 20); do kubectl -n {NS} get configmap hyperhive-ca-trust -o jsonpath='{{.data.trust-bundle\\.pem}}' | grep -q 'refreshed {attempt}' && exit 0; sleep 1; done; exit 1" ) if published == 0: break assert time.monotonic() < deadline, f"the trust bundle's {attempt} refreshes were not published" 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 ' None: """The health listener answers inside the pod's network namespace and refuses the node on the pod's IP. The first arm is the control that the refusal is the bind and not an outage.""" code = machine.succeed(f"nsenter --target {pid} --net -- curl -s -o /dev/null -w '%{{http_code}}' --max-time 5 http://127.0.0.1:{port}/healthz").strip() assert code == "200", (port, code) rc = machine.execute(f"curl -s -o /dev/null --max-time 5 http://{ip}:{port}/healthz")[0] assert rc == 7, (ip, port, rc) 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 egress 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 ' 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, responders: str = LOGS_AUTH) -> 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(responders): 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 {responders} --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": responders}) 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/{responders}") 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 {responders} -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={responders} -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 STORE_AUTH_DIR = "/var/lib/swarm-store-auth" STORE_PASSWORD = f"{STORE_AUTH_DIR}/victorialogs.password" STORE_CONF = f"{STORE_AUTH_DIR}/victorialogs.conf" def store_direct(path: str, *args: str, credential: bool = True) -> tuple[int, str]: """One request from the node to the store's pod address, past the gateway.""" vl_ip = kube(machine, f"get pod {vl_pod} -o jsonpath='{{.status.podIP}}'").strip() auth = f'--user "swarm-store:$(cat {STORE_PASSWORD})" ' if credential else "" _, out = machine.execute(f"curl -sS --max-time 20 -w '\\n%{{http_code}}' {auth}{' '.join(args)} 'http://{vl_ip}:9428{path}'") body, _, code = out.rpartition("\n") return int(code or 0), body with subtest("the log store refuses every route without its credential from the node itself, past the gateway, and takes the credential the host keeps in the secret store"): stored = as_root("bao kv get -mount=secret -field=value swarm/services/victorialogs/store-auth").strip() assert len(stored) == 64, "the unit stores 64 hex digits" # The three ends agree: the secret store's value, the file the unit # keeps for the Secret, and the Secret itself. The files are root's # and nobody else's. assert machine.succeed(f"cat {STORE_PASSWORD}").strip() == stored secret = machine.succeed(f"kubectl -n {NS} get secret swarm-victorialogs-credentials -o jsonpath='{{.data.store-auth}}' | base64 -d").strip() assert secret == stored assert machine.succeed(f"stat -c '%a %U %G' {STORE_PASSWORD} {STORE_CONF} {STORE_AUTH_DIR}").split("\n")[:3] == ["600 root root", "600 root root", "700 root root"] assert stored not in machine.succeed(f"cat {MANIFESTS}/{VL}.yaml"), "the manifest holds no credential" # Insert, select, a delete route, the admin routes, the store's own # metrics and the UI answer 401 with no credential and with a caller's # bearer, which is all a node process without the credential has. refused = [ ("POST", "/insert/opentelemetry/v1/logs"), ("POST", "/insert/jsonline"), ("POST", "/select/logsql/query"), ("GET", "/select/logsql/tail"), ("POST", "/delete/run_task"), ("POST", "/delete/active_tasks"), ("POST", "/internal/force_merge"), ("POST", "/internal/partition/list"), ("GET", "/metrics"), ("GET", "/flags"), ("GET", "/select/vmui/"), ("GET", "/"), ] for method, path in refused: for label, args in (("no credential", ()), ("a caller's bearer", (f"-H 'Authorization: Bearer {AGENT_TOKEN}'",))): status, body = store_direct(path, f"-X {method}", *args, credential=False) assert status == 401, (method, path, label, status, body[:200]) # The same routes with the credential are answered by the store: its # select and metrics routes answer 200, the insert accepts a record and # the delete route is reached (the store runs without `-delete.enable`, # so it says so) instead of being refused with 401. status, body = store_direct("/select/logsql/query", "-X POST --data-urlencode 'query=switch'") assert status == 200 and "written before the switch" in body, (status, body[:200]) status, body = store_direct("/metrics") assert status == 200 and "vl_" in body, (status, body[:200]) status, body = store_direct("/insert/jsonline?_stream_fields=app", "-X POST --data-binary '{\"_msg\":\"written to the store directly\",\"app\":\"vm-test\"}'") assert status == 200, (status, body[:200]) status, body = store_direct("/delete/run_task", "-X POST") assert status != 401 and "disabled" in body, (status, body[:200]) # What stays open: the probes' route. assert store_direct("/health", credential=False)[0] == 200 # A wrong password is refused like none. vl_ip = kube(machine, f"get pod {vl_pod} -o jsonpath='{{.status.podIP}}'").strip() status = machine.execute(f"curl -sS -o /dev/null -w '%{{http_code}}' --user swarm-store:{'0' * 64} -X POST --data-urlencode 'query=switch' http://{vl_ip}:9428/select/logsql/query")[1] assert status.strip() == "401", status with subtest("the gateway sends the store's credential in place of the caller's bearer, and a gateway without it gets 401 from the store"): # The bearer cases above went through the gateway with the credential in # place. With the include file emptied, the caller's own bearer reaches # the store, which refuses it, although the responders still grant it. saved = machine.succeed(f"cat {STORE_CONF}") assert "proxy_set_header Authorization" in saved machine.succeed(f": > {STORE_CONF} && systemctl reload logs-gateway") machine.wait_until_succeeds("systemctl is-active logs-gateway", timeout=30) for _ in range(10): status, body = vl_query(AGENT_TOKEN, "switch") if status == 401: break time.sleep(1) assert status == 401, (status, body[:200]) # The unit writes the file again, and the same request is granted: the # control that the 401 is the missing credential. machine.succeed("systemctl restart swarm-bao-store-auth.service") store_credential_published() machine.succeed("systemctl reload logs-gateway") assert machine.succeed(f"cat {STORE_CONF}") == saved wait_for_record(AGENT_TOKEN, "switch", "written before the switch") 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") # The peer pod can dial out, which is the control that the dials below # are refused by the stores' policies. machine.succeed(dials(router_pid, "${bridgeIp}", 9999)) for ip, port in ((vl_ip, 9428), (auth_ip, 8081), (auth_ip, 8082)): machine.succeed(f"timeout 5 bash -c ' str: return f"ip netns exec agent timeout 5 bash -c ' str: return kube(machine, f"get pod {name} -o jsonpath='{{.status.podIP}}'").strip() peers = {name: pod_pid(name) for name in (SERVICE, CLASSIFIER, LOGIN)} coredns_pid = pod_pid("coredns") health = { SERVICE: (pod_ip(service_pods(SERVICE)[0].removeprefix("pod/")), [8080]), STT: (stt_ip, [8080]), CLASSIFIER: (pod_ip(DAEMON_PODS[CLASSIFIER]), [8080]), LOGIN: (pod_ip(DAEMON_PODS[LOGIN]), [8080]), LOGS_AUTH: (auth_ip, [8080, 8083]), } health_pids = {name: pod_pid(name) for name in (SERVICE, STT, CLASSIFIER, LOGIN, LOGS_AUTH)} # The listeners the pods open besides the health ones, which are on the # pods' loopback: the store and the responders' own. listeners = { VL: (vl_ip, [9428]), LOGS_AUTH: (auth_ip, [8081, 8082]), } def sources(target: str): peer = next(pid for name, pid in peers.items() if name != target) return { "a pod of kube-system": lambda ip, port: dials(coredns_pid, ip, port), "a peer pod of the namespace": lambda ip, port: dials(peer, ip, port), "a client of the hive bridge": agent_dials, } # Each health listener answers on its pod's loopback, refuses the node, # and none of the three sources reaches it. The listeners below are the # control that these dials refuse only a port nothing serves to them: # the node reaches those and the same sources do not. for name, (ip, ports) in health.items(): for port in ports: loopback_only(health_pids[name], ip, port) for source, dial in sources(name).items(): assert machine.execute(dial(ip, port))[0] != 0, (name, port, source) machine.succeed(f"curl -sf --max-time 5 http://{vl_ip}:9428/health") for name, (ip, ports) in listeners.items(): for port in ports: machine.succeed(f"timeout 5 bash -c ' tuple[int, str]: """One request to the metrics 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)} {METRICS_GATEWAY}{path}") body, _, code = out.rpartition("\n") return int(code or 0), body def vm_export(token: str, name: str) -> tuple[int, str]: """The series of one metric name, through the read API's export route, which no query offset hides recent samples from.""" return vm_request("/api/v1/export", token, f"--data-urlencode 'match[]={{__name__=~\"{name}.*\"}}'") def wait_for_series(token: str, name: str) -> None: """Exports until the response holds the series, for as long as the pod and the policy engine take to settle.""" deadline = time.monotonic() + 300 while True: status, body = vm_export(token, name) if status == 200 and name in body: return if time.monotonic() >= deadline: metrics_diagnostics(token) raise AssertionError((status, body)) time.sleep(3) def metrics_diagnostics(token: str) -> None: """What to read when the metrics gateway answers a bearer something other than what the store grants: the gateway's diagnostics, the store's own logs, both responders' Services and endpoints, and each responder asked directly with every bearer the test uses.""" gateway_diagnostics(token, METRICS_AUTH) print("=== metrics store diagnostics") for pod in service_pods(VM): print(f"--- {pod} logs") print(machine.execute(f"kubectl -n {NS} logs {pod} --tail=100 2>&1")[1]) print(f"--- {pod} previous logs") print(machine.execute(f"kubectl -n {NS} logs {pod} --previous --tail=100 2>&1")[1]) print("--- services and endpoints") print(machine.execute(f"kubectl -n {NS} get svc,endpoints {VM} {METRICS_AUTH} swarm-metrics-grafana-auth -o wide 2>&1")[1]) print("--- the store's counters of the push route, through the gateway") _, body = vm_request("/metrics", None) print("\n".join(line for line in body.splitlines() if "opentelemetry" in line and not line.startswith("#"))) if machine.execute("test -f /tmp/otlp-metrics.bin")[0] == 0: vm_ip = kube(machine, f"get pods --selector app.kubernetes.io/name={VM} -o jsonpath='{{.items[0].status.podIP}}'").strip() print("--- the same request, sent to the store's pod directly") print( machine.execute( f"curl -sS -m 10 -w '\\nstatus %{{http_code}}\\n' -X POST -H 'Content-Type: application/x-protobuf' --data-binary @/tmp/otlp-metrics.bin http://{vm_ip}:8428/opentelemetry/api/v1/push 2>&1; " f"curl -s http://{vm_ip}:8428/metrics | grep opentelemetry | grep -v '^#'" )[1] ) bearers = { "agent": AGENT_TOKEN, "agent without the grant": f"swarm-agent.{OTHER_AGENT}.{AGENT_SECRETS[OTHER_AGENT]}", "agent with the logs grant only": f"swarm-agent.{LOGS_ONLY_AGENT}.{AGENT_SECRETS[LOGS_ONLY_AGENT]}", "Grafana": GRAFANA_BEARER, } ip = kube(machine, f"get pods --selector app.kubernetes.io/name={METRICS_AUTH} -o jsonpath='{{.items[0].status.podIP}}'").strip() for port in (8083, 8084): for who, bearer in bearers.items(): print( f"--- port {port}, {who}: " + machine.execute(f"curl -sS -m 10 -o /dev/null -w '%{{http_code}}' -H 'Authorization: Bearer {bearer}' http://{ip}:{port}/ 2>&1")[1] ) def metrics_expect(label: str, got: int, want: int, token: str = "") -> None: if got != want: metrics_diagnostics(token or AGENT_TOKEN) raise AssertionError(f"{label}: the gateway answered {got}, wanted {want}") with subtest("an agent's bearer reads the sample written before the switch through the gateway, and the other bearers are granted or refused as the store says"): wait_for_series(AGENT_TOKEN, "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 ((METRICS_AUTH, "8083"), ("swarm-metrics-grafana-auth", "8084")): 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. metrics_expect("an agent without the grant", vm_export(f"swarm-agent.{OTHER_AGENT}.{AGENT_SECRETS[OTHER_AGENT]}", "written_before_the_switch")[0], 403) metrics_expect("a wrong agent secret", vm_export(f"swarm-agent.{AGENT}.{'0' * 32}", "written_before_the_switch")[0], 401) # The surfaces are separate grants: this agent may read the log store and not the metrics store. scout = f"swarm-agent.{LOGS_ONLY_AGENT}.{AGENT_SECRETS[LOGS_ONLY_AGENT]}" metrics_expect("an agent with the logs grant only, on the metrics store", vm_export(scout, "written_before_the_switch")[0], 403) metrics_expect("the same agent, on the log store", vl_query(scout, "switch")[0], 200) # Grafana's bearer goes to the second responder of the same pod. status, body = vm_export(GRAFANA_BEARER, "written_before_the_switch") if status != 200 or "written_before_the_switch" not in body: metrics_diagnostics(GRAFANA_BEARER) raise AssertionError((status, body)) metrics_expect("a wrong Grafana bearer", vm_export("0" * 64, "written_before_the_switch")[0], 401) with subtest("the gateway refuses the store's write and admin routes with a bearer that reads, and a sample pushed to the ingest route and the store's own metrics come through it, and a restarted pod still holds both samples"): import base64 import struct # The store serves these on the listener its queries use; only the # locations the module names reach it. for path in ("/api/v1/admin/tsdb/delete_series", "/api/v1/import/prometheus"): metrics_expect(path, vm_request(path, GRAFANA_BEARER, "-X POST --data-binary 'x 1'")[0], 403) metrics_expect("the store's export route, as the control for the refusals above", vm_export(GRAFANA_BEARER, "written_before_the_switch")[0], 200) 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 metrics request with one gauge point: the name (field 1), a # gauge (field 5) of one point with its time (field 3, fixed64) and # value (field 4, double). now_ns = int(machine.succeed("date +%s%N")) point = varint(3 << 3 | 1) + now_ns.to_bytes(8, "little") + varint(4 << 3 | 1) + struct.pack(" /tmp/otlp-metrics.bin") status, body = vm_request( "/opentelemetry/api/v1/push", None, "-X POST -H 'Content-Type: application/x-protobuf' --data-binary @/tmp/otlp-metrics.bin" ) metrics_expect("the ingest route", status, 200) # The sample's arrival is what counts: the series is read back below, and # the store's counters are printed if it never shows. wait_for_series(AGENT_TOKEN, "written_through_the_gateway") kube(machine, f"delete pod {vm_pod} --wait=true", timeout=120) vm_pod = wait_pod_ready(VM) wait_for_series(AGENT_TOKEN, "written_before_the_switch") wait_for_series(AGENT_TOKEN, "written_through_the_gateway") VM_PASSWORD = f"{STORE_AUTH_DIR}/victoriametrics.password" VM_CONF = f"{STORE_AUTH_DIR}/victoriametrics.conf" def vm_direct(path: str, *args: str, credential: bool = True) -> tuple[int, str]: """One request from the node to the metrics store's pod address, past the gateway.""" vm_ip = kube(machine, f"get pod {vm_pod} -o jsonpath='{{.status.podIP}}'").strip() auth = f'--user "swarm-store:$(cat {VM_PASSWORD})" ' if credential else "" _, out = machine.execute(f"curl -sS --max-time 20 -w '\\n%{{http_code}}' {auth}{' '.join(args)} 'http://{vm_ip}:8428{path}'") body, _, code = out.rpartition("\n") return int(code or 0), body with subtest("the metrics store refuses every route without its credential from the node itself, past the gateway, and takes the credential the host keeps in the secret store"): stored = as_root("bao kv get -mount=secret -field=value swarm/services/victoriametrics/store-auth").strip() assert len(stored) == 64, "the unit stores 64 hex digits" # Each store has a credential of its own. assert stored != as_root("bao kv get -mount=secret -field=value swarm/services/victorialogs/store-auth").strip() assert machine.succeed(f"cat {VM_PASSWORD}").strip() == stored secret = machine.succeed(f"kubectl -n {NS} get secret swarm-victoriametrics-credentials -o jsonpath='{{.data.store-auth}}' | base64 -d").strip() assert secret == stored assert machine.succeed(f"stat -c '%a %U %G' {VM_PASSWORD} {VM_CONF}").split("\n")[:2] == ["600 root root", "600 root root"] assert stored not in machine.succeed(f"cat {MANIFESTS}/{VM}.yaml"), "the manifest holds no credential" # Writes, imports, queries, exports, the routes that delete and # snapshot, the config and reload routes, the store's own metrics and # the UI answer 401 with no credential and with a caller's bearer. refused = [ ("POST", "/api/v1/write"), ("POST", "/api/v1/import"), ("POST", "/api/v1/import/prometheus"), ("POST", "/opentelemetry/api/v1/push"), ("POST", "/influx/write"), ("GET", "/api/v1/query?query=up"), ("GET", "/api/v1/export?match[]={__name__!=\"\"}"), ("POST", "/api/v1/admin/tsdb/delete_series?match[]={__name__!=\"\"}"), ("POST", "/api/v1/admin/tsdb/snapshot"), ("GET", "/snapshot/create"), ("POST", "/internal/force_merge"), ("POST", "/internal/resetRollupResultCache"), ("GET", "/config"), ("GET", "/-/reload"), ("GET", "/metrics"), ("GET", "/flags"), ("GET", "/vmui/"), ("GET", "/"), ] for method, path in refused: for label, args in (("no credential", ()), ("a caller's bearer", (f"-H 'Authorization: Bearer {AGENT_TOKEN}'",))): status, body = vm_direct(path, f"-g -X {method}", *args, credential=False) assert status == 401, (method, path, label, status, body[:200]) # With the credential the store answers: a query and an export read the # sample written before the switch, the store's metrics come back, and # a delete that matches nothing is accepted (204) instead of refused. status, body = vm_direct("/api/v1/export", "-g --data-urlencode 'match[]={__name__=\"written_before_the_switch\"}'") assert status == 200 and "written_before_the_switch" in body, (status, body[:200]) status, body = vm_direct("/api/v1/query?query=vm_app_version") assert status == 200 and "success" in body, (status, body[:200]) status, body = vm_direct("/metrics") assert status == 200 and "vm_" in body, (status, body[:200]) status, body = vm_direct("/api/v1/admin/tsdb/delete_series", "-g -X POST --data-urlencode 'match[]={__name__=\"no_such_series_in_this_store\"}'") assert status == 204, (status, body[:200]) assert vm_direct("/health", credential=False)[0] == 200 vm_ip = kube(machine, f"get pod {vm_pod} -o jsonpath='{{.status.podIP}}'").strip() status = machine.execute(f"curl -sS -o /dev/null -w '%{{http_code}}' --user swarm-store:{'0' * 64} 'http://{vm_ip}:8428/api/v1/query?query=up'")[1] assert status.strip() == "401", status with subtest("the gateway sends the metrics store's credential in place of the caller's bearer, and a gateway without it gets 401 from the store"): saved = machine.succeed(f"cat {VM_CONF}") assert "proxy_set_header Authorization" in saved and saved != machine.succeed(f"cat {STORE_CONF}") machine.succeed(f": > {VM_CONF} && systemctl reload logs-gateway") machine.wait_until_succeeds("systemctl is-active logs-gateway", timeout=30) for _ in range(10): status, body = vm_export(AGENT_TOKEN, "written_before_the_switch") if status == 401: break time.sleep(1) assert status == 401, (status, body[:200]) machine.succeed("systemctl restart swarm-bao-store-auth.service") store_credential_published() machine.succeed("systemctl reload logs-gateway") assert machine.succeed(f"cat {VM_CONF}") == saved wait_for_series(AGENT_TOKEN, "written_before_the_switch") with subtest("only the node reaches the metrics store's pods, and the responders' pod reaches the store's pod listener and no other port of the host"): vm_ip = kube(machine, f"get pod {vm_pod} -o jsonpath='{{.status.podIP}}'").strip() metrics_auth_ip = kube(machine, f"get pod {metrics_auth_pod} -o jsonpath='{{.status.podIP}}'").strip() machine.succeed(f"curl -sf --max-time 5 http://{vm_ip}:8428/health") # The peer pod can dial out, which is the control that the dials below # are refused by the stores' policies. machine.succeed(dials(router_pid, "${bridgeIp}", 9999)) for ip, port in ((vm_ip, 8428), (metrics_auth_ip, 8083), (metrics_auth_ip, 8084)): machine.succeed(f"timeout 5 bash -c '= 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 other_secrets() == set(), other_secrets() # 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 ''; }