Watch
0
0
Fork
You've already forked hyperhive
0

k8s: the queue's client port is a loadbalancer service

The queue's client port was a hostPort on 0.0.0.0, which Pod Security baseline and restricted forbid. It is a LoadBalancer Service now, which k3s's service load balancer binds on every address of the node with a hostPort of its own in kube-system, so hives on other hosts keep their URL. No node port is allocated. The stt policy allows the load balancer's pods in place of the queue's, and the prune unit waits for them to go before the host unit starts. The egress published-port rule and the raw-table rules apply to the load balancer's hostPort as to the pod's.
This commit is contained in:
atlas 2026-11-23 19:09:02 +01:00 • committed by mara
commit 796fd6201f
6 changed files with 200 additions and 75 deletions

View file

@ -370,11 +370,11 @@ let
};
# What the policy of a pod that reaches `reaches` allows: the cluster's DNS,
# those host ports, and the queue's own pod where the queue runs in the
# cluster, because its `hostPort` is forwarded to the pod before the policy
# sees the packet. The policy selects every pod of the service for ingress
# too and allows none, so only the node's own traffic (the kubelet's probes,
# which the policy engine always admits) reaches it.
# those host ports, and the pods of the queue's load balancer where the queue
# runs in the cluster, because the `hostPort` they bind is forwarded to them
# before the policy sees the packet. The policy selects every pod of the
# service for ingress too and allows none, so only the node's own traffic
# (the kubelet's probes, which the policy engine always admits) reaches it.
networkPolicyOf =
name: reaches:
let
@ -416,7 +416,15 @@ let
}
]
++ lib.optional (queueOnCluster && lib.elem "queue" reaches) {
to = [ { podSelector.matchLabels = labelsFor "swarm-nats"; } ];
to = [
{
namespaceSelector.matchLabels."kubernetes.io/metadata.name" = "kube-system";
podSelector.matchLabels = {
"svccontroller.k3s.cattle.io/svcname" = "swarm-nats";
"svccontroller.k3s.cattle.io/svcnamespace" = k8sCfg.namespace;
};
}
];
ports = [ (tcp hostPorts.queue) ];
};
};

View file

@ -29,6 +29,15 @@ let
'';
apiReady = waitFor 600 "the cluster's API" "${kubectl} get --raw /readyz >/dev/null 2>&1";
# The service load balancer binds a Service's port on the node with a
# `hostPort` in a pod of `kube-system`, which its controller deletes some time
# after the Service. The rule that forwards the port to that pod stays until
# the pod is gone, and would swallow what the host unit then listens on.
lbPodsGone =
name:
waitFor 180 "the load balancer's pods of ${name}"
"[ -z \"\$(${kubectl} --namespace kube-system get pods --selector svccontroller.k3s.cattle.io/svcname=${name},svccontroller.k3s.cattle.io/svcnamespace=${cfg.namespace} --output name)\" ]";
caFiles = lib.filterAttrs (_: path: path != null) rendered.caSources;
# The services on the cluster whose pods run in a user namespace.
@ -148,6 +157,7 @@ in
${kubectl} --namespace ${cfg.namespace} delete deployment,cronjob,serviceaccount,networkpolicy,service \
--selector=app.kubernetes.io/name=${name} \
--cascade=foreground --wait=true --timeout=180s --ignore-not-found
${lbPodsGone name}
${kubectl} --namespace kube-system delete addons.k3s.cattle.io ${name} --ignore-not-found
rm -f "$pending"
'';

View file

@ -1,10 +1,11 @@
# The iptables rules that give the queue pod's client `hostPort` the reach the
# queue's container has. A `hostPort` is a DNAT rule, and what a DNAT rule
# rewrites is forwarded, never delivered to the host: the INPUT rules (the
# firewall's `allowedTCPPorts` and per-interface rules) never see it, and the
# cluster's own forwarding rules accept it. The raw table is read before the
# DNAT and before any of those, so a rule there reads the original
# destination, as INPUT does for the container's listener.
# The iptables rules that give the `hostPort` the cluster's load balancer binds
# for the queue's client port the reach the queue's container has. A
# `hostPort` is a DNAT rule, and what a DNAT rule rewrites is forwarded, never
# delivered to the host: the INPUT rules (the firewall's `allowedTCPPorts` and
# per-interface rules) never see it, and the cluster's own forwarding rules
# accept it. The raw table is read before the DNAT and before any of those, so a
# rule there reads the original destination, as INPUT does for the container's
# listener.
#
# The client port is dropped for a packet addressed to the host unless it
# arrives on one of `trusted` (the host's loopback, the hive bridge and the

View file

@ -984,13 +984,11 @@ let
image = ref server;
imagePullPolicy = "Never";
args = lib.tail (lib.splitString " " natsSystem.systemd.services.nats.serviceConfig.ExecStart);
# Every address of the node, which is where the queue listens today.
# The port the client Service targets.
ports = [
{
name = "client";
containerPort = cfg.port;
hostPort = cfg.port;
hostIP = "0.0.0.0";
}
];
# The monitor is on the pod's loopback, so the probe runs in the
@ -1108,6 +1106,34 @@ let
];
};
};
# The client port, on every address of the node, which is where the
# queue listens in its container, so the hives of other hosts keep their
# URL. The cluster's service load balancer (k3s's servicelb) binds the
# Service's port on each node with a `hostPort` of its own, in
# `kube-system`, and forwards it to the pod through the Service. It does
# that by the Service's cluster address, so no node port is needed, and
# none is allocated: a node port would be a second way in, which the
# raw-table rules (./lib/swarm-nats-raw-rules.nix) don't name. The server
# sees the load balancer's pod as the client, not the client's address.
objects."${machine}/loadbalancer" = {
apiVersion = "v1";
kind = "Service";
metadata = metaFor machine;
spec = {
type = "LoadBalancer";
allocateLoadBalancerNodePorts = false;
selector = (metaFor machine).labels;
ports = [
{
name = "client";
protocol = "TCP";
port = cfg.port;
targetPort = "client";
}
];
};
};
objects."${machine}/networkpolicy" = {
apiVersion = "networking.k8s.io/v1";
kind = "NetworkPolicy";
@ -1615,13 +1641,15 @@ in
# sets no listen host), so reachability is the firewall alone.
networking.firewall.allowedTCPPorts = lib.mkIf deployCfg.nats.openFirewall [ cfg.port ];
# The pod's client `hostPort` is a DNAT rule, which the INPUT rules above
# never see: ./lib/swarm-nats-raw-rules.nix gives it the container's reach.
services.hyperhive.network.enable = lib.mkIf onK8s (lib.mkDefault true);
# An agent dials the queue at the bridge's address; the pod's `hostPort` is
# forwarded to the cluster, which the egress forward chain would refuse.
# An agent dials the queue at the bridge's address, and the load
# balancer's `hostPort` forwards that to the cluster, which the egress
# forward chain would refuse.
services.hyperhive.deploy.hive-controller.egress.publishedPorts = lib.mkIf onK8s [ cfg.port ];
# The load balancer's `hostPort` is a DNAT rule, which the INPUT rules above
# never see: ./lib/swarm-nats-raw-rules.nix gives it the container's reach.
networking.firewall.extraCommands = lib.mkIf onK8s (
import ./lib/swarm-nats-raw-rules.nix { inherit lib; } {
chain = "nixos-fw-nats";

View file

@ -1115,8 +1115,10 @@ let
{
to = [
{
podSelector.matchLabels = objects."swarm-stt/deployment".spec.selector.matchLabels // {
"app.kubernetes.io/name" = "swarm-nats";
namespaceSelector.matchLabels."kubernetes.io/metadata.name" = "kube-system";
podSelector.matchLabels = {
"svccontroller.k3s.cattle.io/svcname" = "swarm-nats";
"svccontroller.k3s.cattle.io/svcnamespace" = "hyperhive";
};
}
];
@ -1782,15 +1784,13 @@ let
"-c"
"/var/lib/nats-callout/nats.conf"
]
# The client port is published on every address of the node. The
# exporter's port is named for its Service and has no `hostPort`.
# Both ports are named for their Services, and neither has a `hostPort`:
# the load balancer publishes the client port on the node.
&&
(named "nats").ports == [
{
name = "client";
containerPort = 4222;
hostPort = 4222;
hostIP = "0.0.0.0";
}
]
&&
@ -2025,6 +2025,47 @@ let
&& has "-t raw -A nixos-fw-nats -p tcp --dport 4222 -m addrtype --dst-type LOCAL -j DROP" onCluster.networking.firewall.extraCommands
&& has "-t raw -F nixos-fw-nats" onCluster.networking.firewall.extraStopCommands;
}
{
# The host with the queue on it renders the same Service, the control that
# a `deploy.nats.runtime` changes none of it.
name = "the queue's client port is a LoadBalancer Service with no node port, and the pod has no hostPort";
ok =
let
cluster = render onCluster;
svc = cluster."swarm-nats/loadbalancer";
pod = cluster."swarm-nats/deployment".spec.template;
ports = lib.concatMap (c: c.ports or [ ]) pod.spec.containers;
in
svc.kind == "Service"
&& svc.metadata.name == "swarm-nats"
&& svc.metadata.labels."app.kubernetes.io/name" == "swarm-nats"
&& svc.spec.type == "LoadBalancer"
&& svc.spec.allocateLoadBalancerNodePorts == false
&& svc.spec.selector == pod.metadata.labels
&&
svc.spec.ports == [
{
name = "client";
protocol = "TCP";
port = 4222;
targetPort = "client";
}
]
&& !(svc.spec ? loadBalancerClass)
&& !(svc.spec ? externalTrafficPolicy)
&& !(lib.any (p: p ? hostPort || p ? hostIP) ports)
&&
lib.sort lib.lessThan (map (p: p.name) ports) == [
"client"
"health"
"metrics"
]
&& (render withNode)."swarm-nats/loadbalancer" == svc
# Waiting for the load balancer's pods to go is part of every prune, and
# names the service's own Service and namespace.
&& lib.hasInfix "--selector svccontroller.k3s.cattle.io/svcname=swarm-nats,svccontroller.k3s.cattle.io/svcnamespace=hyperhive" withNode.systemd.services.swarm-nats-k8s-prune.script
&& !(lib.hasInfix "svcname=swarm-nats," withNode.systemd.services.swarm-controller-k8s-prune.script);
}
{
# The host with the queue on it is the control: it publishes no port, and
# its chain has no rule of the kind.

View file

@ -10,8 +10,8 @@
# sampler counts the processes every 200 ms), and the container and the pod
# never overlap;
# - the pod is Ready by its exec probe on the server's monitor, holds the leaf
# and the callout config as init containers, and publishes the client port
# on every address, with no `hostPort` on the exporter;
# 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;
@ -22,8 +22,8 @@
# - the store is the container's own directory: a key the host server wrote is
# read by the pod, and a key the pod wrote is read by the host server after
# the switch back, which hands the files back to the server's user;
# - the switch back leaves no pod, Deployment, Service, NetworkPolicy or AddOn,
# and the container starts after the prune unit.
# - the switch back leaves no pod, Service, NetworkPolicy or AddOn, and the
# container starts after the prune unit.
#
# 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
@ -623,14 +623,14 @@ pkgs.testers.runNixOSTest {
machine.fail("test -e /etc/nixos-containers/swarm-nats.conf")
assert counts() == (1, 1), counts()
with subtest("the pod holds the leaf and the config as init containers, publishes the client port on every address, and has no hostPort on the exporter"):
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["hostPort"] == PORT and client["hostIP"] == "0.0.0.0", 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")
@ -664,6 +664,26 @@ pkgs.testers.runNixOSTest {
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)
@ -769,7 +789,12 @@ pkgs.testers.runNixOSTest {
assert pods() == [], pods()
assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get service {METRICS_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 load balancer's pod and its `hostPort` rule are gone before the
# container listens on the port.
assert machine.succeed(f"kubectl -n kube-system get pods --selector svccontroller.k3s.cattle.io/svcname={SERVICE} -o name").strip() == ""
assert f"--dport {PORT} " not in machine.succeed("iptables -t nat -S")
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