use super::manager::CodexAuth; use super::manager::ExternalAuth; use super::manager::ExternalAuthFuture; use super::manager::ExternalAuthRefreshContext; use codex_protocol::config_types::ModelProviderAuthInfo; use std::collections::HashMap; use std::ffi::OsString; use std::fmt; use std::io; use std::ops::Deref; use std::path::Path; use std::path::PathBuf; use std::process::Stdio; use std::sync::Arc; use std::time::Instant; use tokio::process::Command; use tokio::sync::Mutex; #[derive(Clone)] pub(crate) struct BearerTokenRefresher { state: Arc, } impl BearerTokenRefresher { pub(crate) fn new(config: ModelProviderAuthInfo, env: HashMap) -> Self { Self { state: Arc::new(ExternalBearerAuthState::new(config, env)), } } #[expect( clippy::await_holding_invalid_type, reason = "external bearer cache misses intentionally hold cached_token across the provider command to avoid duplicate refreshes" )] async fn resolve(&self) -> io::Result { let access_token = { let mut cached = self.state.cached_token.lock().await; if let Some(cached_token) = cached.as_ref() { let should_use_cached_token = match self.state.config.refresh_interval() { Some(refresh_interval) => cached_token.fetched_at.elapsed() < refresh_interval, None => true, }; if should_use_cached_token { return Ok(CodexAuth::from_api_key(cached_token.access_token.as_str())); } } let access_token = run_provider_auth_command(&self.state.config, &self.state.env).await?; *cached = Some(CachedExternalBearerToken { access_token: access_token.clone(), fetched_at: Instant::now(), }); access_token }; Ok(CodexAuth::from_api_key(access_token.as_str())) } async fn refresh(&self, _context: ExternalAuthRefreshContext) -> io::Result { let access_token = run_provider_auth_command(&self.state.config, &self.state.env).await?; let mut cached = self.state.cached_token.lock().await; *cached = Some(CachedExternalBearerToken { access_token: access_token.clone(), fetched_at: Instant::now(), }); Ok(CodexAuth::from_api_key(access_token.as_str())) } } impl ExternalAuth for BearerTokenRefresher { fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> { Box::pin(BearerTokenRefresher::resolve(self)) } fn refresh(&self, context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> { Box::pin(BearerTokenRefresher::refresh(self, context)) } } impl fmt::Debug for BearerTokenRefresher { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("BearerTokenRefresher") .finish_non_exhaustive() } } struct ExternalBearerAuthState { config: ModelProviderAuthInfo, env: HashMap, cached_token: Mutex>, } impl ExternalBearerAuthState { fn new(config: ModelProviderAuthInfo, env: HashMap) -> Self { Self { config, env, cached_token: Mutex::new(None), } } } struct CachedExternalBearerToken { access_token: String, fetched_at: Instant, } async fn run_provider_auth_command( config: &ModelProviderAuthInfo, env: &HashMap, ) -> io::Result { let program = resolve_provider_auth_program(&config.command, &config.cwd)?; let mut command = Command::from(codex_utils_process::background_command(&program)); command .args(config.args.iter().map(Deref::deref)) .envs(env) .current_dir(config.cwd.as_path()) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .kill_on_drop(true); let output = tokio::time::timeout(config.timeout(), command.output()) .await .map_err(|_| { io::Error::other(format!( "provider auth command `{}` timed out after {} ms", config.command, config.timeout_ms.get() )) })? .map_err(|err| { io::Error::new( err.kind(), format!( "provider auth command `{}` failed to start: {err}", config.command ), ) })?; if !output.status.success() { let status = output.status; let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string(); let stderr_suffix = if stderr.is_empty() { String::new() } else { format!(": {stderr}") }; return Err(io::Error::other(format!( "provider auth command `{}` exited with status {status}{stderr_suffix}", config.command ))); } let stdout = String::from_utf8(output.stdout).map_err(|_| { io::Error::other(format!( "provider auth command `{}` wrote non-UTF-8 data to stdout", config.command )) })?; let access_token = stdout.trim().to_string(); if access_token.is_empty() { return Err(io::Error::other(format!( "provider auth command `{}` produced an empty token", config.command ))); } Ok(access_token) } fn resolve_provider_auth_program(command: &str, cwd: &Path) -> io::Result { let path = Path::new(command); if path.is_absolute() { return Ok(path.to_path_buf()); } if path.components().count() > 1 { return Ok(cwd.join(path)); } Ok(PathBuf::from(command)) }