Watch
0
0
Fork
You've already forked hyperhive
0

k8s: stt's pod gets a network policy: dns and four host ports out, nothing in

This commit is contained in:
atlas 2026-11-23 13:36:51 +01:00 • committed by mara
commit 6051a83044
9 changed files with 262 additions and 22 deletions

View file

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

View file

@ -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).

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -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/tcp/{address}/{port}'"
with subtest("the speech-to-text pod answers a request on the queue, the path production uses, with its decoder running"):
assert json.loads(kube(machine, f"get networkpolicy {STT} -o json"))["spec"]["policyTypes"] == ["Ingress", "Egress"]
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])
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 '</dev/tcp/${bridgeIp}/9999'", timeout=30)
machine.succeed(dials(router_pid, "${bridgeIp}", 9999))
for port in (${toString podPort}, 443, ${toString natsPort}):
machine.succeed(dials(stt_pid, "${bridgeIp}", port))
cluster_dns = kube(machine, "-n kube-system get service kube-dns -o jsonpath='{.spec.clusterIP}'").strip()
machine.succeed(f"nsenter --target {stt_pid} --net -- dig +short +time=5 +tries=1 @{cluster_dns} ${baoName} | grep -qx ${bridgeIp}")
# The pod's own policy refuses what it names no port for. Waited for
# first: the policy engine syncs a moment after the pod starts.
machine.wait_until_fails(dials(stt_pid, "${bridgeIp}", 9999), timeout=60)
for _ in range(3):
assert machine.execute(dials(stt_pid, "${bridgeIp}", 9999))[0] != 0
classifier_ip = kube(machine, f"get pod {DAEMON_PODS[CLASSIFIER]} -o jsonpath='{{.status.podIP}}'").strip()
machine.succeed(dials(router_pid, classifier_ip, 8080))
assert machine.execute(dials(stt_pid, classifier_ip, 8080))[0] != 0
with subtest("no peer pod reaches the speech-to-text pod, and the kubelet's probes still do"):
stt_ip = kube(machine, f"get pod {stt_pod} -o jsonpath='{{.status.podIP}}'").strip()
# Another pod reaches a pod with no policy on its health port, and
# the node reaches the speech-to-text pod's.
machine.succeed(dials(router_pid, classifier_ip, 8080))
machine.succeed(f"timeout 5 bash -c '</dev/tcp/{stt_ip}/8080'")
machine.wait_until_fails(dials(router_pid, stt_ip, 8080), timeout=60)
status = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["status"]
assert status["containerStatuses"][0]["ready"] and status["containerStatuses"][0]["restartCount"] == 0, status
with subtest("the poller's Job completes against the forge and pushes the run to the poller's own route with a token the identity provider minted"):
tokens_before = int(machine.succeed(f"grep -cF '/api/oidc/token ${ci}:{CI_SECRET}' ${tokenLog} || true"))
job_log = ci_job(f"{CI}-first")
@ -1010,6 +1061,7 @@ pkgs.testers.runNixOSTest {
assert service_pods(STT) == [], service_pods(STT)
assert machine.execute(f"kubectl -n {NS} get deployment {STT}")[0] != 0
assert machine.execute(f"kubectl -n kube-system get addons.k3s.cattle.io {STT}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get networkpolicy {STT}")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{STT}.yaml")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{STT}.yaml.pruning")[0] != 0
pruned_stt = int(machine.succeed(f"systemctl show -p ExecMainExitTimestampMonotonic --value {STT_PRUNE}.service"))