Skip to main content

session_core/
stored_auth.rs

1//! The auth.json credential a request uses (`resolveProviderAuth` over the composed provider auth of
2//! `provider-composer.ts`): a stored credential owns its provider. An `api_key` credential's key (its `$VAR` template
3//! resolved against the credential's `env`, then the environment) wins over the models.json `apiKey` and the
4//! environment; a credential without a usable key falls back to the built-in provider's environment key (a custom
5//! provider has none). An `oauth` credential gives its access token, refreshed under the store's lock when it expires
6//! within five minutes, for the providers with an OAuth handler; any other credential type leaves the provider
7//! unconfigured (no environment fallback).
8
9use crate::RunEnv as Env;
10use ai::auth::{AuthContext, AuthOverrides, FileCredentialStore, ProviderAuth};
11use serde_json::Value;
12use std::path::PathBuf;
13use std::sync::Arc;
14
15/// What auth.json says about one provider's request key.
16#[derive(Debug, PartialEq)]
17pub enum Stored {
18    /// No credential stored: models.json and the environment decide.
19    Nothing,
20    /// The credential owns the provider: this key, or none at all.
21    Owns(Option<String>),
22}
23
24/// The stored credential of `provider` in the profile's auth.json. A file that is not JSON fails the request the
25/// way the TypeScript store's read does.
26pub fn stored_key(env: &Env, provider: &str) -> Result<Stored, String> {
27    let path = config::paths::AgentPaths::new(env.agent_dir()).auth();
28    let Ok(text) = std::fs::read_to_string(&path) else {
29        return Ok(Stored::Nothing);
30    };
31    let data = config::json::parse(&text).map_err(|e| format!("Credential store read failed for {provider}: {e}"))?;
32    let Some(credential) = data.get(provider).filter(|c| !c.is_null()).cloned() else {
33        return Ok(Stored::Nothing);
34    };
35    match credential.get("type").and_then(Value::as_str) {
36        Some("api_key") => {
37            let var = env.var.clone();
38            let resolved = config::auth::resolve_stored_api_key(credential, &move |name: &str| var(name))
39                .map_err(|e| format!("Credential store read failed for {provider}: {e}"))?;
40            let key = resolved
41                .as_ref()
42                .and_then(|c| c.get("key"))
43                .and_then(Value::as_str)
44                .filter(|k| !k.is_empty())
45                .map(str::to_string);
46            // `envApiKeyAuth.resolve`: no stored key, so the built-in provider's ambient key; a custom provider
47            // (no inherited auth) is not configured. The credential's own `env` counts first (a Bedrock AWS-profile
48            // or Vertex project/location login stores only that).
49            let builtin = ai::models::builtin_providers().any(|p| p == provider)
50                || crate::lane::registry(env).radius_gateway(provider).is_some();
51            let stored_env = string_map(resolved.as_ref().and_then(|c| c.get("env")));
52            Ok(Stored::Owns(key.or_else(|| {
53                builtin
54                    .then(|| crate::lane::env_api_key_over(env, provider, &stored_env))
55                    .flatten()
56            })))
57        }
58        Some("oauth") => oauth_auth(env, provider, path, None, &OAuthOptions::for_env(env))
59            .map(|auth| Stored::Owns(auth.and_then(|a| a.api_key))),
60        _ => Ok(Stored::Owns(None)),
61    }
62}
63
64/// The credential of `provider`'s stored OAuth credential (`getAuthCredential`: its key or bearer token), refreshed when it has less than `min_validity_ms` (five
65/// minutes by default) left; `None` when nothing usable is stored.
66pub fn oauth_access(env: &Env, provider: &str, min_validity_ms: Option<f64>) -> Result<Option<String>, String> {
67    oauth_access_with(env, provider, min_validity_ms, &OAuthOptions::for_env(env))
68}
69
70/// [`oauth_access`] over `options` (the transport token refreshes go through).
71pub fn oauth_access_with(
72    env: &Env,
73    provider: &str,
74    min_validity_ms: Option<f64>,
75    options: &OAuthOptions,
76) -> Result<Option<String>, String> {
77    let path = config::paths::AgentPaths::new(env.agent_dir()).auth();
78    Ok(oauth_auth(env, provider, path, min_validity_ms, options)?.and_then(|auth| credential_of(&auth)))
79}
80
81/// `getAuthCredential`: the API key, else the token of an `Authorization: Bearer` header (Kimi's OAuth auth).
82fn credential_of(auth: &ai::auth::ModelAuth) -> Option<String> {
83    if let Some(key) = auth.api_key.as_ref().filter(|k| !k.is_empty()) {
84        return Some(key.clone());
85    }
86    let header = auth
87        .headers
88        .iter()
89        .flatten()
90        .find(|(name, _)| name.eq_ignore_ascii_case("authorization"))
91        .and_then(|(_, value)| value.clone())?;
92    let (scheme, token) = header.split_once(char::is_whitespace)?;
93    let token = token.trim_start();
94    (scheme.eq_ignore_ascii_case("bearer") && !token.is_empty()).then(|| token.to_string())
95}
96
97/// What a stored OAuth credential adds to a request beyond its key (`ModelAuth`): the base URL it names (GitHub
98/// Copilot's token proxy endpoint, else its enterprise or individual endpoint) and its headers (Kimi For Coding's
99/// `Authorization: Bearer <access>`), refreshed first when the token expires soon; `None` for any other credential.
100pub fn oauth_request_auth(env: &Env, provider: &str) -> Option<ai::model_registry::StoredRequestAuth> {
101    let path = config::paths::AgentPaths::new(env.agent_dir()).auth();
102    let stored = config::auth::read_stored_credential(&path, provider)?;
103    if stored.get("type").and_then(Value::as_str) != Some("oauth") {
104        return None;
105    }
106    let auth = oauth_auth(env, provider, path, None, &OAuthOptions::for_env(env))
107        .ok()
108        .flatten()?;
109    Some(ai::model_registry::StoredRequestAuth {
110        base_url: auth.base_url,
111        headers: auth.headers,
112        env: None,
113    })
114}
115
116/// What `provider`'s resolved auth adds to each request beyond its key: a stored OAuth credential's base URL and
117/// headers ([`oauth_request_auth`]), else the api-key auth's headers and env ([`api_key_request_auth`]).
118pub fn request_auth(env: &Env, provider: &str) -> Option<ai::model_registry::StoredRequestAuth> {
119    if let Some(oauth) = oauth_request_auth(env, provider) {
120        return Some(oauth);
121    }
122    let result = api_key_request_auth(env, provider).ok().flatten()?;
123    let request = ai::model_registry::StoredRequestAuth {
124        base_url: None,
125        headers: result.auth.headers,
126        env: result.env.map(|env| env.into_iter().collect()),
127    };
128    (request.headers.is_some() || request.env.is_some()).then_some(request)
129}
130
131/// Whether requests of `provider` need [`request_auth`]: a stored OAuth credential, a provider whose api-key auth
132/// adds headers or env (Anthropic, Vertex, Cloudflare), or a stored api-key credential with an `env`.
133pub fn has_request_auth(env: &Env, provider: &str) -> bool {
134    if ai::auth::builtin_api_key_auth(provider).is_some() {
135        return true;
136    }
137    let path = config::paths::AgentPaths::new(env.agent_dir()).auth();
138    config::auth::read_stored_credential(&path, provider).is_some_and(|c| match c.get("type").and_then(Value::as_str) {
139        Some("oauth") => true,
140        Some("api_key") => c.get("env").and_then(Value::as_object).is_some_and(|e| !e.is_empty()),
141        _ => false,
142    })
143}
144
145/// Whether `provider` authenticates by headers alone with no key (`ANTHROPIC_AUTH_TOKEN`'s bearer, the AI Gateway's
146/// `cf-aig-authorization`): its requests carry no API key, and they need none.
147pub fn header_owned(env: &Env, provider: &str) -> bool {
148    api_key_request_auth(env, provider)
149        .ok()
150        .flatten()
151        .is_some_and(|result| {
152            result.auth.api_key.is_none() && result.auth.headers.iter().flatten().any(|(_, value)| value.is_some())
153        })
154}
155
156/// The request key of a provider whose built-in api-key auth decides it (Anthropic: a stored or models.json key,
157/// else `ANTHROPIC_AUTH_TOKEN` with no key, else `ANTHROPIC_OAUTH_TOKEN`/`ANTHROPIC_API_KEY`; Cloudflare: the
158/// Workers AI key, none for the AI Gateway, and no key at all, so not configured, without the account or gateway
159/// id); `None` for every other provider and when a stored OAuth credential owns the provider.
160pub fn resolved_key(env: &Env, provider: &str) -> Result<Option<Option<String>>, String> {
161    if !matches!(
162        provider,
163        "anthropic" | "cloudflare-workers-ai" | "cloudflare-ai-gateway"
164    ) {
165        return Ok(None);
166    }
167    let path = config::paths::AgentPaths::new(env.agent_dir()).auth();
168    if config::auth::read_stored_credential(&path, provider)
169        .filter(|c| !c.is_null())
170        .is_some_and(|c| c.get("type").and_then(Value::as_str) != Some("api_key"))
171    {
172        return Ok(None);
173    }
174    // An unreadable auth.json fails the request as the store's read does.
175    stored_key(env, provider)?;
176    Ok(Some(api_key_request_auth(env, provider)?.and_then(|r| r.auth.api_key)))
177}
178
179/// `composeApiKeyAuth(...).resolve` (provider-composer.ts) for one request: the stored api-key credential (its key
180/// template resolved, with its `env`), else the models.json `apiKey` as the credential's key, else none, resolved by
181/// the provider's built-in api-key auth ([`ai::auth::builtin_api_key_auth`]), or for any other provider the stored
182/// key with the credential's `env`. `None` when a stored OAuth (or other) credential owns the provider or nothing
183/// resolves.
184pub fn api_key_request_auth(env: &Env, provider: &str) -> Result<Option<ai::auth::AuthResult>, String> {
185    let path = config::paths::AgentPaths::new(env.agent_dir()).auth();
186    let stored = config::auth::read_stored_credential(&path, provider).filter(|c| !c.is_null());
187    let credential = match stored {
188        Some(credential) if credential.get("type").and_then(Value::as_str) == Some("api_key") => {
189            let var = env.var.clone();
190            let resolved = config::auth::resolve_stored_api_key(credential, &move |name: &str| var(name))
191                .map_err(|e| format!("Credential store read failed for {provider}: {e}"))?
192                .unwrap_or(Value::Null);
193            Some(ai::auth::ApiKeyCredential {
194                key: resolved.get("key").and_then(Value::as_str).map(str::to_string),
195                env: resolved.get("env").and_then(Value::as_object).map(|env| {
196                    env.iter()
197                        .filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string())))
198                        .collect()
199                }),
200            })
201        }
202        Some(_) => return Ok(None),
203        None => crate::lane::registry(env)
204            .api_key(provider, None, &*env.var, None)?
205            .map(|key| ai::auth::ApiKeyCredential {
206                key: Some(key),
207                env: None,
208            }),
209    };
210    let Some(auth) = ai::auth::builtin_api_key_auth(provider) else {
211        return Ok(credential.and_then(|c| {
212            let key = c.key.filter(|k| !k.is_empty())?;
213            Some(ai::auth::AuthResult {
214                auth: ai::auth::ModelAuth {
215                    api_key: Some(key),
216                    ..Default::default()
217                },
218                env: c.env,
219                source: Some("stored credential".into()),
220            })
221        }));
222    };
223    let ctx = EnvContext(env.clone());
224    ready(auth.resolve(&ctx, credential.as_ref()))
225        .unwrap_or_else(|| Err(format!("API key auth for {provider} did not resolve at once")))
226}
227
228/// The string members of a credential's `env` object.
229fn string_map(value: Option<&Value>) -> std::collections::HashMap<String, String> {
230    value
231        .and_then(Value::as_object)
232        .map(|env| {
233            env.iter()
234                .filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string())))
235                .collect()
236        })
237        .unwrap_or_default()
238}
239
240/// The value of a future that is ready on its first poll (the built-in api-key auths read only the environment and
241/// the file system); `None` when it is not.
242fn ready<T>(future: impl std::future::Future<Output = T>) -> Option<T> {
243    let mut future = std::pin::pin!(future);
244    match future
245        .as_mut()
246        .poll(&mut std::task::Context::from_waker(std::task::Waker::noop()))
247    {
248        std::task::Poll::Ready(value) => Some(value),
249        std::task::Poll::Pending => None,
250    }
251}
252
253/// How an OAuth handler reaches its provider: the transport, and the port a browser login's callback server listens
254/// on instead of the registered one (`Some(0)`: any free port; tests).
255#[derive(Clone)]
256pub struct OAuthOptions {
257    pub transport: Arc<dyn ai::Transport>,
258    pub callback_port: Option<u16>,
259}
260
261impl OAuthOptions {
262    /// The options of a run in `env`: its proxies (`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`) reach the providers.
263    pub fn for_env(env: &Env) -> OAuthOptions {
264        OAuthOptions {
265            transport: Arc::new(ai::ReqwestTransport::for_env(&*env.var, None)),
266            callback_port: None,
267        }
268    }
269}
270
271impl Default for OAuthOptions {
272    fn default() -> Self {
273        OAuthOptions {
274            transport: Arc::new(ai::ReqwestTransport::new(None)),
275            callback_port: None,
276        }
277    }
278}
279
280/// The OAuth handler of `provider` over `options`: a built-in provider's, or Radius's on the provider's gateway (the
281/// built-in `radius`, or a models.json provider with `"oauth": "radius"`); every provider TypeScript signs in with an
282/// account (Anthropic, OpenAI Codex, GitHub Copilot, xAI, Kimi For Coding, Meta, OpenRouter, Radius).
283pub fn oauth_handler_with(env: &Env, provider: &str, options: &OAuthOptions) -> Option<Arc<dyn ai::auth::OAuthAuth>> {
284    let transport = options.transport.clone();
285    let clock = ai::oauth_flow::system_clock;
286    if let Some((name, gateway)) = crate::lane::registry(env).radius_gateway(provider) {
287        let mut radius = ai::oauth_radius::RadiusOAuth::new(&name, &gateway, transport, clock);
288        if let Some(port) = options.callback_port {
289            radius = radius.with_callback_port(port);
290        }
291        return Some(Arc::new(radius));
292    }
293    Some(match provider {
294        "xai" => Arc::new(ai::oauth_xai::XaiOAuth { transport, clock }),
295        "kimi-coding" => Arc::new(ai::oauth_kimi::KimiCodingOAuth { transport, clock }),
296        "meta" => Arc::new(ai::oauth_meta::MetaOAuth { transport, clock }),
297        "openrouter" => Arc::new(ai::oauth_openrouter::OpenRouterOAuth { transport }),
298        _ => Arc::new(ai::auth::BuiltinOAuth {
299            provider: ai::oauth::OAuthProvider::from_id(provider)?,
300            transport,
301            clock,
302            callback_port: options.callback_port,
303        }),
304    })
305}
306
307/// The request auth of a stored OAuth credential (`resolveStoredOAuth`, then `toAuth`: the access token, and a base
308/// URL for some providers), refreshed through the provider's token endpoint when it expires soon. Providers without
309/// an OAuth handler are not configured by it.
310fn oauth_auth(
311    env: &Env,
312    provider: &str,
313    path: PathBuf,
314    min_validity_ms: Option<f64>,
315    options: &OAuthOptions,
316) -> Result<Option<ai::auth::ModelAuth>, String> {
317    let Some(oauth) = oauth_handler_with(env, provider, options) else {
318        return Ok(None);
319    };
320    let auth = ProviderAuth {
321        api_key: None,
322        oauth: Some(oauth),
323    };
324    let ctx = EnvContext(env.clone());
325    let store = FileCredentialStore::new(path);
326    // Callers are synchronous and may sit inside a runtime: the resolution runs on its own thread and runtime.
327    std::thread::scope(|scope| {
328        scope
329            .spawn(|| {
330                let runtime = tokio::runtime::Builder::new_current_thread()
331                    .enable_all()
332                    .build()
333                    .map_err(|e| e.to_string())?;
334                runtime
335                    .block_on(ai::auth::resolve_provider_auth(
336                        provider,
337                        &auth,
338                        &store,
339                        &ctx,
340                        &AuthOverrides {
341                            min_oauth_validity_ms: min_validity_ms,
342                            ..AuthOverrides::default()
343                        },
344                    ))
345                    .map(|result| result.map(|r| r.auth))
346                    .map_err(|e| e.message())
347            })
348            .join()
349            .unwrap_or_else(|_| Err(format!("OAuth auth failed for {provider}")))
350    })
351}
352
353/// The session's environment as the auth context (`defaultProviderAuthContext` over the injected lookup).
354struct EnvContext(Env);
355
356impl AuthContext for EnvContext {
357    fn env(&self, name: &str) -> Option<String> {
358        (self.0.var)(name).filter(|v| !v.trim().is_empty())
359    }
360
361    fn file_exists(&self, path: &str) -> bool {
362        match path.strip_prefix('~') {
363            Some(rest) => PathBuf::from(format!("{}{rest}", self.0.home.display())).exists(),
364            None => PathBuf::from(path).exists(),
365        }
366    }
367}