Watch
0
0
Fork
You've already forked hyperhive
0

k8s: deny ingress to every pod by default

This commit is contained in:
atlas 2026-11-27 15:10:15 +01:00 • committed by maia
commit 67218f4052
7 changed files with 241 additions and 27 deletions

View file

@ -57,7 +57,8 @@ in
internal = true;
description = ''
What ./runtime.nix applies: each enabled service's
objects, the namespace object, and the CA ConfigMap's name
objects, the namespace's own objects (the namespace and its
default-deny ingress policy), and the CA ConfigMap's name
and host files.
'';
};
@ -72,7 +73,10 @@ in
userNamespaces
;
services = withoutContext rendered.services;
namespaceObject = withoutContext rendered.objects.namespace;
namespaceObjects = withoutContext [
rendered.objects.namespace
rendered.objects."default-deny-ingress/networkpolicy"
];
};
# The images those pods run, for a node to load: ./node.nix.

View file

@ -1190,6 +1190,28 @@ in
};
};
}
# Every pod of the namespace is selected for ingress and no rule admits
# anyone, so a pod is reachable from the node alone until a policy of its own
# admits more. The cluster's policy engine takes the union of the policies
# that select a pod and always admits the node's own addresses, so the
# kubelet's probes and the host's gateway still reach every pod. A port a pod
# opens later is closed to the other pods and to the hive bridge without a
# line here.
// {
"default-deny-ingress/networkpolicy" = {
apiVersion = "networking.k8s.io/v1";
kind = "NetworkPolicy";
metadata = {
name = "default-deny-ingress";
inherit (k8sCfg) namespace;
labels."app.kubernetes.io/part-of" = "hyperhive";
};
spec = {
podSelector = { };
policyTypes = [ "Ingress" ];
};
};
}
// lib.concatMapAttrs (_: w: w.objects) enabled;
# The image each enabled service's pod runs: what the main node imports,

View file

@ -59,7 +59,7 @@ in
# configuration drops before it activates the new configuration, and
# the files are linked in by the activation.
services.k3s.manifests = {
hyperhive-namespace.content = rendered.namespaceObject;
hyperhive-namespace.content = rendered.namespaceObjects;
}
// lib.genAttrs onCluster (name: {
content = lib.attrValues rendered.services.${name}.objects;

View file

@ -820,7 +820,11 @@ let
"swarm-stt"
"swarm-victorialogs"
]
&& onCluster.services.k3s.manifests.hyperhive-namespace.content.kind == "Namespace"
&&
map (o: o.kind) onCluster.services.k3s.manifests.hyperhive-namespace.content == [
"Namespace"
"NetworkPolicy"
]
&&
lib.sort lib.lessThan (map (o: o.kind) onCluster.services.k3s.manifests.swarm-notify-router.content)
== [
@ -965,6 +969,39 @@ let
"swarm-ci-metrics"
];
}
{
# The policy is pinned by value: an empty selector is the property, since
# a `matchLabels` would leave every pod it does not name open, and a rule
# would admit someone. The pods the lists name have no ingress policy of
# their own and rely on it; the speech-to-text pod and the controller are
# the controls that the lookup finds a pod's own policy.
name = "the namespace has a default-deny ingress policy that selects every pod and admits nobody, and the pods without an ingress policy of their own rely on it";
ok =
let
policy = objects."default-deny-ingress/networkpolicy";
manifest = onCluster.services.k3s.manifests.hyperhive-namespace.content;
ownPolicy = name: objects ? "${name}/networkpolicy";
in
policy.kind == "NetworkPolicy"
&& policy.metadata.namespace == "hyperhive"
&&
policy.spec == {
podSelector = { };
policyTypes = [ "Ingress" ];
}
&& lib.elem policy manifest
&& lib.all (name: !(ownPolicy name)) [
"swarm-notify-router"
"swarm-review-classifier"
"swarm-claude-login"
"swarm-ci-metrics"
]
&& lib.all ownPolicy [
"swarm-stt"
"swarm-controller"
"swarm-nats"
];
}
{
# 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
@ -1040,12 +1077,13 @@ let
ports = [ (tcp 4222) ];
}
]
# Only the controller (its listener), the log store and its responders
# (listeners), the queue and this pod have a policy: the others have no
# egress and no listener.
# The namespace's default, the controller (its listener), the log store
# and its responders (listeners), the queue and this pod have a policy:
# the others have no egress and no listener, and rely on the default.
&&
lib.sort lib.lessThan (lib.filter (n: lib.hasSuffix "/networkpolicy" n) (lib.attrNames objects))
== [
"default-deny-ingress/networkpolicy"
"swarm-controller/networkpolicy"
"swarm-logs-auth/networkpolicy"
"swarm-nats/networkpolicy"

View file

@ -28,6 +28,7 @@ let
inherit (pkgs) lib;
bridgeIp = "10.42.0.1";
agentIp = "10.42.0.200";
baoName = "bao.t.local";
baoPort = 8200;
podPort = 8208;
@ -135,7 +136,10 @@ pkgs.testers.runNixOSTest {
nodes.machine =
{ config, ... }:
{
imports = [ self.nixosModules.default ];
imports = [
self.nixosModules.default
./lib/agent-netns.nix
];
services.hyperhive = {
deploy.k8s.enable = true;
@ -544,6 +548,26 @@ pkgs.testers.runNixOSTest {
for _ in range(3):
assert machine.execute(dials(other, ip, PORT))[0] != 0
with subtest("a client of the hive bridge and another pod cannot reach the controller's pod, and the node reads its health port"):
deny = json.loads(kube(machine, "get networkpolicy default-deny-ingress -o json"))["spec"]
assert deny == {"podSelector": {}, "policyTypes": ["Ingress"]}, deny
bridge_if = machine.succeed("ip -o -4 addr show | grep -F 'inet ${bridgeIp}/' | cut -d' ' -f2").strip()
machine.succeed(
"ip link add va type veth peer name vb && ip link set vb netns agent "
f"&& ip link set va master {bridge_if} && ip link set va up "
"&& ip -n agent addr add ${agentIp}/24 dev vb && ip -n agent link set vb up && ip -n agent link set lo up "
"&& ip -n agent route add default via ${bridgeIp}"
)
pod_ip = kube(machine, f"get pod {pod_name} -o jsonpath='{{.status.podIP}}'").strip()
code = machine.succeed(f"curl -s -o /dev/null -w '%{{http_code}}' --max-time 5 http://{pod_ip}:8080/healthz").strip()
assert code == "200", code
# The listener is reached by the node's own dial, the control that the
# refusals below are the policy's.
machine.succeed(f"timeout 5 bash -c '</dev/tcp/{pod_ip}/{PORT}'")
for port in (8080, PORT):
machine.wait_until_fails(dials(other, pod_ip, port), timeout=120)
machine.wait_until_fails(f"ip netns exec agent timeout 5 bash -c '</dev/tcp/{pod_ip}/{port}'", timeout=120)
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

View file

@ -687,6 +687,18 @@ pkgs.testers.runNixOSTest {
machine.wait_until_fails(dials(other, ip, METRICS), timeout=120)
for _ in range(3):
assert machine.execute(dials(other, ip, METRICS))[0] != 0
# The responder's health port answers the node with a status and is
# closed to the same two sources: the namespace's default admits the
# node and nobody else, and the pod's own policy names the client port
# only.
code = machine.succeed(f"curl -s -o /dev/null -w '%{{http_code}}' --max-time 5 http://{pod_ip}:8080/healthz").strip()
assert code == "200", code
machine.wait_until_fails(dials(other, pod_ip, 8080), timeout=120)
for port in (8080, METRICS):
assert machine.execute(dials(other, pod_ip, port))[0] != 0, port
assert machine.execute(f"ip netns exec agent nc -z -w 4 {pod_ip} {port}")[0] != 0, port
deny = json.loads(kube(machine, "get networkpolicy default-deny-ingress -o json"))["spec"]
assert deny == {"podSelector": {}, "policyTypes": ["Ingress"]}, deny
with subtest("a leaf that has to be issued again is issued beside the running server, which reloads it for new connections"):
uid = pod(machine, pod_name)["metadata"]["uid"]

View file

@ -33,6 +33,7 @@ let
inherit (pkgs) lib;
bridgeIp = "10.42.0.1";
agentIp = "10.42.0.200";
baoName = "bao.t.local";
baoPort = 8200;
podPort = 8208;
@ -231,7 +232,10 @@ pkgs.testers.runNixOSTest {
nodes.machine =
{ config, ... }:
{
imports = [ self.nixosModules.default ];
imports = [
self.nixosModules.default
./lib/agent-netns.nix
];
services.hyperhive = {
deploy.k8s.enable = true;
@ -797,8 +801,8 @@ pkgs.testers.runNixOSTest {
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.
# host and the router's pod, which has no egress 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))
@ -812,14 +816,14 @@ pkgs.testers.runNixOSTest {
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))
# Its egress policy names no port of a peer pod, so the dial is refused
# on the way out, which the ingress policy of the peer does not decide.
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))
# The node reaches the speech-to-text pod's health port, a peer pod
# does not.
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"]
@ -967,9 +971,9 @@ pkgs.testers.runNixOSTest {
vl_ip = kube(machine, f"get pod {vl_pod} -o jsonpath='{{.status.podIP}}'").strip()
auth_ip = kube(machine, f"get pod {auth_pod} -o jsonpath='{{.status.podIP}}'").strip()
machine.succeed(f"curl -sf --max-time 5 http://{vl_ip}:9428/health")
# A peer pod reaches the classifier's health port, which has no policy:
# the control that the dial below is refused by the policy.
machine.succeed(dials(router_pid, classifier_ip, 8080))
# The peer pod can dial out, which is the control that the dials below
# are refused by the stores' policies.
machine.succeed(dials(router_pid, "${bridgeIp}", 9999))
for ip, port in ((vl_ip, 9428), (auth_ip, 8081), (auth_ip, 8082)):
machine.succeed(f"timeout 5 bash -c '</dev/tcp/{ip}/{port}'")
machine.wait_until_fails(dials(router_pid, ip, port), timeout=60)
@ -982,6 +986,102 @@ pkgs.testers.runNixOSTest {
status = json.loads(kube(machine, f"get pod {name} -o json"))["status"]
assert all(c["ready"] for c in status["containerStatuses"]), status
with subtest("another pod and a client of the hive bridge cannot reach a listener of the cluster's pods, and the node still does"):
# The namespace's one policy that selects every pod and admits nobody.
deny = json.loads(kube(machine, "get networkpolicy default-deny-ingress -o json"))["spec"]
assert deny == {"podSelector": {}, "policyTypes": ["Ingress"]}, deny
# The three pods that name no ingress policy of their own are the
# control that the default is what closes them: no policy but that one
# selects them.
names = kube(machine, "get networkpolicy -o jsonpath='{.items[*].metadata.name}'").split()
for name in (SERVICE, CLASSIFIER, LOGIN):
assert name not in names, (name, names)
assert "default-deny-ingress" in names, names
# A client on the hive's bridge, as an agent's network namespace is.
bridge_if = machine.succeed("ip -o -4 addr show | grep -F 'inet ${bridgeIp}/' | cut -d' ' -f2").strip()
machine.succeed(
"ip link add va type veth peer name vb && ip link set vb netns agent "
f"&& ip link set va master {bridge_if} && ip link set va up "
"&& ip -n agent addr add ${agentIp}/24 dev vb && ip -n agent link set vb up && ip -n agent link set lo up "
"&& ip -n agent route add default via ${bridgeIp}"
)
def agent_dials(address: str, port: int) -> str:
return f"ip netns exec agent timeout 5 bash -c '</dev/tcp/{address}/{port}'"
def pod_ip(name: str) -> str:
return kube(machine, f"get pod {name} -o jsonpath='{{.status.podIP}}'").strip()
peers = {name: pod_pid(name) for name in (SERVICE, CLASSIFIER, LOGIN)}
coredns_pid = pod_pid("coredns")
health = {
SERVICE: (pod_ip(service_pods(SERVICE)[0].removeprefix("pod/")), [8080]),
STT: (stt_ip, [8080]),
CLASSIFIER: (pod_ip(DAEMON_PODS[CLASSIFIER]), [8080]),
LOGIN: (pod_ip(DAEMON_PODS[LOGIN]), [8080]),
LOGS_AUTH: (auth_ip, [8080, 8083]),
}
# Every listener the pods open: the health ports, the store, and the
# responders' own.
listeners = {
**health,
VL: (vl_ip, [9428]),
LOGS_AUTH: (auth_ip, [8080, 8081, 8082, 8083]),
}
def sources(target: str):
peer = next(pid for name, pid in peers.items() if name != target)
return {
"a pod of kube-system": lambda ip, port: dials(coredns_pid, ip, port),
"a peer pod of the namespace": lambda ip, port: dials(peer, ip, port),
"a client of the hive bridge": agent_dials,
}
# The node answers each health port with a status and no body, the
# control that every dial below refuses a port that is open.
for name, (ip, ports) in health.items():
for port in ports:
code = machine.succeed(f"curl -s -o /dev/null -w '%{{http_code}}' --max-time 5 http://{ip}:{port}/healthz").strip()
assert code == "200", (name, port, code)
machine.succeed(f"curl -sf --max-time 5 http://{vl_ip}:9428/health")
for name, (ip, ports) in listeners.items():
for port in ports:
machine.succeed(f"timeout 5 bash -c '</dev/tcp/{ip}/{port}'")
for source, dial in sources(name).items():
machine.wait_until_fails(dial(ip, port), timeout=60)
assert machine.execute(dial(ip, port))[0] != 0, (name, port, source)
for pod_name in (service_pods(SERVICE)[0].removeprefix("pod/"), DAEMON_PODS[CLASSIFIER], DAEMON_PODS[LOGIN], stt_pod):
status = json.loads(kube(machine, f"get pod {pod_name} -o json"))["status"]
assert all(c["ready"] and c["restartCount"] == 0 for c in status["containerStatuses"]), status
with subtest("a policy that admits every source opens the notify router's health port to the same sources, and removing it closes it again"):
# The union of the policies that select a pod: the default admits
# nobody and this one admits everybody, so the sources that were refused
# reach the port, which is the control that the dials above fail on the
# policy and not on the path.
router_ip, _ = health[SERVICE]
allow = {
"apiVersion": "networking.k8s.io/v1",
"kind": "NetworkPolicy",
"metadata": {"name": "test-admit-router", "namespace": NS},
"spec": {
"podSelector": {"matchLabels": {"app.kubernetes.io/name": SERVICE}},
"policyTypes": ["Ingress"],
"ingress": [{}],
},
}
machine.succeed(f"echo '{json.dumps(allow)}' | kubectl apply -f -")
try:
for source, dial in sources(SERVICE).items():
machine.wait_until_succeeds(dial(router_ip, 8080), timeout=120)
finally:
kube(machine, "delete networkpolicy test-admit-router --ignore-not-found")
for source, dial in sources(SERVICE).items():
machine.wait_until_fails(dial(router_ip, 8080), timeout=120)
assert machine.execute(dial(router_ip, 8080))[0] != 0, source
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")