Watch
0
0
Fork
You've already forked hyperhive
0

k8s: the controller's listener is a ClusterIP service the host dials by name

The controller's api port was a hostPort on the node, which Pod Security baseline and restricted forbid. It is a ClusterIP Service now, behind a NetworkPolicy that admits only the node. The host's resolver (the hive's dnsmasq) forwards cluster.local to CoreDNS, and the gateway dials the Service by name through nginx's resolver. tcp.hostAddress goes.
This commit is contained in:
atlas 2026-11-23 17:20:22 +01:00 • committed by maia
commit 3cf89f25f1
13 changed files with 355 additions and 103 deletions

View file

@ -19,14 +19,14 @@ to the cluster, when the service's `runtime` says `"k8s"`.
A service gets manifests on the host whose configuration deploys it: A service gets manifests on the host whose configuration deploys it:
| service | workload | other objects | | service | workload | other objects |
| ------------------------- | ---------- | ------------------------------------------------------------------------------------------------ | | ------------------------- | ---------- | ------------------------------------------------------------------------------------------ |
| `swarm-controller` | Deployment | ServiceAccount, PersistentVolumeClaim `swarm-controller-state`, ConfigMap `swarm-controller-etc` | | `swarm-controller` | Deployment | ServiceAccount, ConfigMap `swarm-controller-etc`; Service, NetworkPolicy with the listener |
| `swarm-notify-router` | Deployment | ServiceAccount | | `swarm-notify-router` | Deployment | ServiceAccount |
| `swarm-stt` | Deployment | ServiceAccount, NetworkPolicy `swarm-stt` | | `swarm-stt` | Deployment | ServiceAccount, NetworkPolicy `swarm-stt` |
| `swarm-review-classifier` | Deployment | ServiceAccount | | `swarm-review-classifier` | Deployment | ServiceAccount |
| `swarm-claude-login` | Deployment | ServiceAccount | | `swarm-claude-login` | Deployment | ServiceAccount |
| `swarm-ci-metrics` | CronJob | ServiceAccount, PersistentVolumeClaim `swarm-ci-metrics-state` | | `swarm-ci-metrics` | CronJob | ServiceAccount, PersistentVolumeClaim `swarm-ci-metrics-state` |
`namespace.yaml` holds the Namespace. NATS with its auth responder has no `namespace.yaml` holds the Namespace. NATS with its auth responder has no
manifests yet: its image doesn't exist yet. manifests yet: its image doesn't exist yet.
@ -133,11 +133,11 @@ credential directory.
(see [Readiness checks](../swarm/readiness.md)). `swarm-controller` is one of (see [Readiness checks](../swarm/readiness.md)). `swarm-controller` is one of
them, with `SWARM_CONTROLLER_HEALTH_ADDR`. them, with `SWARM_CONTROLLER_HEALTH_ADDR`.
- **Listener and init container:** a service with a TCP `listener` - **Listener and init container:** a service with a TCP `listener`
(`swarm-controller`, with `swarm.controller.tcp.enable`) publishes its port on (`swarm-controller`, with `swarm.controller.tcp.enable`) publishes its port
the node's address with a `hostPort`, and gets an init container and a with a ClusterIP Service, admits only the node to it with a NetworkPolicy, and
renewal container that issue its leaf into an `emptyDir` gets an init container and a renewal container that issue its leaf into an
([runtime](runtime.md#the-controller)). The image of those containers is part `emptyDir` ([runtime](runtime.md#the-controller)). The image of those
of `system.build.k8sImages`. containers is part of `system.build.k8sImages`.
- **More than the daemon:** a service whose pod holds more than its daemon - **More than the daemon:** a service whose pod holds more than its daemon
(the queue, whose server and exporter run beside the responder) names a (the queue, whose server and exporter run beside the responder) names a
function in its entry that adds containers, init containers, volumes, host function in its entry that adds containers, init containers, volumes, host

View file

@ -69,6 +69,31 @@ these listeners without a firewall rule per port. Each service still
authenticates its callers: every listener of the secret store but its pods' authenticates its callers: every listener of the secret store but its pods'
one refuses a connection without a client certificate. one refuses a connection without a client certificate.
## Reaching the cluster from the host
The host's resolver, the hive's dnsmasq (the host's own `/etc/resolv.conf`
names it), forwards the cluster's domain to CoreDNS. `deploy.k8s.clusterDomain`
is `cluster.local` and `deploy.k8s.clusterDns`, the tenth address of
`deploy.k8s.serviceCidr`, is the address k3s gives CoreDNS: the node passes
both as flags (`--cluster-domain`, `--cluster-dns`) and the resolver's
`server=/cluster.local/<address>` line reads the same values. A process on the
host, nginx included, so reaches a Service as
`<name>.<namespace>.svc.cluster.local`. The node doesn't set the line without
`gateway.dns.enable`, the option that runs that resolver.
A ClusterIP answers the host because kube-proxy (k3s runs it in `iptables`
mode) rewrites a host process's connection to the Service's address into the
pod's, and the firewall trusts the pod network's interfaces. The bridge's
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
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
selects it for ingress and allows nothing. kube-router, the policy engine, adds
a rule at the top of every pod's chain that admits traffic from any address of
the node (`-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
A pod holds no client certificate. It logs in to the secret store with a A pod holds no client certificate. It logs in to the secret store with a

View file

@ -93,9 +93,9 @@ Job:
delete. With no link, nothing went in, so the unit does nothing and needs no delete. With no link, nothing went in, so the unit does nothing and needs no
cluster. cluster.
2. Wait for the cluster's API, then delete the service's Deployment, CronJob, 2. Wait for the cluster's API, then delete the service's Deployment, CronJob,
NetworkPolicy and ServiceAccount (selected by `app.kubernetes.io/name`), and Service, NetworkPolicy and ServiceAccount (selected by
wait until its pods have gone. A pod exits 0 within its termination grace `app.kubernetes.io/name`), and wait until its pods have gone. A pod exits 0
period. within its termination grace period.
3. Delete the cluster's AddOn for the file, so that a later switch to `"k8s"` 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. applies the same manifest again. Then remove the renamed link.
@ -142,16 +142,24 @@ leader lock exists, so a cluster of more than one node needs one before the
controller may move there. controller may move there.
- **The gateway's hop.** The host can't reach a unix socket inside a pod, so - **The gateway's hop.** The host can't reach a unix socket inside a pod, so
the pod serves the TCP listener, and publishes it with a `hostPort` on the pod serves the TCP listener, and a ClusterIP Service,
`deploy.swarm-controller.tcp.hostAddress`. That address is the hive bridge's `swarm-controller.<namespace>.svc.<cluster domain>`, publishes it. The
by default, the one the pods already reach the host's services on. The
listener binds `0.0.0.0` inside the pod (`tcp.listenAddress`, which the listener binds `0.0.0.0` inside the pod (`tcp.listenAddress`, which the
evaluation holds there). The gateway's `/api/` and `/webhook/forge/` evaluation holds there). The host's resolver, the hive's dnsmasq, hands the
locations dial the node's address and port, and verify the listener's cluster's domain to CoreDNS
certificate as `swarm.controller.tcp.domain` (`proxy_ssl_name`, ([the node](node.md#reaching-the-cluster-from-the-host)). The gateway's
`proxy_ssl_verify`). With the controller on the host the locations dial the `/api/` and `/webhook/forge/` locations dial the Service's name through
name. A `hostPort` reaches one node: a cluster of more than one node needs a nginx's own `resolver` (the same dnsmasq) and a variable upstream, so nginx
Service instead. looks the name up per request. A name written into `proxy_pass` gets one
lookup when nginx loads its configuration, and nginx refuses to load when it
doesn't resolve. The locations verify the listener's certificate as
`swarm.controller.tcp.domain` (`proxy_ssl_name`, `proxy_ssl_verify`). With
the controller on the host the locations dial that name. The Service has a
NetworkPolicy that selects the pod for ingress and allows nothing: the
cluster's policy engine always admits traffic from an address of the node, so
the gateway's connection and the kubelet's probes reach the pod, and no other
pod does. A Service works on a cluster of more than one node, but the
controller's Deployment still has the one replica.
- **The listener's leaf.** The pod issues its own, from the store's - **The listener's leaf.** The pod issues its own, from the store's
`swarm-controller-tls` role, with the same script as `swarm-controller-tls` role, with the same script as
`swarm-controller-tls.service`. An init container logs in with the pod's `swarm-controller-tls.service`. An init container logs in with the pod's

View file

@ -530,10 +530,13 @@ What you provide:
on another host dials it. The port (`swarm.controller.tcp.port`, default 9443) stays closed on another host dials it. The port (`swarm.controller.tcp.port`, default 9443) stays closed
until you do, and `deploy.swarm-controller.tcp.listenAddress` picks the bound address. until you do, and `deploy.swarm-controller.tcp.listenAddress` picks the bound address.
With `deploy.swarm-controller.runtime = "k8s"` the listener is the pod's `hostPort`. The gateway With `deploy.swarm-controller.runtime = "k8s"` a ClusterIP Service publishes the
dials `deploy.swarm-controller.tcp.hostAddress` (the hive bridge's address by default) at the pod's listener. The gateway dials the Service's name,
same port, and still verifies the certificate as `swarm.controller.tcp.domain`, so that name `swarm-controller.hyperhive.svc.cluster.local` by default, at the same port. The
needs no address of its own. The pod issues its server leaf itself hive's resolver answers it through the cluster's DNS, so `gateway.dns.enable`
has to be on. The gateway still verifies the certificate as
`swarm.controller.tcp.domain`, so that name needs no address of its own. The
pod issues its server leaf itself
([`runtime.md`](../k8s/runtime.md#the-controller)). ([`runtime.md`](../k8s/runtime.md#the-controller)).
What you don't: both certificates come from the secret store with no manual step What you don't: both certificates come from the secret store with no manual step

View file

@ -34,6 +34,8 @@ in
# The single-host swarm fixture's k8s manifests (../host-modules/k8s), # The single-host swarm fixture's k8s manifests (../host-modules/k8s),
# validated offline by `kubeconform -strict` against the schemas below. # validated offline by `kubeconform -strict` against the schemas below.
# The node fixture is validated too: with the controller's TCP listener on,
# its Service and NetworkPolicy render.
# The invalid Deployment must fail, which shows the schemas load and an # The invalid Deployment must fail, which shows the schemas load and an
# unknown field is refused. # unknown field is refused.
k8s-manifests-all-local = k8s-manifests-all-local =
@ -59,6 +61,7 @@ in
namespace-v1 = "sha256-Mk+uZ3uY0abVQ0DbDDNNBT6P+6/Os/czJuQd4mENWEM="; namespace-v1 = "sha256-Mk+uZ3uY0abVQ0DbDDNNBT6P+6/Os/czJuQd4mENWEM=";
serviceaccount-v1 = "sha256-gZPWw1YUdcbT1cROH67bHfU5BTc9kEvBcBVpQybWWc8="; serviceaccount-v1 = "sha256-gZPWw1YUdcbT1cROH67bHfU5BTc9kEvBcBVpQybWWc8=";
networkpolicy-networking-v1 = "sha256-9jJMxGT2IiiwQY9DjRZyCOT4bH42d7ow9gjnmosmunk="; networkpolicy-networking-v1 = "sha256-9jJMxGT2IiiwQY9DjRZyCOT4bH42d7ow9gjnmosmunk=";
service-v1 = "sha256-i/AZhU2u1RHnwXSJaomBc/pl2I7Fk3xoejcwPUzJNRs=";
} }
); );
invalid = pkgs.writeText "invalid-deployment.yaml" '' invalid = pkgs.writeText "invalid-deployment.yaml" ''
@ -85,6 +88,8 @@ in
pkgs.runCommand "k8s-manifests-all-local" { nativeBuildInputs = [ pkgs.kubeconform ]; } '' pkgs.runCommand "k8s-manifests-all-local" { nativeBuildInputs = [ pkgs.kubeconform ]; } ''
${validate} ${moduleEvalShared.allLocal.system.build.k8sManifests}/ ${validate} ${moduleEvalShared.allLocal.system.build.k8sManifests}/
test -e ${moduleEvalShared.allLocal.system.build.k8sManifests}/swarm-controller/deployment.yaml test -e ${moduleEvalShared.allLocal.system.build.k8sManifests}/swarm-controller/deployment.yaml
${validate} ${moduleEvalShared.k8sNode.system.build.k8sManifests}/
test -e ${moduleEvalShared.k8sNode.system.build.k8sManifests}/swarm-controller/service.yaml
if ${validate} ${invalid}; then if ${validate} ${invalid}; then
echo "kubeconform accepted a Deployment with an unknown field" >&2 echo "kubeconform accepted a Deployment with an unknown field" >&2
exit 1 exit 1

View file

@ -40,12 +40,33 @@ let
in in
builtins.bitAnd pa.base keep == builtins.bitAnd pb.base keep; builtins.bitAnd pa.base keep == builtins.bitAnd pb.base keep;
# The first address of a range, and the dotted form of an integer.
networkOf =
cidr:
let
p = parseCidr cidr;
in
builtins.bitAnd p.base (4294967296 - pow2 (32 - p.len));
intToIp =
n:
lib.concatMapStringsSep "." (d: toString (lib.mod (n / d) 256)) [
16777216
65536
256
1
];
cidrType = lib.types.strMatching "([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}"; cidrType = lib.types.strMatching "([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}";
# k3s's own defaults, named so the flags below and the ServiceAccount # k3s's own defaults, named so the flags below and the ServiceAccount
# issuer and key paths read from one place. # issuer and key paths read from one place.
dataDir = "/var/lib/rancher/k3s"; dataDir = "/var/lib/rancher/k3s";
clusterDomain = "cluster.local"; clusterDomain = "cluster.local";
# k3s's default for `--cluster-dns` is the tenth address of the service
# range (`GetIndexedIP(svcCIDR, 10)` in k3s' `pkg/cli/server/server.go`). It
# is passed explicitly below, so the address the host's resolver forwards
# to and the one CoreDNS gets agree by construction.
clusterDns = intToIp (networkOf cfg.serviceCidr + 10);
in in
{ {
options.services.hyperhive.deploy.k8s = { options.services.hyperhive.deploy.k8s = {
@ -93,6 +114,29 @@ in
''; '';
}; };
clusterDomain = lib.mkOption {
type = lib.types.str;
readOnly = true;
internal = true;
default = clusterDomain;
description = ''
The cluster's DNS domain (`--cluster-domain`). A Service is
`<name>.<namespace>.svc.<this>`.
'';
};
clusterDns = lib.mkOption {
type = lib.types.str;
readOnly = true;
internal = true;
default = clusterDns;
description = ''
The address of the cluster's DNS service (`--cluster-dns`): the tenth
address of {option}`services.hyperhive.deploy.k8s.serviceCidr`. The
host's resolver forwards the cluster's domain to it.
'';
};
cniInterfaces = lib.mkOption { cniInterfaces = lib.mkOption {
type = lib.types.listOf lib.types.str; type = lib.types.listOf lib.types.str;
default = [ default = [
@ -194,6 +238,7 @@ in
"--service-cidr=${cfg.serviceCidr}" "--service-cidr=${cfg.serviceCidr}"
"--data-dir=${dataDir}" "--data-dir=${dataDir}"
"--cluster-domain=${clusterDomain}" "--cluster-domain=${clusterDomain}"
"--cluster-dns=${clusterDns}"
]; ];
# k3s's own images come first: with no registry the node pulls nothing, # k3s's own images come first: with no registry the node pulls nothing,
# not even CoreDNS. # not even CoreDNS.
@ -204,5 +249,13 @@ in
}; };
networking.firewall.trustedInterfaces = cfg.cniInterfaces; networking.firewall.trustedInterfaces = cfg.cniInterfaces;
# The host's resolver (the hive's dnsmasq, which the host's own
# `/etc/resolv.conf` names) hands the cluster's domain to CoreDNS, so a
# Service is reachable from the host by its name. The bridge's agents ask
# the same resolver and get the same answers.
services.dnsmasq.settings.server = lib.mkIf config.services.hyperhive.gateway.dns.enable [
"/${clusterDomain}/${clusterDns}"
];
}; };
} }

View file

@ -134,8 +134,8 @@ let
# /readyz listener. `publicCredentials` maps the ids of the credentials that # /readyz listener. `publicCredentials` maps the ids of the credentials that
# hold a public CA file to their key in the CA ConfigMap, and `publicFiles` # hold a public CA file to their key in the CA ConfigMap, and `publicFiles`
# the paths the unit names that hold one to theirs. `listener`, where a # the paths the unit names that hold one to theirs. `listener`, where a
# service has one, is the TCP port the pod publishes on the node # service has one, is the TCP port a Service publishes in the cluster and the
# (`hostAddress`) and the directory its init container writes the leaf to. # directory the pod's init container writes the leaf to.
# `ephemeralState` gives a service an `emptyDir` in place of a claim for its # `ephemeralState` gives a service an `emptyDir` in place of a claim for its
# state directory: what it keeps there is re-derived at start. A pod starts on # state directory: what it keeps there is re-derived at start. A pod starts on
# whatever volume it gets. # whatever volume it gets.
@ -168,11 +168,10 @@ let
"hive-client-ca.pem" = hiveClientCaKey; "hive-client-ca.pem" = hiveClientCaKey;
}; };
publicFiles = lib.optionalAttrs controllerTcp.enable { ${servicesRootPath} = servicesRootKey; }; publicFiles = lib.optionalAttrs controllerTcp.enable { ${servicesRootPath} = servicesRootKey; };
# The TCP listener, as a `hostPort` on the node's address: the gateway # The TCP listener, behind a Service the gateway on the host dials by
# on the host dials it there. # name.
listener = lib.optionalAttrs controllerTcp.enable { listener = lib.optionalAttrs controllerTcp.enable {
port = controllerTcp.port; port = controllerTcp.port;
hostAddress = controllerCfg.tcp.hostAddress;
tlsDir = controllerCfg.tcp.tlsDir; tlsDir = controllerCfg.tcp.tlsDir;
}; };
# The unit pushes to the swarm collector's route and mints its own bearer # The unit pushes to the swarm collector's route and mints its own bearer
@ -423,6 +422,42 @@ let
}; };
}; };
# The listener's Service, and the policy that lets only the node reach it. The
# cluster's policy engine (kube-router) admits traffic whose source is a local
# address of the node to any pod (`--src-type LOCAL`, the rule it labels "from
# local node"), and a policy that selects the pod for ingress and allows
# nothing refuses every other source. The gateway on the host dials the
# Service's name, so its connection reaches the pod from the node; a pod of
# the cluster does not.
listenerObjects = name: listener: {
"${name}/service" = {
apiVersion = "v1";
kind = "Service";
metadata = metaFor name;
spec = {
type = "ClusterIP";
selector = labelsFor name;
ports = [
{
name = "api";
protocol = "TCP";
port = listener.port;
targetPort = "api";
}
];
};
};
"${name}/networkpolicy" = {
apiVersion = "networking.k8s.io/v1";
kind = "NetworkPolicy";
metadata = metaFor name;
spec = {
podSelector.matchLabels = labelsFor name;
policyTypes = [ "Ingress" ];
};
};
};
# systemd duration "<n>min", the only form these units use. # systemd duration "<n>min", the only form these units use.
minutesOf = minutesOf =
name: what: value: name: what: value:
@ -776,8 +811,7 @@ let
cpu = "0"; cpu = "0";
}; };
# `hostPort` publishes the listener on the node's address. The cluster's # The listener's Service targets this port by its name.
# portmap plugin forwards it to the pod, so it reaches this one node.
ports = ports =
lib.optional (svc.healthEnv != null) { lib.optional (svc.healthEnv != null) {
name = "health"; name = "health";
@ -786,8 +820,6 @@ let
++ lib.optional (listener != { }) { ++ lib.optional (listener != { }) {
name = "api"; name = "api";
containerPort = listener.port; containerPort = listener.port;
hostPort = listener.port;
hostIP = listener.hostAddress;
}; };
container = { container = {
@ -994,6 +1026,7 @@ let
// lib.optionalAttrs (svc ? egress) { // lib.optionalAttrs (svc ? egress) {
"${name}/networkpolicy" = networkPolicyOf name svc.egress; "${name}/networkpolicy" = networkPolicyOf name svc.egress;
} }
// lib.optionalAttrs (listener != { }) (listenerObjects name listener)
// lib.optionalAttrs baoLogin { // lib.optionalAttrs baoLogin {
# Named after the service: the store's jwt role binds this account. # Named after the service: the store's jwt role binds this account.
"${name}/serviceaccount" = { "${name}/serviceaccount" = {
@ -1031,6 +1064,8 @@ let
fail name "the unit already sets ${svc.healthEnv}" fail name "the unit already sets ${svc.healthEnv}"
else if svc ? egress && !(lib.all (r: hostPorts ? ${r}) svc.egress) then 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)})" fail name "egress names a host service the renderer has no port for (${lib.concatStringsSep ", " (lib.attrNames hostPorts)})"
else if svc ? egress && listener != { } then
fail name "has an egress policy and a listener, which would share one NetworkPolicy"
else if lib.head execWords != entrypoint then else if lib.head execWords != entrypoint then
fail name "ExecStart is not ${entrypoint} with plain arguments" fail name "ExecStart is not ${entrypoint} with plain arguments"
else if lib.any (w: lib.hasInfix "\"" w) execWords then else if lib.any (w: lib.hasInfix "\"" w) execWords then

View file

@ -145,7 +145,7 @@ in
exit 0 exit 0
fi fi
${apiReady} ${apiReady}
${kubectl} --namespace ${cfg.namespace} delete deployment,cronjob,serviceaccount,networkpolicy \ ${kubectl} --namespace ${cfg.namespace} delete deployment,cronjob,serviceaccount,networkpolicy,service \
--selector=app.kubernetes.io/name=${name} \ --selector=app.kubernetes.io/name=${name} \
--cascade=foreground --wait=true --timeout=180s --ignore-not-found --cascade=foreground --wait=true --timeout=180s --ignore-not-found
${kubectl} --namespace kube-system delete addons.k3s.cattle.io ${name} --ignore-not-found ${kubectl} --namespace kube-system delete addons.k3s.cattle.io ${name} --ignore-not-found

View file

@ -17,7 +17,7 @@
# #
# `deploy.swarm-controller.runtime = "k8s"` runs the daemon as a pod in this # `deploy.swarm-controller.runtime = "k8s"` runs the daemon as a pod in this
# host's cluster instead (./k8s/render.nix renders it from the unit below). The # host's cluster instead (./k8s/render.nix renders it from the unit below). The
# unit is then disabled, and the gateway dials the pod's `hostPort`. # unit is then disabled, and the gateway dials the pod's Service by name.
{ {
pkgs, pkgs,
lib, lib,
@ -635,7 +635,8 @@ in
The pod needs the TCP listener The pod needs the TCP listener
({option}`services.hyperhive.swarm.controller.tcp.enable`): the host ({option}`services.hyperhive.swarm.controller.tcp.enable`): the host
cannot reach a unix socket inside a pod, so the gateway dials the cannot reach a unix socket inside a pod, so the gateway dials the
listener on {option}`tcp.hostAddress`. The pod's state directory is an listener, which a Service in the cluster publishes at
{option}`tcp.serviceHost`. The pod's state directory is an
`emptyDir`: the operator grant record is in the queue's key-value `emptyDir`: the operator grant record is in the queue's key-value
store, and what is left in the directory (the forge avatar markers, the store, and what is left in the directory (the forge avatar markers, the
legacy webhook secret the store also holds) is made again at start. A legacy webhook secret the store also holds) is made again at start. A
@ -790,23 +791,22 @@ in
With {option}`services.hyperhive.deploy.swarm-controller.runtime` set With {option}`services.hyperhive.deploy.swarm-controller.runtime` set
to `k8s` this is the bind inside the pod, so it must stay `0.0.0.0`. to `k8s` this is the bind inside the pod, so it must stay `0.0.0.0`.
The node's address is {option}`hostAddress`.
''; '';
}; };
hostAddress = lib.mkOption { serviceHost = lib.mkOption {
type = lib.types.str; type = lib.types.str;
default = config.services.hyperhive.network.bridgeIp; readOnly = true;
defaultText = lib.literalExpression "config.services.hyperhive.network.bridgeIp"; internal = true;
default = "swarm-controller.${config.services.hyperhive.k8s.namespace}.svc.${config.services.hyperhive.deploy.k8s.clusterDomain}";
defaultText = lib.literalExpression ''"swarm-controller.<namespace>.svc.<cluster domain>"'';
description = '' description = ''
With {option}`services.hyperhive.deploy.swarm-controller.runtime` set With {option}`services.hyperhive.deploy.swarm-controller.runtime` set
to `k8s`: the node address the pod's `hostPort` binds and the gateway to `k8s`: the name of the Service in front of the pod's listener,
dials. The default is the hive bridge's address, the one the pods which the gateway dials. The host's resolver answers it through the
already reach the host's services on. The gateway verifies the cluster's DNS. The gateway verifies the listener's certificate as
listener's certificate as {option}`services.hyperhive.swarm.controller.tcp.domain`, not as this
{option}`services.hyperhive.swarm.controller.tcp.domain`, not as name.
this address. A `hostPort` reaches one node: a cluster of several
nodes needs a Service instead.
''; '';
}; };
@ -939,8 +939,8 @@ in
users.groups.swarm-controller = { }; users.groups.swarm-controller = { };
users.groups.${clientsGroup} = { }; users.groups.${clientsGroup} = { };
# The pod's `hostPort` is on the hive bridge's address by default, and the # The cluster's pods reach the host's services through the bridge, and the
# cluster's pods reach the host's services through the bridge. # host's resolver (the hive's dnsmasq, on the bridge) answers the Service's name.
services.hyperhive.network.enable = lib.mkIf onK8s (lib.mkDefault true); services.hyperhive.network.enable = lib.mkIf onK8s (lib.mkDefault true);
# Through the unit, not `users.users.nginx.extraGroups`: systemd resolves # Through the unit, not `users.users.nginx.extraGroups`: systemd resolves
@ -1028,8 +1028,16 @@ in
services.hyperhive.deploy.swarm-controller.tcp.listenAddress is services.hyperhive.deploy.swarm-controller.tcp.listenAddress is
"${tcpHost.listenAddress}", and with runtime = "k8s" it is the bind "${tcpHost.listenAddress}", and with runtime = "k8s" it is the bind
inside the pod, where any address but "0.0.0.0" leaves the listener inside the pod, where any address but "0.0.0.0" leaves the listener
unbound and the pod NotReady. Leave it at "0.0.0.0"; the node's unbound and the pod NotReady. Leave it at "0.0.0.0".
address is services.hyperhive.deploy.swarm-controller.tcp.hostAddress. '';
}
{
assertion = !onK8s || config.services.hyperhive.gateway.dns.enable;
message = ''
services.hyperhive.deploy.swarm-controller.runtime = "k8s" needs
services.hyperhive.gateway.dns.enable: the gateway dials the pod's
Service by name, and the hive's resolver is what hands the cluster's
domain to its DNS. Set it, or leave the controller's runtime at "host".
''; '';
} }
{ {

View file

@ -107,17 +107,20 @@ let
# `toString` below so an unset `domain` reaches the assertion that names it # `toString` below so an unset `domain` reaches the assertion that names it
# instead of failing evaluation first. # instead of failing evaluation first.
controllerTcp = swarmCfg.controller.tcp; controllerTcp = swarmCfg.controller.tcp;
# In the cluster the listener is the pod's `hostPort` on the node's address. # In the cluster the listener is behind a Service, which the host's resolver
# The name the certificate is verified as stays `tcp.domain` # answers through the cluster's DNS. The upstream is a variable, so nginx asks
# (`controllerDial`), so the address needs no certificate of its own. # the resolver per request: a name in the `proxy_pass` is looked up when the
controllerAddress = # configuration loads, which fails the load while the cluster is not up and
if deployCfg.swarm-controller.runtime == "k8s" then # keeps the address of a Service that has since been recreated. The name the
deployCfg.swarm-controller.tcp.hostAddress # certificate is verified as stays `tcp.domain` (`controllerDial`), so the
else # Service needs no certificate name of its own.
toString controllerTcp.domain; controllerOnCluster = deployCfg.swarm-controller.runtime == "k8s";
controllerUpstream = controllerUpstream =
if controllerTcp.enable then if controllerTcp.enable then
"https://${controllerAddress}:${toString controllerTcp.port}" if controllerOnCluster then
"https://$swarm_controller_upstream"
else
"https://${toString controllerTcp.domain}:${toString controllerTcp.port}"
else else
"http://unix:${deployCfg.swarm-controller.socketPath}:"; "http://unix:${deployCfg.swarm-controller.socketPath}:";
# `proxy_http_version` and `Connection` because `recommendedProxySettings`, # `proxy_http_version` and `Connection` because `recommendedProxySettings`,
@ -125,6 +128,10 @@ let
# them nginx speaks HTTP/1.0 to the upstream, which ends the SSE streams' # them nginx speaks HTTP/1.0 to the upstream, which ends the SSE streams'
# keep-alive. # keep-alive.
controllerDial = lib.optionalString controllerTcp.enable '' controllerDial = lib.optionalString controllerTcp.enable ''
${lib.optionalString controllerOnCluster ''
resolver ${config.services.hyperhive.network.bridgeIp} valid=10s ipv6=off;
set $swarm_controller_upstream ${deployCfg.swarm-controller.tcp.serviceHost}:${toString controllerTcp.port};
''}
${gatewayCfg.lib.verifiedProxyToWithClientCert (toString controllerTcp.domain) { ${gatewayCfg.lib.verifiedProxyToWithClientCert (toString controllerTcp.domain) {
certificate = deployCfg.swarm-controller.tcp.gatewayClientCertFile; certificate = deployCfg.swarm-controller.tcp.gatewayClientCertFile;
key = deployCfg.swarm-controller.tcp.gatewayClientKeyFile; key = deployCfg.swarm-controller.tcp.gatewayClientKeyFile;

View file

@ -33,27 +33,9 @@ let
allLocal = shared.allLocal; allLocal = shared.allLocal;
# The four auth responder packages pinned to four distinct derivations, as # The all-local host with the node on, shared with the manifests' schema check.
# in ./shared.nix: the all-local host needs them set. nodeSettings = shared.k8sNodeSettings;
marker = name: pkgs.runCommand "auth-marker-${name}" { } "mkdir $out"; withNode = shared.k8sNode;
# The all-local host with the node on. It does not set
# `services.hyperhive.k8s.enable`: the node turns the rendering on.
nodeSettings = {
deploy.singleHostSwarm = true;
deploy.k8s.enable = true;
deploy.victorialogs.authPackage = marker "logs";
deploy.victorialogs.grafanaAuthPackage = marker "logs-grafana";
deploy.victoriametrics.authPackage = marker "metrics";
deploy.victoriametrics.agentAuthPackage = marker "metrics-agent";
# The controller's TCP listener, which the controller in the cluster needs
# and the one on the host serves as well.
swarm.controller.tcp = {
enable = true;
domain = "controller.t.local";
};
};
withNode = hiveWithController nodeSettings;
# The same host with the router, the speech-to-text service, the review # The same host with the router, the speech-to-text service, the review
# classifier, the claude login minter and the CI run poller in the cluster, # classifier, the claude login minter and the CI run poller in the cluster,
@ -375,7 +357,8 @@ let
# Nothing the host already runs differs but the store's side of the pods' # Nothing the host already runs differs but the store's side of the pods'
# login: every unit, timer and container is still there, the only new # login: every unit, timer and container is still there, the only new
# units are k3s's and the one that writes the pods' login, every unit but # units are k3s's and the one that writes the pods' login, every unit but
# the firewall (whose rules carry the pod network's interfaces) and the # the firewall (whose rules carry the pod network's interfaces), the
# resolver (which hands the cluster's domain to its DNS) and the
# granter's role unit (which enables the login's auth mount) starts the # granter's role unit (which enables the login's auth mount) starts the
# same command, and the manifests are the same as without the node. The # same command, and the manifests are the same as without the node. The
# fixture has the controller's TCP listener on, which `allLocal` has off: # fixture has the controller's TCP listener on, which `allLocal` has off:
@ -424,6 +407,7 @@ let
( (
lib.subtractLists [ lib.subtractLists [
"firewall" "firewall"
"dnsmasq"
"nginx" "nginx"
"opentelemetry-collector" "opentelemetry-collector"
"swarm-bao-controller-policy" "swarm-bao-controller-policy"
@ -1429,6 +1413,7 @@ let
&& lib.any ( && lib.any (
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
# 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;
@ -1543,12 +1528,51 @@ let
== [ == [
"ConfigMap" "ConfigMap"
"Deployment" "Deployment"
"NetworkPolicy"
"Service"
"ServiceAccount" "ServiceAccount"
]; ];
} }
{
# The host with no listener is the control: the controller has no Service
# or policy there, and the policy admits nothing but the node.
name = "the controller's listener is a ClusterIP Service that only the node reaches, with the cluster's DNS handed the cluster's domain by the host's resolver";
ok =
let
cluster = render onCluster;
svc = cluster."swarm-controller/service";
policy = cluster."swarm-controller/networkpolicy";
h = withNode.services.hyperhive;
prune = withNode.systemd.services.swarm-controller-k8s-prune.script;
in
svc.kind == "Service"
&& svc.spec.type == "ClusterIP"
&& svc.spec.selector == policy.spec.podSelector.matchLabels
&& !(svc.spec ? clusterIP)
&&
svc.spec.ports == [
{
name = "api";
protocol = "TCP";
port = 9443;
targetPort = "api";
}
]
&& policy.spec.policyTypes == [ "Ingress" ]
&& !(policy.spec ? ingress)
&& !(policy.spec ? egress)
&& !(objects ? "swarm-controller/service")
&& !(objects ? "swarm-controller/networkpolicy")
&& h.swarm.controller.tcp.enable
&& h.deploy.swarm-controller.tcp.serviceHost == "swarm-controller.hyperhive.svc.cluster.local"
&& lib.elem "/cluster.local/10.201.0.10" withNode.services.dnsmasq.settings.server
&& lib.elem "--cluster-dns=10.201.0.10" withNode.services.k3s.extraFlags
&& !(lib.elem "/cluster.local/10.201.0.10" (allLocal.services.dnsmasq.settings.server or [ ]))
&& lib.hasInfix "networkpolicy,service \\" prune;
}
{ {
# The host with the controller on it dials the name, as it always did. # The host with the controller on it dials the name, as it always did.
name = "the gateway dials the controller pod's hostPort and verifies its certificate as the listener's name"; name = "the gateway dials the controller's Service by name, resolved per request, and verifies its certificate as the listener's name";
ok = ok =
let let
loc = c: path: c.services.nginx.virtualHosts."t.local".locations.${path}; loc = c: path: c.services.nginx.virtualHosts."t.local".locations.${path};
@ -1561,8 +1585,24 @@ let
&& dials c path "proxy_ssl_verify on;" && dials c path "proxy_ssl_verify on;"
&& dials c path "proxy_ssl_certificate "; && dials c path "proxy_ssl_certificate ";
in in
(loc onCluster "/webhook/forge/").proxyPass == "https://10.42.0.1:9443" (loc onCluster "/webhook/forge/").proxyPass == "https://\$swarm_controller_upstream"
&& (loc onCluster "/api/").proxyPass == "https://10.42.0.1:9443" && (loc onCluster "/api/").proxyPass == "https://\$swarm_controller_upstream"
&&
lib.all
(
p:
dials onCluster p "resolver 10.42.0.1 valid=10s ipv6=off;"
&&
dials onCluster p
"set \$swarm_controller_upstream swarm-controller.hyperhive.svc.cluster.local:9443;"
)
[
"/webhook/forge/"
"/api/"
]
# The host with the controller on it names no variable and no resolver.
&& !(dials withNode "/api/" "resolver")
&& !(dials withNode "/api/" "swarm_controller_upstream")
&& (loc withNode "/webhook/forge/").proxyPass == "https://controller.t.local:9443" && (loc withNode "/webhook/forge/").proxyPass == "https://controller.t.local:9443"
&& (loc withNode "/api/").proxyPass == "https://controller.t.local:9443" && (loc withNode "/api/").proxyPass == "https://controller.t.local:9443"
&& verified onCluster "/webhook/forge/" && verified onCluster "/webhook/forge/"
@ -1570,7 +1610,7 @@ let
&& verified withNode "/api/"; && verified withNode "/api/";
} }
{ {
name = "the controller's pod publishes its listener on the node, is probed on the health listener, and rolls with its rev file"; name = "the controller's pod serves its listener on a named port with no hostPort, is probed on the health listener, and rolls with its rev file";
ok = ok =
let let
cluster = render onCluster; cluster = render onCluster;
@ -1588,9 +1628,9 @@ let
c.readinessProbe.httpGet.path == "/readyz" c.readinessProbe.httpGet.path == "/readyz"
&& c.livenessProbe.httpGet.path == "/healthz" && c.livenessProbe.httpGet.path == "/healthz"
&& (byName "health" c.ports).containerPort == 8080 && (byName "health" c.ports).containerPort == 8080
&& api.hostPort == 9443
&& api.containerPort == 9443 && api.containerPort == 9443
&& api.hostIP == "10.42.0.1" && !(api ? hostPort)
&& !(api ? hostIP)
&& deployment.spec.replicas == 1 && deployment.spec.replicas == 1
&& deployment.spec.strategy.type == "Recreate" && deployment.spec.strategy.type == "Recreate"
# The checksum is of the ConfigMap's content, and a changed rev changes it. # The checksum is of the ConfigMap's content, and a changed rev changes it.

View file

@ -35,6 +35,22 @@ let
# The four auth responder packages pinned to four distinct derivations, so # The four auth responder packages pinned to four distinct derivations, so
# a unit's ExecStart names which option it read. Nothing else reads them. # a unit's ExecStart names which option it read. Nothing else reads them.
marker = name: pkgs.runCommand "auth-marker-${name}" { } "mkdir $out"; marker = name: pkgs.runCommand "auth-marker-${name}" { } "mkdir $out";
# The all-local host with the k3s node on, and the controller's TCP listener
# that a controller in the cluster needs and the one on the host serves as
# well. It does not set `k8s.enable`: the node turns the rendering on.
k8sNodeSettings = {
deploy.singleHostSwarm = true;
deploy.k8s.enable = true;
deploy.victorialogs.authPackage = marker "logs";
deploy.victorialogs.grafanaAuthPackage = marker "logs-grafana";
deploy.victoriametrics.authPackage = marker "metrics";
deploy.victoriametrics.agentAuthPackage = marker "metrics-agent";
swarm.controller.tcp = {
enable = true;
domain = "controller.t.local";
};
};
in in
{ {
agentBare = agent { }; agentBare = agent { };
@ -55,6 +71,9 @@ in
deploy.victoriametrics.agentAuthPackage = marker "metrics-agent"; deploy.victoriametrics.agentAuthPackage = marker "metrics-agent";
}; };
inherit k8sNodeSettings;
k8sNode = hiveWithController k8sNodeSettings;
autheliaOnly = hive { deploy.authelia.enable = true; }; autheliaOnly = hive { deploy.authelia.enable = true; };
forgeHere = hive { deploy.forgejo.enable = true; }; forgeHere = hive { deploy.forgejo.enable = true; };

View file

@ -13,12 +13,14 @@
# name against the hive's root, and a handshake with no client leaf is refused; # name against the hive's root, and a handshake with no client leaf is refused;
# - the gateway's own controller location, rendered by the module for each # - the gateway's own controller location, rendered by the module for each
# runtime and run here in a nginx of its own, reaches the controller: on the # runtime and run here in a nginx of its own, reaches the controller: on the
# host by name, in the cluster by the node's address, verifying the leaf as # host by name, in the cluster by the Service's name, which the host's
# the name; the controller answers an unsigned webhook 401 both times; # 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`);
# - a changed hyperhive rev rolls the Deployment; the pod's state directory is # - a changed hyperhive rev rolls the Deployment; the pod's state directory is
# an emptyDir, with no claim and no gate; # an emptyDir, with no claim and no gate;
# - the switch back leaves no pod, Deployment or AddOn, and the host unit # - the switch back leaves no pod, Deployment, Service, NetworkPolicy or
# starts after the prune unit. # AddOn, and the host unit starts after the prune unit.
# #
# The queue is a plain nats-server with TLS and one stub is the token endpoint # The queue is a plain nats-server with TLS and one stub is the token endpoint
# and the forge; they replace services that stay host-run and unchanged. The # and the forge; they replace services that stay host-run and unchanged. The
@ -156,6 +158,9 @@ pkgs.testers.runNixOSTest {
deploy.k8s.enable = true; deploy.k8s.enable = true;
network.enable = true; network.enable = true;
network.bridgeIp = bridgeIp; network.bridgeIp = bridgeIp;
# The hive's resolver hands the cluster's domain to CoreDNS, which is how the
# host reaches the controller's Service by name.
gateway.dns.enable = true;
deploy.bao.enable = true; deploy.bao.enable = true;
deploy.bao.seal = "shamir"; deploy.bao.seal = "shamir";
deploy.bao.bootstrapTokenFile = "/var/lib/swarm-bao-bootstrap/grant.token"; deploy.bao.bootstrapTokenFile = "/var/lib/swarm-bao-bootstrap/grant.token";
@ -332,7 +337,8 @@ pkgs.testers.runNixOSTest {
PRUNE = "${prune}" PRUNE = "${prune}"
NAME = "${controllerName}" NAME = "${controllerName}"
PORT = ${toString controllerPort} PORT = ${toString controllerPort}
NODE_ADDRESS = "${bridgeIp}" BRIDGE = "${bridgeIp}"
SERVICE_HOST = "${service}.${namespace}.svc.cluster.local"
SOCKET = "/run/swarm-controller/controller.sock" SOCKET = "/run/swarm-controller/controller.sock"
MANIFESTS = "/var/lib/rancher/k3s/server/manifests" MANIFESTS = "/var/lib/rancher/k3s/server/manifests"
SERVICES_ROOT = "${tlsDir}/swarm-services-root.pem" SERVICES_ROOT = "${tlsDir}/swarm-services-root.pem"
@ -428,6 +434,21 @@ pkgs.testers.runNixOSTest {
)[1] )[1]
def cluster_ip() -> str:
return kube(machine, f"get service {SERVICE} -o jsonpath='{{.spec.clusterIP}}'").strip()
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}'"
with subtest("the node is Ready and holds every image"): with subtest("the node is Ready and holds every image"):
wait_node_ready(machine, timeout=300) wait_node_ready(machine, timeout=300)
wait_images(machine, timeout=300) wait_images(machine, timeout=300)
@ -497,6 +518,8 @@ pkgs.testers.runNixOSTest {
assert pods() == [], pods() assert pods() == [], pods()
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"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 {SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get networkpolicy {SERVICE}")[0] != 0
# The controller's own listener presents the leaf the host unit issued. # The controller's own listener presents the leaf the host unit issued.
settle(f"echo | openssl s_client -connect 127.0.0.1:{PORT} -servername {NAME} -CAfile {SERVICES_ROOT} -verify_hostname {NAME} -verify_return_error -cert {GATEWAY_CERT} -key {GATEWAY_KEY} 2>&1 | grep -F 'Verification: OK'", 120, [HOST_UNIT]) settle(f"echo | openssl s_client -connect 127.0.0.1:{PORT} -servername {NAME} -CAfile {SERVICES_ROOT} -verify_hostname {NAME} -verify_return_error -cert {GATEWAY_CERT} -key {GATEWAY_KEY} 2>&1 | grep -F 'Verification: OK'", 120, [HOST_UNIT])
assert gateway("gateway.service") == 401 assert gateway("gateway.service") == 401
@ -523,7 +546,7 @@ pkgs.testers.runNixOSTest {
probe = main["readinessProbe"]["httpGet"] probe = main["readinessProbe"]["httpGet"]
assert probe["path"] == "/readyz", probe assert probe["path"] == "/readyz", probe
api = next(p for p in main["ports"] if p["name"] == "api") api = next(p for p in main["ports"] if p["name"] == "api")
assert api["hostPort"] == PORT and api["hostIP"] == NODE_ADDRESS, api assert api["containerPort"] == PORT and "hostPort" not in api and "hostIP" not in api, api
assert [c["name"] for c in spec["initContainers"]] == ["tls-issue"], spec["initContainers"] assert [c["name"] for c in spec["initContainers"]] == ["tls-issue"], spec["initContainers"]
assert "tls-renew" in [c["name"] for c in spec["containers"]] assert "tls-renew" in [c["name"] for c in 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"]
@ -545,10 +568,10 @@ pkgs.testers.runNixOSTest {
with subtest("the pod's listener presents the leaf its own init container issued, valid as the listener's name against the hive's root, and refuses a client with no leaf"): with subtest("the pod's listener presents the leaf its own init container issued, valid as the listener's name against the hive's root, and refuses a client with no leaf"):
issued = machine.succeed(f"kubectl -n {NS} logs {pod_name} -c tls-issue") issued = machine.succeed(f"kubectl -n {NS} logs {pod_name} -c tls-issue")
assert "requesting the controller's listener leaf for {NAME} from the store".format(NAME=NAME) in issued, issued assert "requesting the controller's listener leaf for {NAME} from the store".format(NAME=NAME) in issued, issued
good = handshake(NODE_ADDRESS, f"-cert {GATEWAY_CERT} -key {GATEWAY_KEY}") good = handshake(cluster_ip(), f"-cert {GATEWAY_CERT} -key {GATEWAY_KEY}")
assert "Verification: OK" in good, good assert "Verification: OK" in good, good
refused = machine.execute( refused = machine.execute(
f"curl -s -o /dev/null --cacert {SERVICES_ROOT} --resolve {NAME}:{PORT}:{NODE_ADDRESS} https://{NAME}:{PORT}/api/openapi.json" f"curl -s -o /dev/null --cacert {SERVICES_ROOT} --resolve {NAME}:{PORT}:{cluster_ip()} https://{NAME}:{PORT}/api/openapi.json"
)[0] )[0]
assert refused != 0, "a client with no leaf was served" assert refused != 0, "a client with no leaf was served"
# The renewal container runs the same script and finds the leaf valid. # The renewal container runs the same script and finds the leaf valid.
@ -557,14 +580,40 @@ pkgs.testers.runNixOSTest {
timeout=120, timeout=120,
) )
with subtest("the gateway's controller location reaches the pod by the node's address and verifies it as the listener's name"): with subtest("the gateway's controller location reaches the pod by the Service's name and verifies it as the listener's name"):
assert gateway("gateway.service") == 401 assert gateway("gateway.service") == 401
api_status = int(machine.succeed( api_status = int(machine.succeed(
f"curl -s -o /dev/null -w '%{{http_code}}' --cacert {SERVICES_ROOT} --resolve {NAME}:{PORT}:{NODE_ADDRESS} " f"curl -s -o /dev/null -w '%{{http_code}}' --cacert {SERVICES_ROOT} --resolve {NAME}:{PORT}:{cluster_ip()} "
f"--cert {GATEWAY_CERT} --key {GATEWAY_KEY} https://{NAME}:{PORT}/api/openapi.json" f"--cert {GATEWAY_CERT} --key {GATEWAY_KEY} https://{NAME}:{PORT}/api/openapi.json"
)) ))
assert api_status == 200, api_status assert api_status == 200, api_status
with subtest("the listener is a ClusterIP Service the host reaches by its name, and the Service refuses a pod of the cluster that reaches the host's own listeners"):
svc = json.loads(kube(machine, f"get service {SERVICE} -o json"))
assert svc["spec"]["type"] == "ClusterIP", svc["spec"]
assert [(p["port"], p["targetPort"]) for p in svc["spec"]["ports"]] == [(PORT, "api")], svc["spec"]
ip = cluster_ip()
assert ip.startswith("10.201."), ip
# The host's resolver forwards the cluster's domain to CoreDNS.
assert machine.succeed(f"getent ahostsv4 {SERVICE_HOST}").split()[0] == ip
assert "Verification: OK" in handshake(SERVICE_HOST, f"-cert {GATEWAY_CERT} -key {GATEWAY_KEY}")
policy = json.loads(kube(machine, f"get networkpolicy {SERVICE} -o json"))["spec"]
assert policy["policyTypes"] == ["Ingress"] and "ingress" not in policy, policy
# A pod of the cluster reaches a listener of the host, the control that
# a pod can dial out at all, and not the controller's Service.
other = pod_pid("coredns")
machine.succeed(dials(other, BRIDGE, ${toString natsPort}))
machine.wait_until_fails(dials(other, ip, PORT), timeout=120)
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("a changed rev rolls the Deployment, and the old pod is gone first"): with subtest("a changed rev rolls the Deployment, and the old pod is gone first"):
old_uid = pod(machine, pod_name)["metadata"]["uid"] old_uid = pod(machine, pod_name)["metadata"]["uid"]
old_annotation = pod(machine, pod_name)["metadata"]["annotations"]["checksum/etc"] old_annotation = pod(machine, pod_name)["metadata"]["annotations"]["checksum/etc"]