Watch
0
0
Fork
You've already forked hyperhive
0

k8s: the queue's exporter is a ClusterIP service only the node reaches

The exporter's metrics port was a hostPort on the bridge's address, which Pod Security baseline and restricted forbid. It is a ClusterIP Service now, and the pod has a NetworkPolicy that admits the client port from any source and nothing else, so only the node reads the exporter, as the raw-table rules made it. The gateway's /metrics location dials the Service by name through nginx's resolver. The raw-table rules no longer name the exporter's port.
This commit is contained in:
atlas 2026-11-23 18:02:25 +01:00 • committed by maia
commit 7ef9444e42
7 changed files with 228 additions and 63 deletions

View file

@ -88,11 +88,12 @@ agents ask the same resolver, so they get the same names. A name is no route:
the hive's egress rules decide whether the host forwards their traffic to the the hive's egress rules decide whether the host forwards their traffic to the
cluster's addresses, and a pod's NetworkPolicy refuses what it forwards. cluster's addresses, and a pod's NetworkPolicy refuses what it forwards.
A pod that serves the host, such as the controller's, has a NetworkPolicy that A pod that serves the host, such as the controller or the queue's exporter, has
selects it for ingress and allows nothing. kube-router, the policy engine, adds a NetworkPolicy that selects it for ingress and allows no more than the port it
a rule at the top of every pod's chain that admits traffic from any address of serves everyone, if it has one. kube-router, the policy engine, adds a rule at
the node (`-m addrtype --src-type LOCAL`, commented "from local node"), so the the top of every pod's chain that admits traffic from any address of the node
host reaches the pod and no other pod does. (`-m addrtype --src-type LOCAL`, commented "from local node"), so the host
reaches the pod and no other pod does.
## Logging in to the secret store ## Logging in to the secret store

View file

@ -228,10 +228,17 @@ holds the container back until the pod has gone.
read before the DNAT: a packet for the node's address and the client port is read before the DNAT: a packet for the node's address and the client port is
dropped unless it arrives on the host's loopback, the hive bridge or a pod dropped unless it arrives on the host's loopback, the hive bridge or a pod
interface, or unless `deploy.nats.openFirewall` is on. The container's port interface, or unless `deploy.nats.openFirewall` is on. The container's port
has that reach. The exporter's port is a `hostPort` on the bridge's address, has that reach.
for the gateway's `/metrics` location on the host. The rules drop it on every - **The exporter's port.** The exporter's port has no `hostPort`: a ClusterIP
interface but the host's loopback: the exporter answers with the name of Service, `swarm-nats-metrics`, fronts it, and the gateway's `/metrics`
every client, and only the host's own processes may read it. location on the host dials the Service's name through nginx's `resolver` (the
hive's dnsmasq), as [the controller's](#the-controller) does, so
`gateway.dns.enable` has to be on. The exporter answers with the name of every
client, and only the node may read it. The pod's NetworkPolicy selects it for
ingress and allows the client port from any source and nothing else. The
cluster's policy engine always admits traffic from an address of the node, so
the gateway and the kubelet's probes reach the pod, and a pod of the cluster,
or a client of the bridge that the host forwards, doesn't reach the exporter.
- **The leaf.** `tls-issue` logs in to the store with the pod's token as the - **The leaf.** `tls-issue` logs in to the store with the pod's token as the
role `swarm-nats` and issues the server's leaf from the same script as the role `swarm-nats` and issues the server's leaf from the same script as the
host's `swarm-bao-nats-tls`. The key lands in a volume in memory. The host's `swarm-bao-nats-tls`. The key lands in a volume in memory. The
@ -253,8 +260,8 @@ holds the container back until the pod has gone.
`swarm-bao-nats-callout-xkey` deliver into the container, so the configuration `swarm-bao-nats-callout-xkey` deliver into the container, so the configuration
turns them off. `swarm-bao-nats-tls` stays: it issues the host's own copy of turns them off. `swarm-bao-nats-tls` stays: it issues the host's own copy of
the leaf for the gateway's `/metrics` vhost, and with no container it has the leaf for the gateway's `/metrics` vhost, and with no container it has
nothing to restart. The gateway's location dials the exporter on the bridge's nothing to restart. The gateway's location dials the exporter's Service by
address where it dialled loopback. name where it dialled loopback.
- **State.** The server's store directory, `/var/lib/nats`, is the container's - **State.** The server's store directory, `/var/lib/nats`, is the container's
own on the host, `/var/lib/nixos-containers/swarm-nats/var/lib/nats`: the own on the host, `/var/lib/nixos-containers/swarm-nats/var/lib/nats`: the
PersistentVolumeClaim `swarm-nats-store` binds a static local volume on it, PersistentVolumeClaim `swarm-nats-store` binds a static local volume on it,
@ -382,9 +389,9 @@ it dials the pod by name and verifies the name, and the responder in the pod
admits it. A key written on the host before the switch is the pod's to read, a admits it. A key written on the host before the switch is the pod's to read, a
key the pod writes is the host server's after the switch back, and a stream key the pod writes is the host server's after the switch back, and a stream
written before a pod delete survives it: the replacement pod reads it from the written before a pod delete survives it: the replacement pod reads it from the
same directory. The exporter answers the host's own processes through the same directory. The exporter answers the host's own processes through its
published port, and the switch back removes the pod before the container Service and no pod or bridge client, and the switch back removes the pod before
starts. the container starts.
The VM test `k8s-controller-switch` moves the controller. It asserts one copy at The VM test `k8s-controller-switch` moves the controller. It asserts one copy at
each step by the switch's own timestamps and by a sampler, that the pod is Ready each step by the switch's own timestamps and by a sampler, that the pod is Ready

View file

@ -19,7 +19,7 @@ You rarely switch it on yourself. `gateway.enable` defaults to off, and every mo
| `chat.<swarm>/_matrix/*` | tuwunel (unix socket `/run/hive-matrix/tuwunel.sock`) | `hive-matrix.nix`, `swarm.matrix.gatewayHost != null` | | `chat.<swarm>/_matrix/*` | tuwunel (unix socket `/run/hive-matrix/tuwunel.sock`) | `hive-matrix.nix`, `swarm.matrix.gatewayHost != null` |
| `chat.<swarm>/` | fluffychat-web static | `hive-matrix.nix`, `swarm.matrix.gatewayHost != null` | | `chat.<swarm>/` | fluffychat-web static | `hive-matrix.nix`, `swarm.matrix.gatewayHost != null` |
| `chat.<swarm>/config.json` | inline JSON (FluffyChat boot config) | `hive-matrix.nix`, `swarm.matrix.gatewayHost != null` | | `chat.<swarm>/config.json` | inline JSON (FluffyChat boot config) | `hive-matrix.nix`, `swarm.matrix.gatewayHost != null` |
| `<queue domain>/metrics` | the queue exporter's `/metrics` on loopback, behind an authelia `auth_request`; every other path, `/` included, returns `403`, so `/varz` and `/connz` are never reachable | `swarm-nats.nix`, the queue's host | | `<queue domain>/metrics` | the queue exporter's `/metrics` on loopback, or behind its Service where the queue runs in the cluster, behind an authelia `auth_request`; every other path, `/` included, returns `403`, so `/varz` and `/connz` are never reachable | `swarm-nats.nix`, the queue's host |
| `grafana.<swarm>`, `metrics.<swarm>`, `logs.<swarm>`, `otel.<swarm>`, `bao.<swarm>` | the matching swarm service | that service's module → [`2-handbook/swarm/services.md`](../../2-handbook/swarm/services.md) | | `grafana.<swarm>`, `metrics.<swarm>`, `logs.<swarm>`, `otel.<swarm>`, `bao.<swarm>` | the matching swarm service | that service's module → [`2-handbook/swarm/services.md`](../../2-handbook/swarm/services.md) |
A service module declares its vhost as `services.hyperhive.gateway.vhosts.<name>`: the locations, `forceSSL` and any `extraConfig` it needs. The gateway renders it into `services.nginx.virtualHosts.<name>` and adds the `listen` set ([listen addresses](#listen-addresses)), the certificate for that name and the [security headers](#security-headers) (ahead of the vhost's own `extraConfig`), and drops `addSSL` from a vhost that sets `forceSSL`. The eval fails for a vhost that sets `listen`, `addSSL`, `onlySSL`, `enableACME`, `useACMEHost`, `sslCertificate` or `sslCertificateKey` itself, and for any vhost declared while `gateway.enable` is false. A name with a certificate from outside the gateway's leaves (the queue's) sets `certificate = { cert; key; }` instead. `hive-gateway/vhosts.nix` declares the gateway's own catch-all (`_`) the same way, `hive-c0re/vhosts.nix` the dashboard and the hive domain, and `glue-matrix-hive-discovery.nix` adds the matrix redirect to the hive domain where the homeserver runs, and discovery there when the hive domain is the pinned server name. The catch-all sets `securityHeaders = false` because it sends no response, and the gateway renders a vhost's `default` at `mkDefault` priority. A service module declares its vhost as `services.hyperhive.gateway.vhosts.<name>`: the locations, `forceSSL` and any `extraConfig` it needs. The gateway renders it into `services.nginx.virtualHosts.<name>` and adds the `listen` set ([listen addresses](#listen-addresses)), the certificate for that name and the [security headers](#security-headers) (ahead of the vhost's own `extraConfig`), and drops `addSSL` from a vhost that sets `forceSSL`. The eval fails for a vhost that sets `listen`, `addSSL`, `onlySSL`, `enableACME`, `useACMEHost`, `sslCertificate` or `sslCertificateKey` itself, and for any vhost declared while `gateway.enable` is false. A name with a certificate from outside the gateway's leaves (the queue's) sets `certificate = { cert; key; }` instead. `hive-gateway/vhosts.nix` declares the gateway's own catch-all (`_`) the same way, `hive-c0re/vhosts.nix` the dashboard and the hive domain, and `glue-matrix-hive-discovery.nix` adds the matrix redirect to the hive domain where the homeserver runs, and discovery there when the hive domain is the pinned server name. The catch-all sets `securityHeaders = false` because it sends no response, and the gateway renders a vhost's `default` at `mkDefault` priority.

View file

@ -1,4 +1,4 @@
# The iptables rules that give the queue pod's `hostPort`s the reach the # The iptables rules that give the queue pod's client `hostPort` the reach the
# queue's container has. A `hostPort` is a DNAT rule, and what a DNAT rule # queue's container has. A `hostPort` is a DNAT rule, and what a DNAT rule
# rewrites is forwarded, never delivered to the host: the INPUT rules (the # rewrites is forwarded, never delivered to the host: the INPUT rules (the
# firewall's `allowedTCPPorts` and per-interface rules) never see it, and the # firewall's `allowedTCPPorts` and per-interface rules) never see it, and the
@ -9,8 +9,7 @@
# The client port is dropped for a packet addressed to the host unless it # The client port is dropped for a packet addressed to the host unless it
# arrives on one of `trusted` (the host's loopback, the hive bridge and the # arrives on one of `trusted` (the host's loopback, the hive bridge and the
# pods' interfaces), or `openClient` is set, which is # pods' interfaces), or `openClient` is set, which is
# `deploy.nats.openFirewall`. The exporter's port answers with every client's # `deploy.nats.openFirewall`.
# name, so it is dropped for all but the host's own loopback.
# #
# Pure function — NOT a NixOS module. Returns the text for the firewall's # Pure function — NOT a NixOS module. Returns the text for the firewall's
# `extraCommands`. # `extraCommands`.
@ -18,7 +17,6 @@
{ {
chain, chain,
clientPort, clientPort,
metricsPort,
trusted, trusted,
openClient, openClient,
}: }:
@ -28,8 +26,6 @@ let
in in
'' ''
iptables -t raw -N ${chain} 2>/dev/null || iptables -t raw -F ${chain} iptables -t raw -N ${chain} 2>/dev/null || iptables -t raw -F ${chain}
${rule} -p tcp --dport ${toString metricsPort} -i lo -j RETURN
${rule} -p tcp --dport ${toString metricsPort} ${local}
${lib.optionalString (!openClient) '' ${lib.optionalString (!openClient) ''
${lib.concatMapStrings (i: '' ${lib.concatMapStrings (i: ''
${rule} -p tcp --dport ${toString clientPort} -i ${i} -j RETURN ${rule} -p tcp --dport ${toString clientPort} -i ${i} -j RETURN

View file

@ -354,6 +354,11 @@ let
# host's cluster, which ./k8s/render.nix renders from the units below. # host's cluster, which ./k8s/render.nix renders from the units below.
onK8s = deployCfg.nats.runtime == "k8s"; onK8s = deployCfg.nats.runtime == "k8s";
# The Service in front of the pod's exporter, and the name the host's resolver
# answers for it through the cluster's DNS.
metricsService = "${machine}-metrics";
metricsHost = "${metricsService}.${config.services.hyperhive.k8s.namespace}.svc.${deployCfg.k8s.clusterDomain}";
# The server's monitoring endpoint, which the exporter reads, and the # The server's monitoring endpoint, which the exporter reads, and the
# collectors it serves. # collectors it serves.
monitorUrl = "http://127.0.0.1:${toString deployCfg.nats.monitorPort}"; monitorUrl = "http://127.0.0.1:${toString deployCfg.nats.monitorPort}";
@ -1027,15 +1032,11 @@ let
] ]
++ exporterFlags ++ exporterFlags
++ [ monitorUrl ]; ++ [ monitorUrl ];
# On the bridge's address, for the host's gateway: the exporter # The port the metrics Service targets.
# answers a request with every client's name, so the host's firewall
# lets only the host's own processes reach it.
ports = [ ports = [
{ {
name = "metrics"; name = "metrics";
containerPort = deployCfg.nats.metricsPort; containerPort = deployCfg.nats.metricsPort;
hostPort = deployCfg.nats.metricsPort;
hostIP = networkCfg.bridgeIp;
} }
]; ];
inherit securityContext; inherit securityContext;
@ -1083,6 +1084,50 @@ let
}; };
}; };
# The exporter answers a request with every client's name, so only the
# node may read it: the Service is reached by name from the host's
# gateway, and the policy admits the node's own traffic (which the
# cluster's policy engine always lets in, ./k8s/render.nix) and, from
# anywhere else, the client port alone.
objects."${machine}/service" = {
apiVersion = "v1";
kind = "Service";
metadata = metaFor machine // {
name = metricsService;
};
spec = {
type = "ClusterIP";
selector = (metaFor machine).labels;
ports = [
{
name = "metrics";
protocol = "TCP";
port = deployCfg.nats.metricsPort;
targetPort = "metrics";
}
];
};
};
objects."${machine}/networkpolicy" = {
apiVersion = "networking.k8s.io/v1";
kind = "NetworkPolicy";
metadata = metaFor machine;
spec = {
podSelector.matchLabels = (metaFor machine).labels;
policyTypes = [ "Ingress" ];
ingress = [
{
ports = [
{
protocol = "TCP";
port = cfg.port;
}
];
}
];
};
};
images = [ images = [
init init
server server
@ -1138,6 +1183,10 @@ in
{option}`services.hyperhive.swarm.nats.domain` proxies it, behind {option}`services.hyperhive.swarm.nats.domain` proxies it, behind
the swarm collector's authelia check. the swarm collector's authelia check.
With the queue in the cluster this is the exporter container's port in
the pod, which the Service `swarm-nats-metrics` publishes on the same
number and only the node reaches.
⚠️ This and {option}`services.hyperhive.deploy.nats.monitorPort` are two ⚠️ This and {option}`services.hyperhive.deploy.nats.monitorPort` are two
more claims on a port more claims on a port
space every swarm container shares — they run in this container but space every swarm container shares — they run in this container but
@ -1379,14 +1428,24 @@ in
# Authelia's rules for it admit the collector's client and deny # Authelia's rules for it admit the collector's client and deny
# every other subject (`metricsRules` in ./swarm-authelia.nix). # every other subject (`metricsRules` in ./swarm-authelia.nix).
"= /metrics" = { "= /metrics" = {
# In the cluster the exporter is a container of the pod, published on # In the cluster the exporter is behind a Service, which the host's
# the bridge's address. # resolver answers through the cluster's DNS. The upstream is a
proxyPass = "http://${ # variable, so nginx asks the resolver per request: a name in the
if onK8s then networkCfg.bridgeIp else "127.0.0.1" # `proxy_pass` gets one lookup when the configuration loads, which
}:${toString deployCfg.nats.metricsPort}/metrics"; # fails the load while the cluster is down.
extraConfig = '' proxyPass =
auth_request /__nats_metrics_authz; if onK8s then
''; "http://\$swarm_nats_metrics_upstream/metrics"
else
"http://127.0.0.1:${toString deployCfg.nats.metricsPort}/metrics";
extraConfig =
lib.optionalString onK8s ''
resolver ${networkCfg.bridgeIp} valid=10s ipv6=off;
set $swarm_nats_metrics_upstream ${metricsHost}:${toString deployCfg.nats.metricsPort};
''
+ ''
auth_request /__nats_metrics_authz;
'';
}; };
# The subrequest, same shape as the forge's `= /__forge_metrics_authz` # The subrequest, same shape as the forge's `= /__forge_metrics_authz`
@ -1470,6 +1529,18 @@ in
this host, or leave the queue's runtime at "host". this host, or leave the queue's runtime at "host".
''; '';
} }
{
# The gateway's `/metrics` location dials the exporter's Service by
# name, which only the hive's resolver answers.
assertion = !onK8s || config.services.hyperhive.gateway.dns.enable;
message = ''
services.hyperhive.deploy.nats.runtime = "k8s" needs
services.hyperhive.gateway.dns.enable: the gateway dials the pod's
metrics Service by name, and the hive's resolver is what hands the
cluster's domain to its DNS. Set it, or leave the queue's runtime at
"host".
'';
}
{ {
# The callout xkey and the responder's OIDC client secret are read # The callout xkey and the responder's OIDC client secret are read
# from the store under this identity; without either the server or # from the store under this identity; without either the server or
@ -1544,14 +1615,13 @@ in
# sets no listen host), so reachability is the firewall alone. # sets no listen host), so reachability is the firewall alone.
networking.firewall.allowedTCPPorts = lib.mkIf deployCfg.nats.openFirewall [ cfg.port ]; networking.firewall.allowedTCPPorts = lib.mkIf deployCfg.nats.openFirewall [ cfg.port ];
# The pod's `hostPort`s are DNAT rules, which the INPUT rules above never # The pod's client `hostPort` is a DNAT rule, which the INPUT rules above
# see: ./lib/swarm-nats-raw-rules.nix gives them the container's reach. # never see: ./lib/swarm-nats-raw-rules.nix gives it the container's reach.
services.hyperhive.network.enable = lib.mkIf onK8s (lib.mkDefault true); services.hyperhive.network.enable = lib.mkIf onK8s (lib.mkDefault true);
networking.firewall.extraCommands = lib.mkIf onK8s ( networking.firewall.extraCommands = lib.mkIf onK8s (
import ./lib/swarm-nats-raw-rules.nix { inherit lib; } { import ./lib/swarm-nats-raw-rules.nix { inherit lib; } {
chain = "nixos-fw-nats"; chain = "nixos-fw-nats";
clientPort = cfg.port; clientPort = cfg.port;
metricsPort = deployCfg.nats.metricsPort;
trusted = [ trusted = [
"lo" "lo"
networkCfg.bridgeName networkCfg.bridgeName

View file

@ -66,6 +66,9 @@ let
deploy.swarm-controller.runtime = "k8s"; deploy.swarm-controller.runtime = "k8s";
deploy.swarm-controller.tcp.listenAddress = "10.0.0.5"; deploy.swarm-controller.tcp.listenAddress = "10.0.0.5";
deploy.nats.runtime = "k8s"; deploy.nats.runtime = "k8s";
deploy.nats.enable = true;
deploy.nats.authPackage = pkgs.emptyDirectory;
gateway.dns.enable = lib.mkForce false;
}; };
runtimeRefusals = lib.filter (a: !a.assertion) runtimeRefused.assertions; runtimeRefusals = lib.filter (a: !a.assertion) runtimeRefused.assertions;
@ -1120,9 +1123,14 @@ let
ports = [ (tcp 4222) ]; ports = [ (tcp 4222) ];
} }
] ]
&& !(lib.any (n: lib.hasSuffix "/networkpolicy" n) ( # Only the queue and this pod have a policy here: the others have no
lib.attrNames (removeAttrs objects [ "swarm-stt/networkpolicy" ]) # egress and, with no listener, no ingress rule to give one.
)); &&
lib.sort lib.lessThan (lib.filter (n: lib.hasSuffix "/networkpolicy" n) (lib.attrNames objects))
== [
"swarm-nats/networkpolicy"
"swarm-stt/networkpolicy"
];
} }
{ {
# Other spellings of a ceiling: bytes, megabytes, a fractional core, no # Other spellings of a ceiling: bytes, megabytes, a fractional core, no
@ -1414,6 +1422,7 @@ let
a: lib.hasInfix "tcp.listenAddress is" a.message && lib.hasInfix "\"10.0.0.5\"" a.message a: lib.hasInfix "tcp.listenAddress is" a.message && lib.hasInfix "\"10.0.0.5\"" a.message
) runtimeRefusals ) runtimeRefusals
&& lib.any (a: lib.hasInfix "gateway.dns.enable: the gateway dials" a.message) runtimeRefusals && lib.any (a: lib.hasInfix "gateway.dns.enable: the gateway dials" a.message) runtimeRefusals
&& lib.any (a: lib.hasInfix "metrics Service by name" a.message) runtimeRefusals
# The all-local host binds the default, which the refusal lets through. # The all-local host binds the default, which the refusal lets through.
&& onCluster.services.hyperhive.deploy.swarm-controller.tcp.listenAddress == "0.0.0.0" && onCluster.services.hyperhive.deploy.swarm-controller.tcp.listenAddress == "0.0.0.0"
&& lib.all (a: a.assertion) onCluster.assertions; && lib.all (a: a.assertion) onCluster.assertions;
@ -1773,8 +1782,8 @@ let
"-c" "-c"
"/var/lib/nats-callout/nats.conf" "/var/lib/nats-callout/nats.conf"
] ]
# The client port is published on every address of the node, and the # The client port is published on every address of the node. The
# exporter's on the bridge's. # exporter's port is named for its Service and has no `hostPort`.
&& &&
(named "nats").ports == [ (named "nats").ports == [
{ {
@ -1789,8 +1798,6 @@ let
{ {
name = "metrics"; name = "metrics";
containerPort = 7777; containerPort = 7777;
hostPort = 7777;
hostIP = "10.42.0.1";
} }
] ]
&& lib.elem "0.0.0.0" (named "exporter").args && lib.elem "0.0.0.0" (named "exporter").args
@ -1907,10 +1914,11 @@ let
{ {
# The host with the queue on it is the control for each absence: it has # The host with the queue on it is the control for each absence: it has
# the container, both delivery units and no rule in the raw table. # the container, both delivery units and no rule in the raw table.
name = "the queue in the cluster leaves the host no container and no delivery unit, keeps the leaf for the gateway's vhost, and points the vhost at the exporter's published port"; name = "the queue in the cluster leaves the host no container and no delivery unit, keeps the leaf for the gateway's vhost, and points the vhost at the exporter's Service by name";
ok = ok =
let let
vhost = c: c.services.nginx.virtualHosts."nats.t.local".locations."= /metrics".proxyPass; vhost = c: c.services.nginx.virtualHosts."nats.t.local".locations."= /metrics".proxyPass;
extra = c: c.services.nginx.virtualHosts."nats.t.local".locations."= /metrics".extraConfig;
tls = onCluster.systemd.services.swarm-bao-nats-tls; tls = onCluster.systemd.services.swarm-bao-nats-tls;
in in
withNode.containers ? swarm-nats withNode.containers ? swarm-nats
@ -1924,7 +1932,7 @@ let
&& !(lib.hasInfix "nixos-fw-nats" withNode.networking.firewall.extraCommands) && !(lib.hasInfix "nixos-fw-nats" withNode.networking.firewall.extraCommands)
&& vhost withNode == "http://127.0.0.1:7777/metrics" && vhost withNode == "http://127.0.0.1:7777/metrics"
# In the cluster: nothing to start the server or deliver to it, a leaf # In the cluster: nothing to start the server or deliver to it, a leaf
# that restarts nothing, the exporter on the bridge, the bridge up. # that restarts nothing, the exporter behind its Service, the bridge up.
&& !(onCluster.containers ? swarm-nats) && !(onCluster.containers ? swarm-nats)
&& !(onCluster.systemd.services ? "container@swarm-nats") && !(onCluster.systemd.services ? "container@swarm-nats")
&& !onCluster.systemd.services.swarm-nats-auth-secrets.enable && !onCluster.systemd.services.swarm-nats-auth-secrets.enable
@ -1932,20 +1940,68 @@ let
&& !(lib.elem "container@swarm-nats.service" tls.before) && !(lib.elem "container@swarm-nats.service" tls.before)
&& !(lib.elem "container@swarm-nats.service" tls.wantedBy) && !(lib.elem "container@swarm-nats.service" tls.wantedBy)
&& onCluster.systemd.services ? swarm-nats-gateway-cert && onCluster.systemd.services ? swarm-nats-gateway-cert
&& vhost onCluster == "http://10.42.0.1:7777/metrics" && vhost onCluster == "http://\$swarm_nats_metrics_upstream/metrics"
&& lib.hasInfix "resolver 10.42.0.1 valid=10s ipv6=off;" (extra onCluster)
&& lib.hasInfix "set \$swarm_nats_metrics_upstream swarm-nats-metrics.hyperhive.svc.cluster.local:7777;" (
extra onCluster
)
&& !(lib.hasInfix "resolver" (extra withNode))
&& onCluster.services.hyperhive.network.enable; && onCluster.services.hyperhive.network.enable;
} }
{
# The host with the queue on it renders the same objects, the control that
# a `deploy.nats.runtime` changes none of them.
name = "the queue's exporter is a ClusterIP Service only the node reaches, and the pod admits the client port from anywhere and nothing else";
ok =
let
cluster = render onCluster;
svc = cluster."swarm-nats/service";
policy = cluster."swarm-nats/networkpolicy";
pod = cluster."swarm-nats/deployment".spec.template.metadata.labels;
in
svc.kind == "Service"
&& svc.metadata.name == "swarm-nats-metrics"
&& svc.metadata.labels."app.kubernetes.io/name" == "swarm-nats"
&& svc.spec.type == "ClusterIP"
&& !(svc.spec ? clusterIP)
&& svc.spec.selector == pod
&&
svc.spec.ports == [
{
name = "metrics";
protocol = "TCP";
port = 7777;
targetPort = "metrics";
}
]
&& policy.spec.podSelector.matchLabels == pod
&& policy.spec.policyTypes == [ "Ingress" ]
&&
policy.spec.ingress == [
{
ports = [
{
protocol = "TCP";
port = 4222;
}
];
}
]
&& !(policy.spec ? egress)
&& (render withNode)."swarm-nats/service" == svc
&& (render withNode)."swarm-nats/networkpolicy" == policy
&& lib.hasInfix "networkpolicy,service \\" withNode.systemd.services.swarm-nats-k8s-prune.script;
}
{ {
# Both arms of `openFirewall`, from the function the module calls, and # Both arms of `openFirewall`, from the function the module calls, and
# the module's own text for the default. # the module's own text for the default.
name = "the pod's raw-table rules close the client port as the container's INPUT rules do, and the exporter's port to all but the host's loopback"; name = "the pod's raw-table rules close the client port as the container's INPUT rules do, and name no other port";
ok = ok =
let let
rules = import ../host-modules/lib/swarm-nats-raw-rules.nix { inherit lib; }; rules = import ../host-modules/lib/swarm-nats-raw-rules.nix { inherit lib; };
args = { args = {
chain = "c"; chain = "c";
clientPort = 4222; clientPort = 4222;
metricsPort = 7777;
trusted = [ trusted = [
"lo" "lo"
"br0" "br0"
@ -1959,13 +2015,11 @@ let
has "-p tcp --dport 4222 -i br0 -j RETURN" closed has "-p tcp --dport 4222 -i br0 -j RETURN" closed
&& has "-p tcp --dport 4222 -i cni0 -j RETURN" closed && has "-p tcp --dport 4222 -i cni0 -j RETURN" closed
&& has "-p tcp --dport 4222 -m addrtype --dst-type LOCAL -j DROP" closed && has "-p tcp --dport 4222 -m addrtype --dst-type LOCAL -j DROP" closed
# Open, the client port has no rule; the exporter's still has. # Open, the client port has no rule. The exporter's port, behind a
# Service, has none in either.
&& !(has "--dport 4222" open) && !(has "--dport 4222" open)
&& has "-p tcp --dport 7777 -i lo -j RETURN" open && !(has "7777" closed)
&& has "-p tcp --dport 7777 -m addrtype --dst-type LOCAL -j DROP" open && !(has "7777" onCluster.networking.firewall.extraCommands)
# The exporter's port is not returned for the bridge or the pods.
&& !(has "--dport 7777 -i br0" closed)
&& !(has "--dport 7777 -i cni0" closed)
&& has "-t raw -I PREROUTING -j c" closed && has "-t raw -I PREROUTING -j c" closed
&& has "-t raw -A nixos-fw-nats -p tcp --dport 4222 -i cni0 -j RETURN" onCluster.networking.firewall.extraCommands && has "-t raw -A nixos-fw-nats -p tcp --dport 4222 -i cni0 -j RETURN" onCluster.networking.firewall.extraCommands
&& has "-t raw -A nixos-fw-nats -p tcp --dport 4222 -m addrtype --dst-type LOCAL -j DROP" onCluster.networking.firewall.extraCommands && has "-t raw -A nixos-fw-nats -p tcp --dport 4222 -m addrtype --dst-type LOCAL -j DROP" onCluster.networking.firewall.extraCommands

View file

@ -11,18 +11,18 @@
# never overlap; # never overlap;
# - the pod is Ready by its exec probe on the server's monitor, holds the leaf # - the pod is Ready by its exec probe on the server's monitor, holds the leaf
# and the callout config as init containers, and publishes the client port # and the callout config as init containers, and publishes the client port
# on every address and the exporter's on the bridge's; # on every address, with no `hostPort` on the exporter;
# - a client on the hive's bridge reaches the queue by name through the # - a client on the hive's bridge reaches the queue by name through the
# published port, and the responder in the pod admits the router's token; # published port, and the responder in the pod admits the router's token;
# - the port is as closed to a host outside the node as the container's is, and # - the port is as closed to a host outside the node as the container's is, and
# open with `openFirewall`, where a second node dials it by name and verifies # open with `openFirewall`, where a second node dials it by name and verifies
# the name. The exporter's port answers the host's own processes only; # the name. The exporter answers the host only, by its Service's name;
# - a stream written before the pod is deleted is read after; # - a stream written before the pod is deleted is read after;
# - the store is the container's own directory: a key the host server wrote is # - the store is the container's own directory: a key the host server wrote is
# read by the pod, and a key the pod wrote is read by the host server after # read by the pod, and a key the pod wrote is read by the host server after
# the switch back, which hands the files back to the server's user; # the switch back, which hands the files back to the server's user;
# - the switch back leaves no pod, Deployment or AddOn, and the container # - the switch back leaves no pod, Deployment, Service, NetworkPolicy or AddOn,
# starts after the prune unit. # and the container starts after the prune unit.
# #
# One stub is the identity provider: it introspects the test's one token as the # One stub is the identity provider: it introspects the test's one token as the
# notification router, whose permissions create and fill a stream. The test # notification router, whose permissions create and fill a stream. The test
@ -352,6 +352,8 @@ pkgs.testers.runNixOSTest {
NAME = "${natsName}" NAME = "${natsName}"
PORT = ${toString natsPort} PORT = ${toString natsPort}
METRICS = ${toString metricsPort} METRICS = ${toString metricsPort}
METRICS_SERVICE = "${service}-metrics"
METRICS_HOST = f"{METRICS_SERVICE}.{NS}.svc.cluster.local"
NODE = "${nodeIp}" NODE = "${nodeIp}"
BRIDGE = "${bridgeIp}" BRIDGE = "${bridgeIp}"
CONTROL = ${toString controlPort} CONTROL = ${toString controlPort}
@ -394,6 +396,17 @@ pkgs.testers.runNixOSTest {
return machine.succeed(f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o name || true").split() return machine.succeed(f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o name || true").split()
def pod_pid(container: str) -> str:
id_ = machine.succeed(f"k3s crictl ps --name '^{container}$' --state running -q").split()[0]
return machine.succeed(f"k3s crictl inspect {id_} | 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}'"
def host_state() -> str: def host_state() -> str:
return machine.execute(f"systemctl is-active {HOST_UNIT}")[1].strip() return machine.execute(f"systemctl is-active {HOST_UNIT}")[1].strip()
@ -545,6 +558,8 @@ pkgs.testers.runNixOSTest {
assert machine.succeed(f"systemctl is-active {PRUNE}.service").strip() == "active" assert machine.succeed(f"systemctl is-active {PRUNE}.service").strip() == "active"
assert pods() == [], pods() assert pods() == [], pods()
assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0 assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get service {METRICS_SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get networkpolicy {SERVICE}")[0] != 0
# The control for its absence under the cluster. # The control for its absence under the cluster.
machine.succeed("test -e /etc/nixos-containers/swarm-nats.conf") machine.succeed("test -e /etc/nixos-containers/swarm-nats.conf")
assert counts() == (1, 1), counts() assert counts() == (1, 1), counts()
@ -594,7 +609,7 @@ pkgs.testers.runNixOSTest {
machine.fail("test -e /etc/nixos-containers/swarm-nats.conf") machine.fail("test -e /etc/nixos-containers/swarm-nats.conf")
assert counts() == (1, 1), counts() assert counts() == (1, 1), counts()
with subtest("the pod holds the leaf and the config as init containers, and publishes the client port on every address and the exporter's on the bridge"): with subtest("the pod holds the leaf and the config as init containers, publishes the client port on every address, and has no hostPort on the exporter"):
spec = pod(machine, pod_name)["spec"] spec = pod(machine, pod_name)["spec"]
assert [c["name"] for c in spec["initContainers"]] == ["tls-issue", "callout-config"], spec["initContainers"] assert [c["name"] for c in spec["initContainers"]] == ["tls-issue", "callout-config"], spec["initContainers"]
assert [c["name"] for c in spec["containers"]] == ["swarm-nats", "nats", "tls-renew", "exporter"], spec["containers"] assert [c["name"] for c in spec["containers"]] == ["swarm-nats", "nats", "tls-renew", "exporter"], spec["containers"]
@ -605,7 +620,7 @@ pkgs.testers.runNixOSTest {
command = server["readinessProbe"]["exec"]["command"] command = server["readinessProbe"]["exec"]["command"]
assert command[0] == "/bin/wget" and command[-1].endswith("/healthz?js-enabled-only=true"), command assert command[0] == "/bin/wget" and command[-1].endswith("/healthz?js-enabled-only=true"), command
exporter = next(c for c in spec["containers"] if c["name"] == "exporter") exporter = next(c for c in spec["containers"] if c["name"] == "exporter")
assert exporter["ports"][0]["hostIP"] == BRIDGE, exporter["ports"] assert exporter["ports"] == [{"name": "metrics", "containerPort": METRICS, "protocol": "TCP"}], exporter["ports"]
assert not any(c.get("resources") for c in spec["containers"]), spec["containers"] assert not any(c.get("resources") for c in spec["containers"]), spec["containers"]
assert not any("secret" in v for v in spec["volumes"]), spec["volumes"] assert not any("secret" in v for v in spec["volumes"]), spec["volumes"]
assert spec["hostAliases"] == [{"ip": "127.0.0.1", "hostnames": [NAME]}], spec["hostAliases"] assert spec["hostAliases"] == [{"ip": "127.0.0.1", "hostnames": [NAME]}], spec["hostAliases"]
@ -627,6 +642,14 @@ pkgs.testers.runNixOSTest {
print(limits) print(limits)
assert int(limits.split()[3]) >= 800000, limits assert int(limits.split()[3]) >= 800000, limits
with subtest("the exporter is a ClusterIP Service, and the pod's policy admits the client port from any source and nothing else"):
svc = json.loads(kube(machine, f"get service {METRICS_SERVICE} -o json"))
assert svc["spec"]["type"] == "ClusterIP", svc["spec"]
assert [(p["port"], p["targetPort"]) for p in svc["spec"]["ports"]] == [(METRICS, "metrics")], svc["spec"]
policy = json.loads(kube(machine, f"get networkpolicy {SERVICE} -o json"))["spec"]
assert policy["policyTypes"] == ["Ingress"], policy
assert policy["ingress"] == [{"ports": [{"port": PORT, "protocol": "TCP"}]}], policy
with subtest("one server and one responder run, and the queue answers by name with its name verified"): with subtest("one server and one responder run, and the queue answers by name with its name verified"):
assert counts() == (1, 1), counts() assert counts() == (1, 1), counts()
assert probe(machine, BRIDGE)[0], probe(machine, BRIDGE) assert probe(machine, BRIDGE)[0], probe(machine, BRIDGE)
@ -657,9 +680,21 @@ pkgs.testers.runNixOSTest {
assert reachable(outside, NODE, CONTROL) assert reachable(outside, NODE, CONTROL)
assert not reachable(outside, NODE, PORT), "the pod's port is open to a host outside the node" assert not reachable(outside, NODE, PORT), "the pod's port is open to a host outside the node"
with subtest("the exporter answers the host's own processes through the pod's published port"): with subtest("the exporter answers the host's own processes by its Service's name, and refuses a client of the bridge and a pod of the cluster"):
body = machine.succeed(f"curl -sf http://{BRIDGE}:{METRICS}/metrics") ip = kube(machine, f"get service {METRICS_SERVICE} -o jsonpath='{{.spec.clusterIP}}'").strip()
assert machine.succeed(f"getent ahostsv4 {METRICS_HOST}").split()[0] == ip
body = machine.succeed(f"curl -sf http://{METRICS_HOST}:{METRICS}/metrics")
assert "gnatsd_varz_connections" in body, body[:500] assert "gnatsd_varz_connections" in body, body[:500]
# The bridge's client has the route to the Service's address through the
# host, and the pod's policy refuses it. A pod of the cluster reaches the
# queue's client port, the control that it can dial out, and not the
# exporter.
assert machine.execute(f"ip netns exec agent nc -z -w 4 {ip} {METRICS}")[0] != 0
other = pod_pid("coredns")
machine.succeed(dials(other, BRIDGE, PORT))
machine.wait_until_fails(dials(other, ip, METRICS), timeout=120)
for _ in range(3):
assert machine.execute(dials(other, ip, METRICS))[0] != 0
with subtest("a leaf that has to be issued again is issued beside the running server, which reloads it for new connections"): 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"] uid = pod(machine, pod_name)["metadata"]["uid"]
@ -712,6 +747,8 @@ pkgs.testers.runNixOSTest {
settle(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", 600, [HOST_UNIT, f"{PRUNE}.service"]) settle(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", 600, [HOST_UNIT, f"{PRUNE}.service"])
assert pods() == [], pods() assert pods() == [], pods()
assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0 assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get service {METRICS_SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get networkpolicy {SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n kube-system get addons.k3s.cattle.io {SERVICE}")[0] != 0 assert machine.execute(f"kubectl -n kube-system get addons.k3s.cattle.io {SERVICE}")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml")[0] != 0 assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml.pruning")[0] != 0 assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml.pruning")[0] != 0