run grafana as a pod in the cluster
The Deployment swarm-grafana replaces the swarm-grafana container: one replica on a static local volume that is the container's data directory, an init container that fetches the OIDC client secret and creates the administrator password, the datasources' bearer and the encryption key in the secret store, and a sidecar that keeps the controller's Viewer token. The datasources reach the stores through the gateway with that bearer, and Grafana's /metrics asks for the stores' kind of credential, which the vhost sends. The five host units, the journal forwarder, its client glue and the unix-socket directory go with the container.
This commit is contained in:
parent
26ef09b0d7
commit
9f62e71dae
1 changed files with 1938 additions and 1953 deletions
|
|
@ -1,7 +1,7 @@
|
|||
# `vmTests.<system>.k8s-services`: the notification router, the speech-to-text
|
||||
# service, the CI run poller, the review classifier and the claude login minter
|
||||
# run as pods in the host's cluster, against the real secret store and a real
|
||||
# queue. The script asserts that:
|
||||
# service, the CI run poller, the review classifier, the claude login minter,
|
||||
# the log and metrics stores and Grafana run as pods in the host's cluster,
|
||||
# against the real secret store and a real queue. The script asserts that:
|
||||
#
|
||||
# - each runs once, as a pod or CronJob: the host has no container, unit, timer or
|
||||
# prune unit for it;
|
||||
|
|
@ -9,22 +9,22 @@
|
|||
# token, read its client secret and minted a token with it. The router
|
||||
# routes an event and a deleted pod exits 0 within its grace period; the
|
||||
# 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 and metrics stores run as pods on the directories their old
|
||||
# containers kept, which units of this test filled as other users: each pod
|
||||
# reads that record and writes a new one, the gateway's own locations
|
||||
# (rendered by the modules) reach the stores and the responders, bearers are
|
||||
# granted or refused as the store says, the metrics gateway refuses the
|
||||
# store's write and admin routes, and no other pod reaches either store;
|
||||
# in a user namespace, and its NetworkPolicy lets a queue request in and
|
||||
# only DNS and four host ports out;
|
||||
# - the stores and Grafana run on the directories their old containers kept,
|
||||
# which units of this test filled as other users: the gateway's own
|
||||
# locations (rendered by the modules) reach the stores and the responders,
|
||||
# bearers are granted or refused as the store says, and no other pod
|
||||
# reaches a store or Grafana's port 3000;
|
||||
# - Grafana's database made under the default administrator takes the stored
|
||||
# password and survives a pod delete, every route refuses a caller with no
|
||||
# session, `/metrics` takes the listener credential the gateway adds and
|
||||
# nothing else, a datasource query reaches the metrics store through the
|
||||
# gateway, and the controller's Viewer token is in the secret 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
|
||||
# gate;
|
||||
# its own route of the swarm collector, and keeps its cursor in a volume;
|
||||
# - the minter's jwt token writes an agent's credentials and the classifier's
|
||||
# cannot; the daemons' pods have a read-only root, and `claude` writes its
|
||||
# config under `HOME` in the /tmp volume only, as the real login step does.
|
||||
#
|
||||
# cannot; the daemons' pods have a read-only root.
|
||||
# The queue is a plain nats-server with TLS, and one stub is the token endpoint,
|
||||
# the forge and the swarm collector, which records what it is given. The
|
||||
# speech-to-text model is a placeholder; the hive's CA and leaves come at boot.
|
||||
|
|
@ -87,6 +87,15 @@ let
|
|||
legacyVmUser = "legacy-victoriametrics";
|
||||
legacyVmPort = 19429;
|
||||
|
||||
# Grafana, as the module names it. The gateway answers its name over TLS for
|
||||
# the pods, on a loopback port the SNI stream below leads the bridge's 443 to.
|
||||
grafanaDir = "/var/lib/nixos-containers/swarm-grafana/var/lib/grafana";
|
||||
grafanaGateway = "127.0.0.1:18083";
|
||||
gatewayTls = "127.0.0.1:18443";
|
||||
stubPort = 1443;
|
||||
legacyGrafanaUser = "legacy-grafana";
|
||||
legacyGrafanaPort = 19430;
|
||||
|
||||
# One nginx with the log and metrics stores' locations as the modules render
|
||||
# them: the Services they dial, the responders they check a bearer with and
|
||||
# the variables between. The identity provider's checks are stand-ins that
|
||||
|
|
@ -118,6 +127,8 @@ let
|
|||
# Every location of the vhost but the two that dial the identity
|
||||
# provider, so a location the module adds is served here too.
|
||||
metrics = cfg.services.nginx.virtualHosts."metrics.t.local".locations;
|
||||
grafana = cfg.services.nginx.virtualHosts."grafana.t.local".locations;
|
||||
grafanaServed = lib.filter (n: n != "= /__grafana_metrics_authz") (lib.attrNames grafana);
|
||||
metricsServed = lib.filter (
|
||||
n:
|
||||
!(lib.elem n [
|
||||
|
|
@ -132,19 +143,32 @@ let
|
|||
events {}
|
||||
http {
|
||||
access_log off;
|
||||
ssl_certificate ${pkiDir}/svc.pem;
|
||||
ssl_certificate_key ${pkiDir}/svc-key.pem;
|
||||
${cfg.services.nginx.appendHttpConfig}
|
||||
server {
|
||||
listen ${vlGateway};
|
||||
listen ${gatewayTls} ssl;
|
||||
server_name logs.t.local;
|
||||
location = /__swarm_logs_ingest_authz { internal; return 200; }
|
||||
location = /__hive_authelia { internal; return 200; }
|
||||
${lib.concatMapStrings (block logs) logsServed}
|
||||
}
|
||||
server {
|
||||
listen ${vmGateway};
|
||||
listen ${gatewayTls} ssl;
|
||||
server_name metrics.t.local;
|
||||
location = /__metrics_ingest_authz { internal; return 200; }
|
||||
location = /__metrics_authelia { internal; return 200; }
|
||||
${lib.concatMapStrings (block metrics) metricsServed}
|
||||
}
|
||||
server {
|
||||
listen ${grafanaGateway};
|
||||
listen ${gatewayTls} ssl;
|
||||
server_name grafana.t.local;
|
||||
location = /__grafana_metrics_authz { internal; return 200; }
|
||||
${lib.concatMapStrings (block grafana) grafanaServed}
|
||||
}
|
||||
}
|
||||
'';
|
||||
requestLog = "/var/log/stub-requests.log";
|
||||
|
|
@ -227,7 +251,7 @@ let
|
|||
self.send_error(404)
|
||||
|
||||
|
||||
server = http.server.ThreadingHTTPServer(("${bridgeIp}", 443), Handler)
|
||||
server = http.server.ThreadingHTTPServer(("127.0.0.1", ${toString stubPort}), Handler)
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain("${pkiDir}/svc.pem", "${pkiDir}/svc-key.pem")
|
||||
server.socket = context.wrap_socket(server.socket, server_side=True)
|
||||
|
|
@ -275,6 +299,7 @@ pkgs.testers.runNixOSTest {
|
|||
deploy.ci-metrics.enable = true;
|
||||
deploy.victorialogs.enable = true;
|
||||
deploy.victoriametrics.enable = true;
|
||||
deploy.grafana.enable = true;
|
||||
deploy.hive-controller.hiveName = "h1";
|
||||
swarm.domain = "t.local";
|
||||
swarm.forge.domain = forgeName;
|
||||
|
|
@ -327,6 +352,19 @@ pkgs.testers.runNixOSTest {
|
|||
events {}
|
||||
stream {
|
||||
${config.services.nginx.streamConfig}
|
||||
# The names the cluster's pods dial on 443 go to the gateway, the
|
||||
# rest (identity provider, forge, collector) to the stand-in.
|
||||
map $ssl_preread_server_name $swarm_443_backend {
|
||||
metrics.t.local ${gatewayTls};
|
||||
logs.t.local ${gatewayTls};
|
||||
grafana.t.local ${gatewayTls};
|
||||
default 127.0.0.1:${toString stubPort};
|
||||
}
|
||||
server {
|
||||
listen ${bridgeIp}:443;
|
||||
ssl_preread on;
|
||||
proxy_pass $swarm_443_backend;
|
||||
}
|
||||
}
|
||||
'';
|
||||
in
|
||||
|
|
@ -353,7 +391,7 @@ pkgs.testers.runNixOSTest {
|
|||
-subj "/CN=test-ca" -days 3650 \
|
||||
-addext basicConstraints=critical,CA:TRUE -addext keyUsage=critical,keyCertSign
|
||||
openssl req -newkey rsa:2048 -nodes -keyout svc-key.pem -out svc.csr -subj "/CN=${natsName}"
|
||||
printf 'subjectAltName=DNS:${natsName},DNS:${authName},DNS:${forgeName},DNS:${otelName}\n' > svc.ext
|
||||
printf 'subjectAltName=DNS:${natsName},DNS:${authName},DNS:${forgeName},DNS:${otelName},DNS:metrics.t.local,DNS:logs.t.local,DNS:grafana.t.local\n' > svc.ext
|
||||
openssl x509 -req -in svc.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial \
|
||||
-days 3650 -extfile svc.ext -out svc.pem
|
||||
chmod 0644 ca.pem svc.pem svc-key.pem
|
||||
|
|
@ -512,6 +550,79 @@ pkgs.testers.runNixOSTest {
|
|||
'';
|
||||
};
|
||||
|
||||
# What the dashboard's container left on the host: its data directory
|
||||
# with a database created under Grafana's default administrator, holding
|
||||
# one annotation. The pinned binary writes it as a user of its own.
|
||||
users.users.${legacyGrafanaUser} = {
|
||||
isSystemUser = true;
|
||||
group = legacyGrafanaUser;
|
||||
};
|
||||
users.groups.${legacyGrafanaUser} = { };
|
||||
systemd.services.grafana-legacy = {
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
before = [ "k3s.service" ];
|
||||
path = [
|
||||
pkgs.curl
|
||||
pkgs.coreutils
|
||||
pkgs.findutils
|
||||
pkgs.gnugrep
|
||||
];
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
RemainAfterExit = true;
|
||||
User = legacyGrafanaUser;
|
||||
# k3s waits for this unit, so an annotation that never shows must
|
||||
# fail it and not hold the boot.
|
||||
TimeoutStartSec = 180;
|
||||
UMask = "0007";
|
||||
ExecStartPre = "+${pkgs.writeShellScript "grafana-legacy-dir" ''
|
||||
mkdir -p ${grafanaDir}
|
||||
chown ${legacyGrafanaUser}:${legacyGrafanaUser} ${grafanaDir}
|
||||
chmod 0700 ${grafanaDir}
|
||||
''}";
|
||||
RuntimeDirectory = "grafana-legacy";
|
||||
};
|
||||
environment = {
|
||||
GF_PATHS_DATA = grafanaDir;
|
||||
GF_PATHS_LOGS = "/run/grafana-legacy";
|
||||
GF_PATHS_PLUGINS = "/run/grafana-legacy/plugins";
|
||||
GF_PATHS_PROVISIONING = "/run/grafana-legacy/provisioning";
|
||||
GF_SERVER_HTTP_ADDR = "127.0.0.1";
|
||||
GF_SERVER_HTTP_PORT = toString legacyGrafanaPort;
|
||||
GF_ANALYTICS_REPORTING_ENABLED = "false";
|
||||
GF_ANALYTICS_CHECK_FOR_UPDATES = "false";
|
||||
GF_ANALYTICS_CHECK_FOR_PLUGIN_UPDATES = "false";
|
||||
GF_PLUGINS_PREINSTALL_DISABLED = "true";
|
||||
};
|
||||
script = ''
|
||||
store=http://127.0.0.1:${toString legacyGrafanaPort}
|
||||
pkg=${config.services.hyperhive.deploy.grafana.package}
|
||||
${lib.getExe' config.services.hyperhive.deploy.grafana.package "grafana"} server \
|
||||
--homepath $pkg/share/grafana &
|
||||
pid=$!
|
||||
until curl -sf $store/api/health; do sleep 1; done
|
||||
# The default administrator of a database made without the setting.
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' -u admin:admin -H 'Content-Type: application/json' \
|
||||
-d '{"text":"written before the switch","tags":["legacy"]}' $store/api/annotations)
|
||||
found=
|
||||
for _ in $(seq 60); do
|
||||
if curl -s -u admin:admin "$store/api/annotations?tags=legacy" | grep -q 'written before the switch'; then
|
||||
found=1
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
if [ -z "$found" ]; then
|
||||
echo "the seeded annotation is not found; the post replied $code; the store holds:"
|
||||
curl -s -u admin:admin "$store/api/annotations"
|
||||
exit 1
|
||||
fi
|
||||
kill -TERM "$pid"
|
||||
wait "$pid" || true
|
||||
test -s ${grafanaDir}/grafana.db
|
||||
'';
|
||||
};
|
||||
|
||||
# The log and metrics stores' locations, from the active configuration's own text.
|
||||
systemd.services.logs-gateway = {
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
|
|
@ -630,6 +741,9 @@ pkgs.testers.runNixOSTest {
|
|||
METRICS_AUTH = "swarm-metrics-auth"
|
||||
VM_DIR = "${vmDir}"
|
||||
METRICS_GATEWAY = "http://${vmGateway}"
|
||||
GRAFANA = "swarm-grafana"
|
||||
GRAFANA_DIR = "${grafanaDir}"
|
||||
GRAFANA_GATEWAY = "http://${grafanaGateway}"
|
||||
# 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"}
|
||||
|
|
@ -765,6 +879,7 @@ pkgs.testers.runNixOSTest {
|
|||
"swarm-bao-claude-login-policy",
|
||||
"swarm-bao-logs-auth-policy",
|
||||
"swarm-bao-store-auth-policy",
|
||||
"swarm-bao-grafana-oidc-policy",
|
||||
"swarm-bao-k8s-jwt-policy",
|
||||
]:
|
||||
settle(f'[ "$(systemctl is-active {unit}.service)" = active ]', 900, [f"{unit}.service"])
|
||||
|
|
@ -805,6 +920,10 @@ pkgs.testers.runNixOSTest {
|
|||
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}")
|
||||
# The dashboard's OIDC client secret, which the identity provider's mint
|
||||
# stores in production; the pod's init container reads it.
|
||||
GRAFANA_OIDC = machine.succeed("openssl rand -hex 16").strip()
|
||||
as_root(f"bao kv put -mount=secret swarm/services/swarm-grafana/oidc/client value={GRAFANA_OIDC}")
|
||||
|
||||
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")
|
||||
|
|
@ -1599,6 +1718,221 @@ pkgs.testers.runNixOSTest {
|
|||
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 dashboard runs only as a pod: the host has no container, unit, timer or socket directory for it"):
|
||||
machine.fail("test -e /etc/nixos-containers/swarm-grafana.conf")
|
||||
assert host_state("container@swarm-grafana.service") == "inactive"
|
||||
for unit in (
|
||||
"swarm-bao-grafana-oidc",
|
||||
"swarm-bao-grafana-admin",
|
||||
"swarm-bao-grafana-metrics-bearer",
|
||||
"swarm-bao-grafana-secret-key",
|
||||
"swarm-bao-grafana-controller-token",
|
||||
"swarm-grafana-forwarder-oidc",
|
||||
):
|
||||
machine.fail(f"systemctl cat {unit}.service")
|
||||
for timer in ("swarm-bao-grafana-oidc", "swarm-bao-grafana-controller-token", "swarm-grafana-forwarder-oidc"):
|
||||
machine.fail(f"systemctl cat {timer}.timer")
|
||||
machine.fail("test -e /run/swarm-grafana")
|
||||
machine.fail("test -e /run/swarm-grafana-secrets")
|
||||
# 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")
|
||||
machine.succeed(f"test -L {MANIFESTS}/{GRAFANA}.yaml")
|
||||
assert machine.execute("machinectl list --no-legend | grep -q swarm-grafana")[0] != 0
|
||||
grafana_pod = wait_pod_ready(GRAFANA, timeout=900)
|
||||
|
||||
with subtest("the dashboard's init container fetched its secrets, its sidecar runs, and the pod mounts no store's credential"):
|
||||
pod = json.loads(kube(machine, f"get pod {grafana_pod} -o json"))
|
||||
init = pod["status"]["initContainerStatuses"]
|
||||
assert [c["name"] for c in init] == ["fetch-secrets"] and init[0]["state"]["terminated"]["exitCode"] == 0, init
|
||||
running = {c["name"]: c for c in pod["status"]["containerStatuses"]}
|
||||
assert set(running) == {GRAFANA, "controller-token"}, running.keys()
|
||||
assert all(c["ready"] and "running" in c["state"] for c in running.values()), running
|
||||
# The pod mounts the one Secret of its own listener's credential and
|
||||
# none of the two stores', which it reaches through the gateway with
|
||||
# its bearer; the values it fetched are in no container's log.
|
||||
secrets = {v["secret"]["secretName"] for v in pod["spec"]["volumes"] if "secret" in v}
|
||||
assert secrets <= {"swarm-grafana-credentials"}, secrets
|
||||
stored = as_root("bao kv get -mount=secret -field=value swarm/services/grafana/store-auth").strip()
|
||||
for name in (GRAFANA, "controller-token"):
|
||||
logs = machine.succeed(f"kubectl -n {NS} logs {grafana_pod} -c {name} --tail=200 2>&1")
|
||||
assert stored not in logs and GRAFANA_BEARER not in logs and GRAFANA_OIDC not in logs, name
|
||||
|
||||
with subtest("the dashboard'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 {GRAFANA}-store -o json"))
|
||||
assert pv["spec"]["local"]["path"] == GRAFANA_DIR and pv["status"]["phase"] == "Bound", pv
|
||||
pvc = json.loads(kube(machine, f"get pvc {GRAFANA}-store -o json"))
|
||||
assert pvc["status"]["phase"] == "Bound" and pvc["spec"]["volumeName"] == pv["metadata"]["name"], pvc
|
||||
assert machine.succeed(f"stat -c %g {GRAFANA_DIR}").strip() == "65532"
|
||||
assert machine.succeed(f"find {GRAFANA_DIR} -name grafana.db -user ${legacyGrafanaUser} | head -1").strip() != ""
|
||||
status = json.loads(kube(machine, f"get pod {grafana_pod} -o json"))
|
||||
main = next(c for c in status["spec"]["containers"] if c["name"] == GRAFANA)
|
||||
assert main["startupProbe"]["failureThreshold"] == 30, main
|
||||
|
||||
def grafana_request(path: str, *args: str, gateway: bool = True) -> tuple[int, str]:
|
||||
"""One request to the dashboard: through the gateway's locations, or
|
||||
from the node to the pod's address past the gateway. The status and the
|
||||
body."""
|
||||
base = GRAFANA_GATEWAY if gateway else f"http://{grafana_ip}:3000"
|
||||
_, out = machine.execute(f"curl -sS --max-time 20 -w '\\n%{{http_code}}' {' '.join(args)} '{base}{path}'")
|
||||
body, _, code = out.rpartition("\n")
|
||||
return int(code or 0), body
|
||||
|
||||
def grafana_head(path: str, *args: str) -> tuple[str, str]:
|
||||
"""The status and the redirect target of one request through the gateway."""
|
||||
out = machine.succeed(f"curl -sS --max-time 20 -o /dev/null -w '%{{http_code}} %{{redirect_url}}' {' '.join(args)} '{GRAFANA_GATEWAY}{path}'")
|
||||
code, _, target = out.partition(" ")
|
||||
return code, target
|
||||
|
||||
grafana_ip = kube(machine, f"get pod {grafana_pod} -o jsonpath='{{.status.podIP}}'").strip()
|
||||
GRAFANA_ADMIN = as_root("bao kv get -mount=secret -field=value swarm/services/swarm-grafana/admin/password").strip()
|
||||
|
||||
with subtest("the dashboard refuses every route without an OIDC session and sends the browser to the identity provider"):
|
||||
# The page and the API refuse a caller with no session.
|
||||
code, target = grafana_head("/")
|
||||
assert code == "302" and target.endswith("/login"), (code, target)
|
||||
for path in ("/api/search", "/api/datasources", "/api/user", "/api/datasources/proxy/uid/swarm-victoriametrics/api/v1/query?query=up"):
|
||||
status, body = grafana_request(path)
|
||||
assert status == 401, (path, status, body[:200])
|
||||
# The login route sends the browser to the identity provider's authorization endpoint with the client the module registers.
|
||||
code, target = grafana_head("/login/generic_oauth")
|
||||
assert code == "302" and "/api/oidc/authorization" in target and "client_id=swarm-grafana" in target, (code, target)
|
||||
# Health is the one unauthenticated route, and says nothing but the version and the database.
|
||||
status, body = grafana_request("/api/health")
|
||||
assert status == 200 and json.loads(body)["database"] == "ok", (status, body)
|
||||
# Anonymous access is off and a made-up bearer is no session.
|
||||
status, _ = grafana_request("/api/search", "-H 'Authorization: Bearer glsa_made_up'")
|
||||
assert status == 401, status
|
||||
|
||||
with subtest("the stored administrator password is applied to the database written before the switch, and the default one is refused"):
|
||||
status, body = grafana_request("/api/user", f"-u admin:{GRAFANA_ADMIN}")
|
||||
assert status == 200 and json.loads(body)["login"] == "admin", (status, body[:200])
|
||||
for wrong in ("admin", "x" * 24):
|
||||
status, body = grafana_request("/api/user", f"-u admin:{wrong}")
|
||||
assert status == 401, (wrong, status, body[:200])
|
||||
# The annotation the old container's database held is there.
|
||||
status, body = grafana_request("/api/annotations?tags=legacy", f"-u admin:{GRAFANA_ADMIN}")
|
||||
assert status == 200 and "written before the switch" in body, (status, body[:300])
|
||||
|
||||
with subtest("the dashboard reads the metrics store through the gateway with its own bearer, and its log datasource is provisioned"):
|
||||
deadline = time.monotonic() + 300
|
||||
while True:
|
||||
status, body = grafana_request(
|
||||
"/api/datasources/proxy/uid/swarm-victoriametrics/api/v1/export",
|
||||
f"-u admin:{GRAFANA_ADMIN}",
|
||||
"-g --data-urlencode 'match[]=written_before_the_switch' -G",
|
||||
)
|
||||
if status == 200 and "written_before_the_switch" in body:
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
print(machine.execute(f"kubectl -n {NS} logs {grafana_pod} -c {GRAFANA} --tail=100 2>&1")[1])
|
||||
metrics_diagnostics(GRAFANA_BEARER)
|
||||
raise AssertionError((status, body[:300]))
|
||||
time.sleep(3)
|
||||
status, body = grafana_request("/api/datasources", f"-u admin:{GRAFANA_ADMIN}")
|
||||
uids = {d["uid"] for d in json.loads(body)}
|
||||
assert status == 200 and uids == {"swarm-victoriametrics", "swarm-victorialogs"}, (status, uids)
|
||||
|
||||
GRAFANA_CONF = f"{STORE_AUTH_DIR}/grafana.conf"
|
||||
GRAFANA_PASSWORD = f"{STORE_AUTH_DIR}/grafana.password"
|
||||
|
||||
with subtest("Grafana's /metrics is refused without the listener credential past the gateway and answered with it, and the gateway puts the credential in place"):
|
||||
machine.succeed("systemctl restart swarm-bao-store-auth.service")
|
||||
store_credential_published()
|
||||
machine.succeed("systemctl reload logs-gateway")
|
||||
stored = as_root("bao kv get -mount=secret -field=value swarm/services/grafana/store-auth").strip()
|
||||
assert len(stored) == 64, "the unit stores 64 hex digits"
|
||||
for other in ("victoriametrics", "victorialogs"):
|
||||
assert stored != as_root(f"bao kv get -mount=secret -field=value swarm/services/{other}/store-auth").strip()
|
||||
assert machine.succeed(f"cat {GRAFANA_PASSWORD}").strip() == stored
|
||||
secret = machine.succeed(f"kubectl -n {NS} get secret swarm-grafana-credentials -o jsonpath='{{.data.store-auth}}' | base64 -d").strip()
|
||||
assert secret == stored
|
||||
assert stored not in machine.succeed(f"cat {MANIFESTS}/{GRAFANA}.yaml"), "the manifest holds no credential"
|
||||
# With no credential, and with a caller's bearer or the administrator's login, the pod answers 401.
|
||||
for label, args in (
|
||||
("no credential", ()),
|
||||
("a caller's bearer", (f"-H 'Authorization: Bearer {AGENT_TOKEN}'",)),
|
||||
("the administrator's login", (f"-u admin:{GRAFANA_ADMIN}",)),
|
||||
("a wrong password", (f"-u swarm-store:{'0' * 64}",)),
|
||||
):
|
||||
status, body = grafana_request("/metrics", *args, gateway=False)
|
||||
assert status == 401, (label, status, body[:200])
|
||||
status, body = grafana_request("/metrics", f'--user "swarm-store:$(cat {GRAFANA_PASSWORD})"', gateway=False)
|
||||
assert status == 200 and "grafana_" in body, (status, body[:200])
|
||||
# Through the gateway the same request needs no credential of the caller's.
|
||||
status, body = grafana_request("/metrics")
|
||||
assert status == 200 and "grafana_" in body, (status, body[:200])
|
||||
# A gateway without the credential gets 401 from the pod.
|
||||
saved = machine.succeed(f"cat {GRAFANA_CONF}")
|
||||
assert "proxy_set_header Authorization" in saved
|
||||
machine.succeed(f": > {GRAFANA_CONF} && systemctl reload logs-gateway")
|
||||
machine.wait_until_succeeds("systemctl is-active logs-gateway", timeout=30)
|
||||
for _ in range(10):
|
||||
status, body = grafana_request("/metrics")
|
||||
if status == 401:
|
||||
break
|
||||
time.sleep(1)
|
||||
assert status == 401, (status, body[:200])
|
||||
machine.succeed("systemctl restart swarm-bao-store-auth.service")
|
||||
store_credential_published()
|
||||
machine.succeed("systemctl reload logs-gateway")
|
||||
assert machine.succeed(f"cat {GRAFANA_CONF}") == saved
|
||||
assert grafana_request("/metrics")[0] == 200
|
||||
# The health route and the health check of the kubelet stay open.
|
||||
assert grafana_request("/api/health", gateway=False)[0] == 200
|
||||
|
||||
with subtest("the controller's Viewer token is in the store and reads the alert rules and nothing it must not write"):
|
||||
read_token = f'BAO_TOKEN="$(jq -r .root_token {INIT})" bao kv get -mount=secret -field=value swarm/controller/swarm-controller/grafana/token 2>/dev/null'
|
||||
token = machine.execute(read_token)[1].strip()
|
||||
deadline = time.monotonic() + 180
|
||||
while not token:
|
||||
if time.monotonic() >= deadline:
|
||||
print(machine.execute(f"kubectl -n {NS} logs {grafana_pod} -c controller-token --tail=100 2>&1")[1])
|
||||
raise AssertionError("the sidecar stored no token")
|
||||
time.sleep(3)
|
||||
token = machine.execute(read_token)[1].strip()
|
||||
status, body = grafana_request("/api/prometheus/grafana/api/v1/alerts", f"-H 'Authorization: Bearer {token}'")
|
||||
assert status == 200, (status, body[:200])
|
||||
status, body = grafana_request("/api/user", f"-H 'Authorization: Bearer {token}'")
|
||||
assert status == 200 and json.loads(body)["login"].startswith("sa-"), (status, body[:200])
|
||||
status, body = grafana_request(
|
||||
"/api/annotations",
|
||||
f"-H 'Authorization: Bearer {token}' -H 'Content-Type: application/json' -X POST -d '{{\"text\":\"a viewer writes\"}}'",
|
||||
)
|
||||
assert status == 403, (status, body[:200])
|
||||
|
||||
with subtest("a deleted pod comes back with the annotation, the stored password and the same token"):
|
||||
kube(machine, f"delete pod {grafana_pod} --wait=true", timeout=120)
|
||||
grafana_pod = wait_pod_ready(GRAFANA, timeout=900)
|
||||
grafana_ip = kube(machine, f"get pod {grafana_pod} -o jsonpath='{{.status.podIP}}'").strip()
|
||||
deadline = time.monotonic() + 300
|
||||
while True:
|
||||
status, body = grafana_request("/api/annotations?tags=legacy", f"-u admin:{GRAFANA_ADMIN}")
|
||||
if status == 200 and "written before the switch" in body:
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
print(machine.execute(f"kubectl -n {NS} logs {grafana_pod} --all-containers --tail=100 2>&1")[1])
|
||||
raise AssertionError((status, body[:300]))
|
||||
time.sleep(3)
|
||||
status, body = grafana_request("/api/prometheus/grafana/api/v1/alerts", f"-H 'Authorization: Bearer {token}'")
|
||||
assert status == 200, (status, body[:200])
|
||||
assert as_root("bao kv get -mount=secret -field=value swarm/services/swarm-grafana/admin/password").strip() == GRAFANA_ADMIN
|
||||
|
||||
with subtest("only the node reaches the dashboard's port, and its pod reaches the secret store and the gateway and no other port of the host"):
|
||||
machine.succeed(f"curl -sf --max-time 5 http://{grafana_ip}:3000/api/health")
|
||||
machine.succeed(f"timeout 5 bash -c '</dev/tcp/{grafana_ip}/3000'")
|
||||
# The peer pod can dial out, which is the control that the dials below are refused by the policy.
|
||||
machine.succeed(dials(router_pid, "${bridgeIp}", 9999))
|
||||
for source, dial in sources(GRAFANA).items():
|
||||
machine.wait_until_fails(dial(grafana_ip, 3000), timeout=60)
|
||||
for _ in range(3):
|
||||
assert machine.execute(dial(grafana_ip, 3000))[0] != 0, source
|
||||
grafana_pid = pod_pid(GRAFANA)
|
||||
machine.succeed(dials(grafana_pid, "${bridgeIp}", ${toString podPort}))
|
||||
machine.succeed(dials(grafana_pid, "${bridgeIp}", 443))
|
||||
machine.wait_until_fails(dials(grafana_pid, "${bridgeIp}", 9999), timeout=60)
|
||||
status = json.loads(kube(machine, f"get pod {grafana_pod} -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")
|
||||
|
|
|
|||
Loading…
Reference in a new issue