Watch
0
0
Fork
You've already forked hyperhive
0

k8s: stt's pod runs in a user namespace of its own

This commit is contained in:
atlas 2026-11-23 13:44:57 +01:00 • committed by maia
commit 4e60183bfa
8 changed files with 111 additions and 26 deletions

View file

@ -101,6 +101,11 @@ credential directory.
escalation, every capability dropped, the runtime's default seccomp profile, 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 and no mounted API token. A service that logs in to the store gets a token
of its own, [below](#the-store-login). 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 - **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 (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 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 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 `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 value in another form fails evaluation. `TasksMax` has no pod field, so the
renderer drops it. The unit's sandbox settings renderer drops it. The unit's sandbox settings (`MemoryDenyWriteExecute`,
(`MemoryDenyWriteExecute`, `SystemCallFilter`, `PrivateUsers` and the rest) `SystemCallFilter` and the rest) stay on the host: the pod has the security
stay on the host: the pod has the security shape above and no other. shape above and no other.
- **Network:** a service whose entry has `egress` (`swarm-stt`) gets a - **Network:** a service whose entry has `egress` (`swarm-stt`) gets a
NetworkPolicy named after it, selecting its pods for ingress and egress. It 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, allows no ingress; its egress is cluster DNS (the CoreDNS pod, port 53) and,

View file

@ -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 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 `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 Burstable. `TasksMax` has no pod counterpart, so the renderer drops it. The
systemd sandbox (`MemoryDenyWriteExecute`, `SystemCallFilter`, `PrivateUsers`, systemd sandbox (`MemoryDenyWriteExecute`, `SystemCallFilter`, the read-only
the read-only `ProtectSystem` and the rest) stays on the host. The pod is a `ProtectSystem` and the rest) stays on the host, and `PrivateUsers` is the pod's
non-root user with a read-only root filesystem, every capability dropped, the own user namespace (`hostUsers: false`). The pod is a non-root user with a
runtime's default seccomp profile and no API token. The host unit doesn't read-only root filesystem, every capability dropped, the runtime's default
restrict the network. The pod has a NetworkPolicy (`swarm-stt`, rendered with seccomp profile and no API token. The host unit doesn't restrict the network.
the pod): it may reach cluster DNS, and on the node's bridge address the store's The pod has a NetworkPolicy (`swarm-stt`, rendered with the pod): it may reach
pod listener, the identity provider, the queue and the hive collector, each on cluster DNS, and on the node's bridge address the store's pod listener, the
its one port. It admits no ingress. The kubelet's probes still reach the pod, identity provider, the queue and the hive collector, each on its one port. It
because the node's own traffic to a pod is always admitted, and the pod doesn't admits no ingress. The kubelet's probes still reach the pod, because the node's
serve anything else: requests reach it as queue messages, over the connection it own traffic to a pod is always admitted, and the pod doesn't serve anything
opens. Where the queue runs in the cluster, the policy also allows the queue's else: requests reach it as queue messages, over the connection it opens. Where
pod on its port, because the node forwards the queue's `hostPort` to the pod the queue runs in the cluster, the policy also allows the queue's pod on its
before the policy sees the packet. port, because the node forwards the queue's `hostPort` to the pod before the
policy sees the packet.
## Telemetry and credentials of the poller ## Telemetry and credentials of the poller

View file

@ -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. (`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 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 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 the security shape every pod has, in a user namespace of its own as the unit has
DNS and the store, identity provider, queue and hive collector on the host and `PrivateUsers`. The pod's NetworkPolicy lets it reach cluster DNS and the store,
nothing else, and admits no ingress. Nothing moves in a switch, so each side identity provider, queue and hive collector on the host and nothing else, and
keeps the cache it last had; see [the runtime switch](../k8s/runtime.md). 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 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 unprivileged user under a tight systemd sandbox, with a memory ceiling and a CPU

View file

@ -69,7 +69,12 @@ in
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
services.hyperhive.k8s.rendered = { services.hyperhive.k8s.rendered = {
inherit (rendered) caConfigMap caSources switches; inherit (rendered)
caConfigMap
caSources
switches
userNamespaces
;
services = withoutContext rendered.services; services = withoutContext rendered.services;
namespaceObject = withoutContext rendered.objects.namespace; namespaceObject = withoutContext rendered.objects.namespace;
}; };

View file

@ -153,9 +153,10 @@ let
# containers, init containers, volumes, host aliases, pod settings, objects and # 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 # and images. An `otlp` of `"none"` is a daemon that pushes no telemetry of its
# own. # own.
# `egress`, where a service has it, names the host services its pod may reach # `egress`, where a service has it, names the host services (`hostPorts`) its
# (`hostPorts`). The pod then gets a NetworkPolicy that lets it reach those # pod may reach: it gets a NetworkPolicy that allows those and cluster DNS and
# and cluster DNS and nothing else, and that admits no ingress. # 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 = { services = {
swarm-controller = { swarm-controller = {
inherit (controllerCfg) enable package unit; inherit (controllerCfg) enable package unit;
@ -233,6 +234,9 @@ let
]; ];
otlp = "hive"; otlp = "hive";
ephemeralState = true; ephemeralState = true;
# Stands in for the unit's `PrivateUsers`: the decoder reads audio that
# strangers sent.
hostUsers = false;
switch = { switch = {
inherit (deployCfg.stt) runtime; inherit (deployCfg.stt) runtime;
hostUnit = "container@swarm-stt.service"; hostUnit = "container@swarm-stt.service";
@ -912,6 +916,7 @@ let
}; };
} }
// lib.optionalAttrs baoLogin { serviceAccountName = name; } // lib.optionalAttrs baoLogin { serviceAccountName = name; }
// lib.optionalAttrs (svc ? hostUsers && !svc.hostUsers) { hostUsers = false; }
// lib.optionalAttrs (listener != { } || extra.initContainers != [ ]) { // lib.optionalAttrs (listener != { } || extra.initContainers != [ ]) {
initContainers = lib.optional (listener != { }) leafContainer ++ extra.initContainers; initContainers = lib.optional (listener != { }) leafContainer ++ extra.initContainers;
} }
@ -1068,6 +1073,10 @@ in
switches = lib.mapAttrs (_: svc: svc.switch) ( switches = lib.mapAttrs (_: svc: svc.switch) (
lib.filterAttrs (_: svc: svc.enable && svc.switch != null) services 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; services = lib.mapAttrs (_: w: { inherit (w) objects; }) enabled;
inherit caConfigMap caSources; inherit caConfigMap caSources;
} }

View file

@ -30,10 +30,29 @@ let
apiReady = waitFor 600 "the cluster's API" "${kubectl} get --raw /readyz >/dev/null 2>&1"; apiReady = waitFor 600 "the cluster's API" "${kubectl} get --raw /readyz >/dev/null 2>&1";
caFiles = lib.filterAttrs (_: path: path != null) rendered.caSources; 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 in
{ {
config = lib.mkIf (node.enable && cfg.enable) ( config = lib.mkIf (node.enable && cfg.enable) (
lib.mkMerge [ 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 != { }) { (lib.mkIf (onCluster != { }) {
# The cluster applies each file of the manifests directory when it # The cluster applies each file of the manifests directory when it
# appears: a service's objects go in when its host unit has stopped, # appears: a service's objects go in when its host unit has stopped,

View file

@ -1007,6 +1007,32 @@ let
&& sttPrune.requiredBy == [ "container@swarm-stt.service" ] && sttPrune.requiredBy == [ "container@swarm-stt.service" ]
&& lib.hasInfix "swarm-stt.yaml" sttPrune.script; && 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 # 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, # limits the pod has no field for are not rendered. The controller's pod,

View file

@ -13,8 +13,8 @@
# token, read its client secret and minted a token with it. The router # 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 # 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, # 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 # with no claim and no state gate, in a user namespace, and its NetworkPolicy
# reach it, and it reach DNS and four host ports, and nothing else; # 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 # - 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 # 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 # 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"] router_resources = json.loads(kube(machine, f"get pod {router} -o json"))["spec"]["containers"][0]["resources"]
assert router_resources == {}, router_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"): 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"] 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"] assert [v for v in stt_spec["volumes"] if v["name"] == "state"] == [{"name": "state", "emptyDir": {}}], stt_spec["volumes"]