From ead0ef8719f11b56a9902da2620fda97d6576036 Mon Sep 17 00:00:00 2001 From: atlas Date: Mon, 23 Nov 2026 18:02:25 +0100 Subject: [PATCH] k8s: the queue's exporter is a ClusterIP service only the node reaches The exporter's metrics port was a hostPort on the bridge's address, which Pod Security baseline and restricted forbid. It is a ClusterIP Service now, and the pod has a NetworkPolicy that admits the client port from any source and nothing else, so only the node reads the exporter, as the raw-table rules made it. The gateway's /metrics location dials the Service by name through nginx's resolver. The raw-table rules no longer name the exporter's port. --- docs/4-implementation/k8s/node.md | 11 +- docs/4-implementation/k8s/runtime.md | 25 +++-- docs/4-implementation/networking/gateway.md | 2 +- nix/host-modules/lib/swarm-nats-raw-rules.nix | 8 +- nix/host-modules/swarm-nats.nix | 102 +++++++++++++++--- nix/module-eval/k8s.nix | 90 ++++++++++++---- nix/vm-tests/k8s-nats-switch.nix | 53 +++++++-- 7 files changed, 228 insertions(+), 63 deletions(-) diff --git a/docs/4-implementation/k8s/node.md b/docs/4-implementation/k8s/node.md index 08b5cd738..74bdbadd1 100644 --- a/docs/4-implementation/k8s/node.md +++ b/docs/4-implementation/k8s/node.md @@ -88,11 +88,12 @@ agents ask the same resolver, so they get the same names. A name is no route: the hive's egress rules decide whether the host forwards their traffic to the cluster's addresses, and a pod's NetworkPolicy refuses what it forwards. -A pod that serves the host, such as the controller's, has a NetworkPolicy that -selects it for ingress and allows nothing. kube-router, the policy engine, adds -a rule at the top of every pod's chain that admits traffic from any address of -the node (`-m addrtype --src-type LOCAL`, commented "from local node"), so the -host reaches the pod and no other pod does. +A pod that serves the host, such as the controller or the queue's exporter, has +a NetworkPolicy that selects it for ingress and allows no more than the port it +serves everyone, if it has one. kube-router, the policy engine, adds a rule at +the top of every pod's chain that admits traffic from any address of the node +(`-m addrtype --src-type LOCAL`, commented "from local node"), so the host +reaches the pod and no other pod does. ## Logging in to the secret store diff --git a/docs/4-implementation/k8s/runtime.md b/docs/4-implementation/k8s/runtime.md index d88d97e14..7c6e60b59 100644 --- a/docs/4-implementation/k8s/runtime.md +++ b/docs/4-implementation/k8s/runtime.md @@ -228,10 +228,17 @@ holds the container back until the pod has gone. read before the DNAT: a packet for the node's address and the client port is dropped unless it arrives on the host's loopback, the hive bridge or a pod interface, or unless `deploy.nats.openFirewall` is on. The container's port - has that reach. The exporter's port is a `hostPort` on the bridge's address, - for the gateway's `/metrics` location on the host. The rules drop it on every - interface but the host's loopback: the exporter answers with the name of - every client, and only the host's own processes may read it. + has that reach. +- **The exporter's port.** The exporter's port has no `hostPort`: a ClusterIP + Service, `swarm-nats-metrics`, fronts it, and the gateway's `/metrics` + location on the host dials the Service's name through nginx's `resolver` (the + hive's dnsmasq), as [the controller's](#the-controller) does, so + `gateway.dns.enable` has to be on. The exporter answers with the name of every + client, and only the node may read it. The pod's NetworkPolicy selects it for + ingress and allows the client port from any source and nothing else. The + cluster's policy engine always admits traffic from an address of the node, so + the gateway and the kubelet's probes reach the pod, and a pod of the cluster, + or a client of the bridge that the host forwards, doesn't reach the exporter. - **The leaf.** `tls-issue` logs in to the store with the pod's token as the role `swarm-nats` and issues the server's leaf from the same script as the host's `swarm-bao-nats-tls`. The key lands in a volume in memory. The @@ -253,8 +260,8 @@ holds the container back until the pod has gone. `swarm-bao-nats-callout-xkey` deliver into the container, so the configuration turns them off. `swarm-bao-nats-tls` stays: it issues the host's own copy of the leaf for the gateway's `/metrics` vhost, and with no container it has - nothing to restart. The gateway's location dials the exporter on the bridge's - address where it dialled loopback. + nothing to restart. The gateway's location dials the exporter's Service by + name where it dialled loopback. - **State.** The server's store directory, `/var/lib/nats`, is the container's own on the host, `/var/lib/nixos-containers/swarm-nats/var/lib/nats`: the PersistentVolumeClaim `swarm-nats-store` binds a static local volume on it, @@ -382,9 +389,9 @@ it dials the pod by name and verifies the name, and the responder in the pod admits it. A key written on the host before the switch is the pod's to read, a key the pod writes is the host server's after the switch back, and a stream written before a pod delete survives it: the replacement pod reads it from the -same directory. The exporter answers the host's own processes through the -published port, and the switch back removes the pod before the container -starts. +same directory. The exporter answers the host's own processes through its +Service and no pod or bridge client, and the switch back removes the pod before +the container starts. The VM test `k8s-controller-switch` moves the controller. It asserts one copy at each step by the switch's own timestamps and by a sampler, that the pod is Ready diff --git a/docs/4-implementation/networking/gateway.md b/docs/4-implementation/networking/gateway.md index 01fe6dbef..c2b9b50a3 100644 --- a/docs/4-implementation/networking/gateway.md +++ b/docs/4-implementation/networking/gateway.md @@ -19,7 +19,7 @@ You rarely switch it on yourself. `gateway.enable` defaults to off, and every mo | `chat./_matrix/*` | tuwunel (unix socket `/run/hive-matrix/tuwunel.sock`) | `hive-matrix.nix`, `swarm.matrix.gatewayHost != null` | | `chat./` | fluffychat-web static | `hive-matrix.nix`, `swarm.matrix.gatewayHost != null` | | `chat./config.json` | inline JSON (FluffyChat boot config) | `hive-matrix.nix`, `swarm.matrix.gatewayHost != null` | -| `/metrics` | the queue exporter's `/metrics` on loopback, behind an authelia `auth_request`; every other path, `/` included, returns `403`, so `/varz` and `/connz` are never reachable | `swarm-nats.nix`, the queue's host | +| `/metrics` | the queue exporter's `/metrics` on loopback, or behind its Service where the queue runs in the cluster, behind an authelia `auth_request`; every other path, `/` included, returns `403`, so `/varz` and `/connz` are never reachable | `swarm-nats.nix`, the queue's host | | `grafana.`, `metrics.`, `logs.`, `otel.`, `bao.` | the matching swarm service | that service's module → [`2-handbook/swarm/services.md`](../../2-handbook/swarm/services.md) | A service module declares its vhost as `services.hyperhive.gateway.vhosts.`: the locations, `forceSSL` and any `extraConfig` it needs. The gateway renders it into `services.nginx.virtualHosts.` and adds the `listen` set ([listen addresses](#listen-addresses)), the certificate for that name and the [security headers](#security-headers) (ahead of the vhost's own `extraConfig`), and drops `addSSL` from a vhost that sets `forceSSL`. The eval fails for a vhost that sets `listen`, `addSSL`, `onlySSL`, `enableACME`, `useACMEHost`, `sslCertificate` or `sslCertificateKey` itself, and for any vhost declared while `gateway.enable` is false. A name with a certificate from outside the gateway's leaves (the queue's) sets `certificate = { cert; key; }` instead. `hive-gateway/vhosts.nix` declares the gateway's own catch-all (`_`) the same way, `hive-c0re/vhosts.nix` the dashboard and the hive domain, and `glue-matrix-hive-discovery.nix` adds the matrix redirect to the hive domain where the homeserver runs, and discovery there when the hive domain is the pinned server name. The catch-all sets `securityHeaders = false` because it sends no response, and the gateway renders a vhost's `default` at `mkDefault` priority. diff --git a/nix/host-modules/lib/swarm-nats-raw-rules.nix b/nix/host-modules/lib/swarm-nats-raw-rules.nix index ec413675e..18010d8bd 100644 --- a/nix/host-modules/lib/swarm-nats-raw-rules.nix +++ b/nix/host-modules/lib/swarm-nats-raw-rules.nix @@ -1,4 +1,4 @@ -# The iptables rules that give the queue pod's `hostPort`s the reach the +# 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 @@ -9,8 +9,7 @@ # 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 # pods' interfaces), or `openClient` is set, which is -# `deploy.nats.openFirewall`. The exporter's port answers with every client's -# name, so it is dropped for all but the host's own loopback. +# `deploy.nats.openFirewall`. # # Pure function — NOT a NixOS module. Returns the text for the firewall's # `extraCommands`. @@ -18,7 +17,6 @@ { chain, clientPort, - metricsPort, trusted, openClient, }: @@ -28,8 +26,6 @@ let in '' iptables -t raw -N ${chain} 2>/dev/null || iptables -t raw -F ${chain} - ${rule} -p tcp --dport ${toString metricsPort} -i lo -j RETURN - ${rule} -p tcp --dport ${toString metricsPort} ${local} ${lib.optionalString (!openClient) '' ${lib.concatMapStrings (i: '' ${rule} -p tcp --dport ${toString clientPort} -i ${i} -j RETURN diff --git a/nix/host-modules/swarm-nats.nix b/nix/host-modules/swarm-nats.nix index 0dab60ece..1037575eb 100644 --- a/nix/host-modules/swarm-nats.nix +++ b/nix/host-modules/swarm-nats.nix @@ -354,6 +354,11 @@ let # host's cluster, which ./k8s/render.nix renders from the units below. onK8s = deployCfg.nats.runtime == "k8s"; + # The Service in front of the pod's exporter, and the name the host's resolver + # answers for it through the cluster's DNS. + metricsService = "${machine}-metrics"; + metricsHost = "${metricsService}.${config.services.hyperhive.k8s.namespace}.svc.${deployCfg.k8s.clusterDomain}"; + # The server's monitoring endpoint, which the exporter reads, and the # collectors it serves. monitorUrl = "http://127.0.0.1:${toString deployCfg.nats.monitorPort}"; @@ -1027,15 +1032,11 @@ let ] ++ exporterFlags ++ [ monitorUrl ]; - # On the bridge's address, for the host's gateway: the exporter - # answers a request with every client's name, so the host's firewall - # lets only the host's own processes reach it. + # The port the metrics Service targets. ports = [ { name = "metrics"; containerPort = deployCfg.nats.metricsPort; - hostPort = deployCfg.nats.metricsPort; - hostIP = networkCfg.bridgeIp; } ]; inherit securityContext; @@ -1083,6 +1084,50 @@ let }; }; + # The exporter answers a request with every client's name, so only the + # node may read it: the Service is reached by name from the host's + # gateway, and the policy admits the node's own traffic (which the + # cluster's policy engine always lets in, ./k8s/render.nix) and, from + # anywhere else, the client port alone. + objects."${machine}/service" = { + apiVersion = "v1"; + kind = "Service"; + metadata = metaFor machine // { + name = metricsService; + }; + spec = { + type = "ClusterIP"; + selector = (metaFor machine).labels; + ports = [ + { + name = "metrics"; + protocol = "TCP"; + port = deployCfg.nats.metricsPort; + targetPort = "metrics"; + } + ]; + }; + }; + objects."${machine}/networkpolicy" = { + apiVersion = "networking.k8s.io/v1"; + kind = "NetworkPolicy"; + metadata = metaFor machine; + spec = { + podSelector.matchLabels = (metaFor machine).labels; + policyTypes = [ "Ingress" ]; + ingress = [ + { + ports = [ + { + protocol = "TCP"; + port = cfg.port; + } + ]; + } + ]; + }; + }; + images = [ init server @@ -1138,6 +1183,10 @@ in {option}`services.hyperhive.swarm.nats.domain` proxies it, behind the swarm collector's authelia check. + With the queue in the cluster this is the exporter container's port in + the pod, which the Service `swarm-nats-metrics` publishes on the same + number and only the node reaches. + ⚠️ This and {option}`services.hyperhive.deploy.nats.monitorPort` are two more claims on a port space every swarm container shares — they run in this container but @@ -1379,14 +1428,24 @@ in # Authelia's rules for it admit the collector's client and deny # every other subject (`metricsRules` in ./swarm-authelia.nix). "= /metrics" = { - # In the cluster the exporter is a container of the pod, published on - # the bridge's address. - proxyPass = "http://${ - if onK8s then networkCfg.bridgeIp else "127.0.0.1" - }:${toString deployCfg.nats.metricsPort}/metrics"; - extraConfig = '' - auth_request /__nats_metrics_authz; - ''; + # In the cluster the exporter is behind a Service, which the host's + # resolver answers through the cluster's DNS. The upstream is a + # variable, so nginx asks the resolver per request: a name in the + # `proxy_pass` gets one lookup when the configuration loads, which + # fails the load while the cluster is down. + proxyPass = + if onK8s then + "http://\$swarm_nats_metrics_upstream/metrics" + else + "http://127.0.0.1:${toString deployCfg.nats.metricsPort}/metrics"; + extraConfig = + lib.optionalString onK8s '' + resolver ${networkCfg.bridgeIp} valid=10s ipv6=off; + set $swarm_nats_metrics_upstream ${metricsHost}:${toString deployCfg.nats.metricsPort}; + '' + + '' + auth_request /__nats_metrics_authz; + ''; }; # The subrequest, same shape as the forge's `= /__forge_metrics_authz` @@ -1470,6 +1529,18 @@ in this host, or leave the queue's runtime at "host". ''; } + { + # The gateway's `/metrics` location dials the exporter's Service by + # name, which only the hive's resolver answers. + assertion = !onK8s || config.services.hyperhive.gateway.dns.enable; + message = '' + services.hyperhive.deploy.nats.runtime = "k8s" needs + services.hyperhive.gateway.dns.enable: the gateway dials the pod's + metrics Service by name, and the hive's resolver is what hands the + cluster's domain to its DNS. Set it, or leave the queue's runtime at + "host". + ''; + } { # The callout xkey and the responder's OIDC client secret are read # from the store under this identity; without either the server or @@ -1544,14 +1615,13 @@ in # sets no listen host), so reachability is the firewall alone. networking.firewall.allowedTCPPorts = lib.mkIf deployCfg.nats.openFirewall [ cfg.port ]; - # The pod's `hostPort`s are DNAT rules, which the INPUT rules above never - # see: ./lib/swarm-nats-raw-rules.nix gives them the container's reach. + # 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); networking.firewall.extraCommands = lib.mkIf onK8s ( import ./lib/swarm-nats-raw-rules.nix { inherit lib; } { chain = "nixos-fw-nats"; clientPort = cfg.port; - metricsPort = deployCfg.nats.metricsPort; trusted = [ "lo" networkCfg.bridgeName diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix index 681a95627..8ba3ff8dd 100644 --- a/nix/module-eval/k8s.nix +++ b/nix/module-eval/k8s.nix @@ -66,6 +66,9 @@ let deploy.swarm-controller.runtime = "k8s"; deploy.swarm-controller.tcp.listenAddress = "10.0.0.5"; deploy.nats.runtime = "k8s"; + deploy.nats.enable = true; + deploy.nats.authPackage = pkgs.emptyDirectory; + gateway.dns.enable = lib.mkForce false; }; runtimeRefusals = lib.filter (a: !a.assertion) runtimeRefused.assertions; @@ -1120,9 +1123,14 @@ let ports = [ (tcp 4222) ]; } ] - && !(lib.any (n: lib.hasSuffix "/networkpolicy" n) ( - lib.attrNames (removeAttrs objects [ "swarm-stt/networkpolicy" ]) - )); + # Only the queue and this pod have a policy here: the others have no + # egress and, with no listener, no ingress rule to give one. + && + lib.sort lib.lessThan (lib.filter (n: lib.hasSuffix "/networkpolicy" n) (lib.attrNames objects)) + == [ + "swarm-nats/networkpolicy" + "swarm-stt/networkpolicy" + ]; } { # Other spellings of a ceiling: bytes, megabytes, a fractional core, no @@ -1414,6 +1422,7 @@ let a: lib.hasInfix "tcp.listenAddress is" a.message && lib.hasInfix "\"10.0.0.5\"" a.message ) runtimeRefusals && lib.any (a: lib.hasInfix "gateway.dns.enable: the gateway dials" a.message) runtimeRefusals + && lib.any (a: lib.hasInfix "metrics Service by name" a.message) runtimeRefusals # The all-local host binds the default, which the refusal lets through. && onCluster.services.hyperhive.deploy.swarm-controller.tcp.listenAddress == "0.0.0.0" && lib.all (a: a.assertion) onCluster.assertions; @@ -1773,8 +1782,8 @@ let "-c" "/var/lib/nats-callout/nats.conf" ] - # The client port is published on every address of the node, and the - # exporter's on the bridge's. + # The client port is published on every address of the node. The + # exporter's port is named for its Service and has no `hostPort`. && (named "nats").ports == [ { @@ -1789,8 +1798,6 @@ let { name = "metrics"; containerPort = 7777; - hostPort = 7777; - hostIP = "10.42.0.1"; } ] && lib.elem "0.0.0.0" (named "exporter").args @@ -1907,10 +1914,11 @@ let { # The host with the queue on it is the control for each absence: it has # the container, both delivery units and no rule in the raw table. - name = "the queue in the cluster leaves the host no container and no delivery unit, keeps the leaf for the gateway's vhost, and points the vhost at the exporter's published port"; + name = "the queue in the cluster leaves the host no container and no delivery unit, keeps the leaf for the gateway's vhost, and points the vhost at the exporter's Service by name"; ok = let vhost = c: c.services.nginx.virtualHosts."nats.t.local".locations."= /metrics".proxyPass; + extra = c: c.services.nginx.virtualHosts."nats.t.local".locations."= /metrics".extraConfig; tls = onCluster.systemd.services.swarm-bao-nats-tls; in withNode.containers ? swarm-nats @@ -1924,7 +1932,7 @@ let && !(lib.hasInfix "nixos-fw-nats" withNode.networking.firewall.extraCommands) && vhost withNode == "http://127.0.0.1:7777/metrics" # In the cluster: nothing to start the server or deliver to it, a leaf - # that restarts nothing, the exporter on the bridge, the bridge up. + # that restarts nothing, the exporter behind its Service, the bridge up. && !(onCluster.containers ? swarm-nats) && !(onCluster.systemd.services ? "container@swarm-nats") && !onCluster.systemd.services.swarm-nats-auth-secrets.enable @@ -1932,20 +1940,68 @@ let && !(lib.elem "container@swarm-nats.service" tls.before) && !(lib.elem "container@swarm-nats.service" tls.wantedBy) && onCluster.systemd.services ? swarm-nats-gateway-cert - && vhost onCluster == "http://10.42.0.1:7777/metrics" + && vhost onCluster == "http://\$swarm_nats_metrics_upstream/metrics" + && lib.hasInfix "resolver 10.42.0.1 valid=10s ipv6=off;" (extra onCluster) + && lib.hasInfix "set \$swarm_nats_metrics_upstream swarm-nats-metrics.hyperhive.svc.cluster.local:7777;" ( + extra onCluster + ) + && !(lib.hasInfix "resolver" (extra withNode)) && onCluster.services.hyperhive.network.enable; } + { + # The host with the queue on it renders the same objects, the control that + # a `deploy.nats.runtime` changes none of them. + name = "the queue's exporter is a ClusterIP Service only the node reaches, and the pod admits the client port from anywhere and nothing else"; + ok = + let + cluster = render onCluster; + svc = cluster."swarm-nats/service"; + policy = cluster."swarm-nats/networkpolicy"; + pod = cluster."swarm-nats/deployment".spec.template.metadata.labels; + in + svc.kind == "Service" + && svc.metadata.name == "swarm-nats-metrics" + && svc.metadata.labels."app.kubernetes.io/name" == "swarm-nats" + && svc.spec.type == "ClusterIP" + && !(svc.spec ? clusterIP) + && svc.spec.selector == pod + && + svc.spec.ports == [ + { + name = "metrics"; + protocol = "TCP"; + port = 7777; + targetPort = "metrics"; + } + ] + && policy.spec.podSelector.matchLabels == pod + && policy.spec.policyTypes == [ "Ingress" ] + && + policy.spec.ingress == [ + { + ports = [ + { + protocol = "TCP"; + port = 4222; + } + ]; + } + ] + && !(policy.spec ? egress) + && (render withNode)."swarm-nats/service" == svc + && (render withNode)."swarm-nats/networkpolicy" == policy + && lib.hasInfix "networkpolicy,service \\" withNode.systemd.services.swarm-nats-k8s-prune.script; + } { # Both arms of `openFirewall`, from the function the module calls, and # the module's own text for the default. - name = "the pod's raw-table rules close the client port as the container's INPUT rules do, and the exporter's port to all but the host's loopback"; + name = "the pod's raw-table rules close the client port as the container's INPUT rules do, and name no other port"; ok = let rules = import ../host-modules/lib/swarm-nats-raw-rules.nix { inherit lib; }; args = { chain = "c"; clientPort = 4222; - metricsPort = 7777; trusted = [ "lo" "br0" @@ -1959,13 +2015,11 @@ let has "-p tcp --dport 4222 -i br0 -j RETURN" closed && has "-p tcp --dport 4222 -i cni0 -j RETURN" closed && has "-p tcp --dport 4222 -m addrtype --dst-type LOCAL -j DROP" closed - # Open, the client port has no rule; the exporter's still has. + # Open, the client port has no rule. The exporter's port, behind a + # Service, has none in either. && !(has "--dport 4222" open) - && has "-p tcp --dport 7777 -i lo -j RETURN" open - && has "-p tcp --dport 7777 -m addrtype --dst-type LOCAL -j DROP" open - # The exporter's port is not returned for the bridge or the pods. - && !(has "--dport 7777 -i br0" closed) - && !(has "--dport 7777 -i cni0" closed) + && !(has "7777" closed) + && !(has "7777" onCluster.networking.firewall.extraCommands) && has "-t raw -I PREROUTING -j c" closed && has "-t raw -A nixos-fw-nats -p tcp --dport 4222 -i cni0 -j RETURN" onCluster.networking.firewall.extraCommands && has "-t raw -A nixos-fw-nats -p tcp --dport 4222 -m addrtype --dst-type LOCAL -j DROP" onCluster.networking.firewall.extraCommands diff --git a/nix/vm-tests/k8s-nats-switch.nix b/nix/vm-tests/k8s-nats-switch.nix index fcb121ecd..9097d61a0 100644 --- a/nix/vm-tests/k8s-nats-switch.nix +++ b/nix/vm-tests/k8s-nats-switch.nix @@ -11,18 +11,18 @@ # 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 and the exporter's on the bridge's; +# on every address, with no `hostPort` on the exporter; # - a client on the hive's bridge reaches the queue by name through the # published port, and the responder in the pod admits the router's token; # - the port is as closed to a host outside the node as the container's is, and # open with `openFirewall`, where a second node dials it by name and verifies -# the name. The exporter's port answers the host's own processes only; +# the name. The exporter answers the host only, by its Service's name; # - a stream written before the pod is deleted is read after; # - 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 or AddOn, and the container -# starts after the prune unit. +# - the switch back leaves no pod, Deployment, 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 @@ -352,6 +352,8 @@ pkgs.testers.runNixOSTest { 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} @@ -394,6 +396,17 @@ pkgs.testers.runNixOSTest { return machine.succeed(f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o name || true").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() @@ -545,6 +558,8 @@ pkgs.testers.runNixOSTest { assert machine.succeed(f"systemctl is-active {PRUNE}.service").strip() == "active" 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 networkpolicy {SERVICE}")[0] != 0 # The control for its absence under the cluster. machine.succeed("test -e /etc/nixos-containers/swarm-nats.conf") assert counts() == (1, 1), counts() @@ -594,7 +609,7 @@ 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, and publishes the client port on every address and the exporter's on the bridge"): + 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"): 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"] @@ -605,7 +620,7 @@ pkgs.testers.runNixOSTest { 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"][0]["hostIP"] == BRIDGE, exporter["ports"] + 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"] @@ -627,6 +642,14 @@ pkgs.testers.runNixOSTest { print(limits) assert int(limits.split()[3]) >= 800000, limits + 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("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) @@ -657,9 +680,21 @@ pkgs.testers.runNixOSTest { 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 through the pod's published port"): - body = machine.succeed(f"curl -sf http://{BRIDGE}:{METRICS}/metrics") + 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"] @@ -712,6 +747,8 @@ pkgs.testers.runNixOSTest { settle(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", 600, [HOST_UNIT, f"{PRUNE}.service"]) 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 networkpolicy {SERVICE}")[0] != 0 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