Watch
0
0
Fork
You've already forked hyperhive
0

k8s: the controller's listener is a ClusterIP service the host dials by name

The controller's api port was a hostPort on the node, which Pod Security baseline and restricted forbid. It is a ClusterIP Service now, behind a NetworkPolicy that admits only the node. The host's resolver (the hive's dnsmasq) forwards cluster.local to CoreDNS, and the gateway dials the Service by name through nginx's resolver. tcp.hostAddress goes.
This commit is contained in:
atlas 2026-11-23 17:20:22 +01:00 • committed by maia
commit 9a72d07c05

View file

@ -13,12 +13,14 @@
# 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;
# host by name, in the cluster 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 both times;
# - the Service is a ClusterIP the host dials and a pod can't (no `hostPort`);
# - a changed hyperhive rev rolls the Deployment; the pod's state directory is
# an emptyDir, with no claim and no gate;
# - the switch back leaves no pod, Deployment or AddOn, and the host unit
# starts after the prune unit.
# - the switch back leaves no pod, Deployment, Service, NetworkPolicy 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
@ -156,6 +158,9 @@ pkgs.testers.runNixOSTest {
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";
@ -332,7 +337,8 @@ pkgs.testers.runNixOSTest {
PRUNE = "${prune}"
NAME = "${controllerName}"
PORT = ${toString controllerPort}
NODE_ADDRESS = "${bridgeIp}"
BRIDGE = "${bridgeIp}"
SERVICE_HOST = "${service}.${namespace}.svc.cluster.local"
SOCKET = "/run/swarm-controller/controller.sock"
MANIFESTS = "/var/lib/rancher/k3s/server/manifests"
SERVICES_ROOT = "${tlsDir}/swarm-services-root.pem"
@ -428,6 +434,21 @@ pkgs.testers.runNixOSTest {
)[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)
@ -497,6 +518,8 @@ pkgs.testers.runNixOSTest {
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
assert machine.execute(f"kubectl -n {NS} get service {SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get networkpolicy {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
@ -523,7 +546,7 @@ pkgs.testers.runNixOSTest {
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 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"]
@ -545,10 +568,10 @@ pkgs.testers.runNixOSTest {
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}")
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}:{NODE_ADDRESS} https://{NAME}:{PORT}/api/openapi.json"
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.
@ -557,14 +580,40 @@ pkgs.testers.runNixOSTest {
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"):
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}:{NODE_ADDRESS} "
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("Pod Security restricted would admit the namespace's pods: the API server's dry run of the label names none, and does name kube-system's"):
dry = "label --dry-run=server --overwrite namespace {} pod-security.kubernetes.io/enforce=restricted 2>&1"
control = machine.succeed("kubectl " + dry.format("kube-system"))
assert "violate" in control, control
mine = machine.succeed("kubectl " + dry.format(NS))
assert "violate" not in mine, mine
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"]