# `vmTests..k8s-nats`: the swarm queue and its auth callout run as a pod in # the host's cluster, against the real secret store, on the JetStream store # directory the host keeps (`/var/lib/nixos-containers/swarm-nats/var/lib/nats`), # which is a static volume. `k8s-open` adds `deploy.nats.openFirewall`. The # script asserts that: # # - the host has no container, delivery unit or prune unit for the queue, and one # server and one responder run, as the pod; # - the pod is Ready by its exec probe on the server's monitor, holds the leaf # and the callout config as init containers, and has no `hostPort`: the client # port is a LoadBalancer Service with no node port, bound by the load balancer; # - with the egress intercept on, a client on the hive's bridge reaches the # queue by name through the published port and not by the pod's address or # the node's, and the responder in the pod admits the router's token; # - the port is closed to a host outside the node, and open with `openFirewall`, # where a second node dials it by name and verifies the name. The exporter # answers the host only, by its Service's name; # - a stream written before the pod is deleted is read after, and the files the # pod writes are in the host directory the volume is on. # # One stub is the identity provider: it introspects the test's one token as the # notification router, whose permissions create and fill a stream. The test # makes the hive's CA and the stub's leaf; the queue's own leaf is the store's. { pkgs, self }: let inherit (pkgs) lib; bridgeIp = "10.42.0.1"; nodeIp = "192.168.1.10"; outsideIp = "192.168.1.20"; agentIp = "10.42.0.200"; baoName = "bao.t.local"; baoPort = 8200; natsName = "nats.t.local"; natsPort = 4222; metricsPort = 7777; authName = "auth.t.local"; controlPort = 9999; namespace = "hyperhive"; service = "swarm-nats"; prune = "${service}-k8s-prune"; hostUnit = "container@${service}.service"; pkiDir = "/var/lib/test-ca"; tlsDir = "/var/lib/hive-tls"; oidcLeaf = "swarm/services/${service}/oidc/client"; routerToken = "test-router-token"; tokenLog = "/var/log/stub-token.log"; # The identity provider, by name. The token endpoint answers every # client-credentials request with a token. The introspection endpoint # answers `active` for the test's one token, as the notification router, # and records the client id and secret it was asked with. tokenStub = pkgs.writeText "token-stub.py" '' import base64 import http.server import json import secrets import ssl import time import urllib.parse 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))).decode() auth = self.headers.get("Authorization", "") who = base64.b64decode(auth.removeprefix("Basic ")).decode() if auth.startswith("Basic ") else "none" path = self.path.split("?")[0] with open("${tokenLog}", "a") as log: log.write(f"{path} {who}\n") if path.endswith("/introspection"): token = urllib.parse.parse_qs(raw).get("token", [""])[0] if token == "${routerToken}": self.reply({"active": True, "client_id": "swarm-notify-router", "exp": int(time.time()) + 3600}) else: self.reply({"active": False}) return self.reply({"access_token": secrets.token_hex(16), "token_type": "Bearer", "expires_in": 3600}) 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() ''; # What a client sees of the queue's certificate. The server speaks first # and upgrades to TLS on the same connection, so `openssl s_client` cannot # dial it: this reads the server's greeting, then verifies the certificate # against a root for a name, and prints its serial. tlsProbe = pkgs.writeText "natstls.py" '' import socket import ssl import sys host, name, root = sys.argv[1:4] sock = socket.create_connection((host, ${toString natsPort}), timeout=10) greeting = sock.recv(4096) assert greeting.startswith(b"INFO"), greeting context = ssl.create_default_context(cafile=root) context.verify_flags &= ~ssl.VERIFY_X509_STRICT tls = context.wrap_socket(sock, server_hostname=name) print(tls.getpeercert()["serialNumber"]) ''; # A port the node's firewall opens, which the second node reaches: the control # for every refusal it sees. controlListener = pkgs.writeText "control.py" '' import http.server http.server.ThreadingHTTPServer(("0.0.0.0", ${toString controlPort}), http.server.SimpleHTTPRequestHandler).serve_forever() ''; in pkgs.testers.runNixOSTest { name = "k8s-nats"; # 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 = 2700; nodes.machine = { config, ... }: { imports = [ self.nixosModules.default ]; services.hyperhive = { deploy.k8s.enable = true; network.enable = true; network.bridgeIp = bridgeIp; # The egress intercept is on, which makes the forward chain refuse an # agent's traffic to anything but the bridge, as on a hive controller host. deploy.hive-controller.egress.intercept = { enable = true; refuseEch = false; }; deploy.bao.enable = true; deploy.bao.seal = "shamir"; deploy.bao.bootstrapTokenFile = "/var/lib/swarm-bao-bootstrap/grant.token"; deploy.nats.enable = true; deploy.hive-controller.hiveName = "h1"; swarm.domain = "t.local"; swarm.bao.domain = baoName; swarm.bao.port = baoPort; swarm.hives.h1.domain = "h1.t.local"; # The identity provider is host-run: its name goes to the bridge for the # queue's responder, as the hive's own do. gateway.localNames = [ authName ]; }; system.stateVersion = "25.11"; specialisation.k8s-open.configuration.services.hyperhive.deploy.nats.openFirewall = true; # 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-services` does. services.nginx.enable = lib.mkForce false; networking.hosts."${bridgeIp}" = [ baoName natsName authName ]; 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 identity provider's name, 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. The queue's leaf chains to that root. 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=${authName}" printf 'subjectAltName=DNS:${authName}\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.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.control-listener = { wantedBy = [ "multi-user.target" ]; serviceConfig = { ExecStart = "${pkgs.python3}/bin/python3 ${controlListener}"; WorkingDirectory = "/etc"; }; }; networking.firewall.allowedTCPPorts = [ controlPort ]; networking.interfaces.eth1.ipv4.addresses = lib.mkForce [ { address = nodeIp; prefixLength = 24; } ]; environment.systemPackages = [ pkgs.kubectl pkgs.curl pkgs.jq pkgs.openssl pkgs.natscli pkgs.netcat pkgs.iproute2 pkgs.procps pkgs.python3 ]; environment.etc."natstls.py".source = tlsProbe; 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 = 8192; cores = 4; diskSize = 20480; }; }; # A host outside the node, on its network: it dials the queue by name. nodes.outside = { ... }: { networking.interfaces.eth1.ipv4.addresses = lib.mkForce [ { address = outsideIp; prefixLength = 24; } ]; networking.hosts."${nodeIp}" = [ natsName ]; environment.systemPackages = [ pkgs.natscli pkgs.openssl pkgs.netcat pkgs.curl pkgs.python3 ]; environment.etc."natstls.py".source = tlsProbe; }; testScript = builtins.readFile ./lib/k3s.py + '' INIT = "/root/bao-init.json" NS = "${namespace}" SERVICE = "${service}" HOST_UNIT = "${hostUnit}" PRUNE = "${prune}" NAME = "${natsName}" PORT = ${toString natsPort} METRICS = ${toString metricsPort} METRICS_SERVICE = "${service}-metrics" METRICS_HOST = f"{METRICS_SERVICE}.{NS}.svc.cluster.local" NODE = "${nodeIp}" BRIDGE = "${bridgeIp}" CONTROL = ${toString controlPort} STATE_LABEL = "hyperhive.darkest.space/state-nats" ENTRY_LABELS = { "hyperhive.darkest.space/entry": "true", "svccontroller.k3s.cattle.io/enablelb": "true", } MANIFESTS = "/var/lib/rancher/k3s/server/manifests" SERVICES_ROOT = "${tlsDir}/swarm-services-root.pem" TOKEN = "${routerToken}" STREAM = "ROUTER_TODOS" QUEUE_UP = ( "systemctl --machine=swarm-nats is-active nats.service " "&& systemctl --machine=swarm-nats is-active swarm-nats-auth.service " "&& [ \"$(pgrep -cx nats-server)\" = 1 ] && [ \"$(pgrep -cx swarm-nats-auth)\" = 1 ]" ) BUCKET = "notify-router-state" HOST_STORE = "/var/lib/nixos-containers/swarm-nats/var/lib/nats" SUBJECT = "$SWARM.router.todo.atlas" INBOX = "_INBOX.client.swarm-notify-router" 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]) if unit == HOST_UNIT: print(machine.execute("journalctl --machine=swarm-nats -u nats.service -u swarm-nats-auth.service --no-pager -n 40")[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 live_pods() -> list[str]: """The pods that are not terminating: a deleted pod whose sandbox the runtime can't remove stays in the list.""" return machine.succeed( f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o json " "| jq -r '.items[] | select(.metadata.deletionTimestamp == null) | .metadata.name'" ).split() def pod_pid(container: str) -> str: id_ = machine.succeed(f"k3s crictl ps --name '^{container}$' --state running -q").split()[0] return machine.succeed(f"k3s crictl inspect {id_} | 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 ' str: return machine.execute(f"systemctl is-active {HOST_UNIT}")[1].strip() def wait_pod_ready(not_uid: str = "", timeout: int = 600) -> str: """The name of the Ready pod of the queue 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", "callout-config", SERVICE, "nats", "exporter"): print(machine.execute(f"kubectl -n {NS} logs {name} -c {container} --tail=60")[1]) raise return name def node_labels() -> dict: return json.loads(kube(machine, "get node -o json"))["items"][0]["metadata"]["labels"] 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", "firewall.service"] assert not any(unit in failed for unit in ours), failed # k3s writes its kubeconfig again when it restarts, which a switch that # changes the node's flags does, and with it drops the default namespace. machine.wait_until_succeeds("kubectl get --raw /readyz", timeout=300) kube(machine, f"config set-context --current --namespace={NS}") return out def nats_cmd(root: str, *args: str) -> str: """The `nats` client dialling the queue by name, trusting the root at `root`, as the notification router: its token and its inbox.""" return f"nats --server tls://{NAME}:{PORT} --tlsca {root} --token {TOKEN} --inbox-prefix {INBOX} {' '.join(args)} 2>&1" def nats(node: QemuMachine, *args: str) -> str: return node.succeed(nats_cmd(SERVICES_ROOT, *args), timeout=60) def stream_messages() -> int: out = nats(machine, f"stream info {STREAM} --json") return int(json.loads(out)["state"]["messages"]) def probe(node: QemuMachine, address: str, name: str = NAME, root: str = SERVICES_ROOT) -> tuple[bool, str]: """Whether the queue at `address` presents a certificate that `root` verifies for `name`, and what it printed: the certificate's serial.""" status, out = node.execute(f"python3 /etc/natstls.py {address} {name} {root} 2>&1") return status == 0, out.strip() def probe_from_agent() -> tuple[bool, str]: """`probe` from the netns of the client on the bridge, at the bridge's address, by the name an agent dials.""" status, out = machine.execute(f"ip netns exec agent python3 /etc/natstls.py {BRIDGE} {NAME} {SERVICES_ROOT} 2>&1") return status == 0, out.strip() def reachable(node: QemuMachine, address: str, port: int) -> bool: return node.execute(f"nc -z -w 4 {address} {port}")[0] == 0 def counts() -> tuple[int, int]: """How many servers and responders the node runs.""" servers = int(machine.execute("pgrep -cx nats-server")[1].strip() or 0) responders = int(machine.execute("pgrep -cx swarm-nats-auth")[1].strip() or 0) return servers, responders 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}") outside.start() outside.wait_for_unit("multi-user.target") 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 queue's policies and 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) unseal_bao(machine, INIT) for unit in [ "swarm-bao-nats-tls-policy", "swarm-bao-nats-auth-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/role/swarm-nats-auth'", timeout=300, ) # The responder's client secret at the identity provider, 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 ${oidcLeaf} value={SECRET}") with subtest("the store's services root is in the trust bundle, and the identity provider's stub runs"): machine.wait_for_unit("hive-tls-ca.service") machine.succeed("systemctl reset-failed swarm-services-cert.service || true") machine.succeed("systemctl restart --no-block swarm-services-cert.service") settle(f"test -s {SERVICES_ROOT} && grep -c BEGIN ${tlsDir}/trust-bundle.pem | grep -qx 2", 600, ["swarm-services-cert.service"]) machine.wait_for_unit("token-stub.service") machine.wait_for_unit("control-listener.service") with subtest("the queue runs as a pod only: the host has no container, delivery unit or prune unit"): machine.fail("test -e /etc/nixos-containers/swarm-nats.conf") for unit in ["swarm-nats-auth-secrets", "swarm-bao-nats-callout-xkey", PRUNE]: machine.fail(f"systemctl cat {unit}.service") # The leaf unit that writes the gateway's copy is the control that the lookups find a unit of the queue's that is there. machine.succeed("systemctl cat swarm-bao-nats-tls.service") machine.succeed(f"test -L {MANIFESTS}/{SERVICE}.yaml") pod_name = wait_pod_ready() assert host_state() == "inactive", host_state() assert machine.execute("machinectl list --no-legend | grep -q swarm-nats")[0] != 0 assert counts() == (1, 1), counts() # The bridge's client: an agent's network namespace on the hive's bridge. BRIDGE_IF = machine.succeed("ip -o -4 addr show | grep -F 'inet ${bridgeIp}/' | cut -d' ' -f2").strip() machine.succeed( "ip netns add agent && ip link add va type veth peer name vb && ip link set vb netns agent " f"&& ip link set va master {BRIDGE_IF} && ip link set va up " "&& ip -n agent addr add ${agentIp}/24 dev vb && ip -n agent link set vb up && ip -n agent link set lo up " "&& ip -n agent route add default via ${bridgeIp}" ) with subtest("the pod holds the leaf and the config as init containers, and has no hostPort on the server or the exporter"): spec = pod(machine, pod_name)["spec"] assert [c["name"] for c in spec["initContainers"]] == ["tls-issue", "callout-config"], spec["initContainers"] assert [c["name"] for c in spec["containers"]] == ["swarm-nats", "nats", "tls-renew", "exporter"], spec["containers"] assert spec["shareProcessNamespace"] is True, spec server = next(c for c in spec["containers"] if c["name"] == "nats") client = next(p for p in server["ports"] if p["name"] == "client") assert client == {"name": "client", "containerPort": PORT, "protocol": "TCP"}, client command = server["readinessProbe"]["exec"]["command"] assert command[0] == "/bin/wget" and command[-1].endswith("/healthz?js-enabled-only=true"), command exporter = next(c for c in spec["containers"] if c["name"] == "exporter") assert exporter["ports"] == [{"name": "metrics", "containerPort": METRICS, "protocol": "TCP"}], exporter["ports"] assert not any(c.get("resources") for c in spec["containers"]), spec["containers"] assert not any("secret" in v for v in spec["volumes"]), spec["volumes"] assert spec["hostAliases"] == [{"ip": "127.0.0.1", "hostnames": [NAME]}], spec["hostAliases"] # Ready is the exec probe's and the responder's: every container is. statuses = {c["name"]: c["ready"] for c in pod(machine, pod_name)["status"]["containerStatuses"]} assert statuses == {"swarm-nats": True, "nats": True, "tls-renew": True, "exporter": True}, statuses claim = json.loads(kube(machine, f"get pvc {SERVICE}-store -o json")) assert claim["status"]["phase"] == "Bound", claim STATE_VOLUME = claim["metadata"]["uid"] # The leaf's key is in memory. uid = pod(machine, pod_name)["metadata"]["uid"] mount = f"pods/{uid}/volumes/kubernetes.io~empty-dir" assert machine.succeed(f"grep -F '{mount}/nats-tls ' /proc/mounts | cut -d' ' -f3").strip() == "tmpfs" machine.fail(f"grep -F '{mount}/nats-config ' /proc/mounts") issued = machine.succeed(f"kubectl -n {NS} logs {pod_name} -c tls-issue") assert f"requesting the queue's TLS leaf for {NAME} from the store" in issued, issued # The pod's server keeps the descriptors the container's did. limits = machine.succeed("grep 'Max open files' /proc/$(pgrep -ox nats-server)/limits") print(limits) assert int(limits.split()[3]) >= 800000, limits with subtest("the node carries the state label, and the volume and the pod select on it"): labels = node_labels() assert labels.get(STATE_LABEL) == "true", labels assert all(labels.get(k) == v for k, v in ENTRY_LABELS.items()), labels volume = json.loads(kube(machine, f"get pv {SERVICE}-store -o json")) assert volume["status"]["phase"] == "Bound", volume["status"] assert volume["spec"]["claimRef"]["name"] == f"{SERVICE}-store", volume["spec"] assert volume["spec"]["nodeAffinity"]["required"]["nodeSelectorTerms"] == [ {"matchExpressions": [{"key": STATE_LABEL, "operator": "In", "values": ["true"]}]} ], volume["spec"] assert pod(machine, pod_name)["spec"]["nodeSelector"] == {STATE_LABEL: "true"}, pod(machine, pod_name)["spec"] assert "kubernetes.io/hostname" not in json.dumps(volume["spec"]), volume["spec"] with subtest("a node without the state label cannot run the pod, and the pod starts when the label returns"): node = machine.succeed("kubectl get node -o name").strip() old_uid = pod(machine, pod_name)["metadata"]["uid"] kube(machine, f"label {node} {STATE_LABEL}-") assert STATE_LABEL not in node_labels() kube(machine, f"delete pod {pod_name} --wait=false") unscheduled = ( f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o json " "| jq -r '.items[].status.conditions[]? | select(.type == \"PodScheduled\" and .status == \"False\") | .message'" ) machine.wait_until_succeeds(f"{unscheduled} | grep -q .", timeout=120) message = machine.succeed(unscheduled) assert "node affinity" in message, message assert pods() != [] and counts()[0] == 0, (pods(), counts()) kube(machine, f"label {node} {STATE_LABEL}=true") pod_name = wait_pod_ready(old_uid) assert node_labels().get(STATE_LABEL) == "true" assert counts() == (1, 1), counts() with subtest("the exporter is a ClusterIP Service, and the pod's policy admits the client port from any source and nothing else"): svc = json.loads(kube(machine, f"get service {METRICS_SERVICE} -o json")) assert svc["spec"]["type"] == "ClusterIP", svc["spec"] assert [(p["port"], p["targetPort"]) for p in svc["spec"]["ports"]] == [(METRICS, "metrics")], svc["spec"] policy = json.loads(kube(machine, f"get networkpolicy {SERVICE} -o json"))["spec"] assert policy["policyTypes"] == ["Ingress"], policy assert policy["ingress"] == [{"ports": [{"port": PORT, "protocol": "TCP"}]}], policy with subtest("the client port is a LoadBalancer Service with no node port, which the cluster's load balancer binds on the node from kube-system"): machine.wait_until_succeeds( f"kubectl -n {NS} get service {SERVICE} -o jsonpath='{{.status.loadBalancer.ingress[0].ip}}' | grep -q .", timeout=300, ) svc = json.loads(kube(machine, f"get service {SERVICE} -o json")) assert svc["spec"]["type"] == "LoadBalancer", svc["spec"] assert svc["spec"]["allocateLoadBalancerNodePorts"] is False, svc["spec"] assert [(p["port"], p["targetPort"]) for p in svc["spec"]["ports"]] == [(PORT, "client")], svc["spec"] assert not any("nodePort" in p for p in svc["spec"]["ports"]), svc["spec"] lb_pods = json.loads(kube(machine, f"-n kube-system get pods --selector svccontroller.k3s.cattle.io/svcname={SERVICE} -o json"))["items"] assert len(lb_pods) == 1, lb_pods lb_ports = [p for c in lb_pods[0]["spec"]["containers"] for p in c.get("ports", [])] assert [(p["hostPort"], p["containerPort"]) for p in lb_ports] == [(PORT, PORT)], lb_ports assert all(p.get("hostIP", "") in ("", "0.0.0.0") for p in lb_ports), lb_ports # No node port: the Service has a rule for its cluster address, the # control that the lookup finds it, and none in the chain of node ports. assert f"hyperhive/{SERVICE}:client" in machine.succeed("iptables -t nat -S KUBE-SERVICES") assert f"hyperhive/{SERVICE}:client" not in machine.succeed("iptables -t nat -S KUBE-NODEPORTS") with subtest("one server and one responder run, and the queue answers by name with its name verified"): assert counts() == (1, 1), counts() assert probe(machine, BRIDGE)[0], probe(machine, BRIDGE) assert probe(machine, NODE)[0], probe(machine, NODE) with subtest("the pod's responder admits the router's token and the account holds a stream the router fills"): nats(machine, f"stream add {STREAM} --subjects '{SUBJECT}' --storage file --defaults") nats(machine, f"pub '{SUBJECT}' --count 1 'a todo'") assert stream_messages() == 1 machine.wait_until_succeeds(f"[ \"$(grep -c '/api/oidc/introspection ${service}:{SECRET}' ${tokenLog})\" -ge 2 ]", timeout=60) with subtest("the pod's volume is the host's store directory: the pod writes its keys and its files are there"): pv = json.loads(kube(machine, f"get pv {SERVICE}-store -o json")) assert pv["spec"]["local"]["path"] == HOST_STORE, pv["spec"] assert pv["status"]["phase"] == "Bound" and pv["spec"]["claimRef"]["name"] == f"{SERVICE}-store", pv assert pv["spec"]["persistentVolumeReclaimPolicy"] == "Retain", pv["spec"] assert claim["spec"]["volumeName"] == pv["metadata"]["name"], claim["spec"] nats(machine, f"kv add {BUCKET}") nats(machine, f"kv put {BUCKET} pod-key written-by-pod") assert "written-by-pod" in nats(machine, f"kv get {BUCKET} pod-key --raw") # The control that the lookup finds files: the store is not empty. assert int(machine.succeed(f"find {HOST_STORE} -type f | wc -l")) > 0 with subtest("a client on the hive's bridge reaches the pod through the published port, behind the egress chain that refuses it everything else of the cluster, and a host outside the node does not"): assert machine.execute(f"ip netns exec agent nc -z -w 4 {BRIDGE} {PORT}")[0] == 0 assert probe_from_agent()[0], probe_from_agent() # The same pod by its own address, and the queue by the node's address, # are no flow the host published for the agent: both are refused. pod_ip = kube(machine, f"get pod {pod_name} -o jsonpath='{{.status.podIP}}'").strip() assert pod_ip.startswith("10.200."), pod_ip assert machine.execute(f"ip netns exec agent nc -z -w 4 {pod_ip} {PORT}")[0] != 0 assert machine.execute(f"ip netns exec agent nc -z -w 4 {NODE} {PORT}")[0] != 0 assert machine.execute(f"ip netns exec agent nc -z -w 4 {BRIDGE} {METRICS}")[0] != 0 assert reachable(outside, NODE, CONTROL) assert not reachable(outside, NODE, PORT), "the pod's port is open to a host outside the node" with subtest("the exporter answers the host's own processes by its Service's name, and refuses a client of the bridge and a pod of the cluster"): ip = kube(machine, f"get service {METRICS_SERVICE} -o jsonpath='{{.spec.clusterIP}}'").strip() assert machine.succeed(f"getent ahostsv4 {METRICS_HOST}").split()[0] == ip body = machine.succeed(f"curl -sf http://{METRICS_HOST}:{METRICS}/metrics") assert "gnatsd_varz_connections" in body, body[:500] # The bridge's client has the route to the Service's address through the # host, and the pod's policy refuses it. A pod of the cluster reaches the # queue's client port, the control that it can dial out, and not the # exporter. assert machine.execute(f"ip netns exec agent nc -z -w 4 {ip} {METRICS}")[0] != 0 other = pod_pid("coredns") machine.succeed(dials(other, BRIDGE, PORT)) machine.wait_until_fails(dials(other, ip, METRICS), timeout=120) for _ in range(3): assert machine.execute(dials(other, ip, METRICS))[0] != 0 with subtest("a leaf that has to be issued again is issued beside the running server, which reloads it for new connections"): uid = pod(machine, pod_name)["metadata"]["uid"] leaf_dir = machine.succeed(f"grep -F 'pods/{uid}/volumes/kubernetes.io~empty-dir/nats-tls ' /proc/mounts | cut -d' ' -f2").strip() before = probe(machine, NODE) assert before[0], before machine.succeed(f"rm {leaf_dir}/cert.pem") machine.wait_until_succeeds( f"kubectl -n {NS} logs {pod_name} -c tls-renew | grep -F 'leaf was renewed'", timeout=900, ) machine.wait_until_succeeds(f"[ \"$(python3 /etc/natstls.py {NODE} {NAME} {SERVICES_ROOT})\" != \"{before[1]}\" ]", timeout=60) assert probe(machine, NODE)[0] nats(machine, "account info") assert counts() == (1, 1), counts() with subtest("deleting the pod keeps the stream: the volume is the same and the message is read after"): old_uid = pod(machine, pod_name)["metadata"]["uid"] kube(machine, f"delete pod {pod_name} --wait=false") pod_name = wait_pod_ready(old_uid) assert json.loads(kube(machine, f"get pvc {SERVICE}-store -o json"))["metadata"]["uid"] == STATE_VOLUME machine.wait_until_succeeds(nats_cmd(SERVICES_ROOT, f"stream info {STREAM}"), timeout=120) assert stream_messages() == 1 assert "written-by-pod" in nats(machine, f"kv get {BUCKET} pod-key --raw") assert counts() == (1, 1), counts() with subtest("with openFirewall a host outside the node dials the pod by name and verifies it, and is admitted"): switch("/run/booted-system/specialisation/k8s-open") assert len(live_pods()) == 1, live_pods() machine.wait_until_succeeds(f"nc -z -w 4 {NODE} {PORT}", timeout=60) assert reachable(outside, NODE, PORT), "openFirewall left the pod's port closed to a host outside the node" root = machine.succeed(f"cat {SERVICES_ROOT}") outside.succeed(f"cat > /root/root.pem <<'EOF'\n{root}EOF") verified = probe(outside, NAME, root="/root/root.pem") assert verified[0], verified # By name, as the store's root verifies it, and with the token the # responder in the pod admits. listed = outside.succeed(nats_cmd("/root/root.pem", f"stream info {STREAM} --json"), timeout=60) assert json.loads(listed)["state"]["messages"] == 1, listed # A name the leaf does not carry is refused. wrong = probe(outside, NODE, name="other.t.local", root="/root/root.pem") assert not wrong[0], wrong # The exporter's port stays closed to everyone but the host. assert not reachable(outside, NODE, METRICS) ''; }