k8s: stt's pod gets a network policy: dns and four host ports out, nothing in
This commit is contained in:
parent
4ea3b0e10d
commit
02cc38d89e
5 changed files with 262 additions and 22 deletions
|
|
@ -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" ''
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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"))
|
||||
|
|
|
|||
Loading…
Reference in a new issue