//! API keys, stored only in the OS keyring (Windows Credential Manager, //! Linux Secret Service) under the service `eu.euvino.callrecorder`: the //! DeepScript key the user enters and the euvino admin backend key the //! login creates. use std::collections::HashMap; use std::sync::Mutex; use serde::{Deserialize, Serialize}; use thiserror::Error; /// Keyring service name all keys are stored under. pub const KEYRING_SERVICE: &str = "eu.euvino.callrecorder"; /// The external services whose API keys the app keeps. #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)] #[serde(rename_all = "lowercase")] pub enum Service { DeepScript, Backend, } impl Service { /// Keyring user name of this service's entry. pub fn user(self) -> &'static str { match self { Service::DeepScript => "deepscript", Service::Backend => "backend", } } } #[derive(Debug, Error)] pub enum SecretError { #[error("Schlüsselbund-Fehler: {0}")] Keyring(String), } pub type Result = std::result::Result; pub trait SecretStore: Send + Sync { /// The stored key, or `None` if there is none (or the keyring cannot be /// read). fn get(&self, s: Service) -> Option; fn set(&self, s: Service, v: &str) -> Result<()>; /// Removes the key; removing a key that does not exist is not an error. fn delete(&self, s: Service) -> Result<()>; } /// Keyring users of keys that earlier versions stored and this one no /// longer uses: the Anthropic key of the dropped Claude summary. const UNUSED_USERS: [&str; 1] = ["anthropic"]; /// The OS keyring. pub struct KeyringSecrets; impl KeyringSecrets { fn entry(s: Service) -> Result { keyring::Entry::new(KEYRING_SERVICE, s.user()) .map_err(|e| SecretError::Keyring(e.to_string())) } /// Best-effort deletes the keys earlier versions stored and this one no /// longer uses, so no stale secret lingers in the keyring. Missing /// entries and failures are only logged (never the key). pub fn remove_unused_keys() { for user in UNUSED_USERS { let result = keyring::Entry::new(KEYRING_SERVICE, user).and_then(|e| e.delete_credential()); match result { Ok(()) => log::info!("removed the unused keyring entry {user:?}"), Err(keyring::Error::NoEntry) => {} Err(e) => log::info!("could not remove the unused keyring entry {user:?}: {e}"), } } } } impl SecretStore for KeyringSecrets { fn get(&self, s: Service) -> Option { Self::entry(s).ok()?.get_password().ok() } fn set(&self, s: Service, v: &str) -> Result<()> { Self::entry(s)? .set_password(v) .map_err(|e| SecretError::Keyring(e.to_string())) } fn delete(&self, s: Service) -> Result<()> { match Self::entry(s)?.delete_credential() { Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), Err(e) => Err(SecretError::Keyring(e.to_string())), } } } /// In-memory secret store for tests. #[derive(Default)] pub struct MemorySecrets { keys: Mutex>, } impl SecretStore for MemorySecrets { fn get(&self, s: Service) -> Option { self.keys.lock().unwrap().get(&s).cloned() } fn set(&self, s: Service, v: &str) -> Result<()> { self.keys.lock().unwrap().insert(s, v.to_string()); Ok(()) } fn delete(&self, s: Service) -> Result<()> { self.keys.lock().unwrap().remove(&s); Ok(()) } } #[cfg(test)] mod tests { use super::*; const SERVICES: &[Service] = &[Service::DeepScript, Service::Backend]; #[test] fn memory_secrets_roundtrip() { let secrets = MemorySecrets::default(); assert_eq!(secrets.get(Service::DeepScript), None); secrets.set(Service::DeepScript, "ds-key").unwrap(); assert_eq!(secrets.get(Service::DeepScript).as_deref(), Some("ds-key")); assert_eq!(secrets.get(Service::Backend), None); secrets.delete(Service::DeepScript).unwrap(); assert_eq!(secrets.get(Service::DeepScript), None); secrets.delete(Service::DeepScript).unwrap(); } #[test] fn unused_keys_never_include_a_key_in_use() { for &s in SERVICES { assert!(!UNUSED_USERS.contains(&s.user()), "{s:?}"); } } #[test] fn service_serializes_as_keyring_user() { for &s in SERVICES { let json = serde_json::to_string(&s).unwrap(); assert_eq!(json, format!("\"{}\"", s.user())); assert_eq!(serde_json::from_str::(&json).unwrap(), s); } } }