From 61636cfcc2a788705234ddf1c7039f7bd36dc0b3 Mon Sep 17 00:00:00 2001 From: maia Date: Mon, 30 Nov 2026 15:06:27 +0100 Subject: [PATCH] swarm-metrics-auth: remember a "no bearer stored" answer for the cache TTL When the store answered that it holds no usable bearer, the cache was reset to its default, which forgot that the answer had just been asked for. Every request after that started its own bao login and read, one at a time (up to 5 s each), so anyone sending `Bearer <64 hex>` before Grafana's bearer exists queued Grafana's real requests behind those lookups, on a route with no rate limit because the responder was said to read the store at most once per TTL. Remember the answer for the TTL, as a stored bearer is, and deny without a lookup until it passes (`empty_until`). A bearer that arrives ends it. The "at most once per cache TTL" comments in swarm-victorialogs.nix and swarm-victoriametrics.nix now also say the failure case, one lookup per few seconds while the store does not answer. --- nix/host-modules/swarm-victorialogs.nix | 5 +- nix/host-modules/swarm-victoriametrics.nix | 3 +- swarm-metrics-auth/src/main.rs | 75 ++++++++++++++++++---- 3 files changed, 68 insertions(+), 15 deletions(-) diff --git a/nix/host-modules/swarm-victorialogs.nix b/nix/host-modules/swarm-victorialogs.nix index 00480c100..ed6521a02 100644 --- a/nix/host-modules/swarm-victorialogs.nix +++ b/nix/host-modules/swarm-victorialogs.nix @@ -475,7 +475,10 @@ in # Grafana's bearer, 64 hex digits (`openssl rand -hex 32`), checked by # `swarm-metrics-auth`. The responder reads the store at most once per - # its cache TTL whatever the bearers, so no rate limit sits in front. + # its cache TTL, whatever the bearers and including when the store + # holds none (that answer is remembered for the TTL too), and once + # every few seconds while the store does not answer, so no rate limit + # sits in front. "= /__swarm_logs_grafana_auth" = { proxyPass = "http://unix:${grafanaAuthSocket}:/"; extraConfig = '' diff --git a/nix/host-modules/swarm-victoriametrics.nix b/nix/host-modules/swarm-victoriametrics.nix index 338e7381f..0ace7ea2d 100644 --- a/nix/host-modules/swarm-victoriametrics.nix +++ b/nix/host-modules/swarm-victoriametrics.nix @@ -494,7 +494,8 @@ in # Grafana's bearer, checked by `swarm-metrics-auth`. The # `Authorization` header rides the subrequest unchanged. No rate limit # in front: the responder reads the store at most once per its cache - # TTL, whatever the bearers. + # TTL, whatever the bearers and including when the store holds none, + # and once every few seconds while the store does not answer. "= /__metrics_grafana_auth" = { proxyPass = "http://unix:${metricsAuthSocket}:/"; extraConfig = '' diff --git a/swarm-metrics-auth/src/main.rs b/swarm-metrics-auth/src/main.rs index b63533219..611e04145 100644 --- a/swarm-metrics-auth/src/main.rs +++ b/swarm-metrics-auth/src/main.rs @@ -15,10 +15,12 @@ //! //! The stored value is kept for `--cache-ttl` seconds, and no request reaches //! the store within that window: a replaced bearer is refused, and the one it -//! replaced still accepted, for up to that long. Lookups are serialised, and a -//! failed or timed-out one is remembered for `LOOKUP_FAILURE_WINDOW`, so a -//! burst of requests against an expired copy costs one lookup, success or -//! failure. +//! replaced still accepted, for up to that long. The same holds when the store +//! answers that it holds no bearer: that answer is kept for the TTL too, so a +//! bearer created after it is refused until the TTL has passed. Lookups are +//! serialised, and a failed or timed-out one is remembered for +//! `LOOKUP_FAILURE_WINDOW`, so a burst of requests against an expired copy +//! costs one lookup, success or failure. //! //! When the store does not answer, requests are checked against the last //! value it did return, up to `MAX_KEPT_AGE` after that read, and a wrong @@ -147,6 +149,11 @@ struct Cache { failed_until: Option, /// Whether this failure streak has logged that it checks against `stored`. fallback_logged: bool, + /// Until when requests are denied without a lookup, after the store + /// answered that it holds no usable bearer. As long as a stored bearer + /// is used without a read (`--cache-ttl`): nobody sending bearers can + /// make the responder log in to the store more often than that. + empty_until: Option, } impl Cache { @@ -198,7 +205,12 @@ enum Refresh { /// Reads the store into `cache`, unless a lookup failed less than /// `LOOKUP_FAILURE_WINDOW` ago. -async fn refresh(source: &impl BearerSource, cache: &mut Cache, now: Instant) -> Refresh { +async fn refresh( + source: &impl BearerSource, + cache: &mut Cache, + now: Instant, + ttl: Duration, +) -> Refresh { if cache.failed_until.is_some_and(|until| now < until) { return Refresh::Unanswered; } @@ -211,11 +223,18 @@ async fn refresh(source: &impl BearerSource, cache: &mut Cache, now: Instant) -> }); cache.failed_until = None; cache.fallback_logged = false; + cache.empty_until = None; Refresh::Replaced } Ok(Ok(_)) => { tracing::warn!("no bearer is stored; denying"); - *cache = Cache::default(); + // The answer is cached for the TTL like a bearer would be, so the + // next request does not log in again: a reset to `Cache::default()` + // would forget it and let every request start a lookup. + cache.stored = None; + cache.failed_until = None; + cache.fallback_logged = false; + cache.empty_until = Some(now + ttl); Refresh::Empty } Ok(Err(e)) => { @@ -244,12 +263,17 @@ async fn decide( // Held across the lookup, so concurrent requests wait for one read // rather than each starting their own. let mut cache = responder.cached.lock().await; + // The store said a moment ago that it holds no bearer: deny without + // asking again until the TTL has passed. + if cache.empty_until.is_some_and(|until| now < until) { + return StatusCode::UNAUTHORIZED; + } let fresh = cache .stored .as_ref() .is_some_and(|c| now.saturating_duration_since(c.read_at) < responder.ttl); if !fresh { - match refresh(&responder.source, &mut cache, now).await { + match refresh(&responder.source, &mut cache, now, responder.ttl).await { Refresh::Replaced => {} Refresh::Empty => return StatusCode::UNAUTHORIZED, Refresh::Unanswered => { @@ -452,14 +476,17 @@ mod tests { } /// Nothing stored, an empty value, and a store that cannot answer are - /// all denials, whatever the bearer, when no value was ever read. + /// all denials, whatever the bearer, when no value was ever read, and + /// the store is asked once for all of those requests: each answer is + /// remembered (the failure for its window, the others for the TTL), so + /// bearers sent at the responder cannot make it log in over and over. #[tokio::test] - async fn no_usable_stored_value_is_401() { + async fn no_usable_stored_value_is_401_and_is_asked_once() { for answer in [holds_nothing, || holds(""), fails] { let mut source = MockBearerSource::new(); - source.expect_lookup().returning(answer); + source.expect_lookup().times(1).returning(answer); let r = responder(source); - for authorization in [GOOD, "Bearer "] { + for authorization in [GOOD, "Bearer ", GOOD, "Bearer other", GOOD] { assert_eq!( decide(&r, Some(authorization), Instant::now()).await, StatusCode::UNAUTHORIZED @@ -468,6 +495,27 @@ mod tests { } } + /// Once the TTL has passed the store is asked again, and a bearer that has + /// been created since is used: the remembered "nothing" is not for ever. + #[tokio::test] + async fn a_remembered_nothing_ends_with_the_ttl() { + let r = responder(store(&[holds_nothing, secret])); + let t0 = Instant::now(); + assert_eq!(decide(&r, Some(GOOD), t0).await, StatusCode::UNAUTHORIZED); + let within = t0 + Duration::from_secs(59); + assert_eq!( + decide(&r, Some(GOOD), within).await, + StatusCode::UNAUTHORIZED + ); + let after = t0 + TTL; + assert_eq!(decide(&r, Some(GOOD), after).await, StatusCode::OK); + // A request that took its time before the lock, queued behind the one + // that read the bearer, is answered with it too: the remembered + // "nothing" went when the bearer arrived. + let queued = t0 + Duration::from_secs(10); + assert_eq!(decide(&r, Some(GOOD), queued).await, StatusCode::OK); + } + /// Within the TTL no request reaches the store, a wrong bearer included, /// and a replacement the store already holds goes unseen; after it the /// store is read again, and its answer replaces the old value at once. @@ -558,7 +606,8 @@ mod tests { } /// A store that answers it holds no bearer drops the value: a later - /// outage does not bring it back. + /// outage, once the remembered "nothing" has passed and the store is + /// asked again, does not bring it back. #[tokio::test] async fn an_empty_answer_drops_the_last_good_bearer() { let r = responder(store(&[secret, holds_nothing, fails])); @@ -568,7 +617,7 @@ mod tests { StatusCode::UNAUTHORIZED ); assert_eq!( - decide(&r, Some(GOOD), Instant::now()).await, + decide(&r, Some(GOOD), Instant::now() + TTL).await, StatusCode::UNAUTHORIZED ); }