Skip to main content

vtcode_config/
api_keys.rs

1//! API key management module for secure retrieval from environment variables,
2//! .env files, and configuration files.
3//!
4//! This module provides a unified interface for retrieving API keys for different providers,
5//! prioritizing security by checking environment variables first, then .env files, and finally
6//! falling back to configuration file values.
7//!
8//! The facade owns provider/key identity and discovery. Source precedence,
9//! storage migration, and credential material stay behind the private
10//! `credential_resolution` boundary.
11
12use anyhow::Result;
13use std::str::FromStr;
14
15use crate::auth::CredentialIdentity;
16use crate::constants::defaults;
17use crate::models::Provider;
18
19mod credential_resolution;
20
21pub use credential_resolution::{
22    CredentialSource, ResolvedCredential, clear_credential_with_mode, get_api_key, get_api_key_in_workspace_with_mode,
23    get_api_key_with_mode, load_stored_api_key_with_mode, load_stored_credential_with_mode, resolve_credential,
24    resolve_credential_with_mode, resolve_openai_api_key_for_auth, store_credential_with_mode,
25};
26
27/// API key sources for different providers
28///
29/// Retained for backward compatibility. New code should use [`get_api_key`] directly —
30/// the struct is no longer consumed by the key resolution logic.
31#[derive(Debug, Clone, Default)]
32pub struct ApiKeySources {
33    gemini_env: String,
34    anthropic_env: String,
35    openai_env: String,
36    openrouter_env: String,
37    deepseek_env: String,
38    zai_env: String,
39    ollama_env: String,
40    lmstudio_env: String,
41    gemini_config: Option<String>,
42    anthropic_config: Option<String>,
43    openai_config: Option<String>,
44    openrouter_config: Option<String>,
45    deepseek_config: Option<String>,
46    zai_config: Option<String>,
47    ollama_config: Option<String>,
48    lmstudio_config: Option<String>,
49}
50
51pub fn api_key_env_var(provider: &str) -> String {
52    let trimmed = provider.trim();
53    if trimmed.is_empty() {
54        return defaults::DEFAULT_API_KEY_ENV.to_owned();
55    }
56
57    if trimmed.eq_ignore_ascii_case("codex") {
58        return String::new();
59    }
60
61    if let Ok(resolved) = Provider::from_str(trimmed)
62        && resolved.uses_managed_auth()
63    {
64        return String::new();
65    }
66
67    Provider::from_str(trimmed)
68        .map(|resolved| resolved.default_api_key_env().to_owned())
69        .unwrap_or_else(|_| {
70            let mut key = String::new();
71            for ch in trimmed.chars() {
72                if ch.is_ascii_alphanumeric() {
73                    key.push(ch.to_ascii_uppercase());
74                } else if !key.ends_with('_') {
75                    key.push('_');
76                }
77            }
78            if key.chars().next().is_some_and(|ch| ch.is_ascii_digit()) {
79                key.insert(0, '_');
80            }
81            if !key.ends_with("_API_KEY") {
82                if !key.ends_with('_') {
83                    key.push('_');
84                }
85                key.push_str("API_KEY");
86            }
87            key
88        })
89}
90
91pub fn resolve_api_key_env(provider: &str, configured_env: &str) -> String {
92    let trimmed = configured_env.trim();
93    if trimmed.is_empty() || trimmed.eq_ignore_ascii_case(defaults::DEFAULT_API_KEY_ENV) {
94        api_key_env_var(provider)
95    } else {
96        trimmed.to_owned()
97    }
98}
99
100/// Whether `env_key` is a known default API-key variable belonging to another
101/// provider. `agent.api_key_env` is agent-wide, so a provider switch performed
102/// outside the model picker (manual config edit, another surface) can leave a
103/// concrete foreign default behind; using it presents provider A's key to B.
104fn is_foreign_provider_api_key_env(provider: &str, env_key: &str) -> bool {
105    let Some(canonical) = static_env_var(env_key) else {
106        return false;
107    };
108    if canonical.eq_ignore_ascii_case(&api_key_env_var(provider)) {
109        return false;
110    }
111    // Some providers accept an alternate name that is another provider's
112    // default (GOOGLE_API_KEY for Gemini, for example). Keep those.
113    if let Ok(active) = provider.parse::<Provider>()
114        && alternate_env_var(active).is_some_and(|alternate| alternate.eq_ignore_ascii_case(canonical))
115    {
116        return false;
117    }
118    true
119}
120
121/// Resolve the agent-wide API-key env fallback for a provider.
122///
123/// Unlike [`resolve_api_key_env`], a concrete value that is another known
124/// provider's default is treated as a stale provider-switch remnant and is
125/// replaced by the active provider's default. Genuinely custom names and the
126/// active provider's own accepted names still win. Explicit CLI and
127/// provider-scoped overrides must keep using [`resolve_api_key_env`] so their
128/// intent is never second-guessed.
129pub fn resolve_agent_api_key_env(provider: &str, configured_env: &str) -> String {
130    let trimmed = configured_env.trim();
131    if trimmed.is_empty()
132        || trimmed.eq_ignore_ascii_case(defaults::DEFAULT_API_KEY_ENV)
133        || is_foreign_provider_api_key_env(provider, trimmed)
134    {
135        api_key_env_var(provider)
136    } else {
137        trimmed.to_owned()
138    }
139}
140
141/// Build the normalized identity used by credential storage for a provider
142/// and an optional configured environment-variable name.
143pub fn credential_identity(provider: &str, key_name: &str) -> Result<Option<CredentialIdentity>> {
144    let default_key_name = api_key_env_var(provider);
145    let requested_key_name = if key_name.trim().is_empty() {
146        default_key_name
147    } else {
148        key_name.trim().to_owned()
149    };
150    if requested_key_name.is_empty() {
151        return Ok(None);
152    }
153    CredentialIdentity::new(provider, &requested_key_name).map(Some)
154}
155
156/// Return the stable configuration metadata key for a provider/key identity.
157pub fn credential_metadata_key(provider: &str, key_name: &str) -> Result<Option<String>> {
158    Ok(credential_identity(provider, key_name)?
159        .map(|identity| format!("{}/{}", identity.provider(), identity.key_name())))
160}
161
162fn read_env_var(key: &str) -> Option<String> {
163    crate::env_helpers::read_env_var(key)
164}
165
166/// Retained for compatibility. Workspace credentials are read on demand and
167/// are never imported into the process environment.
168#[deprecated(since = "0.180.6", note = "workspace `.env` is never imported; this is a no-op")]
169pub fn load_dotenv() -> Result<()> {
170    Ok(())
171}
172
173/// A provider with a discoverable credential — ready to use without prompting
174/// the user to paste a key.
175#[derive(Debug, Clone, Copy)]
176pub struct DiscoveredProvider {
177    pub provider: Provider,
178    pub source: CredentialSource,
179    /// The specific environment variable that satisfied discovery, when
180    /// `source == Env`. Carries the *alternate* name (e.g. `GOOGLE_API_KEY`)
181    /// when discovery used the alternate rather than the primary env var, so
182    /// the UI can tell the user exactly what was read — e.g. "Found
183    /// GOOGLE_API_KEY in your environment" instead of a generic "found in
184    /// environment". `None` for non-env sources and for providers with no env
185    /// var (local / managed-auth).
186    pub env_var: Option<&'static str>,
187}
188
189/// Determine whether a single built-in provider has a usable credential right
190/// now, and the full detail of where it came from. Returns `None` when no
191/// credential is found.
192///
193/// Mirrors the resolution order of [`get_api_key`]: env var (including
194/// provider-specific alternate env vars) → OAuth session → secure storage.
195/// Local and managed-auth providers are always considered ready.
196///
197/// Prefer this over [`provider_credential_source`] when you need to surface
198/// *which* env var was read (e.g. the first-run wizard and `api_key_hint`).
199pub fn provider_credential_detail(provider: Provider) -> Option<DiscoveredProvider> {
200    provider_credential_detail_with_mode(provider, crate::auth::AuthCredentialsStoreMode::default())
201}
202
203/// Determine whether a provider has a usable credential using `storage_mode`.
204pub fn provider_credential_detail_with_mode(
205    provider: Provider,
206    storage_mode: crate::auth::AuthCredentialsStoreMode,
207) -> Option<DiscoveredProvider> {
208    provider_credential_detail_in_workspace_with_mode(provider, None, storage_mode)
209}
210
211/// Workspace-aware [`provider_credential_detail_with_mode`]: pass the turn's
212/// workspace so a workspace `.env` credential wins over secure storage, the
213/// same order the turn's own resolution used. Auth-failure guidance needs
214/// this to name the rejected key's actual source.
215pub fn provider_credential_detail_in_workspace_with_mode(
216    provider: Provider,
217    workspace: Option<&std::path::Path>,
218    storage_mode: crate::auth::AuthCredentialsStoreMode,
219) -> Option<DiscoveredProvider> {
220    if provider.is_local() {
221        return Some(DiscoveredProvider {
222            provider,
223            source: CredentialSource::Local,
224            env_var: None,
225        });
226    }
227    if provider.uses_managed_auth() {
228        return Some(DiscoveredProvider {
229            provider,
230            source: CredentialSource::ManagedAuth,
231            env_var: None,
232        });
233    }
234
235    let resolved =
236        resolve_credential_with_mode(provider.as_ref(), provider.default_api_key_env(), workspace, storage_mode)
237            .ok()??;
238    if matches!(resolved.source, CredentialSource::SecureStorage)
239        || matches!(resolved.source, CredentialSource::Env | CredentialSource::Workspace | CredentialSource::OAuth)
240    {
241        return Some(DiscoveredProvider {
242            provider,
243            source: resolved.source,
244            env_var: resolved.env_var.as_deref().and_then(static_env_var),
245        });
246    }
247
248    None
249}
250
251/// Thin wrapper over [`provider_credential_detail`] that returns only the
252/// credential source. Kept for backward compatibility with callers that don't
253/// need the env-var detail.
254pub fn provider_credential_source(provider: Provider) -> Option<CredentialSource> {
255    provider_credential_detail(provider).map(|detail| detail.source)
256}
257
258/// Scan all built-in providers and return those with a discoverable credential.
259///
260/// "Discoverable" means the provider can be used right now without the user
261/// pasting a key: the env var is set (shell export or loaded `.env`), a key is
262/// in secure storage, an OAuth session is active, auth is managed by an
263/// external CLI, or the provider is local and needs no key.
264///
265/// Results follow `Provider::all_providers()` order. This does not consult
266/// `vtcode.toml` custom providers — the first-run wizard runs before a config
267/// exists. Runtime custom-provider auth is handled by `resolve_runtime_provider_auth`.
268pub fn discover_available_providers() -> Vec<DiscoveredProvider> {
269    discover_available_providers_with_mode(crate::auth::AuthCredentialsStoreMode::default())
270}
271
272/// Scan all built-in providers using the configured secure-storage backend.
273pub fn discover_available_providers_with_mode(
274    storage_mode: crate::auth::AuthCredentialsStoreMode,
275) -> Vec<DiscoveredProvider> {
276    Provider::all_providers()
277        .into_iter()
278        .filter_map(|provider| provider_credential_detail_with_mode(provider, storage_mode))
279        .collect()
280}
281
282/// Look up a provider in a discovery snapshot.
283pub fn find_discovered(discovered: &[DiscoveredProvider], provider: Provider) -> Option<&DiscoveredProvider> {
284    discovered.iter().find(|entry| entry.provider == provider)
285}
286
287/// Check whether any provider in the slice has an OAuth session or managed auth.
288///
289/// Used by secret-management UIs to decide whether to show the generic
290/// `secret add/delete` hints or the OAuth-specific `login` hint.
291pub fn has_oauth_or_managed_auth(discovered: &[DiscoveredProvider]) -> bool {
292    discovered
293        .iter()
294        .any(|entry| matches!(entry.source, CredentialSource::OAuth | CredentialSource::ManagedAuth))
295}
296
297fn static_env_var(env_key: &str) -> Option<&'static str> {
298    Provider::all_providers()
299        .into_iter()
300        .find(|provider| provider.default_api_key_env().eq_ignore_ascii_case(env_key))
301        .map(|provider| provider.default_api_key_env())
302        .or(match env_key {
303            "GOOGLE_API_KEY" => Some("GOOGLE_API_KEY"),
304            "DASHSCOPE_API_KEY" => Some("DASHSCOPE_API_KEY"),
305            "MODEL_API_KEY" => Some("MODEL_API_KEY"),
306            _ => None,
307        })
308}
309
310/// Alternate env var names that `get_api_key` accepts for a provider.
311fn alternate_env_var(provider: Provider) -> Option<&'static str> {
312    match provider {
313        Provider::Gemini => Some("GOOGLE_API_KEY"),
314        Provider::Qwen => Some("DASHSCOPE_API_KEY"),
315        Provider::Meta => Some("MODEL_API_KEY"),
316        _ => None,
317    }
318}
319
320#[cfg(test)]
321fn test_storage_lookup_is_overridden(key_name: &str) -> bool {
322    crate::env_helpers::test_env_overrides::is_overridden(key_name)
323}
324
325#[cfg(test)]
326mod tests;