|
| 1 | +//! Cloud AI provider API key storage. |
| 2 | +//! |
| 3 | +//! Delegates to `crate::secrets::store()` for platform-agnostic secret storage so each provider's |
| 4 | +//! key sits in the OS-native secret backend (macOS Keychain, Linux Secret Service, etc.) instead |
| 5 | +//! of `settings.json`. One entry per provider keyed as `ai.apiKey.<providerId>`. |
| 6 | +
|
| 7 | +use crate::secrets::SecretStoreError; |
| 8 | +use log::{debug, info}; |
| 9 | +use serde::{Deserialize, Serialize}; |
| 10 | + |
| 11 | +/// Builds the secret-store key for a given provider id. |
| 12 | +fn store_key(provider_id: &str) -> String { |
| 13 | + format!("ai.apiKey.{provider_id}") |
| 14 | +} |
| 15 | + |
| 16 | +/// Error types surfaced over IPC for AI API key operations. |
| 17 | +#[derive(Debug, Clone, Serialize, Deserialize, specta::Type)] |
| 18 | +#[serde(rename_all = "snake_case", tag = "type", content = "message")] |
| 19 | +pub enum AiApiKeyError { |
| 20 | + NotFound(String), |
| 21 | + AccessDenied(String), |
| 22 | + Other(String), |
| 23 | +} |
| 24 | + |
| 25 | +impl std::fmt::Display for AiApiKeyError { |
| 26 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 27 | + match self { |
| 28 | + Self::NotFound(msg) => write!(f, "AI API key not found: {msg}"), |
| 29 | + Self::AccessDenied(msg) => write!(f, "AI API key access denied: {msg}"), |
| 30 | + Self::Other(msg) => write!(f, "AI API key error: {msg}"), |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +impl std::error::Error for AiApiKeyError {} |
| 36 | + |
| 37 | +impl From<SecretStoreError> for AiApiKeyError { |
| 38 | + fn from(e: SecretStoreError) -> Self { |
| 39 | + match e { |
| 40 | + SecretStoreError::NotFound(msg) => Self::NotFound(msg), |
| 41 | + SecretStoreError::AccessDenied(msg) => Self::AccessDenied(msg), |
| 42 | + SecretStoreError::Other(msg) => Self::Other(msg), |
| 43 | + } |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +/// Saves the API key for a provider. Overwrites any existing entry. Logs at INFO without ever |
| 48 | +/// touching the key value — the *change event* is the actionable signal for postmortem debugging |
| 49 | +/// (when did the key get set? did the save reach the keychain?), the key itself is not. |
| 50 | +pub fn save(provider_id: &str, api_key: &str) -> Result<(), AiApiKeyError> { |
| 51 | + let key = store_key(provider_id); |
| 52 | + let key_len = api_key.len(); |
| 53 | + crate::secrets::store().set(&key, api_key.as_bytes())?; |
| 54 | + info!("AI API key saved for provider {provider_id} ({key_len} bytes)"); |
| 55 | + Ok(()) |
| 56 | +} |
| 57 | + |
| 58 | +/// Returns the stored API key for a provider, or an error if none is stored. |
| 59 | +pub fn get(provider_id: &str) -> Result<String, AiApiKeyError> { |
| 60 | + let key = store_key(provider_id); |
| 61 | + let data = crate::secrets::store().get(&key)?; |
| 62 | + String::from_utf8(data).map_err(|e| AiApiKeyError::Other(format!("Stored key is not valid UTF-8: {e}"))) |
| 63 | +} |
| 64 | + |
| 65 | +/// Deletes the API key for a provider. Returns `Ok(())` even if no entry existed (idempotent). |
| 66 | +pub fn delete(provider_id: &str) -> Result<(), AiApiKeyError> { |
| 67 | + let key = store_key(provider_id); |
| 68 | + match crate::secrets::store().delete(&key) { |
| 69 | + Ok(()) => { |
| 70 | + info!("AI API key deleted for provider {provider_id}"); |
| 71 | + Ok(()) |
| 72 | + } |
| 73 | + Err(SecretStoreError::NotFound(_)) => { |
| 74 | + debug!("AI API key delete for {provider_id} was a no-op (none stored)"); |
| 75 | + Ok(()) |
| 76 | + } |
| 77 | + Err(e) => Err(e.into()), |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +/// Returns true if an API key is stored for the provider. |
| 82 | +pub fn has(provider_id: &str) -> bool { |
| 83 | + get(provider_id).is_ok() |
| 84 | +} |
| 85 | + |
| 86 | +// --- Tauri commands --- |
| 87 | + |
| 88 | +#[tauri::command] |
| 89 | +#[specta::specta] |
| 90 | +pub fn save_ai_api_key(provider_id: String, api_key: String) -> Result<(), AiApiKeyError> { |
| 91 | + save(&provider_id, &api_key) |
| 92 | +} |
| 93 | + |
| 94 | +/// Returns the stored API key for the provider, or an empty string if none is stored. |
| 95 | +/// Returning empty (rather than an error) on missing keys keeps the call sites simple — they all |
| 96 | +/// pass the value through to `configure_ai`, which already treats empty-string as "not configured." |
| 97 | +#[tauri::command] |
| 98 | +#[specta::specta] |
| 99 | +pub fn get_ai_api_key(provider_id: String) -> Result<String, AiApiKeyError> { |
| 100 | + match get(&provider_id) { |
| 101 | + Ok(key) => Ok(key), |
| 102 | + Err(AiApiKeyError::NotFound(_)) => Ok(String::new()), |
| 103 | + Err(e) => Err(e), |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +#[tauri::command] |
| 108 | +#[specta::specta] |
| 109 | +pub fn delete_ai_api_key(provider_id: String) -> Result<(), AiApiKeyError> { |
| 110 | + delete(&provider_id) |
| 111 | +} |
| 112 | + |
| 113 | +#[tauri::command] |
| 114 | +#[specta::specta] |
| 115 | +pub fn has_ai_api_key(provider_id: String) -> bool { |
| 116 | + has(&provider_id) |
| 117 | +} |
| 118 | + |
| 119 | +#[cfg(test)] |
| 120 | +mod tests { |
| 121 | + use super::*; |
| 122 | + use std::sync::atomic::{AtomicU64, Ordering}; |
| 123 | + |
| 124 | + /// Per-test isolation: each test runs in its own data dir so the PlainFileStore's JSON file |
| 125 | + /// doesn't race across nextest's per-test processes (which would share the prod app-support |
| 126 | + /// dir otherwise — secrets `save` succeeds but the subsequent `get` sees another test's write). |
| 127 | + /// |
| 128 | + /// Must be called BEFORE the first secret store access in the test — the secret store backend |
| 129 | + /// is a `LazyLock` and reads these env vars exactly once. |
| 130 | + /// |
| 131 | + /// SAFETY: `std::env::set_var` is racy across threads, but each nextest test runs in its own |
| 132 | + /// process, so the only env-var writes happen here on the test's main thread before any code |
| 133 | + /// that reads them. |
| 134 | + fn isolate_secrets() { |
| 135 | + static COUNTER: AtomicU64 = AtomicU64::new(0); |
| 136 | + let id = COUNTER.fetch_add(1, Ordering::Relaxed); |
| 137 | + let dir = std::env::temp_dir().join(format!("cmdr-api-keys-test-{}-{}", std::process::id(), id)); |
| 138 | + std::fs::create_dir_all(&dir).expect("create test data dir"); |
| 139 | + unsafe { |
| 140 | + std::env::set_var("CMDR_DATA_DIR", &dir); |
| 141 | + std::env::set_var("CMDR_SECRET_STORE", "file"); |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + #[test] |
| 146 | + fn save_and_get_roundtrip() { |
| 147 | + isolate_secrets(); |
| 148 | + save("openai", "sk-test-abc123").unwrap(); |
| 149 | + assert_eq!(get("openai").unwrap(), "sk-test-abc123"); |
| 150 | + } |
| 151 | + |
| 152 | + #[test] |
| 153 | + fn get_missing_returns_not_found() { |
| 154 | + isolate_secrets(); |
| 155 | + match get("openai") { |
| 156 | + Err(AiApiKeyError::NotFound(_)) => {} |
| 157 | + other => panic!("expected NotFound, got {other:?}"), |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + #[test] |
| 162 | + fn has_reflects_save_and_delete() { |
| 163 | + isolate_secrets(); |
| 164 | + assert!(!has("openai")); |
| 165 | + save("openai", "sk-test").unwrap(); |
| 166 | + assert!(has("openai")); |
| 167 | + delete("openai").unwrap(); |
| 168 | + assert!(!has("openai")); |
| 169 | + } |
| 170 | + |
| 171 | + #[test] |
| 172 | + fn delete_missing_is_idempotent() { |
| 173 | + isolate_secrets(); |
| 174 | + delete("openai").unwrap(); |
| 175 | + delete("openai").unwrap(); |
| 176 | + } |
| 177 | + |
| 178 | + #[test] |
| 179 | + fn save_overwrites_existing() { |
| 180 | + isolate_secrets(); |
| 181 | + save("openai", "sk-first").unwrap(); |
| 182 | + save("openai", "sk-second").unwrap(); |
| 183 | + assert_eq!(get("openai").unwrap(), "sk-second"); |
| 184 | + } |
| 185 | +} |
0 commit comments