require k8s: swarm services with a pod run in the cluster only
This commit is contained in:
parent
23865cb223
commit
44670249b6
1 changed files with 1044 additions and 3125 deletions
601
nix/vm-tests/k8s-controller.nix
Normal file
601
nix/vm-tests/k8s-controller.nix
Normal file
|
|
@ -0,0 +1,601 @@
|
|||
# `vmTests.<system>.k8s-controller`: swarm-controller runs as a pod in the host's
|
||||
# cluster, against the real secret store, a real queue and the real TCP listener.
|
||||
# `k8s-rev` is the configuration with another hyperhive rev. The script asserts
|
||||
# that:
|
||||
#
|
||||
# - the host has no unit for the controller, its listener leaf or a prune, and the
|
||||
# controller runs once, as a pod;
|
||||
# - 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 and run here
|
||||
# in a nginx of its own, reaches the controller by the Service's name, which
|
||||
# the host's resolver answers through CoreDNS, verifying the leaf as the
|
||||
# listener's name; the controller answers an unsigned webhook 401;
|
||||
# - the Service is a ClusterIP the host dials and a pod can't (no `hostPort`);
|
||||
# Pod Security `restricted` refuses a host port, a capability or privilege;
|
||||
# - a changed hyperhive rev rolls the Deployment; the pod's state directory is
|
||||
# an emptyDir, with no claim and no gate.
|
||||
#
|
||||
# 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" "";
|
||||
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"
|
||||
}
|
||||
'';
|
||||
|
||||
# One nginx with the controller's two locations as the module renders them: 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";
|
||||
|
||||
# The store takes a few minutes to open its raft storage, and the script
|
||||
# switches the configuration once. 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;
|
||||
# The hive's resolver hands the cluster's domain to CoreDNS, which is how the
|
||||
# host reaches the controller's Service by name.
|
||||
gateway.dns.enable = true;
|
||||
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.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-rev.configuration.services.hyperhive.deploy.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-services` 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;
|
||||
};
|
||||
};
|
||||
|
||||
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}
|
||||
BRIDGE = "${bridgeIp}"
|
||||
SERVICE_HOST = "${service}.${namespace}.svc.cluster.local"
|
||||
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 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]
|
||||
|
||||
|
||||
def cluster_ip() -> str:
|
||||
return kube(machine, f"get service {SERVICE} -o jsonpath='{{.spec.clusterIP}}'").strip()
|
||||
|
||||
|
||||
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 '</dev/tcp/{address}/{port}'"
|
||||
|
||||
|
||||
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}")
|
||||
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 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)
|
||||
unseal_bao(machine, INIT)
|
||||
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
|
||||
)
|
||||
|
||||
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_KEY} && openssl verify -CAfile {SERVICES_ROOT} -purpose sslclient {GATEWAY_CERT}", 600, ["swarm-services-cert.service", "swarm-controller-gateway-client.service"])
|
||||
machine.succeed(f"openssl verify -CAfile {SERVICES_ROOT} -purpose sslclient {GATEWAY_CERT}")
|
||||
|
||||
with subtest("the controller runs as a pod only: the host has no unit for it, its listener leaf or a prune"):
|
||||
# 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 host_state() == "inactive", host_state()
|
||||
assert "ExecStart" not in machine.execute("systemctl cat swarm-controller-tls.service")[1]
|
||||
machine.fail("systemctl start swarm-controller-tls.service")
|
||||
machine.fail(f"systemctl cat {PRUNE}.service")
|
||||
# The gateway's client leaf unit is the control that the lookups find a unit of the listener's that is there.
|
||||
machine.succeed("systemctl cat swarm-controller-gateway-client.service")
|
||||
machine.succeed(f"test -L {MANIFESTS}/{SERVICE}.yaml")
|
||||
pod_name = wait_pod_ready()
|
||||
assert len(pods()) == 1, pods()
|
||||
machine.wait_until_succeeds(f"grep -F '/api/oidc/token swarm-controller:{SECRET}' ${tokenLog}", 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["containerPort"] == PORT and "hostPort" not in api and "hostIP" not in api, 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
|
||||
# The state directory is an emptyDir: no claim, no gate.
|
||||
assert [v for v in spec["volumes"] if v["name"] == "state"] == [{"name": "state", "emptyDir": {}}], spec["volumes"]
|
||||
machine.fail(f"kubectl -n {NS} get pvc {SERVICE}-state")
|
||||
# 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(cluster_ip(), 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}:{cluster_ip()} 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 Service's name 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}:{cluster_ip()} "
|
||||
f"--cert {GATEWAY_CERT} --key {GATEWAY_KEY} https://{NAME}:{PORT}/api/openapi.json"
|
||||
))
|
||||
assert api_status == 200, api_status
|
||||
|
||||
with subtest("the listener is a ClusterIP Service the host reaches by its name, and the Service refuses a pod of the cluster that reaches the host's own listeners"):
|
||||
svc = json.loads(kube(machine, f"get service {SERVICE} -o json"))
|
||||
assert svc["spec"]["type"] == "ClusterIP", svc["spec"]
|
||||
assert [(p["port"], p["targetPort"]) for p in svc["spec"]["ports"]] == [(PORT, "api")], svc["spec"]
|
||||
ip = cluster_ip()
|
||||
assert ip.startswith("10.201."), ip
|
||||
# The host's resolver forwards the cluster's domain to CoreDNS.
|
||||
assert machine.succeed(f"getent ahostsv4 {SERVICE_HOST}").split()[0] == ip
|
||||
assert "Verification: OK" in handshake(SERVICE_HOST, f"-cert {GATEWAY_CERT} -key {GATEWAY_KEY}")
|
||||
policy = json.loads(kube(machine, f"get networkpolicy {SERVICE} -o json"))["spec"]
|
||||
assert policy["policyTypes"] == ["Ingress"] and "ingress" not in policy, policy
|
||||
# A pod of the cluster reaches a listener of the host, the control that
|
||||
# a pod can dial out at all, and not the controller's Service.
|
||||
other = pod_pid("coredns")
|
||||
machine.succeed(dials(other, BRIDGE, ${toString natsPort}))
|
||||
machine.wait_until_fails(dials(other, ip, PORT), timeout=120)
|
||||
for _ in range(3):
|
||||
assert machine.execute(dials(other, ip, PORT))[0] != 0
|
||||
|
||||
with subtest("the namespace enforces Pod Security restricted: the API server admits a compliant pod and refuses the same pod with a host port, a kept capability or privilege"):
|
||||
labels = json.loads(kube(machine, f"get namespace {NS} -o json"))["metadata"]["labels"]
|
||||
assert labels["pod-security.kubernetes.io/enforce"] == "restricted", labels
|
||||
compliant = {
|
||||
"apiVersion": "v1",
|
||||
"kind": "Pod",
|
||||
"metadata": {"name": "psa-probe", "namespace": NS},
|
||||
"spec": {
|
||||
"securityContext": {"runAsNonRoot": True, "seccompProfile": {"type": "RuntimeDefault"}},
|
||||
"containers": [{
|
||||
"name": "c",
|
||||
"image": main["image"],
|
||||
"imagePullPolicy": "IfNotPresent",
|
||||
"securityContext": {"allowPrivilegeEscalation": False, "capabilities": {"drop": ["ALL"]}},
|
||||
}],
|
||||
},
|
||||
}
|
||||
|
||||
def admission(change) -> tuple[int, str]:
|
||||
"""What the API server answers to a server-side dry run of the compliant pod with `change` applied to its container."""
|
||||
pod = json.loads(json.dumps(compliant))
|
||||
change(pod["spec"]["containers"][0])
|
||||
machine.succeed(f"cat > /root/psa.json <<'EOF'\n{json.dumps(pod)}\nEOF")
|
||||
return machine.execute("kubectl apply --dry-run=server -f /root/psa.json 2>&1")
|
||||
|
||||
status, out = admission(lambda c: None)
|
||||
assert status == 0, out
|
||||
for what, change in [
|
||||
("host port", lambda c: c.update(ports=[{"containerPort": 9, "hostPort": 9}])),
|
||||
("kept capability", lambda c: c["securityContext"]["capabilities"].update(drop=[])),
|
||||
("privilege", lambda c: c["securityContext"].update(privileged=True, allowPrivilegeEscalation=True)),
|
||||
]:
|
||||
status, out = admission(change)
|
||||
assert status != 0 and 'violates PodSecurity "restricted:latest"' in out, (what, out)
|
||||
|
||||
with subtest("a changed rev rolls the Deployment, and the old pod is gone first"):
|
||||
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 len(pods()) == 1, pods()
|
||||
|
||||
'';
|
||||
}
|
||||
Loading…
Reference in a new issue