diff --git a/swarm-agent-verify/src/lib.rs b/swarm-agent-verify/src/lib.rs index 12617a433..0aa74001d 100644 --- a/swarm-agent-verify/src/lib.rs +++ b/swarm-agent-verify/src/lib.rs @@ -100,6 +100,56 @@ impl CredentialSource for Store { } } +impl Store { + /// Logs in once, for the several reads one request makes: reading through + /// the returned [`Connection`] does not log in again, where each + /// [`Store::read_optional`] does. Drop it at the end of the request, so no + /// token is left to expire inside a long-lived process. + /// + /// # Errors + /// + /// When the login fails. + pub async fn connect(&self) -> anyhow::Result { + let store = swarm_secret_client::SecretStore::connect( + &self.settings, + &self.cert_role, + DEFAULT_CERT_MOUNT, + ) + .await + .context("logging in to the secret store")?; + Ok(Connection { store }) + } +} + +/// A logged-in handle on the store, from [`Store::connect`]: any number of +/// reads, one login. +pub struct Connection { + store: swarm_secret_client::SecretStore, +} + +impl Connection { + /// The object at `path`, `None` when nothing is stored there. + /// + /// # Errors + /// + /// When the read fails, or the object does not decode. + pub async fn read_optional( + &self, + path: &str, + ) -> anyhow::Result> { + self.store + .read_optional(path) + .await + .with_context(|| format!("reading {path}")) + } +} + +impl CredentialSource for Connection { + async fn lookup(&self, agent: &str) -> anyhow::Result> { + self.read_optional(&queue::agent_queue_path(agent)?).await + } +} + /// Whether `token`'s secret is the one stored for the agent it names. /// /// The lookup is bounded by `timeout`, after which this denies. diff --git a/swarm-logs-auth/src/main.rs b/swarm-logs-auth/src/main.rs index 14027fc5f..f83224848 100644 --- a/swarm-logs-auth/src/main.rs +++ b/swarm-logs-auth/src/main.rs @@ -98,7 +98,24 @@ trait GrantSource { fn grant(&self, agent: &str) -> impl Future>> + Send; } -impl GrantSource for swarm_agent_verify::Store { +/// Where a request's store connection comes from: logged in once, then used +/// for both reads, the agent's credential and its grant. +trait Connector { + type Conn: CredentialSource + GrantSource; + + /// Logs in to the store. + fn connect(&self) -> impl Future> + Send; +} + +impl Connector for swarm_agent_verify::Store { + type Conn = swarm_agent_verify::Connection; + + async fn connect(&self) -> anyhow::Result { + swarm_agent_verify::Store::connect(self).await + } +} + +impl GrantSource for swarm_agent_verify::Connection { async fn grant(&self, agent: &str) -> anyhow::Result> { self.read_optional(&grant_path(agent)?).await } @@ -114,7 +131,7 @@ struct Responder { /// The answer for one subrequest's `Authorization` header, at `now`. async fn decide( - responder: &Responder, + responder: &Responder, authorization: Option<&str>, now: Instant, ) -> StatusCode { @@ -137,10 +154,27 @@ async fn decide( tracing::debug!(agent = token.agent, "verified recently"); return StatusCode::OK; } - if !swarm_agent_verify::verify(&responder.source, &token, responder.lookup_timeout).await { + // One login for both reads: the credential and the grant. + let conn = + match tokio::time::timeout(responder.lookup_timeout, responder.source.connect()).await { + Ok(Ok(conn)) => conn, + Ok(Err(e)) => { + tracing::warn!( + agent = token.agent, + error = format!("{e:#}"), + "store login failed; denying" + ); + return StatusCode::UNAUTHORIZED; + } + Err(_) => { + tracing::warn!(agent = token.agent, "store login timed out; denying"); + return StatusCode::UNAUTHORIZED; + } + }; + if !swarm_agent_verify::verify(&conn, &token, responder.lookup_timeout).await { return StatusCode::UNAUTHORIZED; } - if !holds_permission(responder, token.agent).await { + if !holds_permission(responder, &conn, token.agent).await { return StatusCode::FORBIDDEN; } tracing::info!(agent = token.agent, surface = ?responder.surface, "verified"); @@ -150,30 +184,33 @@ async fn decide( /// Whether `agent` holds the permission for the surface. A grant that is /// absent, unreadable or slow is not held. -async fn holds_permission(responder: &Responder, agent: &str) -> bool { - let grant = - match tokio::time::timeout(responder.lookup_timeout, responder.source.grant(agent)).await { - Ok(Ok(Some(grant))) => grant, - Ok(Ok(None)) => { - tracing::warn!( - agent, - "no permission grant is mirrored for this agent; denying" - ); - return false; - } - Ok(Err(e)) => { - tracing::warn!( - agent, - error = format!("{e:#}"), - "grant lookup failed; denying" - ); - return false; - } - Err(_) => { - tracing::warn!(agent, "grant lookup timed out; denying"); - return false; - } - }; +async fn holds_permission( + responder: &Responder, + conn: &impl GrantSource, + agent: &str, +) -> bool { + let grant = match tokio::time::timeout(responder.lookup_timeout, conn.grant(agent)).await { + Ok(Ok(Some(grant))) => grant, + Ok(Ok(None)) => { + tracing::warn!( + agent, + "no permission grant is mirrored for this agent; denying" + ); + return false; + } + Ok(Err(e)) => { + tracing::warn!( + agent, + error = format!("{e:#}"), + "grant lookup failed; denying" + ); + return false; + } + Err(_) => { + tracing::warn!(agent, "grant lookup timed out; denying"); + return false; + } + }; let held = responder.surface.allowed_by(grant); if !held { tracing::info!(agent, surface = ?responder.surface, "agent lacks the permission; denying"); @@ -293,6 +330,10 @@ mod tests { revoked: AtomicBool, leaf: Mutex, grant_lookups: AtomicUsize, + /// Store logins, one per `connect`. + logins: AtomicUsize, + /// Whether a login is refused. + login_fails: AtomicBool, } impl Atlas { @@ -302,6 +343,8 @@ mod tests { revoked: AtomicBool::new(false), leaf: Mutex::new(leaf), grant_lookups: AtomicUsize::new(0), + logins: AtomicUsize::new(0), + login_fails: AtomicBool::new(false), } } @@ -341,6 +384,18 @@ mod tests { } } + impl Connector for &Atlas { + type Conn = Self; + + async fn connect(&self) -> anyhow::Result { + self.logins.fetch_add(1, Ordering::SeqCst); + if self.login_fails.load(Ordering::SeqCst) { + anyhow::bail!("store refused the certificate"); + } + Ok(*self) + } + } + impl GrantSource for &Atlas { async fn grant(&self, agent: &str) -> anyhow::Result> { self.grant_lookups.fetch_add(1, Ordering::SeqCst); @@ -451,6 +506,39 @@ mod tests { assert_eq!(store.grant_lookups.load(Ordering::SeqCst), 0); } + /// A request that is not remembered logs in to the store once, and both + /// of its reads (the credential, the grant) go through that login: the + /// store's login is the costly part, and a second one per request doubles + /// the cost of every cold bearer. The remembered one logs in no more. + #[tokio::test] + async fn an_uncached_request_logs_in_once_for_both_reads() { + let store = Atlas::both(); + let r = responder(&store, Surface::Logs); + let t0 = Instant::now(); + assert_eq!(decide(&r, Some(GOOD), t0).await, StatusCode::OK); + assert_eq!(store.logins.load(Ordering::SeqCst), 1); + assert_eq!(store.lookups(), 1); + assert_eq!(store.grant_lookups.load(Ordering::SeqCst), 1); + assert_eq!(decide(&r, Some(GOOD), t0).await, StatusCode::OK); + assert_eq!(store.logins.load(Ordering::SeqCst), 1, "remembered"); + } + + /// A store that refuses the login answers nothing, so the request is + /// denied and neither read is tried. + #[tokio::test] + async fn a_refused_login_is_a_denial_and_reads_nothing() { + let store = Atlas::both(); + store.login_fails.store(true, Ordering::SeqCst); + let r = responder(&store, Surface::Logs); + assert_eq!( + decide(&r, Some(GOOD), Instant::now()).await, + StatusCode::UNAUTHORIZED + ); + assert_eq!(store.logins.load(Ordering::SeqCst), 1); + assert_eq!(store.lookups(), 0); + assert_eq!(store.grant_lookups.load(Ordering::SeqCst), 0); + } + /// An allow is reused within the TTL — a revocation the store already /// holds, of the secret or of the permission, goes unseen — and checked /// against the store again after it.