From 719947ea04d39fbd88c5dc8f41aec96982c0f5bd Mon Sep 17 00:00:00 2001 From: maia Date: Mon, 30 Nov 2026 15:41:52 +0100 Subject: [PATCH] swarm-queue-client: bound the token a caller supplies, and log a token body that cannot be read --- Cargo.lock | 1 + swarm-queue-client/Cargo.toml | 4 + swarm-queue-client/src/lib.rs | 167 ++++++++++++++++++++++++++++++---- 3 files changed, 156 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 00d55bbe3..84f34b100 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5718,6 +5718,7 @@ dependencies = [ "thiserror 2.0.21", "tokio", "tracing", + "tracing-subscriber", ] [[package]] diff --git a/swarm-queue-client/Cargo.toml b/swarm-queue-client/Cargo.toml index 17ecb6213..9d3a6fd65 100644 --- a/swarm-queue-client/Cargo.toml +++ b/swarm-queue-client/Cargo.toml @@ -126,6 +126,10 @@ data-encoding.workspace = true tempfile = "3" # StreamExt::next on a pulled batch in those tests. futures-util.workspace = true +# `start_paused`, for the token bound's test. +tokio = { workspace = true, features = ["test-util"] } +# Reads what a test logged. +tracing-subscriber.workspace = true [lints] workspace = true diff --git a/swarm-queue-client/src/lib.rs b/swarm-queue-client/src/lib.rs index fa7191180..c9589ffbe 100644 --- a/swarm-queue-client/src/lib.rs +++ b/swarm-queue-client/src/lib.rs @@ -855,6 +855,55 @@ async fn mint_token( } } +/// How long the token endpoint may take to answer [`connect`]'s requests. Past +/// it the attempt fails and `async-nats` backs off and tries again, rather than +/// a hung call holding the connection attempt that invoked it. +const TOKEN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); + +/// How long the token a [`connect_with_token`] caller supplies may take. +/// +/// Strictly above every caller's own bound on reading it: the callers +/// (`agent_publisher`, the agent harness) bound their store read at ten +/// seconds and, when it hangs, go on with the secret they already hold. An +/// outer bound at or under theirs would end the attempt first and the held +/// secret would never be used. This one is the net for a caller with no bound +/// of its own. +const CALLER_TOKEN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15); + +/// The auth a [`connect_with_token`] attempt presents: `token`, bounded by +/// [`CALLER_TOKEN_TIMEOUT`]. The caller's future runs inside the auth callback, so one +/// that never resolved would hang the connection attempt with nothing in the +/// log; past the bound the attempt fails instead. +async fn token_auth( + token: impl Future>, +) -> Result { + let token = tokio::time::timeout(CALLER_TOKEN_TIMEOUT, token) + .await + .unwrap_or_else(|_| { + Err(format!( + "the token did not arrive within {CALLER_TOKEN_TIMEOUT:?}" + )) + }) + .map_err(async_nats::AuthError::new)?; + let mut auth = async_nats::Auth::new(); + auth.token = Some(token); + Ok(auth) +} + +/// A token-endpoint response body, or empty when it could not be read: the +/// status alone still says what the endpoint answered, and the parse then +/// reports it. The read error is logged with that status, not dropped. +fn body_text(status: reqwest::StatusCode, body: Result) -> String { + body.unwrap_or_else(|e| { + tracing::warn!( + %status, + error = %e, + "the token endpoint's response body could not be read" + ); + String::new() + }) +} + /// One token request presenting `secret`. async fn mint_with( http: &reqwest::Client, @@ -869,7 +918,7 @@ async fn mint_with( .map_err(Error::TokenRequest)?; let status = response.status(); - let body = response.text().await.unwrap_or_default(); + let body = body_text(status, response.text().await); parse_token_response(status, &body) } @@ -977,7 +1026,7 @@ fn load_ca_cert(path: &std::path::Path) -> Result { /// the token endpoint needs the swarm's own CA trusted the same way, so the /// trust-anchor logic lives here once rather than once per caller. fn build_http_client(cfg: &QueueConfig) -> Result { - let mut builder = reqwest::Client::builder().timeout(std::time::Duration::from_secs(10)); + let mut builder = reqwest::Client::builder().timeout(TOKEN_TIMEOUT); if let Some(path) = &cfg.ca_file { builder = builder.add_root_certificate(load_ca_cert(path)?); } @@ -1077,7 +1126,7 @@ fn mint_with_blocking( .map_err(Error::TokenRequest)?; let status = response.status(); - let body = response.text().unwrap_or_default(); + let body = body_text(status, response.text()); Ok(parse_token_response(status, &body)?.token) } @@ -1086,8 +1135,7 @@ fn mint_with_blocking( /// of the async one. See [`mint_token_for_blocking`] for why a caller needs /// this rather than the async builder. fn build_blocking_http_client(cfg: &QueueConfig) -> Result { - let mut builder = - reqwest::blocking::Client::builder().timeout(std::time::Duration::from_secs(10)); + let mut builder = reqwest::blocking::Client::builder().timeout(TOKEN_TIMEOUT); if let Some(path) = &cfg.ca_file { builder = builder.add_root_certificate(load_ca_cert(path)?); } @@ -1327,7 +1375,8 @@ async fn rotate_before_expiry( /// /// `token` runs once per connection attempt, reconnects included, so a /// credential replaced at its source is presented on the next attempt. An -/// `Err` from it fails that attempt, and the next one waits out the same +/// `Err` from it fails that attempt, as does a token that has not arrived +/// within fifteen seconds, and the next one waits out the same /// backoff as a refused connect. /// /// Unlike [`connect`], the first attempt must succeed: a refused or failed @@ -1344,16 +1393,10 @@ where F: Fn() -> Fut + Send + Sync + 'static, Fut: Future> + Send + Sync + 'static, { - let mut options = async_nats::ConnectOptions::with_auth_callback(move |_nonce| { - let token = token(); - async move { - let mut auth = async_nats::Auth::new(); - auth.token = Some(token.await.map_err(async_nats::AuthError::new)?); - Ok(auth) - } - }) - .reconnect_delay_callback(reconnect_delay) - .custom_inbox_prefix(agent_inbox_prefix(agent)); + let mut options = + async_nats::ConnectOptions::with_auth_callback(move |_nonce| token_auth(token())) + .reconnect_delay_callback(reconnect_delay) + .custom_inbox_prefix(agent_inbox_prefix(agent)); if let Some(path) = ca_file { options = options.add_root_certificates(path.to_path_buf()); } @@ -2115,4 +2158,96 @@ mod tests { .expect("a blocking request"); assert_eq!(asked!(a), asked!(b)); } + + /// A token that never arrives fails the attempt at the bound, with the + /// bound in the message, instead of hanging the connection attempt. One that + /// does arrive is presented, and the caller's own `Err` is passed on. + #[tokio::test(start_paused = true)] + async fn a_token_that_never_arrives_fails_the_attempt_at_the_bound() { + let started = tokio::time::Instant::now(); + // The outer bound turns a missing one into a failure, not a hang. + let err = + tokio::time::timeout(CALLER_TOKEN_TIMEOUT * 2, token_auth(std::future::pending())) + .await + .expect("returned by itself, at its own bound") + .err() + .expect("no token ever came"); + assert_eq!(started.elapsed(), CALLER_TOKEN_TIMEOUT); + assert!(err.to_string().contains("did not arrive"), "{err}"); + + let auth = token_auth(std::future::ready(Ok("t".to_owned()))) + .await + .expect("a token that arrives"); + assert_eq!(auth.token.as_deref(), Some("t")); + let err = token_auth(std::future::ready(Err("no secret".to_owned()))) + .await + .err() + .expect("the caller's own error"); + assert!(err.to_string().contains("no secret"), "{err}"); + } + + /// A token that arrives after the ten seconds the callers bound their own + /// store read at is still presented: the bound here sits above theirs, so + /// their fallback to the held secret runs first and this one never races + /// it. + #[tokio::test(start_paused = true)] + async fn a_token_that_arrives_just_after_a_callers_bound_is_still_presented() { + let late = async { + tokio::time::sleep( + std::time::Duration::from_secs(10) + std::time::Duration::from_millis(1), + ) + .await; + Ok("t".to_owned()) + }; + let auth = token_auth(late).await.expect("arrived before the bound"); + assert_eq!(auth.token.as_deref(), Some("t")); + } + + /// A shared buffer a test's `tracing` output goes to. + #[derive(Clone, Default)] + struct Logged(Arc>>); + + impl std::io::Write for Logged { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().expect("unpoisoned").extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Logged { + type Writer = Logged; + fn make_writer(&'a self) -> Logged { + self.clone() + } + } + + /// A body that can't be read is logged with the status and the read + /// error, and reads as empty, so the parse still reports the status; a + /// body that reads is passed through and logs nothing. + #[test] + fn a_body_that_cannot_be_read_is_logged_with_its_status() { + let logged = Logged::default(); + let subscriber = tracing_subscriber::fmt() + .with_writer(logged.clone()) + .with_ansi(false) + .finish(); + let (unreadable, readable) = tracing::subscriber::with_default(subscriber, || { + ( + body_text( + reqwest::StatusCode::BAD_GATEWAY, + Err::("connection reset"), + ), + body_text(reqwest::StatusCode::OK, Ok::<_, String>("{}".to_owned())), + ) + }); + assert_eq!(unreadable, ""); + assert_eq!(readable, "{}"); + let log = String::from_utf8(logged.0.lock().expect("unpoisoned").clone()).expect("utf8"); + assert!(log.contains("502"), "no status in {log:?}"); + assert!(log.contains("connection reset"), "no error in {log:?}"); + assert_eq!(log.lines().count(), 1, "{log:?}"); + } }