Watch
0
0
Fork
You've already forked hyperhive
0

the log and metrics stores ask every request for a credential the gateway supplies

Each store runs with -httpAuth.* and a credential from the secret store, published to the namespace as a Secret by the host. The gateway's locations send it after auth_request has passed, and the collector's scrape and push take the same one, so a process on the node that bypasses the gateway is refused.
This commit is contained in:
atlas 2026-11-27 17:24:08 +01:00 • committed by maia
commit f54aae7927

View file

@ -512,6 +512,7 @@ pkgs.testers.runNixOSTest {
serviceConfig = {
RuntimeDirectory = "logs-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;
};
@ -620,6 +621,13 @@ pkgs.testers.runNixOSTest {
METRICS_AUTH = "swarm-metrics-auth"
VM_DIR = "${vmDir}"
METRICS_GATEWAY = "http://${vmGateway}"
# The only Secrets the cluster holds: the two the host publishes for the
# stores' passwords.
STORE_SECRETS = {f"secret/{VL}-credentials", f"secret/{VM}-credentials"}
def other_secrets() -> set[str]:
names = machine.succeed(f"kubectl -n {NS} get secrets -o name || true").split()
return set(names) - STORE_SECRETS
SELECTOR = f"--selector app.kubernetes.io/name={SERVICE}"
@ -736,9 +744,13 @@ pkgs.testers.runNixOSTest {
"swarm-bao-review-classifier-policy",
"swarm-bao-claude-login-policy",
"swarm-bao-logs-auth-policy",
"swarm-bao-store-auth-policy",
"swarm-bao-k8s-jwt-policy",
]:
settle(f'[ "$(systemctl is-active {unit}.service)" = active ]', 900, [f"{unit}.service"])
# The credential's unit retries until the store has its policy.
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/config'",
timeout=300,
@ -814,7 +826,7 @@ pkgs.testers.runNixOSTest {
data = json.loads(trust)["data"]
assert data["trust-bundle.pem"] == machine.succeed("cat ${tlsDir}/trust-bundle.pem"), data
assert data["bao-server-ca.pem"] == machine.succeed("cat /var/lib/swarm-bao-pki/ca.pem"), data
assert machine.succeed(f"kubectl -n {NS} get secrets -o name || true").strip() == ""
assert other_secrets() == set(), other_secrets()
with subtest("a changed CA file is published again with no manual step"):
# `swarm-services-cert` rewrites the trust bundle once, when the store first
@ -945,6 +957,10 @@ pkgs.testers.runNixOSTest {
machine.succeed("systemctl cat hyperhive-k8s-ca-trust.service")
for name in (VL, LOGS_AUTH):
machine.succeed(f"test -L {MANIFESTS}/{name}.yaml")
# The pod waits for the Secret the unit publishes; the gateway reads its
# include file as it reloads.
settle('[ "$(systemctl is-active swarm-bao-store-auth.service)" = active ]', 900, ["swarm-bao-store-auth.service"])
machine.succeed("systemctl reload logs-gateway")
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
@ -1042,6 +1058,89 @@ pkgs.testers.runNixOSTest {
raise AssertionError((status, body))
assert vl_query("0" * 64, "switch")[0] == 401
STORE_AUTH_DIR = "/var/lib/swarm-store-auth"
STORE_PASSWORD = f"{STORE_AUTH_DIR}/victorialogs.password"
STORE_CONF = f"{STORE_AUTH_DIR}/victorialogs.conf"
def store_direct(path: str, *args: str, credential: bool = True) -> tuple[int, str]:
"""One request from the node to the store's pod address, past the gateway."""
vl_ip = kube(machine, f"get pod {vl_pod} -o jsonpath='{{.status.podIP}}'").strip()
auth = f'--user "swarm-store:$(cat {STORE_PASSWORD})" ' if credential else ""
_, out = machine.execute(f"curl -sS --max-time 20 -w '\\n%{{http_code}}' {auth}{' '.join(args)} 'http://{vl_ip}:9428{path}'")
body, _, code = out.rpartition("\n")
return int(code or 0), body
with subtest("the log store refuses every route without its credential from the node itself, past the gateway, and takes the credential the host keeps in the secret store"):
stored = as_root("bao kv get -mount=secret -field=value swarm/services/victorialogs/store-auth").strip()
assert len(stored) == 64, "the unit stores 64 hex digits"
# The three ends agree: the secret store's value, the file the unit
# keeps for the Secret, and the Secret itself. The files are root's
# and nobody else's.
assert machine.succeed(f"cat {STORE_PASSWORD}").strip() == stored
secret = machine.succeed(f"kubectl -n {NS} get secret swarm-victorialogs-credentials -o jsonpath='{{.data.store-auth}}' | base64 -d").strip()
assert secret == stored
assert machine.succeed(f"stat -c '%a %U %G' {STORE_PASSWORD} {STORE_CONF} {STORE_AUTH_DIR}").split("\n")[:3] == ["600 root root", "600 root root", "700 root root"]
assert stored not in machine.succeed(f"cat {MANIFESTS}/{VL}.yaml"), "the manifest holds no credential"
# Insert, select, a delete route, the admin routes, the store's own
# metrics and the UI answer 401 with no credential and with a caller's
# bearer, which is all a node process without the credential has.
refused = [
("POST", "/insert/opentelemetry/v1/logs"),
("POST", "/insert/jsonline"),
("POST", "/select/logsql/query"),
("GET", "/select/logsql/tail"),
("POST", "/delete/run_task"),
("POST", "/delete/active_tasks"),
("POST", "/internal/force_merge"),
("POST", "/internal/partition/list"),
("GET", "/metrics"),
("GET", "/flags"),
("GET", "/select/vmui/"),
("GET", "/"),
]
for method, path in refused:
for label, args in (("no credential", ()), ("a caller's bearer", (f"-H 'Authorization: Bearer {AGENT_TOKEN}'",))):
status, body = store_direct(path, f"-X {method}", *args, credential=False)
assert status == 401, (method, path, label, status, body[:200])
# The same routes with the credential are answered by the store: its
# select and metrics routes answer 200, the insert accepts a record and
# the delete route is reached (the store runs without `-delete.enable`,
# so it says so) instead of being refused with 401.
status, body = store_direct("/select/logsql/query", "-X POST --data-urlencode 'query=switch'")
assert status == 200 and "written before the switch" in body, (status, body[:200])
status, body = store_direct("/metrics")
assert status == 200 and "vl_" in body, (status, body[:200])
status, body = store_direct("/insert/jsonline?_stream_fields=app", "-X POST --data-binary '{\"_msg\":\"written to the store directly\",\"app\":\"vm-test\"}'")
assert status == 200, (status, body[:200])
status, body = store_direct("/delete/run_task", "-X POST")
assert status != 401 and "disabled" in body, (status, body[:200])
# What stays open: the probes' route.
assert store_direct("/health", credential=False)[0] == 200
# A wrong password is refused like none.
vl_ip = kube(machine, f"get pod {vl_pod} -o jsonpath='{{.status.podIP}}'").strip()
status = machine.execute(f"curl -sS -o /dev/null -w '%{{http_code}}' --user swarm-store:{'0' * 64} -X POST --data-urlencode 'query=switch' http://{vl_ip}:9428/select/logsql/query")[1]
assert status.strip() == "401", status
with subtest("the gateway sends the store's credential in place of the caller's bearer, and a gateway without it gets 401 from the store"):
# The bearer cases above went through the gateway with the credential in
# place. With the include file emptied, the caller's own bearer reaches
# the store, which refuses it, although the responders still grant it.
saved = machine.succeed(f"cat {STORE_CONF}")
assert "proxy_set_header Authorization" in saved
machine.succeed(f": > {STORE_CONF} && systemctl reload logs-gateway")
machine.wait_until_succeeds("systemctl is-active logs-gateway", timeout=30)
for _ in range(10):
status, body = vl_query(AGENT_TOKEN, "switch")
if status == 401:
break
time.sleep(1)
assert status == 401, (status, body[:200])
# The unit writes the file again, and the same request is granted: the
# control that the 401 is the missing credential.
machine.succeed("systemctl restart swarm-bao-store-auth.service && systemctl reload logs-gateway")
assert machine.succeed(f"cat {STORE_CONF}") == saved
wait_for_record(AGENT_TOKEN, "switch", "written before the switch")
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
@ -1311,8 +1410,8 @@ pkgs.testers.runNixOSTest {
import base64
import struct
# The store serves these on the listener its queries use and
# authenticates none of them; only the locations the module names reach it.
# The store serves these on the listener its queries use; only the
# locations the module names reach it.
for path in ("/api/v1/admin/tsdb/delete_series", "/api/v1/import/prometheus"):
metrics_expect(path, vm_request(path, GRAFANA_BEARER, "-X POST --data-binary 'x 1'")[0], 403)
metrics_expect("the store's export route, as the control for the refusals above", vm_export(GRAFANA_BEARER, "written_before_the_switch")[0], 200)
@ -1347,6 +1446,85 @@ pkgs.testers.runNixOSTest {
wait_for_series(AGENT_TOKEN, "written_before_the_switch")
wait_for_series(AGENT_TOKEN, "written_through_the_gateway")
VM_PASSWORD = f"{STORE_AUTH_DIR}/victoriametrics.password"
VM_CONF = f"{STORE_AUTH_DIR}/victoriametrics.conf"
def vm_direct(path: str, *args: str, credential: bool = True) -> tuple[int, str]:
"""One request from the node to the metrics store's pod address, past the gateway."""
vm_ip = kube(machine, f"get pod {vm_pod} -o jsonpath='{{.status.podIP}}'").strip()
auth = f'--user "swarm-store:$(cat {VM_PASSWORD})" ' if credential else ""
_, out = machine.execute(f"curl -sS --max-time 20 -w '\\n%{{http_code}}' {auth}{' '.join(args)} 'http://{vm_ip}:8428{path}'")
body, _, code = out.rpartition("\n")
return int(code or 0), body
with subtest("the metrics store refuses every route without its credential from the node itself, past the gateway, and takes the credential the host keeps in the secret store"):
stored = as_root("bao kv get -mount=secret -field=value swarm/services/victoriametrics/store-auth").strip()
assert len(stored) == 64, "the unit stores 64 hex digits"
# Each store has a credential of its own.
assert stored != as_root("bao kv get -mount=secret -field=value swarm/services/victorialogs/store-auth").strip()
assert machine.succeed(f"cat {VM_PASSWORD}").strip() == stored
secret = machine.succeed(f"kubectl -n {NS} get secret swarm-victoriametrics-credentials -o jsonpath='{{.data.store-auth}}' | base64 -d").strip()
assert secret == stored
assert machine.succeed(f"stat -c '%a %U %G' {VM_PASSWORD} {VM_CONF}").split("\n")[:2] == ["600 root root", "600 root root"]
assert stored not in machine.succeed(f"cat {MANIFESTS}/{VM}.yaml"), "the manifest holds no credential"
# Writes, imports, queries, exports, the routes that delete and
# snapshot, the config and reload routes, the store's own metrics and
# the UI answer 401 with no credential and with a caller's bearer.
refused = [
("POST", "/api/v1/write"),
("POST", "/api/v1/import"),
("POST", "/api/v1/import/prometheus"),
("POST", "/opentelemetry/api/v1/push"),
("POST", "/influx/write"),
("GET", "/api/v1/query?query=up"),
("GET", "/api/v1/export?match[]={__name__!=\"\"}"),
("POST", "/api/v1/admin/tsdb/delete_series?match[]={__name__!=\"\"}"),
("POST", "/api/v1/admin/tsdb/snapshot"),
("GET", "/snapshot/create"),
("POST", "/internal/force_merge"),
("POST", "/internal/resetRollupResultCache"),
("GET", "/config"),
("GET", "/-/reload"),
("GET", "/metrics"),
("GET", "/flags"),
("GET", "/vmui/"),
("GET", "/"),
]
for method, path in refused:
for label, args in (("no credential", ()), ("a caller's bearer", (f"-H 'Authorization: Bearer {AGENT_TOKEN}'",))):
status, body = vm_direct(path, f"-g -X {method}", *args, credential=False)
assert status == 401, (method, path, label, status, body[:200])
# With the credential the store answers: a query and an export read the
# sample written before the switch, the store's metrics come back, and
# a delete that matches nothing is accepted (204) instead of refused.
status, body = vm_direct("/api/v1/export", "-g --data-urlencode 'match[]={__name__=\"written_before_the_switch\"}'")
assert status == 200 and "written_before_the_switch" in body, (status, body[:200])
status, body = vm_direct("/api/v1/query?query=vm_app_version")
assert status == 200 and "success" in body, (status, body[:200])
status, body = vm_direct("/metrics")
assert status == 200 and "vm_" in body, (status, body[:200])
status, body = vm_direct("/api/v1/admin/tsdb/delete_series", "-g -X POST --data-urlencode 'match[]={__name__=\"no_such_series_in_this_store\"}'")
assert status == 204, (status, body[:200])
assert vm_direct("/health", credential=False)[0] == 200
vm_ip = kube(machine, f"get pod {vm_pod} -o jsonpath='{{.status.podIP}}'").strip()
status = machine.execute(f"curl -sS -o /dev/null -w '%{{http_code}}' --user swarm-store:{'0' * 64} 'http://{vm_ip}:8428/api/v1/query?query=up'")[1]
assert status.strip() == "401", status
with subtest("the gateway sends the metrics store's credential in place of the caller's bearer, and a gateway without it gets 401 from the store"):
saved = machine.succeed(f"cat {VM_CONF}")
assert "proxy_set_header Authorization" in saved and saved != machine.succeed(f"cat {STORE_CONF}")
machine.succeed(f": > {VM_CONF} && systemctl reload logs-gateway")
machine.wait_until_succeeds("systemctl is-active logs-gateway", timeout=30)
for _ in range(10):
status, body = vm_export(AGENT_TOKEN, "written_before_the_switch")
if status == 401:
break
time.sleep(1)
assert status == 401, (status, body[:200])
machine.succeed("systemctl restart swarm-bao-store-auth.service && systemctl reload logs-gateway")
assert machine.succeed(f"cat {VM_CONF}") == saved
wait_for_series(AGENT_TOKEN, "written_before_the_switch")
with subtest("only the node reaches the metrics store's pods, and the responders' pod reaches the store's pod listener and no other port of the host"):
vm_ip = kube(machine, f"get pod {vm_pod} -o jsonpath='{{.status.podIP}}'").strip()
metrics_auth_ip = kube(machine, f"get pod {metrics_auth_pod} -o jsonpath='{{.status.podIP}}'").strip()
@ -1403,7 +1581,7 @@ pkgs.testers.runNixOSTest {
assert [src["configMap"]["name"] for src in sources] == ["hyperhive-ca-trust"], sources
assert [(i["key"], i["path"]) for i in sources[0]["configMap"]["items"]] == [("bao-server-ca.pem", "bao-ca.pem")], sources
assert not any("secret" in v or any("secret" in src for src in v.get("projected", {}).get("sources", [])) for v in spec["volumes"]), spec["volumes"]
assert machine.succeed(f"kubectl -n {NS} get secrets -o name || true").strip() == ""
assert other_secrets() == set(), other_secrets()
# The control that the lookup finds the variable: the router's pod sets
# it, and the poller's does not.
router_env = {e["name"]: e.get("value") for e in json.loads(kube(machine, f"get pod {router} -o json"))["spec"]["containers"][0]["env"]}