From 94d31671e09398dedc318433b86d376362fcc62a Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:47 +0100 Subject: [PATCH] capri-llm: add secrets module --- crates/capri-llm/src/secrets.rs | 263 ++++++++++++++++++++++++++++++++ 1 file changed, 263 insertions(+) create mode 100644 crates/capri-llm/src/secrets.rs diff --git a/crates/capri-llm/src/secrets.rs b/crates/capri-llm/src/secrets.rs new file mode 100644 index 0000000..ad404b3 --- /dev/null +++ b/crates/capri-llm/src/secrets.rs @@ -0,0 +1,263 @@ +//! API keys and the Hugging Face token: Secret Service over D-Bus +//! (`org.freedesktop.secrets`: KWallet/ksecretd on KDE, gnome-keyring or ksecretd on i3), +//! with a private 0600 file fallback. Secrets are never logged and never in `Debug` output. +use std::collections::{BTreeMap, HashMap}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use anyhow::{bail, Context, Result}; +use futures::StreamExt; +use serde::{Deserialize, Serialize}; +use zbus::zvariant::{ObjectPath, OwnedObjectPath, OwnedValue, Value}; + +const DEST: &str = "org.freedesktop.secrets"; +const SERVICE: &str = "/org/freedesktop/secrets"; +const DEFAULT_COLLECTION: &str = "/org/freedesktop/secrets/aliases/default"; +/// Secret Service `Secret` struct `(oayays)`: session, parameters, value, content type. +type Secret = (OwnedObjectPath, Vec, Vec, String); + +/// Account name of the Hugging Face read token. +pub const HF_ACCOUNT: &str = "huggingface"; +pub const HF_ORIGIN: &str = "https://huggingface.co"; + +#[derive(Clone)] +pub struct SecretStore(Backend); + +#[derive(Clone)] +enum Backend { + Service { conn: zbus::Connection, session: OwnedObjectPath }, + File(PathBuf), +} + +impl std::fmt::Debug for SecretStore { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(if self.secure() { "SecretStore(secret-service)" } else { "SecretStore(file)" }) + } +} + +#[derive(Serialize, Deserialize)] +struct FileEntry { + origin: String, + secret: String, +} + +async fn proxy<'a>(conn: &zbus::Connection, path: &'a str, interface: &'a str) -> zbus::Result> { + zbus::Proxy::new(conn, DEST, path, interface).await +} + +impl SecretStore { + /// Secret Service when reachable, else `/secrets/credentials.json`. + pub async fn open(data_dir: &Path) -> Self { + match tokio::time::timeout(Duration::from_secs(3), Self::service()).await { + Ok(Ok(backend)) => Self(backend), + _ => { + // TODO: falls back to a plaintext 0600 file when no Secret Service runs; refuse to save when `!secure()` to fail closed. + tracing::warn!("Secret Service unavailable; API keys use a private file"); + Self::file(data_dir.join("secrets").join("credentials.json")) + } + } + } + + pub fn file(path: PathBuf) -> Self { + Self(Backend::File(path)) + } + + /// True when secrets are held by the desktop keyring. + pub fn secure(&self) -> bool { + matches!(self.0, Backend::Service { .. }) + } + + async fn service() -> Result { + let conn = zbus::Connection::session().await?; + let service = proxy(&conn, SERVICE, "org.freedesktop.Secret.Service").await?; + // TODO: the "plain" session sends the secret unencrypted over the private session bus; switch to dh-ietf1024-sha256-aes128-cbc-pkcs7 if the bus can be shared. + let (_, session): (OwnedValue, OwnedObjectPath) = service.call("OpenSession", &("plain", Value::from(""))).await?; + Ok(Backend::Service { conn, session }) + } + + fn attributes<'a>(account: &'a str, origin: Option<&'a str>) -> HashMap<&'a str, &'a str> { + let mut map = HashMap::from([("application", "capri"), ("account", account)]); + if let Some(origin) = origin { + map.insert("origin", origin); + } + map + } + + /// Runs a Secret Service prompt (unlock dialog) and waits for its result. + async fn prompt(conn: &zbus::Connection, path: &OwnedObjectPath) -> Result { + let prompt = proxy(conn, path.as_str(), "org.freedesktop.Secret.Prompt").await?; + let mut completed = prompt.receive_signal("Completed").await?; + prompt.call::<_, _, ()>("Prompt", &("",)).await?; + let message = tokio::time::timeout(Duration::from_secs(120), completed.next()).await?.context("Prompt closed")?; + let (dismissed, result): (bool, OwnedValue) = message.body().deserialize()?; + if dismissed { + bail!("The keyring stayed locked."); + } + Ok(result) + } + + async fn search(conn: &zbus::Connection, attributes: HashMap<&str, &str>) -> Result> { + let service = proxy(conn, SERVICE, "org.freedesktop.Secret.Service").await?; + let (mut unlocked, locked): (Vec, Vec) = service.call("SearchItems", &(attributes,)).await?; + if !locked.is_empty() { + let paths: Vec> = locked.iter().map(|p| p.as_ref()).collect(); + let (now, prompt): (Vec, OwnedObjectPath) = service.call("Unlock", &(paths,)).await?; + unlocked.extend(now); + if prompt.as_str() != "/" { + Self::prompt(conn, &prompt).await?; + unlocked.extend(locked); + } + } + Ok(unlocked) + } + + /// The secret saved for `account`, only if it was saved for the same `origin`. + pub async fn get(&self, account: &str, origin: &str) -> Result> { + match &self.0 { + Backend::Service { conn, session } => { + let Some(item) = Self::search(conn, Self::attributes(account, Some(origin))).await?.into_iter().next() else { return Ok(None) }; + let item = proxy(conn, item.as_str(), "org.freedesktop.Secret.Item").await?; + let (_, _, value, _): Secret = item.call("GetSecret", &(session,)).await.context("Saved access could not be read. Save it again.")?; + Ok(Some(String::from_utf8(value).context("Saved access could not be read. Save it again.")?)) + } + Backend::File(path) => Ok(read_file(path)?.remove(account).filter(|e| e.origin == origin).map(|e| e.secret)), + } + } + + pub async fn set(&self, account: &str, origin: &str, secret: &str) -> Result<()> { + match &self.0 { + Backend::Service { conn, session } => { + // Replacing by attributes would keep an item bound to an old origin, so delete first. + self.delete(account).await?; + let collection = proxy(conn, DEFAULT_COLLECTION, "org.freedesktop.Secret.Collection").await?; + let label = format!("Capri {account}"); + let properties = HashMap::from([ + ("org.freedesktop.Secret.Item.Label", Value::from(label.as_str())), + ("org.freedesktop.Secret.Item.Attributes", Value::from(Self::attributes(account, Some(origin)))), + ]); + let secret: Secret = (session.clone(), vec![], secret.as_bytes().to_vec(), "text/plain".into()); + for _ in 0..2 { + let (item, prompt): (OwnedObjectPath, OwnedObjectPath) = collection.call("CreateItem", &(&properties, &secret, true)).await?; + if item.as_str() != "/" { + return Ok(()); + } + if prompt.as_str() == "/" { + break; + } + Self::prompt(conn, &prompt).await?; // collection unlocked; create again + } + bail!("Secure credential storage is unavailable.") + } + Backend::File(path) => { + let mut entries = read_file(path)?; + entries.insert(account.into(), FileEntry { origin: origin.into(), secret: secret.into() }); + write_file(path, &entries) + } + } + } + + pub async fn delete(&self, account: &str) -> Result<()> { + match &self.0 { + Backend::Service { conn, .. } => { + for item in Self::search(conn, Self::attributes(account, None)).await? { + let item = proxy(conn, item.as_str(), "org.freedesktop.Secret.Item").await?; + let prompt: OwnedObjectPath = item.call("Delete", &()).await?; + if prompt.as_str() != "/" { + Self::prompt(conn, &prompt).await?; + } + } + Ok(()) + } + Backend::File(path) => { + let mut entries = read_file(path)?; + if entries.remove(account).is_some() { + write_file(path, &entries)?; + } + Ok(()) + } + } + } +} + +fn read_file(path: &Path) -> Result> { + match capri_core::fsutil::read_regular(path, 256 * 1024)? { + None => Ok(BTreeMap::new()), + Some(bytes) => serde_json::from_slice(&bytes).context("Saved credentials could not be read."), + } +} + +fn write_file(path: &Path, entries: &BTreeMap) -> Result<()> { + use std::os::unix::fs::DirBuilderExt; + let dir = path.parent().context("no parent")?; + std::fs::DirBuilder::new().recursive(true).mode(0o700).create(dir)?; + capri_core::fsutil::write_json_atomic(path, entries) // temp file is created 0600 +} + +/// Removes copied outer whitespace, zero-width characters and one pair of quotes (Capri `api-key.mjs`). +pub fn normalize_api_key(value: &str) -> String { + let strip = |s: &str| s.trim_matches(|c: char| c.is_whitespace() || matches!(c, '\u{200b}' | '\u{2060}' | '\u{feff}')).to_string(); + let key = strip(value); + match key.strip_prefix('"').and_then(|k| k.strip_suffix('"')) { + Some(inner) if key.len() >= 2 => strip(inner), + _ => key, + } +} + +/// Why a normalized key is unusable, or `None` when valid. +pub fn api_key_problem(key: &str) -> Option<&'static str> { + if key.chars().count() < 8 { + Some("Enter a valid API key.") + } else if key.chars().count() > 4096 { + Some("API key is too long (maximum 4096 characters).") + } else if !key.bytes().all(|b| (0x21..=0x7e).contains(&b) && b != b'"' && b != b'\\') { + Some("Paste only the API key, without spaces or quotation marks.") + } else { + None + } +} + +/// `^hf_[A-Za-z0-9]{20,200}$` +pub fn valid_hf_token(token: &str) -> bool { + token.strip_prefix("hf_").is_some_and(|rest| (20..=200).contains(&rest.len()) && rest.bytes().all(|b| b.is_ascii_alphanumeric())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn file_store_binds_secret_to_origin_and_is_private() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("secrets/credentials.json"); + let store = SecretStore::file(path.clone()); + assert!(!store.secure()); + store.set("c1", "https://a.example", "sk-12345678").await.unwrap(); + assert_eq!(store.get("c1", "https://a.example").await.unwrap().as_deref(), Some("sk-12345678")); + assert_eq!(store.get("c1", "https://b.example").await.unwrap(), None, "a key never goes to another origin"); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + assert_eq!(format!("{store:?}"), "SecretStore(file)"); + store.delete("c1").await.unwrap(); + assert_eq!(store.get("c1", "https://a.example").await.unwrap(), None); + } + + #[test] + fn key_normalization_and_validation() { + assert_eq!(normalize_api_key("\u{feff} \"sk-abcdefgh\" \n"), "sk-abcdefgh"); + assert_eq!(api_key_problem("short"), Some("Enter a valid API key.")); + assert_eq!(api_key_problem("sk abc defgh"), Some("Paste only the API key, without spaces or quotation marks.")); + assert_eq!(api_key_problem(&"a".repeat(4097)), Some("API key is too long (maximum 4096 characters).")); + assert_eq!(api_key_problem("AIzaSyExample_key-123"), None); + assert!(valid_hf_token(&format!("hf_{}", "a".repeat(20)))); + assert!(!valid_hf_token("hf_short")); + } + + /// Read-only check against the session's Secret Service (no item is created). + #[tokio::test] + #[ignore = "needs a desktop session bus with org.freedesktop.secrets"] + async fn secret_service_session_and_search() { + let Backend::Service { conn, .. } = SecretStore::service().await.unwrap() else { unreachable!() }; + let found = SecretStore::search(&conn, HashMap::from([("application", "capri-test-none")])).await.unwrap(); + assert!(found.is_empty()); + } +}