//! The claude login minter. //! //! Connects to the swarm queue as its own OIDC client, takes an operator's //! login steps from swarm-controller on //! [`swarm_wire::claude_login::SUBJECT`], runs `claude auth login` //! for the agent named ([`login`]), and writes the credentials it produces to //! that agent's store leaf, a new version over any stored before. The agent's //! harness takes a version newer than the one it last installed. //! //! The store identity comes from the `BAO_*` environment. The queue client //! secret is read at start and again when authelia refuses it; the store is //! logged in to afresh for each write. use std::path::PathBuf; use std::sync::Arc; use std::time::Instant; use anyhow::{Context, Result, bail}; use futures_util::StreamExt as _; use metrics::Metrics; use swarm_queue_client::{ClientSecret, QueueConfig}; use swarm_secret_client::claude_login::{Credentials, client_secret_path, credentials_path}; use swarm_secret_client::stored_secret::StoredSecret; use swarm_wire::claude_login::{Reply, Request, SESSION_DEADLINE, STEP_DEADLINE, SUBJECT}; mod login; mod metrics; /// The cert-auth role this service logs in to the store as. `swarm-bao.nix` /// writes it, matching the leaf's subject. const CERT_ROLE: &str = "swarm-claude-login"; /// The environment prefix `swarm-claude-login.nix` sets. const PREFIX: &str = "SWARM_CLAUDE_LOGIN"; /// The agent's store leaf, written under this service's certificate. struct AgentLeaf; impl AgentLeaf { /// When the agent's stored login was written, read from the leaf's /// metadata: this service may say it exists, and never reads it back. async fn status(&self, agent: &str) -> Reply { match self.stored_at(agent).await { Ok(stored_at) => Reply::Login { stored_at }, Err(e) => Reply::Failed { error: format!("reading when {agent}'s login was stored failed: {e:#}"), }, } } async fn stored_at(&self, agent: &str) -> Result> { let path = credentials_path(agent)?; let store = swarm_secret_client::SecretStore::from_env(CERT_ROLE) .await .context("logging in to the secret store")?; store .updated_time(&path) .await .with_context(|| format!("reading the metadata of {path}")) } /// Delete the agent's stored login, every version: an older one would /// still be a live session. The agent's harness sees the leaf gone on its /// next read. async fn delete(&self, agent: &str) -> Reply { match self.delete_all(agent).await { Ok(()) => Reply::Deleted, Err(e) => Reply::Failed { error: format!("deleting {agent}'s stored login failed: {e:#}"), }, } } async fn delete_all(&self, agent: &str) -> Result<()> { let path = credentials_path(agent)?; let store = swarm_secret_client::SecretStore::from_env(CERT_ROLE) .await .context("logging in to the secret store")?; store .delete_all_versions(&path) .await .with_context(|| format!("deleting {path}")) } } impl login::CredentialSink for AgentLeaf { async fn put(&self, agent: &str, credentials: &Credentials) -> Result<()> { let path = credentials_path(agent)?; let store = swarm_secret_client::SecretStore::from_env(CERT_ROLE) .await .context("logging in to the secret store")?; // `write`, not `create`: a relogin replaces what an earlier one // stored. store .write(&path, credentials) .await .with_context(|| format!("writing {path}")) } } #[tokio::main] async fn main() -> Result<()> { let stop = swarm_secret_client::shutdown_signal(); hive_log::init(); swarm_secret_client::install_crypto_provider(); let var = |name: &str| { let full = format!("{PREFIX}_{name}"); std::env::var(&full).with_context(|| format!("{full} is unset")) }; let health = swarm_secret_client::health::Health::from_env( &format!("{PREFIX}_HEALTH_ADDR"), stop.clone(), ) .await?; let client_id = var("OIDC_CLIENT_ID")?; let metrics = Arc::new(Metrics::from_env()); let logins = Arc::new(login::Logins::new( PathBuf::from(var("CLAUDE")?), std::env::temp_dir(), STEP_DEADLINE, )); let secret = swarm_secret_client::read_with_startup_retry("reading the queue client secret", || { client_secret(&client_id) }) .await?; let reread_id = client_id.clone(); let secret = StoredSecret::new(client_id.clone(), secret, move || { let client_id = reread_id.clone(); async move { client_secret(&client_id).await.map_err(Into::into) } }); let queue = swarm_queue_client::connect(QueueConfig { url: var("NATS_URL")?, token_endpoint: var("OIDC_TOKEN_ENDPOINT")?, client_id, client_secret: ClientSecret::Stored(secret), ca_file: std::env::var(format!("{PREFIX}_OIDC_CA_FILE")) .ok() .map(PathBuf::from), }) .await?; swarm_queue_client::ready_when_connected(&health, &queue); // No queue group: a running login lives in this process's memory, so // every step for it has to reach this process. let mut requests = health.beating( queue .subscribe(SUBJECT) .await .with_context(|| format!("subscribing to {SUBJECT}"))? .take_until(stop.clone()), ); tracing::info!(subject = SUBJECT, "claude login minter: awaiting logins"); let mut in_flight = swarm_secret_client::InFlight::new(); while let Some(msg) = requests.next().await { let Some(reply_to) = msg.reply.clone() else { tracing::warn!("a login step arrived with no reply subject; dropping it"); continue; }; let queue = queue.clone(); let logins = Arc::clone(&logins); let metrics = Arc::clone(&metrics); in_flight.spawn(async move { let reply = handle(&msg.payload, &logins, &metrics).await; match serde_json::to_vec(&reply) { Ok(body) => { if let Err(e) = queue.publish(reply_to, body.into()).await { tracing::warn!(error = %e, "publishing a login step's reply failed"); } } Err(e) => tracing::warn!(error = %e, "encoding a login step's reply failed"), } }); } in_flight.drain().await; if stop.peek().is_none() { bail!("the subscription to {SUBJECT} ended"); } Ok(()) } /// Answer one step and count it. async fn handle(payload: &[u8], logins: &Arc, metrics: &Arc) -> Reply { let started = Instant::now(); let (step, reply) = run_step(payload, logins, metrics).await; metrics.step(step, &reply, started.elapsed()); metrics.active(logins.active().await); reply } /// Decode one step, run it and log it, with the kind of step it was. Never /// logs the code or the URL. async fn run_step( payload: &[u8], logins: &Arc, metrics: &Arc, ) -> (&'static str, Reply) { let request: Request = match serde_json::from_slice(payload) { Ok(r) => r, Err(e) => { tracing::warn!(error = %e, "an undecodable login step; answering with the error"); let error = format!("the minter could not decode the request: {e}"); return ("invalid", Reply::Failed { error }); } }; // Before anything else: the name becomes a scratch directory's name and // a store path, and this service holds write and delete on every agent's leaf. let (Request::Start { agent, .. } | Request::Code { agent, .. } | Request::Cancel { agent } | Request::Status { agent } | Request::Delete { agent }) = &request; if let Err(reason) = hive_types::Ident::parse(agent) { tracing::warn!(agent = ?agent, reason, "a login step for an invalid agent name; refused"); let error = format!("{agent:?} is not an agent name: {reason}"); return ("invalid", Reply::Failed { error }); } let (step, agent, reply) = match request { Request::Start { agent, operator } => { tracing::info!(%agent, %operator, "starting a claude login"); let (reply, id) = logins.start(&agent).await; if let Some(id) = id { let logins = Arc::clone(logins); let expiring = agent.clone(); let metrics = Arc::clone(metrics); tokio::spawn(async move { tokio::time::sleep(SESSION_DEADLINE).await; if logins.expire(&expiring, id).await { metrics.expired(); metrics.active(logins.active().await); } }); } ("start", agent, reply) } Request::Code { agent, code } => { let reply = logins.code(&agent, &code, &AgentLeaf).await; ("code", agent, reply) } Request::Cancel { agent } => { let reply = logins.cancel(&agent).await; ("cancel", agent, reply) } Request::Status { agent } => { let reply = AgentLeaf.status(&agent).await; ("status", agent, reply) } Request::Delete { agent } => { tracing::info!(%agent, "deleting the agent's stored claude login"); let reply = AgentLeaf.delete(&agent).await; ("delete", agent, reply) } }; match &reply { Reply::Started { .. } => tracing::info!(%agent, "claude login waiting for its code"), Reply::Stored => tracing::info!(%agent, "claude credentials stored"), Reply::Cancelled => tracing::info!(%agent, "claude login cancelled"), Reply::Login { .. } => {} Reply::Deleted => tracing::info!(%agent, "claude login deleted"), Reply::Failed { error } => tracing::warn!(%agent, %error, "claude login step failed"), } (step, reply) } async fn client_secret(client_id: &str) -> Result { use swarm_secret_client::builder::ClientSecret; let path = client_secret_path(client_id)?; let store = swarm_secret_client::SecretStore::from_env(CERT_ROLE) .await .context("logging in to the secret store")?; let stored: Option = store .read_optional(&path) .await .with_context(|| format!("reading {path}"))?; match stored { Some(s) if !s.value.trim().is_empty() => Ok(s.value.trim().to_owned()), _ => bail!( "nothing at {path}: authelia's mint, in its container, has not \ stored this service's client secret" ), } } #[cfg(test)] mod tests { use std::sync::Arc; use std::time::Duration; use swarm_wire::claude_login::{Reply, Request}; use super::{Metrics, handle, login}; #[tokio::test] async fn a_step_for_an_invalid_agent_name_is_refused_before_anything_is_made() { let root = std::env::temp_dir().join(format!( "swarm-claude-login-test-hostile-{}", std::process::id() )); let _ = std::fs::remove_dir_all(&root); let scratch = root.join("scratch"); std::fs::create_dir_all(&scratch).expect("temp dir"); let logins = Arc::new(login::Logins::new( login::tests::stubs().join("claude"), scratch.clone(), Duration::from_secs(10), )); for agent in ["../escaped", "..", "", "a/b", "Atlas"] { for request in [ Request::Start { agent: agent.to_owned(), operator: "op".to_owned(), }, Request::Code { agent: agent.to_owned(), code: "c".to_owned(), }, Request::Cancel { agent: agent.to_owned(), }, Request::Status { agent: agent.to_owned(), }, Request::Delete { agent: agent.to_owned(), }, ] { let payload = serde_json::to_vec(&request).expect("encodes"); let reply = handle(&payload, &logins, &Arc::new(Metrics::noop())).await; assert!( matches!(reply, Reply::Failed { .. }), "{agent:?}: {reply:?}" ); } let made: Vec<_> = std::fs::read_dir(&root) .expect("root") .map(|e| e.expect("entry").file_name()) .collect(); assert_eq!(made, vec!["scratch"], "{agent:?} made a directory"); assert_eq!( std::fs::read_dir(&scratch).expect("scratch").count(), 0, "{agent:?}" ); } // The control: a valid name starts. let payload = serde_json::to_vec(&Request::Start { agent: "atlas".to_owned(), operator: "op".to_owned(), }) .expect("encodes"); assert!(matches!( handle(&payload, &logins, &Arc::new(Metrics::noop())).await, Reply::Started { .. } )); drop(logins); let _ = std::fs::remove_dir_all(&root); } }