Watch
0
0
Fork
You've already forked hyperhive
0

swarm-otel: scrape the authenticated targets only once the collector has its client secret

An empty secret file made the prometheus receiver request a token for each published target every scrape; authelia's per-address limit then refused every client behind that address. Without a secret the collector starts on the config minus those jobs. full-setup asserts the limiter never fired.
This commit is contained in:
atlas 2026-11-23 12:15:37 +01:00 • committed by mara
commit 480855dfaf
4 changed files with 157 additions and 4 deletions

View file

@ -0,0 +1,33 @@
# Pure function — NOT a NixOS module. An OpenTelemetry collector config minus
# the named prometheus scrape jobs.
#
# scrapeWithoutJobs = import ./lib/scrape-without-jobs.nix { inherit lib; };
# scrapeWithoutJobs { inherit settings jobs; pipeline = "metrics/swarm"; }
#
# `jobs` are `job_name`s of the `prometheus` receiver. When none is left the
# receiver goes, and `pipeline` with it: a prometheus receiver without scrape
# configs fails the collector's validation, and a pipeline naming an absent
# receiver does too.
{ lib }:
{
settings,
jobs,
pipeline,
}:
let
kept = lib.filter (job: !(lib.elem job.job_name jobs)) (
settings.receivers.prometheus.config.scrape_configs or [ ]
);
in
if !(settings.receivers ? prometheus) then
settings
else if kept != [ ] then
lib.recursiveUpdate settings { receivers.prometheus.config.scrape_configs = kept; }
else
settings
// {
receivers = removeAttrs settings.receivers [ "prometheus" ];
service = settings.service // {
pipelines = removeAttrs settings.service.pipelines [ pipeline ];
};
}

View file

@ -145,8 +145,9 @@ let
# after a reboot the delivery unit below fetches it again. The container
# sees the directory read-only at the same path. The file starts out empty
# (tmpfiles, below) so `LoadCredential` has a source before the first
# fetch; a collector that starts on it is refused by the stores until the
# fetched secret restarts it.
# fetch; a collector that starts on it exports nothing and scrapes only the
# targets that need no secret (`scrapeNeedsSecret`) until the fetched secret
# restarts it.
#
# Spelled once, for the unit that writes it and the option that names it,
# which are a few hundred lines apart: a collector reading a path nothing
@ -163,8 +164,53 @@ let
# collector cannot open, discovered at runtime and nowhere else.
collectorSecretPath = "/run/credentials/opentelemetry-collector.service/${collectorCredentialId}";
# A container module: the collector starts on the full config only when the
# credential file it loaded holds a secret.
#
# The prometheus receiver reads `client_secret_file` on every scrape and
# requests a token even when the file is empty, so each authenticated scrape
# target is refused at authelia's token endpoint once a minute, and the
# endpoint's per-address rate limit then answers every client of this
# container with 429 for minutes. Without a secret the collector therefore
# starts on the same config minus the `publishedScrapeTargets` jobs (the
# receiver and its pipeline too when nothing else is scraped). The
# authenticated exporters already refuse an empty secret locally. The
# delivery unit restarts a running collector when it writes the secret.
scrapeNeedsSecret =
{ config, ... }:
let
collector = config.services.opentelemetry-collector;
settings = collector.settings;
withoutPublished = scrapeWithoutJobs {
inherit settings;
jobs = lib.attrNames cfg.publishedScrapeTargets;
pipeline = "metrics/${swarmTierName}";
};
# `otelcol validate`, as upstream's module does for `settings`.
validated =
name: value:
pkgs.runCommandLocal "${name}.yaml"
{ generated = (pkgs.formats.yaml { }).generate "${name}.yaml" value; }
''
cp $generated $out
${lib.getExe collector.package} validate --config=file:$out
'';
start = pkgs.writeShellScript "opentelemetry-collector-start" ''
config=${validated "config" settings}
if [ ! -s "$CREDENTIALS_DIRECTORY/${collectorCredentialId}" ]; then
echo "the client secret is empty: not scraping the targets that need it until the secret is delivered and this unit restarts" >&2
config=${validated "config-without-secret" withoutPublished}
fi
exec ${lib.getExe collector.package} --config=file:"$config"
'';
in
{
systemd.services.opentelemetry-collector.serviceConfig.ExecStart = lib.mkForce "${start}";
};
atomicWriteSecret = import ./lib/atomic-write-secret.nix { };
refreshConsumer = import ./lib/refresh-consumer.nix { };
scrapeWithoutJobs = import ./lib/scrape-without-jobs.nix { inherit lib; };
# `attrNames` is sorted, so this is a function of the hive SET and not of
# the order anyone wrote it in.
@ -776,7 +822,7 @@ in
# The bind source must exist when the container starts.
"d ${collectorSecretDir} 0700 root root -"
# `LoadCredential=` fails the unit when the file is missing; an empty
# one lets the collector start and be refused by the stores.
# one lets the collector start, without the scrape jobs that need the secret.
"f ${collectorSecretInContainer} 0400 root root -"
]
# Unless a deployment delivers its own secret to that very path.
@ -1133,7 +1179,9 @@ in
name = cfg.machine;
consumers = [ "opentelemetry-collector" ];
})
];
]
# The scrape side of the client secret: see `scrapeNeedsSecret`.
++ lib.optional haveCollectorSecret scrapeNeedsSecret;
system.stateVersion = config.system.stateVersion;
services.hyperhive.swarmContainer = { inherit privateNetwork; };

View file

@ -466,6 +466,44 @@ let
&& lib.any (p: builtins.elem "otlphttp/victorialogs" p.exporters) ps
&& lib.any (p: builtins.elem "otlphttp/victoriametrics" p.exporters) ps;
}
{
# An empty secret file makes the prometheus receiver request a token
# anyway, once per authenticated scrape target per minute. So the unit
# starts through a wrapper that drops those jobs while the secret is
# empty. Presence arms: every published job is in the full config, the
# loopback job survives the drop, and the unit's start is the wrapper
# (the same unit's `LoadCredential` is asserted by the cases above).
name = "a swarm collector with no client secret yet does not scrape the targets that need one";
ok =
let
scrapeWithoutJobs = import ../host-modules/lib/scrape-without-jobs.nix { inherit lib; };
full = otelSettings otelNoStores;
published = lib.attrNames otelNoStores.services.hyperhive.swarm.otel.publishedScrapeTargets;
pipeline = "metrics/${otelNoStores.services.hyperhive.swarm.otel.producerName}";
jobsOf = s: map (j: j.job_name) s.receivers.prometheus.config.scrape_configs;
dropped = scrapeWithoutJobs {
settings = full;
jobs = published;
inherit pipeline;
};
everything = scrapeWithoutJobs {
settings = full;
jobs = jobsOf full;
inherit pipeline;
};
in
published != [ ]
&& lib.all (j: lib.elem j (jobsOf full)) published
&& lib.all (j: !(lib.elem j (jobsOf dropped))) published
&& lib.elem "collector" (jobsOf dropped)
&& lib.elem pipeline (lib.attrNames dropped.service.pipelines)
&& !(everything.receivers ? prometheus)
&& !(everything.service.pipelines ? ${pipeline})
&& lib.elem pipeline (lib.attrNames full.service.pipelines)
&& lib.hasInfix "opentelemetry-collector-start" (
toString otelNoStores.containers.swarm-otel.config.systemd.services.opentelemetry-collector.serviceConfig.ExecStart
);
}
];
in
runGroup "swarm-otel-core" cases

View file

@ -332,3 +332,25 @@ with subtest("the agents are deployed and need a login"):
2400,
["swarm-controller", "hive-c0re"],
)
with subtest(
"authelia's token endpoint never rate-limited a client while the swarm came up"
):
# Per source address, the limiter refuses once an address has been refused enough times, so
# one client POSTing without a usable secret locks every other client behind that address out.
# The control is a refusal this test causes from the host: the same journal query has to find it.
TOKEN_JOURNAL = (
"journalctl --machine=swarm-authelia -u authelia-swarm.service --no-pager -o cat "
'| grep -F \'"path":"/api/oidc/token"\''
)
machine.succeed(
"curl --silent --insecure -u nobody:wrong -d grant_type=client_credentials "
f"https://auth.{os.environ['FULL_SETUP_SWARM_DOMAIN']}/api/oidc/token"
)
machine.wait_until_succeeds(
f'{TOKEN_JOURNAL} | grep -F \'"remote_ip":"127.0.0.1"\''
)
limited = machine.execute(f"{TOKEN_JOURNAL} | grep -F 'Rate Limit Exceeded'")[1]
assert limited == "", (
"authelia rate-limited the token endpoint:\n" + limited[-3000:]
)