Watch
0
0
Fork
You've already forked hyperhive
0

run the log store and its auth responders as pods

swarm-logs-auth and swarm-metrics-auth take --listen for a TCP address beside
--socket. The log store is a Deployment on a static local volume that is its
old container's data directory, behind a ClusterIP Service the gateway dials by
name. Its two auth_request responders are one unpinned pod with a jwt role.
The renderer gains a plain HTTP listener, a probe path, fsGroupChangePolicy,
and one policy for a pod with both a listener and egress.
This commit is contained in:
atlas 2026-11-26 10:17:57 +01:00 • committed by mara
commit c7c82a6b02

View file

@ -11,6 +11,12 @@
# speech-to-text pod carries its limits and keeps its cache in an emptyDir,
# with no claim and no state gate, in a user namespace, and its NetworkPolicy
# lets a queue request in and only DNS and four host ports out;
# - the log store runs as a pod on the directory its old container kept, which
# a unit of this test filled before the cluster started, as another user: the
# pod reads that record and writes a new one, the gateway's own locations
# (rendered by the module, run in a nginx of their own) reach the store and the
# responders by their Services' names, a bearer is granted or refused by the
# responders with the store's answers, and no other pod reaches the store;
# - the poller's Job completes against a forge that lists one run, pushes it to
# its own route of the swarm collector, holds no Secret, and keeps its cursor
# in a volume, so a second Job pushes nothing, and starts with no state
@ -67,6 +73,56 @@ let
# nothing reads it.
sttModel = pkgs.writeText "ggml-placeholder.bin" "not a model";
tokenLog = "/var/log/stub-token.log";
# The log store, as the module names it.
vlDir = "/var/lib/nixos-containers/swarm-victorialogs/var/lib/victorialogs";
vlGateway = "127.0.0.1:18081";
legacyUser = "legacy-victorialogs";
legacyPort = 19428;
# One nginx with the log store's locations as the module renders them: the
# Services they dial, the responders they check a bearer with and the
# variables between. The identity provider's two checks are stand-ins that
# answer 200, because the VM has no login service; nothing else of the vhost.
gatewayConf =
cfg:
let
locations = cfg.services.nginx.virtualHosts."logs.t.local".locations;
served = [
"= /insert/opentelemetry/v1/logs"
"^~ /select/logsql/"
"= /metrics"
"= /__swarm_logs_auth"
"= /__swarm_logs_agent_auth"
"= /__swarm_logs_grafana_auth"
];
block =
name:
let
l = locations.${name};
in
''
location ${name} {
${lib.optionalString (l.proxyPass != null) "proxy_pass ${l.proxyPass};"}
${l.extraConfig}
}
'';
in
pkgs.writeText "logs-gateway.conf" ''
pid /run/logs-gateway-test/nginx.pid;
error_log stderr;
events {}
http {
access_log off;
${cfg.services.nginx.appendHttpConfig}
server {
listen ${vlGateway};
location = /__swarm_logs_ingest_authz { internal; return 200; }
location = /__hive_authelia { internal; return 200; }
${lib.concatMapStrings block served}
}
}
'';
requestLog = "/var/log/stub-requests.log";
# The identity provider, the forge and the swarm collector, by name, on one
@ -190,6 +246,7 @@ pkgs.testers.runNixOSTest {
deploy.claude-login.enable = true;
deploy.stt.settings.modelFile = sttModel;
deploy.ci-metrics.enable = true;
deploy.victorialogs.enable = true;
deploy.hive-controller.hiveName = "h1";
swarm.domain = "t.local";
swarm.forge.domain = forgeName;
@ -294,6 +351,63 @@ pkgs.testers.runNixOSTest {
};
};
# What the log store's container left on the host before the cluster ran
# the store: its data directory, written by the pinned binary as a user
# of its own with group-writable files, holding one record. A switch from
# the container can't be run here (the container is gone from the
# module), so the directory is what the switch leaves behind.
users.users.${legacyUser} = {
isSystemUser = true;
group = legacyUser;
};
users.groups.${legacyUser} = { };
systemd.services.victorialogs-legacy = {
wantedBy = [ "multi-user.target" ];
before = [ "k3s.service" ];
path = [
pkgs.curl
pkgs.coreutils
pkgs.findutils
];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
User = legacyUser;
UMask = "0007";
ExecStartPre = "+${pkgs.writeShellScript "victorialogs-legacy-dir" ''
mkdir -p ${vlDir}
chown ${legacyUser}:${legacyUser} ${vlDir}
chmod 0700 ${vlDir}
''}";
};
script = ''
${config.services.hyperhive.deploy.victorialogs.package}/bin/victoria-logs \
-storageDataPath=${vlDir} -httpListenAddr=127.0.0.1:${toString legacyPort} &
pid=$!
until curl -sf http://127.0.0.1:${toString legacyPort}/health; do sleep 1; done
curl -sf --data-binary \
"{\"_msg\":\"written before the switch\",\"app\":\"legacy\",\"_time\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}" \
'http://127.0.0.1:${toString legacyPort}/insert/jsonline?_stream_fields=app'
until curl -s --data-urlencode 'query=legacy' http://127.0.0.1:${toString legacyPort}/select/logsql/query \
| grep -q 'written before the switch'; do sleep 1; done
kill -TERM "$pid"
wait "$pid" || true
test -n "$(find ${vlDir} -type f | head -1)"
'';
};
# The log store's locations, from the active configuration's own text.
systemd.services.logs-gateway = {
wantedBy = [ "multi-user.target" ];
after = [ "network.target" ];
serviceConfig = {
RuntimeDirectory = "logs-gateway-test";
ExecStart = "${pkgs.nginx}/bin/nginx -c ${gatewayConf config} -g 'daemon off;'";
Restart = "on-failure";
RestartSec = 2;
};
};
environment.systemPackages = [
pkgs.kubectl
pkgs.curl
@ -386,6 +500,12 @@ pkgs.testers.runNixOSTest {
MANIFESTS = "/var/lib/rancher/k3s/server/manifests"
NATS = "--server tls://${natsName}:${toString natsPort} --tlsca ${pkiDir}/ca.pem"
AGENT = "${agent}"
OTHER_AGENT = "argus"
AGENT_SECRETS: dict[str, str] = {}
VL = "swarm-victorialogs"
LOGS_AUTH = "swarm-logs-auth"
VL_DIR = "${vlDir}"
GATEWAY = "http://${vlGateway}"
SELECTOR = f"--selector app.kubernetes.io/name={SERVICE}"
@ -501,6 +621,7 @@ pkgs.testers.runNixOSTest {
"swarm-bao-ci-metrics-policy",
"swarm-bao-review-classifier-policy",
"swarm-bao-claude-login-policy",
"swarm-bao-logs-auth-policy",
"swarm-bao-k8s-jwt-policy",
]:
settle(f'[ "$(systemctl is-active {unit}.service)" = active ]', 900, [f"{unit}.service"])
@ -523,6 +644,16 @@ pkgs.testers.runNixOSTest {
as_root(f"bao kv put -mount=secret ${classifierLeaf} value={CLASSIFIER_SECRET}")
LOGIN_SECRET = machine.succeed("openssl rand -hex 16").strip()
as_root(f"bao kv put -mount=secret ${loginLeaf} value={LOGIN_SECRET}")
# What the log store's responders read: an agent's queue secret and its
# mirrored grant, one agent that holds no grant, and the bearer
# Grafana's host creates. The grant is a JSON object, so it is a file.
for name, grant in ((AGENT, '{"logs": true}'), (OTHER_AGENT, '{"logs": false}')):
AGENT_SECRETS[name] = machine.succeed("openssl rand -hex 16").strip()
as_root(f"bao kv put -mount=secret swarm/agents/{name}/queue value={AGENT_SECRETS[name]} agent={name}")
machine.succeed(f"echo '{grant}' > /tmp/grant-{name}.json")
as_root(f"bao kv put -mount=secret swarm/agents/{name}/observability @/tmp/grant-{name}.json")
GRAFANA_BEARER = machine.succeed("openssl rand -hex 32").strip()
as_root(f"bao kv put -mount=secret swarm/services/swarm-grafana/metrics/bearer value={GRAFANA_BEARER}")
with subtest("the queue and the token stub run, and the queue holds the roster the router reads"):
machine.wait_for_unit("hive-tls-ca.service")
@ -676,6 +807,113 @@ pkgs.testers.runNixOSTest {
status = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["status"]
assert status["containerStatuses"][0]["ready"] and status["containerStatuses"][0]["restartCount"] == 0, status
with subtest("the log store and its responders run only as pods: the host has no container, unit or socket directory for them"):
machine.fail("test -e /etc/nixos-containers/swarm-victorialogs.conf")
assert host_state("container@swarm-victorialogs.service") == "inactive"
for unit in ("swarm-logs-auth", "swarm-logs-grafana-auth"):
machine.fail(f"systemctl cat {unit}.service")
machine.fail("test -e /run/swarm-victorialogs")
# The CA publisher is the control that the lookups find a unit of the cluster's that is there.
machine.succeed("systemctl cat hyperhive-k8s-ca-trust.service")
for name in (VL, LOGS_AUTH):
machine.succeed(f"test -L {MANIFESTS}/{name}.yaml")
vl_pod = wait_pod_ready(VL)
auth_pod = wait_pod_ready(LOGS_AUTH)
assert machine.execute("machinectl list --no-legend | grep -q swarm-victorialogs")[0] != 0
with subtest("the store's volume is the old container's directory, whose files keep the user that wrote them and whose tree the pod's group owns"):
pv = json.loads(kube(machine, f"get pv {VL}-store -o json"))
assert pv["spec"]["local"]["path"] == VL_DIR and pv["status"]["phase"] == "Bound", pv
pvc = json.loads(kube(machine, f"get pvc {VL}-store -o json"))
assert pvc["status"]["phase"] == "Bound" and pvc["spec"]["volumeName"] == pv["metadata"]["name"], pvc
assert machine.succeed(f"stat -c %g {VL_DIR}").strip() == "65532"
assert machine.succeed(f"find {VL_DIR} -type f -user ${legacyUser} | head -1").strip() != ""
assert machine.succeed(f"kubectl -n {NS} get pods {vl_pod} -o jsonpath='{{.status.containerStatuses[0].restartCount}}'").strip() == "0"
def vl_request(path: str, token: str | None, *args: str) -> tuple[int, str]:
"""One request to the gateway's locations: the status and the body."""
auth = f"-H 'Authorization: Bearer {token}' " if token else ""
_, out = machine.execute(f"curl -sS --max-time 20 -w '\\n%{{http_code}}' {auth}{' '.join(args)} {GATEWAY}{path}")
body, _, code = out.rpartition("\n")
return int(code or 0), body
def vl_query(token: str, text: str) -> tuple[int, str]:
return vl_request("/select/logsql/query", token, f"--data-urlencode 'query={text}'")
def wait_for_record(token: str, text: str, record: str) -> None:
"""Queries until the response holds `record`, for as long as the pod and
the policy engine take to settle."""
deadline = time.monotonic() + 300
while True:
status, body = vl_query(token, text)
if status == 200 and record in body:
return
assert time.monotonic() < deadline, (status, body)
time.sleep(3)
AGENT_TOKEN = f"swarm-agent.{AGENT}.{AGENT_SECRETS[AGENT]}"
with subtest("an agent's bearer reads the record written before the switch through the gateway, and the other bearers are granted or refused as the store says"):
wait_for_record(AGENT_TOKEN, "legacy", "written before the switch")
# Each refusal has the answer above as its control: the same request with
# a bearer the store grants.
assert vl_query(f"swarm-agent.{OTHER_AGENT}.{AGENT_SECRETS[OTHER_AGENT]}", "legacy")[0] == 403
assert vl_query(f"swarm-agent.{AGENT}.{'0' * 32}", "legacy")[0] == 401
# Grafana's bearer goes to the second responder of the same pod.
status, body = vl_query(GRAFANA_BEARER, "legacy")
assert status == 200 and "written before the switch" in body, (status, body)
assert vl_query("0" * 64, "legacy")[0] == 401
with subtest("a record posted to the ingest route and the store's own metrics come through the gateway, and a restarted pod still holds both records"):
import base64
def varint(n: int) -> bytes:
out = b""
while n > 0x7F:
out += bytes([n & 0x7F | 0x80])
n >>= 7
return out + bytes([n])
def field(number: int, payload: bytes) -> bytes:
return varint(number << 3 | 2) + varint(len(payload)) + payload
# An OTLP logs request with one record: time (field 1, fixed64) and a body
# (field 5) that is a string value.
now_ns = int(machine.succeed("date +%s%N"))
record = varint(1 << 3 | 1) + now_ns.to_bytes(8, "little") + field(5, field(1, b"written through the gateway"))
request = field(1, field(2, field(2, record)))
machine.succeed(f"echo {base64.b64encode(request).decode()} | base64 -d > /tmp/otlp.bin")
status, body = vl_request(
"/insert/opentelemetry/v1/logs", None, "-X POST -H 'Content-Type: application/x-protobuf' --data-binary @/tmp/otlp.bin"
)
assert status == 200, (status, body)
wait_for_record(AGENT_TOKEN, "gateway", "written through the gateway")
status, body = vl_request("/metrics", None)
assert status == 200 and "vl_" in body, (status, body[:200])
kube(machine, f"delete pod {vl_pod} --wait=true", timeout=120)
vl_pod = wait_pod_ready(VL)
wait_for_record(AGENT_TOKEN, "legacy", "written before the switch")
wait_for_record(AGENT_TOKEN, "gateway", "written through the gateway")
with subtest("only the node reaches the log store's pods, and the responders' pod reaches the store's pod listener and no other port of the host"):
vl_ip = kube(machine, f"get pod {vl_pod} -o jsonpath='{{.status.podIP}}'").strip()
auth_ip = kube(machine, f"get pod {auth_pod} -o jsonpath='{{.status.podIP}}'").strip()
machine.succeed(f"curl -sf --max-time 5 http://{vl_ip}:9428/health")
# A peer pod reaches the classifier's health port, which has no policy:
# the control that the dial below is refused by the policy.
machine.succeed(dials(router_pid, classifier_ip, 8080))
for ip, port in ((vl_ip, 9428), (auth_ip, 8081), (auth_ip, 8082)):
machine.succeed(f"timeout 5 bash -c '</dev/tcp/{ip}/{port}'")
machine.wait_until_fails(dials(router_pid, ip, port), timeout=60)
for _ in range(3):
assert machine.execute(dials(router_pid, ip, port))[0] != 0
auth_pid = pod_pid(LOGS_AUTH)
machine.succeed(dials(auth_pid, "${bridgeIp}", ${toString podPort}))
machine.wait_until_fails(dials(auth_pid, "${bridgeIp}", 9999), timeout=60)
for name in (vl_pod, auth_pod):
status = json.loads(kube(machine, f"get pod {name} -o json"))["status"]
assert all(c["ready"] for c in status["containerStatuses"]), status
with subtest("the poller's Job completes against the forge and pushes the run to the poller's own route with a token the identity provider minted"):
tokens_before = int(machine.succeed(f"grep -cF '/api/oidc/token ${ci}:{CI_SECRET}' ${tokenLog} || true"))
job_log = ci_job(f"{CI}-first")