From d9023217fc622de4402091000bce6b2dbc98b7f0 Mon Sep 17 00:00:00 2001 From: atlas Date: Mon, 23 Nov 2026 19:32:16 +0100 Subject: [PATCH] k8s: the hyperhive namespace enforces pod security restricted No pod in the namespace has a hostPort any more, and the census found nothing else that restricted refuses. The namespace now carries the restricted level for enforce, warn and audit, so the API server refuses a pod that drifts. The bao-login test's probe pods get the container security context restricted asks for. The controller switch test shows the API server admitting a compliant pod and refusing the same pod with a host port, a kept capability or privilege. --- docs/4-implementation/k8s/manifests.md | 21 ++++++- nix/host-modules/k8s/render.nix | 10 +++- nix/module-eval/k8s.nix | 83 ++++++++++++++++++++++++++ nix/vm-tests/k8s-bao-login.nix | 4 ++ nix/vm-tests/k8s-controller-switch.nix | 41 +++++++++++-- 5 files changed, 150 insertions(+), 9 deletions(-) diff --git a/docs/4-implementation/k8s/manifests.md b/docs/4-implementation/k8s/manifests.md index 7d485f5a8..634f23a10 100644 --- a/docs/4-implementation/k8s/manifests.md +++ b/docs/4-implementation/k8s/manifests.md @@ -22,14 +22,14 @@ A service gets manifests on the host whose configuration deploys it: | service | workload | other objects | | ------------------------- | ---------- | ------------------------------------------------------------------------------------------ | | `swarm-controller` | Deployment | ServiceAccount, ConfigMap `swarm-controller-etc`; Service, NetworkPolicy with the listener | +| `swarm-nats` | Deployment | ServiceAccount, two Services, NetworkPolicy, PersistentVolume and Claim | | `swarm-notify-router` | 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` | -`namespace.yaml` holds the Namespace. NATS with its auth responder has no -manifests yet: its image doesn't exist yet. +`namespace.yaml` holds the Namespace ([Pod Security](#pod-security)). ## One source: the unit @@ -156,6 +156,23 @@ credential directory. - **Rollout:** each Deployment has one replica and the `Recreate` strategy, because each service runs once per swarm. +## Pod Security + +`namespace.yaml` labels the namespace with the `restricted` level of Pod +Security for `enforce`, `warn` and `audit`. The API server refuses a pod that +breaks the level: a host port, a host namespace or path, root, a kept +capability or privilege escalation, or no seccomp profile. A Deployment that +would make such a pod gets a warning on apply, and its pods fail to start, so a +drifted workload shows as a Deployment with no ready replica. The security +settings of [Pods](#pods) are what the level asks for, and no pod needs a +`hostPort`: the controller's port and the queue's exporter are ClusterIP +Services, and the queue's client port is a `LoadBalancer` Service that k3s's +service load balancer binds on the node from `kube-system`, which the label +doesn't cover. The level follows the cluster's Kubernetes version, so an +upgrade can tighten it. `module-eval-k8s` reads every rendered pod against the +level's rules, and the VM test `k8s-controller-switch` shows the API server +refusing a pod with a host port, a kept capability or privilege. + ## The store login A service that has a role at the store's `jwt-k8s` auth mount diff --git a/nix/host-modules/k8s/render.nix b/nix/host-modules/k8s/render.nix index 2befed17f..1727ab4b7 100644 --- a/nix/host-modules/k8s/render.nix +++ b/nix/host-modules/k8s/render.nix @@ -1098,7 +1098,15 @@ in kind = "Namespace"; metadata = { name = k8sCfg.namespace; - labels."app.kubernetes.io/part-of" = "hyperhive"; + labels = { + "app.kubernetes.io/part-of" = "hyperhive"; + # The API server refuses a pod that breaks Pod Security `restricted` (a + # host port, root, a kept capability, ...), and warns on and audits a + # workload whose pods would. The level is the cluster's own version. + "pod-security.kubernetes.io/enforce" = "restricted"; + "pod-security.kubernetes.io/warn" = "restricted"; + "pod-security.kubernetes.io/audit" = "restricted"; + }; }; }; } diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix index 49bb2fb05..e61f147ea 100644 --- a/nix/module-eval/k8s.nix +++ b/nix/module-eval/k8s.nix @@ -2099,6 +2099,89 @@ let && idx onCluster "ct original" < idx onCluster "counter" && idx onCluster "@direct_mac accept" < idx onCluster "ct original"; } + { + # The checker is the control that it finds a violation: the same pod with + # a host port, a kept capability or a missing seccomp profile is flagged, + # and the workloads it reads are all seven. + name = "the namespace enforces Pod Security restricted, and no pod the module renders breaks it"; + ok = + let + ns = (render allLocal).namespace.metadata.labels; + workloads = lib.filterAttrs (_: o: o.kind == "Deployment" || o.kind == "CronJob") ( + render onCluster + ); + specOf = + o: if o.kind == "CronJob" then o.spec.jobTemplate.spec.template.spec else o.spec.template.spec; + specs = map specOf (lib.attrValues workloads); + containersOf = s: s.containers ++ (s.initContainers or [ ]); + problems = + s: + lib.concatMap (k: lib.optional (s.${k} or false) k) [ + "hostNetwork" + "hostPID" + "hostIPC" + ] + ++ lib.optional (lib.any (v: v ? hostPath) s.volumes) "hostPath" + ++ lib.optional ( + !(lib.elem (s.securityContext.seccompProfile.type or "") [ + "RuntimeDefault" + "Localhost" + ]) + ) "seccomp" + ++ lib.concatMap ( + c: + let + sc = c.securityContext or { }; + in + lib.optional ((sc.allowPrivilegeEscalation or null) != false) "escalation ${c.name}" + ++ lib.optional ((sc.capabilities.drop or [ ]) != [ "ALL" ]) "drop ${c.name}" + ++ lib.optional (sc.capabilities ? add) "add ${c.name}" + ++ lib.optional (sc.privileged or false) "privileged ${c.name}" + ++ lib.optional (!(sc.runAsNonRoot or s.securityContext.runAsNonRoot or false)) "root ${c.name}" + ++ lib.concatMap (p: lib.optional (p ? hostPort) "hostPort ${c.name}") (c.ports or [ ]) + ) (containersOf s); + first = lib.head specs; + withHostPort = first // { + containers = [ + ( + (lib.head first.containers) + // { + ports = [ + { + containerPort = 1; + hostPort = 1; + } + ]; + } + ) + ]; + }; + withCaps = first // { + containers = [ + ( + (lib.head first.containers) + // { + securityContext = (lib.head first.containers).securityContext // { + capabilities.add = [ "NET_ADMIN" ]; + }; + } + ) + ]; + }; + withoutSeccomp = first // { + securityContext = removeAttrs first.securityContext [ "seccompProfile" ]; + }; + in + ns."pod-security.kubernetes.io/enforce" == "restricted" + && ns."pod-security.kubernetes.io/warn" == "restricted" + && ns."pod-security.kubernetes.io/audit" == "restricted" + && ns."app.kubernetes.io/part-of" == "hyperhive" + && lib.length specs == 7 + && lib.all (s: problems s == [ ]) specs + && problems withHostPort != [ ] + && problems withCaps != [ ] + && problems withoutSeccomp != [ ]; + } { # The file names the runtime and the host units of every service and no # state: nothing is copied. The units of the poller (timer and service) diff --git a/nix/vm-tests/k8s-bao-login.nix b/nix/vm-tests/k8s-bao-login.nix index d007ee9ae..5302d9d68 100644 --- a/nix/vm-tests/k8s-bao-login.nix +++ b/nix/vm-tests/k8s-bao-login.nix @@ -103,6 +103,10 @@ pkgs.testers.runNixOSTest { "sleep" "3600" ]; + # The namespace enforces Pod Security `restricted`, which asks the + # container for these: the pod-level settings alone leave it able to + # escalate and to keep capabilities. + inherit (lib.head podSpec.containers) securityContext; volumeMounts = [ tokenMount { diff --git a/nix/vm-tests/k8s-controller-switch.nix b/nix/vm-tests/k8s-controller-switch.nix index 307f900d9..ed16fb38a 100644 --- a/nix/vm-tests/k8s-controller-switch.nix +++ b/nix/vm-tests/k8s-controller-switch.nix @@ -17,6 +17,7 @@ # resolver answers through CoreDNS, verifying the leaf as the listener's # name; the controller answers an unsigned webhook 401 both times; # - the Service is a ClusterIP the host dials and a pod can't (no `hostPort`); +# Pod Security `restricted` refuses a host port, a capability or privilege; # - a changed hyperhive rev rolls the Deployment; the pod's state directory is # an emptyDir, with no claim and no gate; # - the switch back leaves no pod, Deployment, Service, NetworkPolicy or @@ -607,12 +608,40 @@ pkgs.testers.runNixOSTest { for _ in range(3): assert machine.execute(dials(other, ip, PORT))[0] != 0 - with subtest("Pod Security restricted would admit the namespace's pods: the API server's dry run of the label names none, and does name kube-system's"): - dry = "label --dry-run=server --overwrite namespace {} pod-security.kubernetes.io/enforce=restricted 2>&1" - control = machine.succeed("kubectl " + dry.format("kube-system")) - assert "violate" in control, control - mine = machine.succeed("kubectl " + dry.format(NS)) - assert "violate" not in mine, mine + with subtest("the namespace enforces Pod Security restricted: the API server admits a compliant pod and refuses the same pod with a host port, a kept capability or privilege"): + labels = json.loads(kube(machine, f"get namespace {NS} -o json"))["metadata"]["labels"] + assert labels["pod-security.kubernetes.io/enforce"] == "restricted", labels + compliant = { + "apiVersion": "v1", + "kind": "Pod", + "metadata": {"name": "psa-probe", "namespace": NS}, + "spec": { + "securityContext": {"runAsNonRoot": True, "seccompProfile": {"type": "RuntimeDefault"}}, + "containers": [{ + "name": "c", + "image": main["image"], + "imagePullPolicy": "Never", + "securityContext": {"allowPrivilegeEscalation": False, "capabilities": {"drop": ["ALL"]}}, + }], + }, + } + + def admission(change) -> tuple[int, str]: + """What the API server answers to a server-side dry run of the compliant pod with `change` applied to its container.""" + pod = json.loads(json.dumps(compliant)) + change(pod["spec"]["containers"][0]) + machine.succeed(f"cat > /root/psa.json <<'EOF'\n{json.dumps(pod)}\nEOF") + return machine.execute("kubectl apply --dry-run=server -f /root/psa.json 2>&1") + + status, out = admission(lambda c: None) + assert status == 0, out + for what, change in [ + ("host port", lambda c: c.update(ports=[{"containerPort": 9, "hostPort": 9}])), + ("kept capability", lambda c: c["securityContext"]["capabilities"].update(drop=[])), + ("privilege", lambda c: c["securityContext"].update(privileged=True, allowPrivilegeEscalation=True)), + ]: + status, out = admission(change) + assert status != 0 and 'violates PodSecurity "restricted:latest"' in out, (what, out) with subtest("a changed rev rolls the Deployment, and the old pod is gone first"): old_uid = pod(machine, pod_name)["metadata"]["uid"]