From 2259b5f27bba0dd253032a8db5e42c5c819901c6 Mon Sep 17 00:00:00 2001 From: atlas Date: Mon, 23 Nov 2026 13:36:51 +0100 Subject: [PATCH] k8s: stt's pod gets a network policy: dns and four host ports out, nothing in --- docs/4-implementation/k8s/manifests.md | 12 +++- docs/4-implementation/k8s/node.md | 4 ++ docs/4-implementation/k8s/runtime.md | 27 ++++++--- docs/4-implementation/swarm/stt.md | 20 ++++--- nix/checks.nix | 1 + nix/host-modules/k8s/render.nix | 82 ++++++++++++++++++++++++++ nix/host-modules/k8s/runtime.nix | 2 +- nix/module-eval/k8s.nix | 82 +++++++++++++++++++++++++- nix/vm-tests/k8s-runtime-switch.nix | 54 ++++++++++++++++- 9 files changed, 262 insertions(+), 22 deletions(-) diff --git a/docs/4-implementation/k8s/manifests.md b/docs/4-implementation/k8s/manifests.md index 1dfb0f10f..e58110d44 100644 --- a/docs/4-implementation/k8s/manifests.md +++ b/docs/4-implementation/k8s/manifests.md @@ -23,7 +23,7 @@ A service gets manifests on the host whose configuration deploys it: | ------------------------- | ---------- | ------------------------------------------------------------------------------------------------ | | `swarm-controller` | Deployment | ServiceAccount, PersistentVolumeClaim `swarm-controller-state`, ConfigMap `swarm-controller-etc` | | `swarm-notify-router` | Deployment | ServiceAccount | -| `swarm-stt` | Deployment | ServiceAccount | +| `swarm-stt` | Deployment | ServiceAccount, NetworkPolicy `swarm-stt` | | `swarm-review-classifier` | Deployment | ServiceAccount | | `swarm-claude-login` | Deployment | ServiceAccount | | `swarm-ci-metrics` | CronJob | ServiceAccount, PersistentVolumeClaim `swarm-ci-metrics-state` | @@ -113,6 +113,16 @@ credential directory. renderer drops it. The unit's sandbox settings (`MemoryDenyWriteExecute`, `SystemCallFilter`, `PrivateUsers` and the rest) stay on the host: the pod has the security shape above and no other. +- **Network:** a service whose entry has `egress` (`swarm-stt`) gets a + NetworkPolicy named after it, selecting its pods for ingress and egress. It + allows no ingress; its egress is cluster DNS (the CoreDNS pod, port 53) and, + on the hive bridge's address, one TCP port per host service the entry names: + the store's pod listener (`store`), the gateway's 443 for the identity + provider (`identity`), the queue's port (`queue`) and the hive collector's + (`collector`). Where the queue runs in the cluster, its pod on its port is + allowed too. The node trusts the pod network's interfaces, so without the + policy a pod reaches every port of the host. A service without `egress` has no + policy. - **Probes:** a service with an opt-in health listener gets its variable set to `0.0.0.0:8080`, with liveness on `/healthz` and readiness on `/readyz` (see [Readiness checks](../swarm/readiness.md)). `swarm-controller` is one of diff --git a/docs/4-implementation/k8s/node.md b/docs/4-implementation/k8s/node.md index f49837810..359597a35 100644 --- a/docs/4-implementation/k8s/node.md +++ b/docs/4-implementation/k8s/node.md @@ -28,6 +28,10 @@ service images loaded and no service's objects applied. bridge's default subnet. - **Firewall:** the pod network's interfaces, `cni0` and `flannel.1`, are trusted, so the node reaches its pods. +- **NetworkPolicy:** k3s's own controller (kube-router, iptables) enforces + NetworkPolicy objects; the node doesn't turn it off. A pod no policy selects + reaches whatever it can route to. [The manifests](manifests.md#pods) say which + pods have one. - **Secret store:** the store gets a second listener and an auth mount for the pods' ServiceAccount tokens, described under [Logging in to the secret store](#logging-in-to-the-secret-store). diff --git a/docs/4-implementation/k8s/runtime.md b/docs/4-implementation/k8s/runtime.md index 92df6d9b6..62ec21308 100644 --- a/docs/4-implementation/k8s/runtime.md +++ b/docs/4-implementation/k8s/runtime.md @@ -92,9 +92,10 @@ Job: cluster doesn't apply it again. The rename also records what remains to delete. With no link, nothing went in, so the unit does nothing and needs no cluster. -2. Wait for the cluster's API, then delete the service's Deployment, CronJob and - ServiceAccount (selected by `app.kubernetes.io/name`), and wait until its pods - have gone. A pod exits 0 within its termination grace period. +2. Wait for the cluster's API, then delete the service's Deployment, CronJob, + NetworkPolicy and ServiceAccount (selected by `app.kubernetes.io/name`), and + wait until its pods have gone. A pod exits 0 within its termination grace + period. 3. Delete the cluster's AddOn for the file, so that a later switch to `"k8s"` applies the same manifest again. Then remove the renamed link. @@ -274,12 +275,20 @@ The pod takes the unit's `MemoryMax` and `CPUQuota` as its container's limits ([manifests](manifests.md#pods)), so `swarm-stt` keeps its 3 GiB and four-core ceilings. The pod requests nothing (memory `0`, cpu `0`, as the unit sets no `MemoryMin` or `MemoryLow`), so the node reserves nothing for it and the pod is -Burstable. `TasksMax` has no pod counterpart, so the renderer drops it. The systemd sandbox -(`MemoryDenyWriteExecute`, `SystemCallFilter`, `PrivateUsers`, the read-only -`ProtectSystem` and the rest) stays on the host. The pod is a non-root user with -a read-only root filesystem, every capability dropped, the runtime's default -seccomp profile and no API token, which is its whole sandbox. Neither side -restricts the network. +Burstable. `TasksMax` has no pod counterpart, so the renderer drops it. The +systemd sandbox (`MemoryDenyWriteExecute`, `SystemCallFilter`, `PrivateUsers`, +the read-only `ProtectSystem` and the rest) stays on the host. The pod is a +non-root user with a read-only root filesystem, every capability dropped, the +runtime's default seccomp profile and no API token. The host unit doesn't +restrict the network. The pod has a NetworkPolicy (`swarm-stt`, rendered with +the pod): it may reach cluster DNS, and on the node's bridge address the store's +pod listener, the identity provider, the queue and the hive collector, each on +its one port. It admits no ingress. The kubelet's probes still reach the pod, +because the node's own traffic to a pod is always admitted, and the pod doesn't +serve anything else: requests reach it as queue messages, over the connection it +opens. Where the queue runs in the cluster, the policy also allows the queue's +pod on its port, because the node forwards the queue's `hostPort` to the pod +before the policy sees the packet. ## Telemetry and credentials of the poller diff --git a/docs/4-implementation/swarm/stt.md b/docs/4-implementation/swarm/stt.md index 2a712b995..f870d51e7 100644 --- a/docs/4-implementation/swarm/stt.md +++ b/docs/4-implementation/swarm/stt.md @@ -101,16 +101,18 @@ With `deploy.stt.runtime = "k8s"` on a host that runs the cluster (`deploy.k8s.enable`), the service runs as a pod and the host has no container. The pod has the unit's memory and CPU ceilings as limits and its cache on a volume of the cluster. The systemd sandbox stays on the host, and the pod has -the security shape every pod has; neither restricts the network. Nothing moves -in a switch, so each side keeps the cache it last had; see -[the runtime switch](../k8s/runtime.md). +the security shape every pod has. The pod's NetworkPolicy lets it reach cluster +DNS and the store, identity provider, queue and hive collector on the host and +nothing else, and admits no ingress. Nothing moves in a switch, so each side +keeps the cache it last had; see [the runtime switch](../k8s/runtime.md). The audio comes from rooms with outside people, so the service runs as its own -unprivileged user under a tight systemd sandbox, with a memory ceiling and -a CPU quota. Its network isn't restricted: the decoder runs in the same -network namespace as the service and can read its credentials, so a decoder +unprivileged user under a tight systemd sandbox, with a memory ceiling and a CPU +quota. In the container its network isn't restricted: the decoder runs in the +same network namespace as the service and can read its credentials, so a decoder exploit could read them and send them anywhere the container can reach. Closing that's for the strict-egress work on service containers, or for running the -decode with no network and no credentials. The file's first bytes must look like an audio container -before anything decodes it. Its leaf and its queue client work as the notification router's -do. +decode with no network and no credentials. In the pod the policy limits where +they can go to those four host services. The file's first bytes must look like +an audio container before anything decodes it. Its leaf and its queue client +work as the notification router's do. diff --git a/nix/checks.nix b/nix/checks.nix index 90dce2921..1a570b08e 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -58,6 +58,7 @@ in configmap-v1 = "sha256-4Ord69Z3wIqgkrLaImTYasT8NO7RErn6wpRbPwDB6bE="; namespace-v1 = "sha256-Mk+uZ3uY0abVQ0DbDDNNBT6P+6/Os/czJuQd4mENWEM="; serviceaccount-v1 = "sha256-gZPWw1YUdcbT1cROH67bHfU5BTc9kEvBcBVpQybWWc8="; + networkpolicy-networking-v1 = "sha256-9jJMxGT2IiiwQY9DjRZyCOT4bH42d7ow9gjnmosmunk="; } ); invalid = pkgs.writeText "invalid-deployment.yaml" '' diff --git a/nix/host-modules/k8s/render.nix b/nix/host-modules/k8s/render.nix index 2df541c74..ae192d092 100644 --- a/nix/host-modules/k8s/render.nix +++ b/nix/host-modules/k8s/render.nix @@ -153,6 +153,9 @@ let # containers, init containers, volumes, host aliases, pod settings, objects and # and images. An `otlp` of `"none"` is a daemon that pushes no telemetry of its # own. + # `egress`, where a service has it, names the host services its pod may reach + # (`hostPorts`). The pod then gets a NetworkPolicy that lets it reach those + # and cluster DNS and nothing else, and that admits no ingress. services = { swarm-controller = { inherit (controllerCfg) enable package unit; @@ -219,6 +222,15 @@ let healthEnv = "SWARM_STT_HEALTH_ADDR"; etcFiles = [ ]; publicCredentials.stt-bao-server-ca = baoServerCaKey; + # The audio it decodes comes from strangers. It reaches the store, the + # identity provider and the queue it logs in to and answers on, and + # pushes telemetry to the hive collector. + egress = [ + "store" + "identity" + "queue" + "collector" + ]; otlp = "hive"; ephemeralState = true; switch = { @@ -342,6 +354,71 @@ let labels = labelsFor name; }; + # The host services a pod's `egress` names, each the TCP port it is reached + # on at the bridge's address (./host-services.nix). The node trusts the pod + # network's interfaces, so a NetworkPolicy is the only thing that limits + # which of the host's ports a pod reaches. The identity provider is the + # gateway's vhost: `swarm.authelia.url` names no port. + hostPorts = { + store = baoDeployCfg.podListenerPort; + identity = 443; + queue = hyperhiveCfg.swarm.nats.port; + collector = hyperhiveCfg.swarm.hiveOtel.collectorPort; + }; + + # 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. + networkPolicyOf = + name: reaches: + let + tcp = port: { + protocol = "TCP"; + inherit port; + }; + queueOnCluster = natsCfg.enable && natsCfg.runtime == "k8s"; + in + { + apiVersion = "networking.k8s.io/v1"; + kind = "NetworkPolicy"; + metadata = metaFor name; + spec = { + podSelector.matchLabels = labelsFor name; + policyTypes = [ + "Ingress" + "Egress" + ]; + egress = [ + { + to = [ + { + namespaceSelector.matchLabels."kubernetes.io/metadata.name" = "kube-system"; + podSelector.matchLabels.k8s-app = "kube-dns"; + } + ]; + ports = [ + { + protocol = "UDP"; + port = 53; + } + (tcp 53) + ]; + } + { + to = [ { ipBlock.cidr = "${hyperhiveCfg.network.bridgeIp}/32"; } ]; + ports = map (r: tcp hostPorts.${r}) reaches; + } + ] + ++ lib.optional (queueOnCluster && lib.elem "queue" reaches) { + to = [ { podSelector.matchLabels = labelsFor "swarm-nats"; } ]; + ports = [ (tcp hostPorts.queue) ]; + }; + }; + }; + # systemd duration "min", the only form these units use. minutesOf = name: what: value: @@ -909,6 +986,9 @@ let "${name}/${lib.toLower svc.kind}" = main; } // extra.objects + // lib.optionalAttrs (svc ? egress) { + "${name}/networkpolicy" = networkPolicyOf name svc.egress; + } // lib.optionalAttrs baoLogin { # Named after the service: the store's jwt role binds this account. "${name}/serviceaccount" = { @@ -944,6 +1024,8 @@ let fail name "the unit names no OTLP endpoint of its own, which the pod would push to" else if svc.healthEnv != null && unitEnv ? ${svc.healthEnv} then fail name "the unit already sets ${svc.healthEnv}" + else if svc ? egress && !(lib.all (r: hostPorts ? ${r}) svc.egress) then + fail name "egress names a host service the renderer has no port for (${lib.concatStringsSep ", " (lib.attrNames hostPorts)})" else if lib.head execWords != entrypoint then fail name "ExecStart is not ${entrypoint} with plain arguments" else if lib.any (w: lib.hasInfix "\"" w) execWords then diff --git a/nix/host-modules/k8s/runtime.nix b/nix/host-modules/k8s/runtime.nix index ef4e77070..64bcfa81e 100644 --- a/nix/host-modules/k8s/runtime.nix +++ b/nix/host-modules/k8s/runtime.nix @@ -126,7 +126,7 @@ in exit 0 fi ${apiReady} - ${kubectl} --namespace ${cfg.namespace} delete deployment,cronjob,serviceaccount \ + ${kubectl} --namespace ${cfg.namespace} delete deployment,cronjob,serviceaccount,networkpolicy \ --selector=app.kubernetes.io/name=${name} \ --cascade=foreground --wait=true --timeout=180s --ignore-not-found ${kubectl} --namespace kube-system delete addons.k3s.cattle.io ${name} --ignore-not-found diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix index c45ae6420..1cf77d49d 100644 --- a/nix/module-eval/k8s.nix +++ b/nix/module-eval/k8s.nix @@ -110,7 +110,11 @@ let objects = render allLocal; # The queue's pod reads the settings of the system it runs from, which differ # in the path of the server's key: what a switch must leave alone is the rest. - notQueue = lib.filterAttrs (n: _: !(lib.hasPrefix "swarm-nats/" n)); + # The speech-to-text policy names the queue's pod only where the queue runs in + # the cluster, so it follows the queue; its own case reads it. + notQueue = lib.filterAttrs ( + n: _: !(lib.hasPrefix "swarm-nats/" n) && n != "swarm-stt/networkpolicy" + ); units = { swarm-controller = allLocal.systemd.services.swarm-controller; @@ -888,6 +892,7 @@ let && lib.sort lib.lessThan (map (o: o.kind) onCluster.services.k3s.manifests.swarm-stt.content) == [ "Deployment" + "NetworkPolicy" "ServiceAccount" ] && @@ -1034,6 +1039,81 @@ let "swarm-ci-metrics" ]; } + { + # The policy is pinned by value: the ports are literals, not the options + # the render reads. The router's pod is the control that a service + # without `egress` has no policy, and the host without the queue in the + # cluster the control that the queue's pod rule follows the queue. + name = "the speech-to-text pod's NetworkPolicy admits no ingress and allows DNS and four host ports, and a pod without egress has none"; + ok = + let + bridge = "${withNode.services.hyperhive.network.bridgeIp}/32"; + policyOf = o: o."swarm-stt/networkpolicy"; + policy = policyOf objects; + clusterPolicy = policyOf (render onCluster); + tcp = port: { + protocol = "TCP"; + inherit port; + }; + dns = { + to = [ + { + namespaceSelector.matchLabels."kubernetes.io/metadata.name" = "kube-system"; + podSelector.matchLabels.k8s-app = "kube-dns"; + } + ]; + ports = [ + { + protocol = "UDP"; + port = 53; + } + (tcp 53) + ]; + }; + host = { + to = [ { ipBlock.cidr = bridge; } ]; + ports = map tcp [ + 8208 + 443 + 4222 + 4318 + ]; + }; + in + policy.kind == "NetworkPolicy" + && policy.metadata.namespace == "hyperhive" + && policy.metadata.labels."app.kubernetes.io/name" == "swarm-stt" + && policy.spec.podSelector.matchLabels == objects."swarm-stt/deployment".spec.selector.matchLabels + && + policy.spec.policyTypes == [ + "Ingress" + "Egress" + ] + && !(policy.spec ? ingress) + && + policy.spec.egress == [ + dns + host + ] + && + clusterPolicy.spec.egress == [ + dns + host + { + to = [ + { + podSelector.matchLabels = objects."swarm-stt/deployment".spec.selector.matchLabels // { + "app.kubernetes.io/name" = "swarm-nats"; + }; + } + ]; + ports = [ (tcp 4222) ]; + } + ] + && !(lib.any (n: lib.hasSuffix "/networkpolicy" n) ( + lib.attrNames (removeAttrs objects [ "swarm-stt/networkpolicy" ]) + )); + } { # Other spellings of a ceiling: bytes, megabytes, a fractional core, no # memory limit. A setting render cannot read fails the evaluation, the diff --git a/nix/vm-tests/k8s-runtime-switch.nix b/nix/vm-tests/k8s-runtime-switch.nix index 4a91b16f8..e0d491a4d 100644 --- a/nix/vm-tests/k8s-runtime-switch.nix +++ b/nix/vm-tests/k8s-runtime-switch.nix @@ -13,7 +13,8 @@ # token, read its client secret and minted a token with it. The router # routes an event and a deleted pod exits 0 within its grace period; the # speech-to-text pod carries its limits and keeps its cache in an emptyDir, -# with no claim and no state gate; +# with no claim and no state gate, and its NetworkPolicy lets a queue request +# reach it, and it reach DNS and four host ports, and nothing else; # - the poller's Job completes against a forge that lists one run, pushes it to # its own route of the swarm collector, holds no Secret, and keeps its cursor # in a volume, so a second Job pushes nothing, and starts with no state @@ -347,6 +348,7 @@ pkgs.testers.runNixOSTest { pkgs.jq pkgs.openssl pkgs.natscli + pkgs.dig ]; environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml"; # The store paths each daemon's `claude` pulls in, so the script can find @@ -742,6 +744,55 @@ pkgs.testers.runNixOSTest { mounts = stt_spec["containers"][0]["volumeMounts"] assert any(m["name"] == "state" and m["mountPath"] == "/var/lib/swarm-stt" for m in mounts), mounts + def pod_pid(service: str) -> str: + container = machine.succeed(f"k3s crictl ps --name '^{service}$' --state running -q").split()[0] + return machine.succeed(f"k3s crictl inspect {container} | 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/null") + reply = json.loads([line for line in out.splitlines() if line.startswith("{")][-1]) + print(f"stt reply: {reply}") + # The audio looks like Ogg, so ffmpeg is started in the pod and refuses it. + assert reply == {"status": "failed", "message": "the audio could not be decoded"}, reply + + with subtest("the speech-to-text pod reaches the host ports its policy names and the cluster's DNS, and no other port of the host"): + stt_pid = pod_pid(STT) + router_pid = pod_pid(SERVICE) + # A listener on a port no policy names, on the bridge's address. The + # host and the router's pod, which has no policy, reach it: the control + # that the listener is up and a pod can dial it. + machine.succeed("systemd-run --unit=exfil-standin ${pkgs.socat}/bin/socat TCP-LISTEN:9999,bind=${bridgeIp},reuseaddr,fork /dev/null") + machine.wait_until_succeeds("timeout 5 bash -c '