Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/nix/vm-tests/k8s-bao-login.nix
atlas 58e59be65e vm-tests: k8s-bao-login expects the roles the module names
The test listed three jwt roles by hand, and the store has eight since the queue, stt, the review classifier and the claude minter joined, so it failed at the role assertion before it reached any pod. The list is now the module's own k8sPrincipals, sorted.
2026-11-27 11:47:16 +01:00

429 lines
19 KiB
Nix

# `vmTests.<system>.k8s-bao-login`: a host with the cluster node
# (`services.hyperhive.deploy.k8s.enable`) and the swarm secret store runs both
# for real, and a pod logs in to the store with its ServiceAccount token. The
# store's side is the module's own (../host-modules/swarm-bao.nix): the pods'
# listener, the `jwt-k8s` auth mount that `swarm-bao-granter-role` enables, the
# config and roles `swarm-bao-k8s-jwt-policy` writes from the node's own key
# files. The pods' side is the manifest the module renders for the CI run
# poller (../host-modules/k8s/render.nix): its ServiceAccount, and its
# projected token volume, mounted into a probe pod that stands in for the
# service. The script asserts:
#
# - the mount's config holds the public half of k3s's signing key and the
# issuer the node's tokens carry, and one role per in-cluster service exists;
# - a pod under the poller's account reads the one value its policy grants,
# with a token the store issued to the poller's role;
# - a pod under another account, a pod whose token is for another audience,
# and the right pod asking for another service's role are all refused, and
# none of them gets a store token;
# - the pods' port is open on the pod network's interfaces only: a client on
# the hive bridge, the way an agent is, reaches a control port there and is
# refused at the pods' port, which the host itself can connect to.
{ pkgs, self }:
let
inherit (pkgs) lib;
bridgeIp = "10.42.0.1";
baoName = "bao.t.local";
baoPort = 8200;
podPort = 8208;
namespace = "hyperhive";
# The in-cluster service whose role and account the pods use.
service = "swarm-ci-metrics";
# The one value that service's policy lets it read.
leaf = "swarm/services/ci-metrics/forge/token";
controlPort = 9000;
# The pod the script execs into: a shell and `curl`.
probeImage = pkgs.dockerTools.buildLayeredImage {
name = "k8s-probe";
tag = "test";
contents = [
pkgs.busybox
pkgs.curl
];
};
in
pkgs.testers.runNixOSTest {
name = "k8s-bao-login";
# The store takes a few minutes to open its raft storage and the granting
# units run one after another. Under the 1 h job bound with room for the
# build before the test starts.
globalTimeout = 2400;
nodes.machine =
{ config, ... }:
let
# The poller's manifests as the module renders them.
objects =
(import ../host-modules/k8s/render.nix {
inherit lib pkgs config;
}).objects;
podSpec = objects."${service}/cronjob".spec.jobTemplate.spec.template.spec;
byName = name: lib.findFirst (x: x.name == name) null;
tokenVolume = byName "bao-token" podSpec.volumes;
tokenMount = byName "bao-token" (lib.head podSpec.containers).volumeMounts;
# The same volume for another audience.
otherAudience = {
inherit (tokenVolume) name;
projected = {
inherit (tokenVolume.projected) defaultMode;
sources = [
{
serviceAccountToken = {
audience = "kubernetes.default.svc";
expirationSeconds = 600;
path = "token";
};
}
];
};
};
# A pod shaped like the poller's under `account`, with the CA the store's
# certificate chains to.
probePod = name: account: volume: {
apiVersion = "v1";
kind = "Pod";
metadata = {
inherit name namespace;
};
spec = {
serviceAccountName = account;
automountServiceAccountToken = false;
inherit (podSpec) securityContext;
containers = [
{
name = "probe";
image = "${probeImage.imageName}:${probeImage.imageTag}";
imagePullPolicy = "Never";
command = [
"sleep"
"3600"
];
# The namespace enforces Pod Security `restricted`, which asks the
# container for these: the pod-level settings alone leave it able to
# escalate and to keep capabilities.
inherit (lib.head podSpec.containers) securityContext;
volumeMounts = [
tokenMount
{
name = "tls";
mountPath = "/tls";
}
];
}
];
volumes = [
volume
{
name = "tls";
configMap.name = "probe-tls";
}
];
};
};
in
{
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.ci-metrics.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";
# A listener of the script's own on the bridge, open there, as the
# control for the refusal below.
network.exposeHostPorts = [ controlPort ];
};
system.stateVersion = "25.11";
# The store's TLS passthrough is a stream server of the host's nginx. The
# gateway's nginx needs certificates this host does not mint, so a second
# nginx carries the passthrough alone. The store's name resolves to the
# bridge for the host as it does for pods.
services.nginx.enable = lib.mkForce false;
networking.hosts."${bridgeIp}" = [ baoName ];
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;'";
};
};
environment.systemPackages = [
pkgs.kubectl
pkgs.curl
pkgs.jq
pkgs.openssl
];
environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml";
services.k3s.images = [ probeImage ];
systemd.services.bridge-control = {
wantedBy = [ "multi-user.target" ];
after = [ "network.target" ];
serviceConfig = {
ExecStart = "${pkgs.python3}/bin/python3 -m http.server ${toString controlPort} --bind ${bridgeIp}";
WorkingDirectory = "/tmp";
Restart = "always";
RestartSec = 2;
};
};
environment.etc = {
"k3s-node/images".text = lib.concatMapStrings (i: "${i.imageName}:${i.imageTag}\n") (
config.system.build.k8sImages ++ [ probeImage ]
);
"k8s-bao/manifests".source = config.system.build.k8sManifests;
# The jwt roles the store has: one per in-cluster principal the module names.
"k8s-bao/in-cluster.json".text = builtins.toJSON (
lib.sort lib.lessThan config.services.hyperhive.deploy.bao.k8sPrincipals
);
"k8s-bao/pod-right.json".text = builtins.toJSON (probePod "right" service tokenVolume);
"k8s-bao/pod-intruder.json".text = builtins.toJSON (probePod "intruder" "intruder" tokenVolume);
"k8s-bao/pod-audience.json".text = builtins.toJSON (probePod "audience" service otherAudience);
};
# 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 = 8192;
};
};
testScript = builtins.readFile ./lib/k3s.py + ''
import base64
import shlex
INIT = "/root/bao-init.json"
NS = "${namespace}"
SERVICE = "${service}"
BRIDGE_IP = "${bridgeIp}"
POD_PORT = ${toString podPort}
CONTROL_PORT = ${toString controlPort}
API = f"https://${baoName}:{POD_PORT}"
ISSUER = "https://kubernetes.default.svc.cluster.local"
IN_CLUSTER = json.loads(machine.succeed("cat /etc/k8s-bao/in-cluster.json"))
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 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 probe(pod_name: str, command: str) -> tuple[int, str]:
return machine.execute(
f"kubectl -n {NS} exec {pod_name} -- sh -c {shlex.quote(command + ' 2>&1')}"
)
def login(pod_name: str, role: str) -> tuple[int, dict]:
"""The status and body of a jwt login from pod `pod_name`, with the
token the pod holds."""
_, out = probe(
pod_name,
"curl -sS -m 20 --cacert /tls/ca.pem -w '\\n%{http_code}' -X POST "
f"-d \"{{\\\"jwt\\\":\\\"$(cat /var/run/secrets/hyperhive/bao/token)\\\",\\\"role\\\":\\\"{role}\\\"}}\" "
f"{API}/v1/auth/jwt-k8s/login",
)
body, _, status = out.rpartition("\n")
return int(status), json.loads(body)
def read_leaf(pod_name: str, token: str) -> tuple[int, str]:
_, out = probe(
pod_name,
"curl -sS -m 20 --cacert /tls/ca.pem -w '\\n%{http_code}' "
f"-H {shlex.quote('X-Vault-Token: ' + token)} {API}/v1/secret/data/${leaf}",
)
body, _, status = out.rpartition("\n")
return int(status), body
with subtest("the node is Ready and holds every image"):
wait_node_ready(machine, timeout=300)
wait_images(machine)
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 principals' policies, 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"])
# 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)
units = [
"swarm-bao-controller-policy",
"swarm-bao-ci-metrics-policy",
"swarm-bao-k8s-jwt-policy",
]
for unit in units:
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,
)
with subtest("the mount holds the public half of k3s's signing key and the node's issuer, and a role per in-cluster service"):
config = json.loads(as_root("bao read -format=json auth/jwt-k8s/config"))["data"]
assert config["bound_issuer"] == ISSUER, config
stored = [k.strip() for k in config["jwt_validation_pubkeys"]]
key_files = machine.succeed("ls /var/lib/rancher/k3s/server/tls/service*.key").split()
assert key_files, "k3s wrote no service account key"
for key_file in key_files:
public = machine.succeed(f"openssl pkey -in {key_file} -pubout").strip()
assert public in stored, (key_file, public, stored)
roles = json.loads(as_root("bao list -format=json auth/jwt-k8s/role"))
assert sorted(roles) == IN_CLUSTER, roles
role = json.loads(as_root(f"bao read -format=json auth/jwt-k8s/role/{SERVICE}"))["data"]
assert role["bound_subject"] == f"system:serviceaccount:{NS}:{SERVICE}", role
assert role["bound_audiences"] == ["bao"], role
assert role["token_policies"] == [SERVICE], role
assert role["token_ttl"] == 3600 and role["token_max_ttl"] == 3600, role
cert_role = json.loads(as_root(f"bao read -format=json auth/cert/certs/{SERVICE}"))["data"]
assert cert_role["token_policies"] == role["token_policies"], (cert_role, role)
assert cert_role["token_ttl"] == role["token_ttl"], (cert_role, role)
assert cert_role["token_max_ttl"] == role["token_max_ttl"], (cert_role, role)
with subtest("the pods' listener is bound on the hive bridge and open on the pod network only"):
# The host reaches it over loopback, which proves the listener is up
# and not that the firewall closes it: the bridge client below does.
machine.succeed(f"bash -c 'exec 3<>/dev/tcp/{BRIDGE_IP}/{POD_PORT}'")
rules = machine.succeed("iptables -S nixos-fw")
port_rules = [r for r in rules.splitlines() if f"--dport {POD_PORT}" in r]
assert port_rules, rules
assert all("-i cni0 " in r or "-i flannel.1 " in r for r in port_rules), port_rules
bridge_rules = [r for r in rules.splitlines() if "-i hive-br0 " in r and "--dport" in r]
assert any(f"--dport {CONTROL_PORT}" in r for r in bridge_rules), rules
assert not any(f"--dport {POD_PORT}" in r for r in bridge_rules), bridge_rules
with subtest("a client on the hive bridge reaches the control port and is refused at the pods' port"):
machine.wait_for_unit("bridge-control.service")
machine.succeed(
"ip netns add agent; "
"ip link add agent0 type veth peer name agent1; "
"ip link set agent0 master hive-br0; ip link set agent0 up; "
"ip link set agent1 netns agent; "
"ip -n agent addr add 10.42.0.50/24 dev agent1; "
"ip -n agent link set agent1 up; ip -n agent link set lo up"
)
connect = "timeout 8 bash -c 'exec 3<>/dev/tcp/%s/%d'"
machine.wait_until_succeeds(f"ip netns exec agent {connect % (BRIDGE_IP, CONTROL_PORT)}", timeout=60)
status, out = machine.execute(f"ip netns exec agent {connect % (BRIDGE_IP, POD_PORT)}")
assert status != 0, out
with subtest("the poller's account, its manifests' token volume and a probe pod"):
kube(machine, "apply -f /etc/k8s-bao/manifests/namespace.yaml")
kube(machine, f"apply -f /etc/k8s-bao/manifests/{SERVICE}/serviceaccount.yaml")
kube(machine, f"-n {NS} create serviceaccount intruder")
kube(machine, f"-n {NS} create configmap probe-tls --from-file=ca.pem=/var/lib/swarm-bao-pki/ca.pem")
kube(machine, f"config set-context --current --namespace={NS}")
for name in ["right", "intruder", "audience"]:
kube(machine, f"apply -f /etc/k8s-bao/pod-{name}.json")
for name in ["right", "intruder", "audience"]:
wait_pod(machine, name, phase="Running", ready=True, timeout=240)
with subtest("the token the kubelet projects names the poller's account, the store's audience and the node's issuer"):
token = machine.succeed("kubectl exec right -- cat /var/run/secrets/hyperhive/bao/token").strip()
header, payload, _ = token.split(".")
pad = "=" * (-len(payload) % 4)
claims = json.loads(base64.urlsafe_b64decode(payload + pad))
alg = json.loads(base64.urlsafe_b64decode(header + "=" * (-len(header) % 4)))["alg"]
assert alg in ["RS256", "ES256"], alg
assert claims["iss"] == ISSUER, claims
assert claims["aud"] == ["bao"], claims
assert claims["sub"] == f"system:serviceaccount:{NS}:{SERVICE}", claims
assert claims["exp"] - claims["iat"] <= 3600, claims
with subtest("the right pod logs in, with no client certificate, and reads the value its policy grants"):
as_root("bao kv put -mount=secret ${leaf} value=read-by-the-pod")
status, body = login("right", SERVICE)
assert status == 200, (status, body)
assert body["auth"]["policies"] == ["default", SERVICE], body
assert body["auth"]["lease_duration"] == 3600, body
status, out = read_leaf("right", body["auth"]["client_token"])
assert status == 200 and "read-by-the-pod" in out, (status, out)
# The control: the same pod, with the token of another role's policy
# reach, is not asked here; the refusals below carry the contrast.
with subtest("another account, another audience and another service's role get no store token"):
for pod_name, role_name in [
("intruder", SERVICE),
("audience", SERVICE),
("right", "swarm-notify-router"),
("right", "swarm-controller"),
]:
status, body = login(pod_name, role_name)
assert status != 200 and "auth" not in body, (pod_name, role_name, status, body)
'';
}