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 9b12532fc1
12 changed files with 808 additions and 72 deletions

View file

@ -44,6 +44,12 @@ let
swarm-bao-nats-tls = deployCfg.nats.enable;
# ./swarm-ci-runner.nix
swarm-bao-ci-runner = deployCfg.ci-runner.enable;
# ./k8s/store-credentials.nix
swarm-bao-store-auth =
(deployCfg.victorialogs.enable || deployCfg.victoriametrics.enable)
&& deployCfg.k8s.enable
&& hyperhiveCfg.k8s.enable
&& havePair baoDeploy.storeAuthClientCertFile baoDeploy.storeAuthClientKeyFile;
};
# Readers that log in under another unit's principal: reader unit → the

View file

@ -130,6 +130,8 @@ in
atticClientKeyFile = lib.mkDefault "${pkiDir}/attic-key.pem";
archiveClientCertFile = lib.mkDefault "${pkiDir}/archive.pem";
archiveClientKeyFile = lib.mkDefault "${pkiDir}/archive-key.pem";
storeAuthClientCertFile = lib.mkDefault "${pkiDir}/store-auth.pem";
storeAuthClientKeyFile = lib.mkDefault "${pkiDir}/store-auth-key.pem";
forgePublisherClientCertFile = lib.mkDefault "${pkiDir}/forge-publisher.pem";
forgePublisherClientKeyFile = lib.mkDefault "${pkiDir}/forge-publisher-key.pem";
servicesIssuerClientCertFile = lib.mkDefault "${pkiDir}/services-issuer.pem";
@ -358,6 +360,13 @@ in
[ -s ${pkiDir}/archive.pem ] || ${signLeaf} ${pkiDir} archive \
${lib.escapeShellArg deployCfg.bao.archiveCommonName} "" clientAuth
# The unit that publishes the log store's and the metrics store's listener
# credentials. Minted here for the matrix-ctl leaf's reason: each store is a
# swarm singleton, so on a store host without the secret store this is the
# file an operator copies.
[ -s ${pkiDir}/store-auth.pem ] || ${signLeaf} ${pkiDir} store-auth \
${lib.escapeShellArg deployCfg.bao.storeAuthCommonName} "" clientAuth
# The forge's token publisher. Minted here for the matrix-ctl leaf's
# reason: the forge is a swarm singleton, so on a forge host without the
# store this is the file an operator copies.

View file

@ -27,6 +27,7 @@ in
./node.nix
./pod-logs.nix
./runtime.nix
./store-credentials.nix
];
options.services.hyperhive.k8s = {

View file

@ -718,7 +718,11 @@ let
);
};
execWords = splitExec name (toString sc.ExecStart);
# A systemd `%d` in an argument is the credential directory, as in the
# environment.
execWords = map (builtins.replaceStrings [ "%d" ] [ credDir ]) (
splitExec name (toString sc.ExecStart)
);
entrypoint = "${svc.package}/bin/${daemon}";
# The credentials that are public CA files come from the CA ConfigMap, the

View file

@ -0,0 +1,180 @@
# The listener credential of the Victoria stores the cluster runs: the unit that
# creates it in the swarm secret store when the store holds none, hands it to
# the gateway's nginx and publishes it to the cluster as the Secret the store's
# pod loads its password from. The store's flags and the locations that send it
# are in ../swarm-victorialogs.nix and ../swarm-victoriametrics.nix; ../lib/store-auth.nix names what they
# share. docs/4-implementation/k8s/runtime.md has the design.
{
pkgs,
lib,
config,
...
}:
let
hyperhiveCfg = config.services.hyperhive;
deployCfg = hyperhiveCfg.deploy;
k8sCfg = hyperhiveCfg.k8s;
node = deployCfg.k8s;
baoCfg = hyperhiveCfg.swarm.bao;
baoDeploy = deployCfg.bao;
storeAuth = import ../lib/store-auth.nix;
storeRetry = import ../lib/store-retry.nix { };
# The stores this host runs, by the name `store-auth.nix` takes.
stores =
lib.optional deployCfg.victorialogs.enable "victorialogs"
++ lib.optional deployCfg.victoriametrics.enable "victoriametrics";
haveIdentity =
baoDeploy.storeAuthClientCertFile != null && baoDeploy.storeAuthClientKeyFile != null;
# Where the store runs on this host, the first login waits for its container.
# No `wants`: a pull would start the container mid-switch on the old closure.
storeContainer = lib.optional baoDeploy.enable "container@${baoCfg.machine}.service";
kubeconfig = "/etc/rancher/k3s/k3s.yaml";
publish = store: ''
publish ${
lib.escapeShellArgs [
store
"secret/${storeAuth.leaf store}"
(storeAuth.passwordFile store)
(storeAuth.nginxFile store)
(storeAuth.secretName store)
]
}
'';
in
{
config = lib.mkIf (stores != [ ]) (
lib.mkMerge [
{
# The files exist before nginx first reads its configuration, because
# an `include` of a missing file is a fatal error there. `f` creates
# a file and never overwrites one, and an empty file sets no header:
# the store then refuses the request, which is the only thing a
# gateway without the credential can get from it.
systemd.tmpfiles.rules = [
"d ${storeAuth.dir} 0700 root root - -"
]
++ map (store: "f ${storeAuth.nginxFile store} 0600 root root -") stores;
}
(lib.mkIf (node.enable && k8sCfg.enable) {
assertions = [
{
assertion = haveIdentity;
message = ''
The ${lib.concatStringsSep " and " stores} the cluster runs takes a credential, which a unit
creates in the swarm secret store and publishes under the identity
services.hyperhive.deploy.bao.storeAuthClientCertFile and
storeAuthClientKeyFile name (the leaf the store mints where
services.hyperhive.deploy.bao.enable is set on this host).
'';
}
];
systemd.services.swarm-bao-store-auth = lib.mkIf haveIdentity {
description = "create the Victoria stores' listener credential in the swarm secret store if absent, and publish it";
wantedBy = [ "multi-user.target" ];
wants = [ "network-online.target" ];
after = [
"k3s.service"
"network-online.target"
]
++ storeContainer;
path = [
baoDeploy.package
pkgs.coreutils
pkgs.gnugrep
pkgs.kubectl
pkgs.openssl
pkgs.systemd
];
# ./lib/store-retry.nix: the login fails for as long as the store is
# sealed or down.
inherit (storeRetry) startLimitBurst startLimitIntervalSec;
serviceConfig = storeRetry.serviceConfig // {
Type = "oneshot";
RemainAfterExit = true;
UMask = "0077";
SyslogIdentifier = "swarm-bao-store-auth";
TimeoutStartSec = "15min";
};
environment = {
BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}";
BAO_CLIENT_CERT = baoDeploy.storeAuthClientCertFile;
BAO_CLIENT_KEY = baoDeploy.storeAuthClientKeyFile;
KUBECONFIG = kubeconfig;
}
// lib.optionalAttrs (baoDeploy.serverCaFile != null) {
BAO_CACERT = baoDeploy.serverCaFile;
};
script = ''
set -euo pipefail
${import ../lib/store-seeded-secret.nix { }}
${import ../lib/atomic-write-secret.nix { }}
${import ../lib/refresh-consumer.nix { }}
install -d -m 0700 ${storeAuth.dir}
# A password of 64 hex digits, as Grafana's bearer is.
mint_password() {
openssl rand -hex 32
}
# <store> <leaf> <password file> <nginx file> <secret>. The store's
# value wins and a leaf that holds none is created, so the first
# password stored is the one every later run reads. The nginx file
# is written first: it is what the gateway needs before the store
# answers anyone, and it needs nothing of the cluster.
reload=0
publish() {
local store="$1" leaf="$2" password_file="$3" nginx_file="$4" secret="$5"
local password directive
password="$(store_seeded "$leaf" /nonexistent mint_password)" || return 1
directive="proxy_set_header Authorization \"Basic $(printf '%s:%s' ${lib.escapeShellArg storeAuth.user} "$password" | base64 -w0)\";"
if secret_differs "$nginx_file" "$directive"; then
atomic_write_secret 0600 root:root "$nginx_file" "$directive"
reload=1
elif written_after_start nginx.service "$nginx_file"; then
reload=1
fi
if secret_differs "$password_file" "$password"; then
atomic_write_secret 0600 root:root "$password_file" "$password"
fi
echo "the credential of $store is at $nginx_file and $password_file; the Secret $secret follows."
}
store_init
store_login
if [ "$STORE_UP" != 1 ]; then
echo "could not log in to the swarm secret store; the stores' credentials are not published." >&2
exit 1
fi
${lib.concatMapStrings publish stores}
# A running nginx reads its files at a reload; one that is not
# running reads them as it starts.
if [ "$reload" = 1 ] && systemctl is-active --quiet nginx.service; then
systemctl reload nginx.service
fi
# A pod that loads the Secret waits in ContainerCreating until this
# has run.
timeout 600 ${pkgs.bash}/bin/bash -c ${lib.escapeShellArg "until kubectl get namespace ${k8sCfg.namespace} >/dev/null 2>&1; do sleep 2; done"}
${lib.concatMapStrings (store: ''
kubectl --namespace ${k8sCfg.namespace} create secret generic ${storeAuth.secretName store} \
--from-file=${storeAuth.credentialId}=${storeAuth.passwordFile store} \
--dry-run=client --output=yaml \
| kubectl --namespace ${k8sCfg.namespace} apply --server-side --force-conflicts --filename=-
'') stores}
'';
};
})
]
);
}

View file

@ -0,0 +1,31 @@
# What the Victoria stores' listener credential is, where it lives, and who
# names it. The store's pod, the gateway's vhost and the unit that mints and
# publishes it (../k8s/store-credentials.nix) all spell it from here.
#
# The credential is the HTTP Basic login every route of the store's listener
# asks for (`-httpAuth.username` and `-httpAuth.password`). The password is a
# leaf of the swarm secret store, created by that unit when the store holds
# none. The pod reads it from the Secret `secretName`; nginx sends it in the
# `Authorization` header that `nginxFile` sets.
rec {
# The Basic login's user name, the same for every store.
user = "swarm-store";
# The credential id the store's unit loads and the key of the Secret that
# holds the password.
credentialId = "store-auth";
# Under KV v2's `secret/` mount, as `bao kv` takes it. `store` is
# `victorialogs` or `victoriametrics`.
leaf = store: "swarm/services/${store}/store-auth";
# On the host, a directory only root reads: the password the Secret is made from,
# and the nginx file the gateway's locations include.
dir = "/var/lib/swarm-store-auth";
passwordFile = store: "${dir}/${store}.password";
nginxFile = store: "${dir}/${store}.conf";
# The Secret the store's pod loads its credentials from
# (../k8s/render.nix names it `<service>-credentials`).
secretName = store: "swarm-${store}-credentials";
}

View file

@ -151,6 +151,7 @@ in
"swarm-bao-ci-runner-policy.service"
"swarm-bao-logs-auth-policy.service"
"swarm-bao-metrics-auth-policy.service"
"swarm-bao-store-auth-policy.service"
"swarm-bao-forge-publisher-policy.service"
]
++ granterAfter;

View file

@ -20,6 +20,8 @@ let
k8sNode = deployCfg.k8s;
podAuth = import ./lib/bao-pod-auth.nix;
storeAuth = import ./lib/store-auth.nix;
shared = import ./lib/swarm-bao-shared.nix { inherit config lib pkgs; };
inherit (shared)
atticFactLeaves
@ -360,6 +362,24 @@ let
}
];
# The unit that publishes the stores' listener credentials
# (`swarm-bao-store-auth`, ./k8s/store-credentials.nix): it creates each
# credential when the store holds none and reads it back, `create` without
# `update`, so a stored value is never replaced. One principal for both
# stores, a leaf each.
storeAuthWriters = [
{
name = "swarm-store-auth";
cn = baoDeploy.storeAuthCommonName;
policyText =
lib.concatMapStrings (store: createReadStanza "${credentialMountPath}/data/${storeAuth.leaf store}")
[
"victorialogs"
"victoriametrics"
];
}
];
# The role name IS the policy name, as for the three service principals
# above: the role attaches the policy by spelling it identically, and one
# string for both objects removes the way they drift apart.
@ -511,6 +531,8 @@ in
systemd.services.swarm-bao-forge-publisher-policy = readerPolicyUnit "write the forge's controller-token-publisher bao policy and cert-auth role" forgePublisherWriters;
systemd.services.swarm-bao-store-auth-policy = readerPolicyUnit "write the Victoria stores' credential publisher's bao policy and cert-auth role" storeAuthWriters;
# The pods' login: the `jwt` auth mount's config and one role per
# in-cluster service. The mount exists once `swarm-bao-granter-role` has
# run with a bootstrap token that carries `sys/auth/jwt-k8s`;

View file

@ -2046,6 +2046,20 @@ in
'';
};
storeAuthCommonName = lib.mkOption {
type = lib.types.str;
default = "swarm-store-auth";
description = ''
Subject the store's `swarm-store-auth` cert-auth role accepts: the
identity the unit that publishes the log store's and the metrics store's
listener credentials presents from the host (./k8s/store-credentials.nix).
Its grant is create and read on `swarm/services/victorialogs/store-auth`
and `swarm/services/victoriametrics/store-auth`, and nothing else.
⚠️ Reserved as a hive name by ./swarm.nix, like its siblings.
'';
};
atticCommonName = lib.mkOption {
type = lib.types.str;
default = "swarm-attic";
@ -2195,6 +2209,32 @@ in
'';
};
storeAuthClientCertFile = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "/var/lib/swarm-bao-pki/store-auth.pem";
description = ''
Certificate the host presents to the store to create and read the log
store's and the metrics store's listener credentials. Its
subject must be {option}`services.hyperhive.deploy.bao.storeAuthCommonName`.
./glue-bao-tls.nix points it at the leaf it mints on the store's host.
On a host that runs either store without the secret store, it is a file
the operator copies from the store's host. A path, never a value.
'';
};
storeAuthClientKeyFile = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "/var/lib/swarm-bao-pki/store-auth-key.pem";
description = ''
Private key for
{option}`services.hyperhive.deploy.bao.storeAuthClientCertFile`.
A path, never a value.
'';
};
forgePublisherClientCertFile = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;

View file

@ -16,11 +16,11 @@
# reaches this at `https://${cfg.domain}/` gated by the same `auth_request`
# check against authelia that swarm-ui's own vhost uses (`swarmAuthRequest`
# below; `swarm-ui.nix` says why forceSSL is load-bearing: authelia answers a
# plain-http auth subrequest with 400). The store's own listener is unauthenticated and takes
# writes as well as reads. Its Service admits only the node's own traffic, and
# the vhost, which dials it by name, is the ONLY way in: the collector pushes
# through it too, at its own `= /insert/...` location, because the collector
# need not share a host with the store.
# plain-http auth subrequest with 400). The store's own listener asks every
# request for the credential in ./lib/store-auth.nix: each location below that
# dials it replaces the caller's `Authorization` with it once its own check has
# passed. The collector pushes through the vhost too, at its own
# `= /insert/...` location, because it need not share a host with the store.
# ⚠️ That ingest location deliberately does not carry `swarmAuthRequest` — a
# pusher handed its `error_page 401 =302` follows the redirect and POSTs at a
# login page, which answers 200. See the location itself.
@ -42,6 +42,7 @@ let
gatewayCfg = hyperhiveCfg.gateway;
k8sCfg = hyperhiveCfg.k8s;
inherit (import ../images { inherit pkgs lib; }) mkServiceImage;
storeAuth = import ./lib/store-auth.nix;
# Copy of `swarm-ui.nix`'s own `swarmAuthRequest` — not shared code because
# this vhost needs exactly the two locations that reference it (`/` and the
@ -125,6 +126,13 @@ let
'';
storeVariable = "$swarm_logs_store_upstream";
upstream = "http://${storeVariable}";
# The store's locations dial it with the store's credential in place of the
# caller's `Authorization`. The file is empty until the unit that mints the
# credential has run (./k8s/store-credentials.nix), and the
# store then refuses the request. The responders' locations never include it.
viaStore =
viaService storeVariable storeService storePort
+ "include ${storeAuth.nginxFile "victorialogs"};\n";
agentAuthVariable = "$swarm_logs_agent_auth_upstream";
grafanaAuthVariable = "$swarm_logs_grafana_auth_upstream";
@ -137,7 +145,12 @@ let
"-storageDataPath=${dataDir}"
"-httpListenAddr=:${toString storePort}"
"-retentionPeriod=${deployCfg.victorialogs.retentionPeriod}"
# Every route but `/health` and the few built-in ones that answer a
# fixed text asks for it (docs/4-implementation/k8s/runtime.md).
"-httpAuth.username=${storeAuth.user}"
"-httpAuth.password=file://%d/${storeAuth.credentialId}"
];
LoadCredential = [ storeAuth.credentialId ];
StateDirectory = "victorialogs";
};
environment = { };
@ -512,8 +525,7 @@ in
services.hyperhive.gateway.dns.enable = lib.mkDefault true;
# Authenticated front door onto the store's Service — see the file-top
# comment for why the store's own unauthenticated listener is reached
# through this vhost alone.
# comment for the credential each location sends the store.
# `forceSSL`: same asymmetry `swarm-ui.nix` documents —
# authelia answers a plain-http auth subrequest with 400, which
# `auth_request` cannot read as anything but a broken check, so this
@ -524,7 +536,7 @@ in
locations = {
"/" = {
proxyPass = upstream;
extraConfig = viaService storeVariable storeService storePort + swarmAuthRequest;
extraConfig = viaStore + swarmAuthRequest;
};
# The swarm collector's ingest route. `=` so it outranks the `/`
@ -544,7 +556,7 @@ in
"= /insert/opentelemetry/v1/logs" = {
proxyPass = upstream;
extraConfig = ''
${viaService storeVariable storeService storePort}
${viaStore}
auth_request /__swarm_logs_ingest_authz;
'';
};
@ -579,7 +591,7 @@ in
# the store as the caller sent them.
proxyPass = upstream;
extraConfig = ''
${viaService storeVariable storeService storePort}
${viaStore}
auth_request /__swarm_logs_auth;
'';
};
@ -597,7 +609,7 @@ in
"= /metrics" = {
proxyPass = upstream;
extraConfig = ''
${viaService storeVariable storeService storePort}
${viaStore}
auth_request /__hive_authelia;
'';
};
@ -710,8 +722,7 @@ in
# nonsense-path control, because a probe where every arm returns the same
# code is not evidence.
#
# ⚠️ Like the metrics store's, that endpoint is unauthenticated — which is
# why the Service's policy admits only the node and why nothing reaches it
# except through the gateway, where the ingest route is authenticated. (This
# module declares a vhost.)
# ⚠️ The endpoint asks for the store's credential like every other route: the
# ingest location replaces the caller's `Authorization` with it once the
# collector's own check has passed.
}

View file

@ -11,10 +11,12 @@
# It is the collector that feeds this (the gateway OTEL collector), not the
# agents directly: one ingest point per swarm, authenticated there.
#
# The store's own listener authenticates nothing and takes writes and admin
# calls beside its queries. Its Service admits only the node's own traffic, and
# the vhost below, which dials it by name, is the way in for everything the
# swarm does.
# The store's own listener takes writes and admin calls beside its queries, and
# asks every request for the credential in ./lib/store-auth.nix: each location
# below that dials it replaces the caller's `Authorization` with that credential
# once its own check has passed, so a caller's bearer never reaches the store.
# Its Service admits only the node's own traffic, and the vhost below, which
# dials it by name, is the way in for everything the swarm does.
{
pkgs,
lib,
@ -30,6 +32,7 @@ let
k8sCfg = hyperhiveCfg.k8s;
baoCfg = hyperhiveCfg.swarm.bao;
inherit (import ../images { inherit pkgs lib; }) mkServiceImage;
storeAuth = import ./lib/store-auth.nix;
# The workloads, as the cluster names them: the store, and the one pod that
# holds both responders. Each has a Service of its name, which the gateway
@ -61,7 +64,13 @@ let
storeVariable = "$swarm_metrics_store_upstream";
agentAuthVariable = "$swarm_metrics_agent_auth_upstream";
grafanaAuthVariable = "$swarm_metrics_grafana_auth_upstream";
viaStore = viaService storeVariable storeService storePort;
# The store's locations dial it with the store's credential in place of the
# caller's `Authorization`. The file is empty until the unit that mints the
# credential has run (./k8s/store-credentials.nix), and the store then refuses
# the request. The responders' locations never include it.
viaStore =
viaService storeVariable storeService storePort
+ "include ${storeAuth.nginxFile "victoriametrics"};\n";
# The store's read API, which the vhost forwards to a caller holding
# Grafana's bearer, an agent's own bearer, or an operator's session.
@ -177,7 +186,12 @@ let
"-storageDataPath=${dataDir}"
"-httpListenAddr=:${toString storePort}"
"-retentionPeriod=${deployCfg.victoriametrics.retentionPeriod}"
# Every route but `/health` and the few built-in ones that answer a
# fixed text asks for it (docs/4-implementation/k8s/runtime.md).
"-httpAuth.username=${storeAuth.user}"
"-httpAuth.password=file://%d/${storeAuth.credentialId}"
];
LoadCredential = [ storeAuth.credentialId ];
StateDirectory = "victoriametrics";
};
environment = { };
@ -581,7 +595,7 @@ in
# Nothing reaches the store unless a location here names it. The
# store serves writes and admin calls (`/api/v1/import`,
# `/api/v1/admin/tsdb/delete_series`, ...) on the same listener as
# its queries, and authenticates none of them.
# its queries, and asks for its credential on all of them.
"/".return = "403";
# The swarm UI's quick link opens the bare domain. The store's own
@ -721,9 +735,9 @@ in
# 400, so that 200 means the route exists). The `-opentelemetry.*` flags
# only tune naming and limits.
#
# ⚠️ That endpoint is unauthenticated, which is why the Service admits only
# the node: the only route to it is the vhost's ingest location, which
# authenticates. The collector is still the only writer, but it arrives by the
# swarm name rather than over loopback, because it need not share a host with
# this store.
# ⚠️ That endpoint asks for the store's credential like every other route: the
# vhost's ingest location authenticates the collector and then replaces its
# `Authorization` with it. The collector is still the only writer, but it
# arrives by the swarm name rather than over loopback, because it need not
# share a host with this store.
}

View file

@ -85,6 +85,7 @@ let
deployCfg.bao.claudeLoginCommonName
deployCfg.bao.notifyRouterCommonName
deployCfg.bao.sttCommonName
deployCfg.bao.storeAuthCommonName
deployCfg.bao.atticCommonName
deployCfg.bao.archiveCommonName
deployCfg.bao.forgePublisherCommonName