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 mara
commit ada980f35c
5 changed files with 111 additions and 26 deletions

View file

@ -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;
};

View file

@ -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;
}

View file

@ -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,

View file

@ -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,

View file

@ -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"]