diff --git a/.forgejo/workflows/vm-nightly.yml b/.forgejo/workflows/vm-nightly.yml index ca3170e3d..04e2fcb85 100644 --- a/.forgejo/workflows/vm-nightly.yml +++ b/.forgejo/workflows/vm-nightly.yml @@ -58,6 +58,7 @@ jobs: - k8s-collector-switch - k8s-bao-login - k8s-runtime-switch + - k8s-controller-switch steps: - uses: actions/checkout@v3 if: inputs.test == '' || inputs.test == matrix.test diff --git a/nix/vm-test-typecheck.nix b/nix/vm-test-typecheck.nix index 7e34f7039..18b9f964b 100644 --- a/nix/vm-test-typecheck.nix +++ b/nix/vm-test-typecheck.nix @@ -140,6 +140,7 @@ let k8s-collector-switch k8s-bao-login k8s-runtime-switch + k8s-controller-switch ; }; in diff --git a/nix/vm-tests.nix b/nix/vm-tests.nix index 9f03c3548..c0826377f 100644 --- a/nix/vm-tests.nix +++ b/nix/vm-tests.nix @@ -20,5 +20,6 @@ k8s-collector-switch = import ./vm-tests/k8s-collector-switch.nix { inherit pkgs self; }; k8s-bao-login = import ./vm-tests/k8s-bao-login.nix { inherit pkgs self; }; k8s-runtime-switch = import ./vm-tests/k8s-runtime-switch.nix { inherit pkgs self; }; + k8s-controller-switch = import ./vm-tests/k8s-controller-switch.nix { inherit pkgs self; }; semi-spread = import ./vm-tests/semi-spread.nix { inherit pkgs self; }; } diff --git a/nix/vm-tests/k8s-controller-switch.nix b/nix/vm-tests/k8s-controller-switch.nix new file mode 100644 index 000000000..9bba8c784 --- /dev/null +++ b/nix/vm-tests/k8s-controller-switch.nix @@ -0,0 +1,620 @@ +# `vmTests..k8s-controller-switch`: swarm-controller moves between its +# host unit and the host's cluster (`services.hyperhive.deploy.swarm-controller.runtime`), +# against the real secret store, a real queue and the real TCP listener. The +# host boots with the controller on the host; the `k8s` specialisation has it in +# the cluster, and `k8s-rev` is that with another hyperhive rev. The script +# switches to the cluster, to the new rev, and back, and asserts that: +# +# - exactly one controller runs at each step: by the order of the switch's own +# timestamps and by a sampler that looks every 200 ms; +# - the pod is Ready on the health listener, which depends on its store login +# and its queue connection; its listener's leaf is the one its init container +# issued from the store with its ServiceAccount token, valid as the listener's +# name against the hive's root, and a handshake with no client leaf is refused; +# - the gateway's own controller location, rendered by the module for each +# runtime and run here in a nginx of its own, reaches the controller: on the +# host by name, in the cluster by the node's address, verifying the leaf as +# the name; the controller answers an unsigned webhook 401 both times; +# - a changed hyperhive rev rolls the Deployment, and the state volume is the +# one the first pod had; +# - the switch back leaves no pod, Deployment or AddOn, and the host unit +# starts after the prune unit. +# +# The queue is a plain nats-server with TLS and one stub is the token endpoint +# and the forge; they replace services that stay host-run and unchanged. The +# gateway's vhost needs a login service the VM lacks, so only the controller's +# locations run, from the module's own text. The test makes the hive's CA and +# the leaf of every name at boot. +{ pkgs, self }: +let + inherit (pkgs) lib; + + bridgeIp = "10.42.0.1"; + baoName = "bao.t.local"; + baoPort = 8200; + podPort = 8208; + natsName = "nats.t.local"; + natsPort = 4222; + authName = "auth.t.local"; + forgeName = "forge.t.local"; + controllerName = "controller.t.local"; + controllerPort = 9443; + namespace = "hyperhive"; + service = "swarm-controller"; + prune = "${service}-k8s-prune"; + hostUnit = "${service}.service"; + pkiDir = "/var/lib/test-ca"; + tlsDir = "/var/lib/hive-tls"; + controllerSecretLeaf = "swarm/controller/swarm-controller/oidc/client"; + revA = lib.fixedWidthString 40 "a" ""; + revB = lib.fixedWidthString 40 "b" ""; + overlapLog = "/var/log/overlap.log"; + tokenLog = "/var/log/stub-token.log"; + + # The identity provider and the forge, 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 answers 404. + tokenStub = pkgs.writeText "token-stub.py" '' + import base64 + import http.server + import json + import secrets + import ssl + + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", 0))) + auth = self.headers.get("Authorization", "") + who = base64.b64decode(auth.removeprefix("Basic ")).decode() if auth.startswith("Basic ") else "none" + with open("${tokenLog}", "a") as log: + log.write(f"{self.path.split('?')[0]} {who}\n") + body = json.dumps({"access_token": secrets.token_hex(16), "token_type": "Bearer", "expires_in": 3600}).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_GET(self): + 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" + } + ''; + + # Looks every 200 ms at whether the controller's host unit runs and how many + # pods the cluster holds for it, a terminating pod included. + sampler = pkgs.writeShellScript "overlap-sampler" '' + while true; do + state="$(systemctl is-active ${hostUnit} || true)" + pods="$(kubectl --namespace ${namespace} get pods --selector app.kubernetes.io/name=${service} --no-headers 2>/dev/null | wc -l)" + echo "$(date +%s.%N) ${service} host=$state pods=$pods" >> ${overlapLog} + sleep 0.2 + done + ''; + + # One nginx per runtime with the controller's two locations as the module + # renders them for that runtime: the upstream, the client leaf and the + # verification of the listener's name. Nothing else of the vhost, which + # answers through a login service. + gatewayConf = + cfg: + let + locations = cfg.services.nginx.virtualHosts."t.local".locations; + in + pkgs.writeText "gateway.conf" '' + pid /run/gateway-test/nginx.pid; + error_log stderr; + events {} + http { + access_log off; + server { + listen 127.0.0.1:18080; + location /webhook/forge/ { + proxy_pass ${locations."/webhook/forge/".proxyPass}; + ${locations."/webhook/forge/".extraConfig} + } + } + } + ''; + gatewayUnit = conf: { + after = [ "network.target" ]; + serviceConfig = { + RuntimeDirectory = "gateway-test"; + ExecStart = "${pkgs.nginx}/bin/nginx -c ${conf} -g 'daemon off;'"; + }; + }; +in +pkgs.testers.runNixOSTest { + name = "k8s-controller-switch"; + + # 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 = 2400; + + nodes.machine = + { config, ... }: + { + imports = [ self.nixosModules.default ]; + + services.hyperhive = { + deploy.k8s.enable = true; + network.enable = true; + network.bridgeIp = bridgeIp; + deploy.bao.enable = true; + deploy.bao.seal = "shamir"; + deploy.bao.bootstrapTokenFile = "/var/lib/swarm-bao-bootstrap/grant.token"; + deploy.swarm-controller.enable = true; + deploy.hive-controller.hiveName = "h1"; + deploy.hive-controller.hyperhiveRev = revA; + swarm.domain = "t.local"; + swarm.forge.domain = forgeName; + swarm.bao.domain = baoName; + swarm.bao.port = baoPort; + swarm.controller.tcp = { + enable = true; + domain = controllerName; + }; + swarm.hives.h1.domain = "h1.t.local"; + # The queue, the identity provider and the forge 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 + ]; + }; + system.stateVersion = "25.11"; + + specialisation.k8s.configuration.services.hyperhive.deploy.swarm-controller.runtime = "k8s"; + specialisation.k8s-rev.configuration.services.hyperhive.deploy = { + swarm-controller.runtime = "k8s"; + hive-controller.hyperhiveRev = lib.mkForce revB; + }; + + # 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-runtime-switch` does. + services.nginx.enable = lib.mkForce false; + users.groups.nginx = { }; + networking.hosts = { + "${bridgeIp}" = [ + baoName + natsName + authName + forgeName + ]; + # The controller on the host listens on every address, and the gateway + # dials it by name. + "127.0.0.1" = [ controllerName ]; + }; + 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 text is the active configuration's own, so after a switch the unit dials + # what that configuration renders. + systemd.services.gateway = gatewayUnit (gatewayConf config); + + # The hive's CA, and one leaf for the names of the queue, the identity + # provider and the forge, 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}\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 + if [ -s ${tlsDir}/swarm-services-root.pem ]; then + cat ${tlsDir}/swarm-services-root.pem >> ${tlsDir}/trust-bundle.pem + fi + 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; + }; + }; + + systemd.services.overlap-sampler = { + path = [ + pkgs.kubectl + pkgs.coreutils + pkgs.systemd + ]; + environment.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml"; + serviceConfig.ExecStart = sampler; + }; + + environment.systemPackages = [ + pkgs.kubectl + pkgs.curl + pkgs.jq + pkgs.openssl + pkgs.natscli + ]; + environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml"; + 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" + ]; + }; + + virtualisation = { + memorySize = 6144; + cores = 4; + diskSize = 12288; + }; + }; + + testScript = builtins.readFile ./lib/k3s.py + '' + INIT = "/root/bao-init.json" + NS = "${namespace}" + SERVICE = "${service}" + HOST_UNIT = "${hostUnit}" + PRUNE = "${prune}" + NAME = "${controllerName}" + PORT = ${toString controllerPort} + NODE_ADDRESS = "${bridgeIp}" + SOCKET = "/run/swarm-controller/controller.sock" + MANIFESTS = "/var/lib/rancher/k3s/server/manifests" + SERVICES_ROOT = "${tlsDir}/swarm-services-root.pem" + GATEWAY_CERT = "${tlsDir}/controller-client.pem" + GATEWAY_KEY = "${tlsDir}/controller-client-key.pem" + WEBHOOK = "http://127.0.0.1:18080/webhook/forge/pull_request" + + + 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 pods() -> list[str]: + return machine.succeed(f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o name || true").split() + + + def host_state() -> str: + return machine.execute(f"systemctl is-active {HOST_UNIT}")[1].strip() + + + def stopped_at(unit: str) -> int: + return int(machine.succeed(f"date -d \"$(systemctl show -p InactiveEnterTimestamp --value {unit})\" +%s")) + + + def created_at_of(pod_name: str) -> int: + stamp = machine.succeed(f"kubectl -n {NS} get pod {pod_name} -o jsonpath='{{.metadata.creationTimestamp}}'") + return int(machine.succeed(f"date -d \"{stamp}\" +%s")) + + + def wait_pod_ready(not_uid: str = "", timeout: int = 600) -> str: + """The name of the Ready pod of the controller that is not terminating + and has a uid other than `not_uid`.""" + live = ( + f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o json " + f"| jq -r '.items[] | select(.metadata.deletionTimestamp == null and .metadata.uid != \"{not_uid}\") | .metadata.name'" + ) + machine.wait_until_succeeds(f"{live} | grep -q .", timeout=timeout) + name = machine.succeed(live).split()[0] + 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]) + for container in ("tls-issue", "tls-renew", SERVICE): + print(machine.execute(f"kubectl -n {NS} logs {name} -c {container} --tail=60")[1]) + raise + return name + + + def switch(target: str) -> str: + """Switches to `target`. Units of this host that fail for reasons of + their own make the exit status 4; the units the switch is about must + not be among them.""" + status, out = machine.execute(f"{target}/bin/switch-to-configuration test 2>&1") + print(out) + assert status in (0, 4), out + failed = next((line for line in out.splitlines() if "the following units failed" in line), "") + ours = [HOST_UNIT, f"{PRUNE}.service", "hyperhive-k8s-ca-trust.service", "k3s.service"] + assert not any(unit in failed for unit in ours), failed + return out + + + def gateway(unit: str) -> int: + """The status the gateway's controller location answers an unsigned + webhook with, under `unit`.""" + machine.succeed(f"systemctl restart {unit}") + machine.wait_until_succeeds("curl -s -o /dev/null http://127.0.0.1:18080/", timeout=30) + status = int(machine.succeed(f"curl -s -o /dev/null -w '%{{http_code}}' -X POST {WEBHOOK}")) + machine.succeed(f"systemctl stop {unit}") + return status + + + def handshake(address: str, *client: str) -> str: + """`openssl s_client` to the listener at `address`, dialled for the + listener's name, answering what it prints.""" + return machine.execute( + f"echo | openssl s_client -connect {address}:{PORT} -servername {NAME} " + f"-CAfile {SERVICES_ROOT} -verify_hostname {NAME} -verify_return_error {' '.join(client)} 2>&1" + )[1] + + + with subtest("the node is Ready and holds every image"): + wait_node_ready(machine, timeout=300) + 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}") + machine.succeed(f"bao operator unseal \"$(jq -r '.unseal_keys_b64[0]' {INIT})\"") + machine.wait_until_succeeds("bao status", timeout=120) + 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 controller's policy and role, the listener's roles 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"]) + 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) + machine.succeed(f"bao operator unseal \"$(jq -r '.unseal_keys_b64[0]' {INIT})\"") + machine.wait_until_succeeds("bao status", timeout=120) + for unit in ["swarm-bao-controller-policy", "swarm-bao-services-issuer-policy", "swarm-bao-k8s-jwt-policy"]: + settle(f'[ "$(systemctl is-active {unit}.service)" = active ]', 900, [f"{unit}.service"]) + machine.wait_until_succeeds( + "journalctl -u swarm-bao-k8s-jwt-policy --no-pager | grep -F 'Success! Data written to: auth/jwt-k8s/config'", + timeout=300, + ) + # The controller's queue client secret, 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 ${controllerSecretLeaf} value={SECRET}") + + with subtest("the queue and the token stub run"): + 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( + "nats --server tls://${natsName}:${toString natsPort} --tlsca ${pkiDir}/ca.pem account info", timeout=120 + ) + machine.succeed("systemctl start overlap-sampler.service") + + with subtest("the gateway's certificates exist: the store's services root, and the gateway's client leaf for the listener"): + for unit in ["swarm-services-cert.service", "swarm-controller-gateway-client.service"]: + machine.succeed(f"systemctl reset-failed {unit} || true") + machine.succeed(f"systemctl restart --no-block {unit}") + settle(f"test -s {SERVICES_ROOT} && test -s {GATEWAY_CERT} && test -s {GATEWAY_KEY}", 600, ["swarm-services-cert.service", "swarm-controller-gateway-client.service"]) + machine.succeed(f"openssl verify -CAfile {SERVICES_ROOT} -purpose sslclient {GATEWAY_CERT}") + + with subtest("on the host, the controller runs, is ready on its socket, serves its listener and answers the gateway, and the cluster holds none of it"): + machine.succeed("systemctl reset-failed swarm-controller-tls.service || true") + machine.succeed("systemctl restart --no-block swarm-controller-tls.service") + settle(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", 600, [HOST_UNIT, "swarm-controller-tls.service"]) + settle(f"curl -sf --unix-socket {SOCKET} http://x/readyz", 300, [HOST_UNIT]) + assert machine.succeed(f"systemctl is-active {PRUNE}.service").strip() == "active" + assert pods() == [], pods() + assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml")[0] != 0 + assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0 + # The controller's own listener presents the leaf the host unit issued. + settle(f"echo | openssl s_client -connect 127.0.0.1:{PORT} -servername {NAME} -CAfile {SERVICES_ROOT} -verify_hostname {NAME} -verify_return_error -cert {GATEWAY_CERT} -key {GATEWAY_KEY} 2>&1 | grep -F 'Verification: OK'", 120, [HOST_UNIT]) + assert gateway("gateway.service") == 401 + machine.wait_until_succeeds(f"grep -F '/api/oidc/token swarm-controller:{SECRET}' ${tokenLog}", timeout=120) + + with subtest("the switch to the cluster stops the unit before it applies the pod"): + TOKENS = int(machine.succeed(f"grep -c '/api/oidc/token swarm-controller:{SECRET}' ${tokenLog}")) + out = switch("/run/booted-system/specialisation/k8s") + assert HOST_UNIT in out and "stopping the following units" in out, out + assert host_state() == "inactive", host_state() + # The unit is disabled, so the host cannot start it: a copy beside the pod would break the one-copy rule. + assert "ExecStart" not in machine.execute(f"systemctl cat {HOST_UNIT}")[1] + machine.fail(f"systemctl start {HOST_UNIT}") + assert "ExecStart" not in machine.execute("systemctl cat swarm-controller-tls.service")[1] + machine.fail("systemctl start swarm-controller-tls.service") + machine.succeed(f"test -L {MANIFESTS}/{SERVICE}.yaml") + pod_name = wait_pod_ready() + assert stopped_at(HOST_UNIT) <= created_at_of(pod_name) + machine.wait_until_succeeds(f"[ \"$(grep -c '/api/oidc/token swarm-controller:{SECRET}' ${tokenLog})\" -gt {TOKENS} ]", timeout=300) + + with subtest("the pod is Ready on its health listener, has the volumes and ports the module renders, and no Secret"): + spec = pod(machine, pod_name)["spec"] + main = next(c for c in spec["containers"] if c["name"] == SERVICE) + probe = main["readinessProbe"]["httpGet"] + assert probe["path"] == "/readyz", probe + api = next(p for p in main["ports"] if p["name"] == "api") + assert api["hostPort"] == PORT and api["hostIP"] == NODE_ADDRESS, api + assert [c["name"] for c in spec["initContainers"]] == ["tls-issue"], spec["initContainers"] + assert "tls-renew" in [c["name"] for c in spec["containers"]] + assert not any("secret" in v for v in spec["volumes"]), spec["volumes"] + env = {e["name"]: e.get("value") for e in main["env"]} + assert env["BAO_AUTH"] == "jwt" and env["BAO_JWT_ROLE"] == SERVICE, env + assert "BAO_CLIENT_CERT" not in env, env + claim = json.loads(kube(machine, f"get pvc {SERVICE}-state -o json")) + assert claim["status"]["phase"] == "Bound", claim + STATE_VOLUME = claim["metadata"]["uid"] + # The listener's key is in memory: the pod's `tls` volume is a tmpfs of + # its own, which the kubelet mounts on the node. The `runtime` volume, + # a plain emptyDir, has no mount of its own: the lookup's control. + uid = pod(machine, pod_name)["metadata"]["uid"] + mount = f"pods/{uid}/volumes/kubernetes.io~empty-dir" + fs = machine.succeed(f"grep -F '{mount}/tls ' /proc/mounts | cut -d' ' -f3").strip() + assert fs == "tmpfs", fs + machine.fail(f"grep -F '{mount}/runtime ' /proc/mounts") + + with subtest("the pod's listener presents the leaf its own init container issued, valid as the listener's name against the hive's root, and refuses a client with no leaf"): + issued = machine.succeed(f"kubectl -n {NS} logs {pod_name} -c tls-issue") + assert "requesting the controller's listener leaf for {NAME} from the store".format(NAME=NAME) in issued, issued + good = handshake(NODE_ADDRESS, f"-cert {GATEWAY_CERT} -key {GATEWAY_KEY}") + assert "Verification: OK" in good, good + refused = machine.execute( + f"curl -s -o /dev/null --cacert {SERVICES_ROOT} --resolve {NAME}:{PORT}:{NODE_ADDRESS} https://{NAME}:{PORT}/api/openapi.json" + )[0] + assert refused != 0, "a client with no leaf was served" + # The renewal container runs the same script and finds the leaf valid. + machine.wait_until_succeeds( + f"kubectl -n {NS} logs {pod_name} -c tls-renew | grep -F 'controller listener leaf valid for {NAME}'", + timeout=120, + ) + + with subtest("the gateway's controller location reaches the pod by the node's address and verifies it as the listener's name"): + assert gateway("gateway.service") == 401 + api_status = int(machine.succeed( + f"curl -s -o /dev/null -w '%{{http_code}}' --cacert {SERVICES_ROOT} --resolve {NAME}:{PORT}:{NODE_ADDRESS} " + f"--cert {GATEWAY_CERT} --key {GATEWAY_KEY} https://{NAME}:{PORT}/api/openapi.json" + )) + assert api_status == 200, api_status + + with subtest("a changed rev rolls the Deployment, the old pod is gone first, and the state volume is the same"): + old_uid = pod(machine, pod_name)["metadata"]["uid"] + old_annotation = pod(machine, pod_name)["metadata"]["annotations"]["checksum/etc"] + switch("/run/booted-system/specialisation/k8s-rev") + machine.wait_until_succeeds( + f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o json " + f"| jq -e '[.items[].metadata.uid] | map(select(. != \"{old_uid}\")) | length >= 1'", + timeout=300, + ) + new_pod = wait_pod_ready(old_uid) + new = pod(machine, new_pod) + assert new["metadata"]["uid"] != old_uid + assert new["metadata"]["annotations"]["checksum/etc"] != old_annotation, new["metadata"]["annotations"] + assert machine.execute(f"kubectl -n {NS} get pod {pod_name}")[0] != 0 + rev = machine.succeed(f"kubectl -n {NS} get configmap {SERVICE}-etc -o json | jq -r '.data[]'") + assert "${revB}" in rev, rev + assert json.loads(kube(machine, f"get pvc {SERVICE}-state -o json"))["metadata"]["uid"] == STATE_VOLUME + assert len(pods()) == 1, pods() + + with subtest("the switch back removes the Deployment, pod and AddOn before the unit starts"): + switch("/run/booted-system") + machine.wait_until_succeeds(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", timeout=600) + assert pods() == [], pods() + assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0 + assert machine.execute(f"kubectl -n kube-system get addons.k3s.cattle.io {SERVICE}")[0] != 0 + assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml")[0] != 0 + assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml.pruning")[0] != 0 + pruned = int(machine.succeed(f"systemctl show -p ExecMainExitTimestampMonotonic --value {PRUNE}.service")) + started = int(machine.succeed(f"systemctl show -p InactiveExitTimestampMonotonic --value {HOST_UNIT}")) + assert 0 < pruned <= started, (pruned, started) + requires = machine.succeed(f"systemctl show -p Requires --value {HOST_UNIT}") + assert f"{PRUNE}.service" in requires, requires + assert json.loads(kube(machine, f"get pvc {SERVICE}-state -o json"))["metadata"]["uid"] == STATE_VOLUME + settle(f"curl -sf --unix-socket {SOCKET} http://x/readyz", 300, [HOST_UNIT]) + assert gateway("gateway.service") == 401 + + with subtest("no moment of any switch had the unit and a pod together"): + machine.succeed("systemctl stop overlap-sampler.service") + lines = machine.succeed("cat ${overlapLog}").splitlines() + host_up = {"active", "activating", "deactivating", "reloading"} + samples = [ + (fields[2].removeprefix("host="), int(fields[3].removeprefix("pods="))) + for fields in (line.split() for line in lines) + if len(fields) == 4 + ] + both = [s for s in samples if s[0] in host_up and s[1] > 0] + assert not both, both[:5] + # The controls: the sampler saw the unit alone and a pod alone. + assert any(s[0] in host_up and s[1] == 0 for s in samples), lines[:5] + assert any(s[0] not in host_up and s[1] > 0 for s in samples), lines[:5] + print(f"{SERVICE}: {len(samples)} samples, none with both") + ''; +}