Watch
0
0
Fork
You've already forked hyperhive
0

the queue's exporter asks every request for a login the gateway supplies

This commit is contained in:
atlas 2026-11-27 15:42:53 +01:00
commit 893b693b46

View file

@ -36,6 +36,7 @@ let
metricsPort = 7777;
authName = "auth.t.local";
controlPort = 9999;
metricsGateway = "127.0.0.1:18083";
namespace = "hyperhive";
service = "swarm-nats";
prune = "${service}-k8s-prune";
@ -115,6 +116,36 @@ let
print(tls.getpeercert()["serialNumber"])
'';
# One nginx with the queue's `/metrics` location as the module renders it: the
# Service it dials, the variable between and the include of the exporter's
# login. The identity provider's check is a stand-in that answers 200, because
# the VM has no login service; nothing else of the vhost.
gatewayConf =
cfg:
let
l =
cfg.services.nginx.virtualHosts.${cfg.services.hyperhive.swarm.nats.domain}.locations."= /metrics";
in
pkgs.writeText "metrics-gateway.conf" ''
pid /run/metrics-gateway-test/nginx.pid;
error_log stderr;
events {}
http {
access_log off;
server {
listen ${metricsGateway};
location = /metrics {
proxy_pass ${l.proxyPass};
${l.extraConfig}
}
location = /__nats_metrics_authz {
internal;
return 200;
}
}
}
'';
# A port the node's firewall opens, which the second node reaches: the control
# for every refusal it sees.
controlListener = pkgs.writeText "control.py" ''
@ -240,6 +271,18 @@ pkgs.testers.runNixOSTest {
};
};
systemd.services.metrics-gateway = {
wantedBy = [ "multi-user.target" ];
after = [ "network.target" ];
serviceConfig = {
RuntimeDirectory = "metrics-gateway-test";
ExecStart = "${pkgs.nginx}/bin/nginx -c ${gatewayConf config} -g 'daemon off;'";
ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
Restart = "on-failure";
RestartSec = 2;
};
};
systemd.services.control-listener = {
wantedBy = [ "multi-user.target" ];
serviceConfig = {
@ -313,6 +356,8 @@ pkgs.testers.runNixOSTest {
};
testScript = builtins.readFile ./lib/k3s.py + ''
import base64
INIT = "/root/bao-init.json"
NS = "${namespace}"
SERVICE = "${service}"
@ -334,6 +379,11 @@ pkgs.testers.runNixOSTest {
MANIFESTS = "/var/lib/rancher/k3s/server/manifests"
SERVICES_ROOT = "${tlsDir}/swarm-services-root.pem"
TOKEN = "${routerToken}"
STORE_AUTH_DIR = "/var/lib/swarm-store-auth"
EXPORTER_PASSWORD = f"{STORE_AUTH_DIR}/nats.password"
EXPORTER_CONF = f"{STORE_AUTH_DIR}/nats.conf"
EXPORTER_HASH_FILE = f"{STORE_AUTH_DIR}/nats.hash"
GATEWAY = "http://${metricsGateway}/metrics"
STREAM = "ROUTER_TODOS"
QUEUE_UP = (
"systemctl --machine=swarm-nats is-active nats.service "
@ -459,6 +509,46 @@ pkgs.testers.runNixOSTest {
return node.execute(f"nc -z -w 4 {address} {port}")[0] == 0
def metrics_status(url: str, login: str | None, *args: str) -> tuple[int, str]:
"""One request to a metrics URL, with the Basic login `user:password`
when there is one: the status and the body."""
auth = f"-u '{login}' " if login else ""
_, out = machine.execute(f"curl -sS --max-time 10 -w '\\n%{{http_code}}' {auth}{' '.join(args)} '{url}'")
body, _, code = out.rpartition("\n")
return int(code or 0), body
def gateway_until(want: int) -> tuple[int, str]:
"""The gateway's answer to a collector's request, asked again for up to
30 seconds until its status is `want`: the last status and body."""
deadline = time.monotonic() + 30
while True:
status, body = metrics_status(GATEWAY, None, "-H 'Authorization: Bearer the-collectors-token'")
if status == want or time.monotonic() >= deadline:
return status, body
time.sleep(1)
def gateway_diagnostics(pod_name: str) -> None:
"""What to read when the gateway's request is refused for good: the test
nginx's journal and error output, the length of the include file (never
its content), whether the exporter takes that header replayed straight
to it, and the exporter's own log."""
def show(title: str, command: str) -> None:
print(f"--- {title}")
print(machine.execute(f"{command} 2>&1")[1])
show("metrics-gateway journal", "journalctl -u metrics-gateway --no-pager -n 40")
show("include file length", f"wc -c {EXPORTER_CONF}")
show(
"the file's header replayed straight to the exporter (status)",
f"hdr=$(sed -E 's/^proxy_set_header Authorization \"(.*)\";$/\\1/' {EXPORTER_CONF}); "
f"curl -s -o /dev/null -w '%{{http_code}}' -H \"Authorization: $hdr\" http://{METRICS_HOST}:{METRICS}/metrics",
)
show("gateway response headers", f"curl -s -D- -o /dev/null -H 'Authorization: Bearer the-collectors-token' {GATEWAY}")
show("exporter log", f"kubectl -n {NS} logs {pod_name} -c exporter --tail=30")
def counts() -> tuple[int, int]:
"""How many servers and responders the node runs."""
servers = int(machine.execute("pgrep -cx nats-server")[1].strip() or 0)
@ -503,9 +593,14 @@ pkgs.testers.runNixOSTest {
"swarm-bao-nats-tls-policy",
"swarm-bao-nats-auth-policy",
"swarm-bao-services-issuer-policy",
"swarm-bao-store-auth-policy",
"swarm-bao-k8s-jwt-policy",
]:
settle(f'[ "$(systemctl is-active {unit}.service)" = active ]', 900, [f"{unit}.service"])
# The exporter's login: the unit creates it, hashes it and publishes the
# hash, which the pod's exporter container waits for.
machine.succeed("systemctl reset-failed swarm-bao-store-auth.service || true")
machine.succeed("systemctl restart --no-block swarm-bao-store-auth.service")
machine.wait_until_succeeds(
"journalctl -u swarm-bao-k8s-jwt-policy --no-pager | grep -F 'Success! Data written to: auth/jwt-k8s/role/swarm-nats-auth'",
timeout=300,
@ -555,6 +650,11 @@ pkgs.testers.runNixOSTest {
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")
assert exporter["ports"] == [{"name": "metrics", "containerPort": METRICS, "protocol": "TCP"}], exporter["ports"]
# The login is on the command line as a hash the Secret supplies, never
# as the password.
assert exporter["args"][exporter["args"].index("-http_user") + 1] == "swarm-exporter", exporter["args"]
assert exporter["args"][exporter["args"].index("-http_pass") + 1] == "$(EXPORTER_HASH)", exporter["args"]
assert exporter["env"] == [{"name": "EXPORTER_HASH", "valueFrom": {"secretKeyRef": {"name": "swarm-nats-exporter-auth", "key": "hash"}}}], exporter["env"]
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 spec["hostAliases"] == [{"ip": "127.0.0.1", "hostnames": [NAME]}], spec["hostAliases"]
@ -675,8 +775,9 @@ pkgs.testers.runNixOSTest {
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"):
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]
password = machine.succeed(f"cat {EXPORTER_PASSWORD}").strip()
status, body = metrics_status(f"http://{METRICS_HOST}:{METRICS}/metrics", f"swarm-exporter:{password}")
assert status == 200 and "gnatsd_varz_connections" in body, (status, 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
@ -700,6 +801,57 @@ pkgs.testers.runNixOSTest {
deny = json.loads(kube(machine, "get networkpolicy default-deny-ingress -o json"))["spec"]
assert deny == {"podSelector": {}, "policyTypes": ["Ingress"]}, deny
with subtest("the exporter answers only a request with its login, from the node and through the gateway, and the Secret holds the hash and no password"):
url = f"http://{METRICS_HOST}:{METRICS}/metrics"
# The password the unit created, in the store, on the host and nowhere
# else: the Secret and the manifest hold its bcrypt hash.
assert len(password) == 64 and all(c in "0123456789abcdef" for c in password), "the password is not 64 hex digits"
assert as_root("bao kv get -mount=secret -field=value swarm/services/nats/exporter-auth").strip() == password
exporter_hash = machine.succeed(f"kubectl -n {NS} get secret swarm-nats-exporter-auth -o jsonpath='{{.data.hash}}' | base64 -d")
assert exporter_hash.startswith("$2a$11$") and len(exporter_hash) == 60, exporter_hash
assert machine.succeed(f"cat {EXPORTER_HASH_FILE}").strip() == exporter_hash
assert password not in kube(machine, "get secret swarm-nats-exporter-auth -o json")
assert password not in kube(machine, f"get pod {pod_name} -o json")
assert machine.succeed(f"stat -c '%a %U %G' {EXPORTER_PASSWORD} {EXPORTER_CONF} {EXPORTER_HASH_FILE} {STORE_AUTH_DIR}").split("\n")[:4] == [
"600 root root",
"600 root root",
"600 root root",
"700 root root",
]
login = base64.b64encode(f"swarm-exporter:{password}".encode()).decode()
assert machine.succeed(f"cat {EXPORTER_CONF}").strip() == f'proxy_set_header Authorization "Basic {login}";'
# The login opens it, the control for each refusal below. The hash is
# no password: the exporter reads only a `$2a$` value as bcrypt, and a
# hash taken for plain text would let its own text in. An empty password
# is refused for the same reason, which is what a missing `-http_pass`
# would let in.
assert metrics_status(url, f"swarm-exporter:{password}")[0] == 200
for who in (None, "swarm-exporter:wrong", f"other:{password}", f"swarm-exporter:{exporter_hash}", "swarm-exporter:", f"swarm-exporter:{password}0"):
status, body = metrics_status(url, who)
assert status == 401 and "gnatsd" not in body, (who, status, body[:200])
pod_ip_now = kube(machine, f"get pod {pod_name} -o jsonpath='{{.status.podIP}}'").strip()
assert metrics_status(f"http://{pod_ip_now}:{METRICS}/metrics", None)[0] == 401
assert metrics_status(f"http://{pod_ip_now}:{METRICS}/metrics", f"swarm-exporter:{password}")[0] == 200
# Through the gateway's location as the module renders it: the caller's
# own bearer is replaced by the login, and the queue's series arrive.
# nginx reads the include file as it loads: this one started at boot
# with the empty file the tmpfiles rule made, before the unit wrote the
# header, so it reloads, as the unit does for the host's nginx. A reload
# answers before the new workers take requests, so each request below
# is repeated until it answers what the file now says.
machine.succeed("systemctl reload metrics-gateway")
status, body = gateway_until(200)
if status != 200 or "gnatsd_varz_connections" not in body:
gateway_diagnostics(pod_name)
raise AssertionError((status, body[:500]))
# With the include file empty the gateway sends nothing and the exporter
# refuses the caller's bearer; the unit writes the file again.
machine.succeed(f": > {EXPORTER_CONF} && systemctl reload metrics-gateway")
status, _ = gateway_until(401)
assert status == 401, status
machine.succeed("systemctl restart swarm-bao-store-auth.service && systemctl reload metrics-gateway")
assert gateway_until(200)[0] == 200
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"]
leaf_dir = machine.succeed(f"grep -F 'pods/{uid}/volumes/kubernetes.io~empty-dir/nats-tls ' /proc/mounts | cut -d' ' -f2").strip()