diff --git a/docs/4-implementation/k8s/manifests.md b/docs/4-implementation/k8s/manifests.md index e58110d44..f664ce69f 100644 --- a/docs/4-implementation/k8s/manifests.md +++ b/docs/4-implementation/k8s/manifests.md @@ -101,6 +101,11 @@ credential directory. escalation, every capability dropped, the runtime's default seccomp profile, and no mounted API token. A service that logs in to the store gets a token of its own, [below](#the-store-login). + `swarm-stt` also runs in a user namespace of its own (`hostUsers: false`), as + the unit's `PrivateUsers` does: its root and every id it holds are + unprivileged ids on the node. A volume keeps the in-pod ownership it has + without one, so `fsGroup` and the credential files' mode work as before. + A service asking for it needs a kernel of 6.3 or later (an assertion). - **Resources:** the unit's `MemoryMax` becomes the container's memory limit (systemd's `K`, `M`, `G` and `T` are Kubernetes' `Ki`, `Mi`, `Gi` and `Ti`; a byte count passes unchanged; `infinity` sets none) and its `CPUQuota`, a @@ -110,9 +115,9 @@ credential directory. cap on the node. The memory request is the unit's `MemoryMin`, else its `MemoryLow`, else `0`, and the cpu request is `0`, so the pod is Burstable. A value in another form fails evaluation. `TasksMax` has no pod field, so the - 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. + renderer drops it. The unit's sandbox settings (`MemoryDenyWriteExecute`, + `SystemCallFilter` 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, diff --git a/docs/4-implementation/k8s/runtime.md b/docs/4-implementation/k8s/runtime.md index 62ec21308..4719ec049 100644 --- a/docs/4-implementation/k8s/runtime.md +++ b/docs/4-implementation/k8s/runtime.md @@ -276,19 +276,20 @@ The pod takes the unit's `MemoryMax` and `CPUQuota` as its container's limits 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. 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. +systemd sandbox (`MemoryDenyWriteExecute`, `SystemCallFilter`, the read-only +`ProtectSystem` and the rest) stays on the host, and `PrivateUsers` is the pod's +own user namespace (`hostUsers: false`). 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 f870d51e7..395b5c20a 100644 --- a/docs/4-implementation/swarm/stt.md +++ b/docs/4-implementation/swarm/stt.md @@ -101,10 +101,11 @@ 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. 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 security shape every pod has, in a user namespace of its own as the unit has +`PrivateUsers`. 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 diff --git a/nix/host-modules/k8s/default.nix b/nix/host-modules/k8s/default.nix index 3392ae4b6..3c8fc1275 100644 --- a/nix/host-modules/k8s/default.nix +++ b/nix/host-modules/k8s/default.nix @@ -69,7 +69,12 @@ in config = lib.mkIf cfg.enable { services.hyperhive.k8s.rendered = { - inherit (rendered) caConfigMap caSources switches; + inherit (rendered) + caConfigMap + caSources + switches + userNamespaces + ; services = withoutContext rendered.services; namespaceObject = withoutContext rendered.objects.namespace; }; diff --git a/nix/host-modules/k8s/render.nix b/nix/host-modules/k8s/render.nix index ae192d092..abe331cc9 100644 --- a/nix/host-modules/k8s/render.nix +++ b/nix/host-modules/k8s/render.nix @@ -153,9 +153,10 @@ 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. + # `egress`, where a service has it, names the host services (`hostPorts`) its + # pod may reach: it gets a NetworkPolicy that allows those and cluster DNS and + # admits no ingress. `hostUsers = false` runs the pod in a user namespace of + # its own, so its ids map to unprivileged ones on the node. services = { swarm-controller = { inherit (controllerCfg) enable package unit; @@ -233,6 +234,9 @@ let ]; otlp = "hive"; ephemeralState = true; + # Stands in for the unit's `PrivateUsers`: the decoder reads audio that + # strangers sent. + hostUsers = false; switch = { inherit (deployCfg.stt) runtime; hostUnit = "container@swarm-stt.service"; @@ -912,6 +916,7 @@ let }; } // lib.optionalAttrs baoLogin { serviceAccountName = name; } + // lib.optionalAttrs (svc ? hostUsers && !svc.hostUsers) { hostUsers = false; } // lib.optionalAttrs (listener != { } || extra.initContainers != [ ]) { initContainers = lib.optional (listener != { }) leafContainer ++ extra.initContainers; } @@ -1068,6 +1073,10 @@ in switches = lib.mapAttrs (_: svc: svc.switch) ( lib.filterAttrs (_: svc: svc.enable && svc.switch != null) services ); + # The services whose pods run in a user namespace. Cheap to read, like `switches`. + userNamespaces = lib.attrNames ( + lib.filterAttrs (_: svc: svc.enable && svc ? hostUsers && !svc.hostUsers) services + ); services = lib.mapAttrs (_: w: { inherit (w) objects; }) enabled; inherit caConfigMap caSources; } diff --git a/nix/host-modules/k8s/runtime.nix b/nix/host-modules/k8s/runtime.nix index 64bcfa81e..0cfd136f8 100644 --- a/nix/host-modules/k8s/runtime.nix +++ b/nix/host-modules/k8s/runtime.nix @@ -30,10 +30,29 @@ let apiReady = waitFor 600 "the cluster's API" "${kubectl} get --raw /readyz >/dev/null 2>&1"; caFiles = lib.filterAttrs (_: path: path != null) rendered.caSources; + + # The services on the cluster whose pods run in a user namespace. + userNamespaced = lib.filter (name: onCluster ? ${name}) rendered.userNamespaces; in { config = lib.mkIf (node.enable && cfg.enable) ( lib.mkMerge [ + # A pod in a user namespace needs idmapped mounts for its volumes, which the + # kernel has for tmpfs from 6.3 on (the projected token and the Secrets + # are tmpfs). + (lib.mkIf (userNamespaced != [ ]) { + assertions = [ + { + assertion = lib.versionAtLeast config.boot.kernelPackages.kernel.version "6.3"; + message = '' + The pods of ${lib.concatStringsSep ", " userNamespaced} run in a user + namespace (`hostUsers = false`), which needs a kernel of 6.3 or + later; this host's kernel is ${config.boot.kernelPackages.kernel.version}. + ''; + } + ]; + }) + (lib.mkIf (onCluster != { }) { # The cluster applies each file of the manifests directory when it # appears: a service's objects go in when its host unit has stopped, diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix index 1cf77d49d..d36aee9b4 100644 --- a/nix/module-eval/k8s.nix +++ b/nix/module-eval/k8s.nix @@ -1007,6 +1007,32 @@ let && sttPrune.requiredBy == [ "container@swarm-stt.service" ] && lib.hasInfix "swarm-stt.yaml" sttPrune.script; } + { + # Only the speech-to-text pod is in a user namespace: every other pod is + # the control that the field is not rendered for a service without it. + # With the service on the host nothing asks for one, so the kernel + # assertion is absent; with it on the cluster the assertion is there and + # holds for the fixture's kernel. + name = "only the speech-to-text pod runs in a user namespace, and a host with it on the cluster asserts a kernel of 6.3 or later"; + ok = + let + # The assertions defined in runtime.nix, found by where their message + # is written: reading every host's messages evaluates NixOS's own, + # which throw when their condition holds. + userns = + c: + lib.filter ( + a: lib.hasSuffix "/k8s/runtime.nix" (builtins.unsafeGetAttrPos "message" a).file + ) c.assertions; + in + (podSpec "swarm-stt").hostUsers == false + && lib.all (n: !((podSpec n) ? hostUsers)) (lib.filter (n: n != "swarm-stt") (lib.attrNames units)) + && withNode.services.hyperhive.k8s.rendered.userNamespaces == [ "swarm-stt" ] + && userns withNode == [ ] + && lib.length (userns onCluster) == 1 + && (lib.head (userns onCluster)).assertion + && lib.versionAtLeast onCluster.boot.kernelPackages.kernel.version "6.3"; + } { # The unit's ceilings are the pod's limits and reserve nothing, and the # limits the pod has no field for are not rendered. The controller's pod, diff --git a/nix/vm-tests/k8s-runtime-switch.nix b/nix/vm-tests/k8s-runtime-switch.nix index e0d491a4d..25a11df80 100644 --- a/nix/vm-tests/k8s-runtime-switch.nix +++ b/nix/vm-tests/k8s-runtime-switch.nix @@ -13,8 +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, and its NetworkPolicy lets a queue request -# reach it, and it reach DNS and four host ports, and nothing else; +# with no claim and no state gate, in a user namespace, and its NetworkPolicy +# lets a queue request in and only DNS and four host ports out; # - 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 @@ -736,6 +736,25 @@ pkgs.testers.runNixOSTest { router_resources = json.loads(kube(machine, f"get pod {router} -o json"))["spec"]["containers"][0]["resources"] assert router_resources == {}, router_resources + with subtest("the speech-to-text pod runs in a user namespace, and still logs in, writes its state and starts its decoder"): + assert kube(machine, f"get pod {stt_pod} -o jsonpath='{{.spec.hostUsers}}'").strip() == "false" + def id_map(service: str) -> list[str]: + container = machine.succeed(f"k3s crictl ps --name '^{service}$' --state running -q").split()[0] + pid = machine.succeed(f"k3s crictl inspect {container} | jq -r .info.pid").strip() + return machine.succeed(f"cat /proc/{pid}/uid_map").split() + + # The router's pod shares the node's ids, which is what reading the map + # shows when there is no namespace. + assert id_map(SERVICE) == ["0", "0", "4294967295"], id_map(SERVICE) + mapping = id_map(STT) + assert mapping[0] == "0" and int(mapping[1]) >= 65536 and mapping[2] == "65536", mapping + # The login read the projected token, and the decode writes a scratch + # directory in the emptyDir; both volumes are idmapped mounts. + machine.wait_until_succeeds(f"grep -F '/api/oidc/token ${sttClientId}:{STT_SECRET}' ${tokenLog}", timeout=120) + out = machine.succeed(f"nats {NATS} req '$SWARM.stt.transcribe.{AGENT}' 'OggS not really audio' --timeout 90s 2>/dev/null") + reply = json.loads([line for line in out.splitlines() if line.startswith("{")][-1]) + assert reply == {"status": "failed", "message": "the audio could not be decoded"}, reply + with subtest("the speech-to-text cache is an emptyDir mounted where the unit keeps its state, with no claim and no state gate"): stt_spec = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["spec"] assert [v for v in stt_spec["volumes"] if v["name"] == "state"] == [{"name": "state", "emptyDir": {}}], stt_spec["volumes"]