From 8717e68021f7f5b1b0e006bed4e76de280d70275 Mon Sep 17 00:00:00 2001 From: maia Date: Mon, 30 Nov 2026 15:29:16 +0100 Subject: [PATCH] swarm-nats-auth: the responder refuses to start under a server callout timeout its lookup bound does not fit --- nix/host-modules/swarm-nats.nix | 9 +++++- nix/module-eval/nats-authelia.nix | 15 ++++++++++ swarm-nats-auth/src/introspect.rs | 43 +++++++++++++++++--------- swarm-nats-auth/src/main.rs | 50 +++++++++++++++++++++++++++++++ 4 files changed, 102 insertions(+), 15 deletions(-) diff --git a/nix/host-modules/swarm-nats.nix b/nix/host-modules/swarm-nats.nix index e7b66b49f..653782c88 100644 --- a/nix/host-modules/swarm-nats.nix +++ b/nix/host-modules/swarm-nats.nix @@ -23,6 +23,12 @@ let calloutAccount = "AUTH"; clientAccount = "APP"; + # How long the server waits for the auth callout, in seconds. The server's + # `authorization.timeout` and the responder's `--server-auth-timeout-secs` both + # render from this one value: the responder refuses to start unless its own + # lookup bound fits under it. + authTimeoutSecs = 2; + machine = "swarm-nats"; # The container's journal forwarder pushes to its own receiver on the swarm @@ -163,7 +169,7 @@ let }; authorization = { - timeout = "2s"; + timeout = "${toString authTimeoutSecs}s"; # 🔒 THIS BLOCK IS THE FAIL-CLOSED STATE, and it is the measured # one rather than the obvious one. # @@ -939,6 +945,7 @@ in # be the same string — which is why both come from one let. "--account ${lib.escapeShellArg clientAccount}" "--introspection-url ${lib.escapeShellArg introspectionUrl}" + "--server-auth-timeout-secs ${toString authTimeoutSecs}" # Each of these names a principal some OTHER module mints, # so each is read out of that module rather than spelled # again here — same argument as `--account` above, one diff --git a/nix/module-eval/nats-authelia.nix b/nix/module-eval/nats-authelia.nix index 8555554ba..9d29c51c3 100644 --- a/nix/module-eval/nats-authelia.nix +++ b/nix/module-eval/nats-authelia.nix @@ -512,6 +512,21 @@ let in !(lib.any (lib.hasSuffix "-policy.service") (u.after ++ u.wants)); } + { + # The responder refuses to start unless its lookup bound fits under the + # server's callout timeout, so it has to be told the value the server + # actually runs with: read from the rendered server settings, not spelled + # again here. + name = "the responder is passed the callout timeout the server runs with"; + ok = + let + c = natsQueueOnly.containers.swarm-nats.config; + timeout = c.services.nats.settings.authorization.timeout; + exec = c.systemd.services.swarm-nats-auth.serviceConfig.ExecStart; + in + lib.hasSuffix "s" timeout + && lib.hasInfix " --server-auth-timeout-secs ${lib.removeSuffix "s" timeout} " exec; + } { # The responder takes no agent-client suffix: no such client is minted. # `--hive-client-prefix` is the control that the lookup finds a flag the diff --git a/swarm-nats-auth/src/introspect.rs b/swarm-nats-auth/src/introspect.rs index 2eee7dff5..b7e23df32 100644 --- a/swarm-nats-auth/src/introspect.rs +++ b/swarm-nats-auth/src/introspect.rs @@ -23,8 +23,8 @@ //! //! # The timeout is not a tuning knob //! -//! `swarm-nats.nix` sets `authorization.timeout = "2s"`, so the server stops -//! waiting after two seconds and denies the connection anyway. An +//! `swarm-nats.nix` sets `authorization.timeout` (two seconds), so the server +//! stops waiting after that long and denies the connection anyway. An //! introspection call allowed to run longer than that cannot produce a useful //! answer — it can only hold a task open past the point where the result //! matters. The budget below is deliberately under the server's. @@ -35,13 +35,30 @@ use anyhow::{Context, Result}; use serde::Deserialize; use tokio::time::Instant; -/// Kept under `swarm-nats.nix`'s `authorization.timeout = "2s"` — see the -/// module docs. A slower answer is not a late success, it is a denial that +/// Kept under the server's `authorization.timeout`, which `swarm-nats.nix` +/// passes in (see [`check_server_timeout`] and the module docs). A slower answer is not a late success, it is a denial that /// already happened. It bounds a whole request, the re-read of this /// responder's own secret and the retry after it included, which is why /// [`identify_caller`] takes a deadline rather than a duration. pub const INTROSPECTION_TIMEOUT: Duration = Duration::from_millis(1500); +/// Refuses a server `authorization.timeout` that [`INTROSPECTION_TIMEOUT`] does +/// not fit under: a lookup allowed that long could answer after the server has +/// already denied the connection. `swarm-nats.nix` renders the same value into +/// the server's config and into `--server-auth-timeout-secs`, so this is the +/// one place the pair is compared. +/// +/// # Errors +/// When `server_timeout` is not longer than [`INTROSPECTION_TIMEOUT`]. +pub fn check_server_timeout(server_timeout: Duration) -> Result<()> { + anyhow::ensure!( + INTROSPECTION_TIMEOUT < server_timeout, + "introspection waits up to {INTROSPECTION_TIMEOUT:?}, which does not fit under the \ + server's authorization.timeout of {server_timeout:?}" + ); + Ok(()) +} + /// What one introspection call said. #[derive(Debug, PartialEq, Eq)] pub enum Answer { @@ -164,17 +181,15 @@ pub async fn identify_caller( mod tests { use super::*; + /// The server's timeout is whatever `swarm-nats.nix` renders into both + /// places; the bound has to fit strictly under it. #[test] - fn the_timeout_stays_under_the_servers() { - // `swarm-nats.nix` sets `authorization.timeout = "2s"`. If someone - // raises this constant past that, the extra time buys nothing: the - // server has already denied the connection. This test is the only - // thing tying the two numbers together, since they live in different - // languages in different files. - assert!( - INTROSPECTION_TIMEOUT < Duration::from_secs(2), - "introspection budget must stay under the server's auth_callout timeout" - ); + fn the_timeout_has_to_fit_under_the_servers() { + assert!(check_server_timeout(Duration::from_secs(2)).is_ok()); + assert!(check_server_timeout(INTROSPECTION_TIMEOUT + Duration::from_millis(1)).is_ok()); + assert!(check_server_timeout(INTROSPECTION_TIMEOUT).is_err()); + assert!(check_server_timeout(Duration::from_secs(1)).is_err()); + assert!(check_server_timeout(Duration::ZERO).is_err()); } fn parse(body: &str) -> IntrospectionResponse { diff --git a/swarm-nats-auth/src/main.rs b/swarm-nats-auth/src/main.rs index 1ca5f7f1c..816eb85a8 100644 --- a/swarm-nats-auth/src/main.rs +++ b/swarm-nats-auth/src/main.rs @@ -105,6 +105,13 @@ struct Args { #[arg(long)] introspection_url: String, + /// The server's `authorization.timeout`, in seconds: how long it waits for + /// this responder's answer. The module passes the value it renders into the + /// server's config, so the two cannot differ; the responder refuses to start + /// unless [`introspect::INTROSPECTION_TIMEOUT`] fits under it. + #[arg(long)] + server_auth_timeout_secs: u64, + /// `OAuth2` client id this responder introspects as, and whose secret it /// reads from the store. Must match /// `services.hyperhive.swarm.nats.clientId`, whose default this mirrors. @@ -215,6 +222,9 @@ async fn main() -> anyhow::Result<()> { /// The responder: answers every authorization request until its /// subscription ends. async fn serve(args: Args, stop: swarm_secret_client::Shutdown) -> anyhow::Result<()> { + introspect::check_server_timeout(std::time::Duration::from_secs( + args.server_auth_timeout_secs, + ))?; // The bucket is NOT a flag. `swarm_queue_client::status`'s own docs say // why: reader and writer must name the same bucket, and an option is a // way for two deployments to disagree about which one that is. This @@ -742,6 +752,8 @@ mod tests { "swarm-nats-auth", "--introspection-url", "https://auth.example/api/oidc/introspection", + "--server-auth-timeout-secs", + "2", "--hive-client-prefix", "hive-", "--agent-token-publish-subject", @@ -844,6 +856,8 @@ mod tests { "swarm-nats-auth", "--introspection-url", "https://auth.example/api/oidc/introspection", + "--server-auth-timeout-secs", + "2", ]) .expect("the required flags alone must parse"); let policy = @@ -1068,6 +1082,42 @@ mod tests { Cli::try_parse_from(["swarm-nats-auth"]).expect_err("the responder's flags are required"); } + /// The responder's flag for the server's callout timeout is required, so a + /// unit that stopped passing it cannot start unchecked. + #[test] + fn the_server_timeout_flag_is_required() { + responder([ + "swarm-nats-auth", + "--introspection-url", + "https://auth.example/api/oidc/introspection", + ]) + .expect_err("a responder with no server timeout would start unchecked"); + } + + /// A server timeout the introspection bound does not fit under ends + /// `serve` before it reads a policy, opens a listener or reaches the + /// store; nothing before that check can fail on its own in this test, so + /// the error is the check's. + #[tokio::test] + async fn a_server_timeout_the_bound_does_not_fit_under_stops_serve_first() { + let mut args = responder([ + "swarm-nats-auth", + "--introspection-url", + "https://auth.example/api/oidc/introspection", + "--server-auth-timeout-secs", + "2", + ]) + .expect("the required flags parse"); + args.server_auth_timeout_secs = 1; + let stop: swarm_secret_client::Shutdown = + futures_util::FutureExt::shared(futures_util::FutureExt::boxed(std::future::pending())); + let err = serve(args, stop).await.expect_err("1 s is under the bound"); + assert!( + format!("{err:#}").contains("authorization.timeout"), + "stopped for another reason: {err:#}" + ); + } + #[test] fn the_verb_does_not_take_the_responders_flags() { Cli::try_parse_from([