Files
call-recorder/crates/core/src/secrets.rs
T
haukeandClaude Opus 5.5 58e96a2954 feat #14740: admin backend client and transcript upload text
recorder-core side of linking the app to the euvino admin backend:
- backend: BackendClient (create a key with the admin's session cookie,
  check a key, upload a transcript; redirects never followed), German
  error messages, the login-window decision (LoginStep) and the upload
  flow with login, one retry after a refused key and no loop
- call_view: the upload text (header + merged, renamed lines) and the
  upload fields on the call
- store: schema v3 with crm_transcript_id and uploaded_at
- settings: backend_url (validated https), the app-managed login fields,
  kept on edit and cleared when the backend URL changes
- secrets: Service::Backend; http: per-request follow_redirects;
  FakeTransport can script transport errors

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-06 14:52:50 +01:00

156 lines
4.7 KiB
Rust

//! 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<T> = std::result::Result<T, SecretError>;
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<String>;
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> {
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<String> {
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<HashMap<Service, String>>,
}
impl SecretStore for MemorySecrets {
fn get(&self, s: Service) -> Option<String> {
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::<Service>(&json).unwrap(), s);
}
}
}