Files
capri-core-rust/crates/capri-llm/src/secrets.rs
T
nocodeandClaude Opus 5.5 844435f21f
CI / test (push) Has been cancelled
Linux port: first run, packaging, single instance, privacy and wiring
First run and backend
- The companion opens without Ollama or a model (OFFLINE / SETUP REQUIRED),
  opens Settings > Language model and picks the model up once downloaded.
- Model, provider and GPU changes apply without restarting (Ollama is
  restarted when launch settings change); no silent fallback from API mode.
- Fatal startup errors are shown in a window; the fallback avatar loads
  again; the shipped Capri artwork is used when nothing was imported.

Packaging and tooling
- packaging/arch/PKGBUILD, capri.desktop (KWin ScreenShot2 key), icons,
  artwork under /usr/share/capri/assets, Gitea Actions CI.
- xtask: `icons` and `release-check` (no private data or credentials).

Runtime
- One instance per data folder (flock + control socket): second launch
  shows the window; capri stop / restart / toggle / status (JSON, starts
  nothing) / doctor / setup / diagnostics export / purge.
- A foreign program on the Ollama port is refused; an Ollama left behind
  by Capri is replaced.

Privacy and security
- No raw Ollama log on disk; API keys are never saved in plaintext (old
  ones move to the keyring); refused credential notes are stored as
  [Credentials omitted]; launched apps get an allow-listed environment.

Fixes
- Stop/Escape silence the voice; saved voice effects apply to replies;
  settings_control glitch settings apply; distinct KWin cursor scripts;
  KDE window capture authorized for source builds; Linux wording.
- Voice pack references zipped with Windows separators are found.

Wired features
- Initiatives, request router, resource monitor, "clip that", questions
  about a snapshot, sleep mode, tap reactions, stopwatch, attachments,
  Internet mode button, voice-synced subtitles, wake visuals, dictation
  draft, tray switches, Spotify seek/shuffle/repeat; computer-control
  planner and classifier follow model switches and API mode.
- Approval cards: one shown, 8 queued, deduplicated, cancelled on stop,
  failure, lock or pause; one Application access switch.

Desktop
- Compositor detection (no black overlay on i3 without picom), i3lock
  detection, unsupported desktops reported at startup, screenshot-only
  control without AT-SPI, fontconfig fallbacks, translatable feature
  pages with French translations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:15:49 +01:00

308 lines
14 KiB
Rust

//! API keys and the Hugging Face token: Secret Service over D-Bus
//! (`org.freedesktop.secrets`: KWallet/ksecretd on KDE, gnome-keyring or KeePassXC on i3).
//! Without a Secret Service nothing new is saved (fail closed); keys an older build wrote to
//! the private 0600 file stay readable and move into the keyring once it is available.
//! 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<u8>, Vec<u8>, 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 },
/// `writable` only for explicit file stores (tests); the fallback is read-only.
File { path: PathBuf, writable: bool },
}
/// Shown when a key cannot be saved because no keyring answers.
pub const NO_KEYRING: &str = "Secure credential storage is unavailable: no Secret Service is running. Start KWallet (KDE Plasma), or gnome-keyring or KeePassXC with its Secret Service option (i3), then save the key again.";
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<'a>> {
zbus::Proxy::new(conn, DEST, path, interface).await
}
impl SecretStore {
/// Secret Service when reachable, else `<data>/secrets/credentials.json`.
pub async fn open(data_dir: &Path) -> Self {
let legacy = data_dir.join("secrets").join("credentials.json");
match tokio::time::timeout(Duration::from_secs(3), Self::service()).await {
Ok(Ok(backend)) => {
let store = Self(backend);
store.migrate(&legacy).await;
store
}
_ => {
tracing::warn!("Secret Service unavailable; API keys cannot be saved until a keyring runs");
Self(Backend::File { path: legacy, writable: false })
}
}
}
/// Moves keys from the plaintext file of older builds into the keyring, then deletes the file.
async fn migrate(&self, legacy: &Path) {
let Ok(entries) = read_file(legacy) else { return };
if entries.is_empty() {
return;
}
for (account, entry) in &entries {
if let Err(e) = self.set(account, &entry.origin, &entry.secret).await {
tracing::warn!("saved access not moved to the keyring: {e:#}");
return;
}
}
match std::fs::remove_file(legacy) {
Ok(()) => tracing::info!(count = entries.len(), "saved access moved to the keyring"),
Err(e) => tracing::warn!("plaintext credentials file not removed: {e}"),
}
}
/// File store that also saves (tests and explicit tooling only).
pub fn file(path: PathBuf) -> Self {
Self(Backend::File { path, writable: true })
}
/// True when secrets are held by the desktop keyring.
pub fn secure(&self) -> bool {
matches!(self.0, Backend::Service { .. })
}
async fn service() -> Result<Backend> {
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<OwnedValue> {
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<Vec<OwnedObjectPath>> {
let service = proxy(conn, SERVICE, "org.freedesktop.Secret.Service").await?;
let (mut unlocked, locked): (Vec<OwnedObjectPath>, Vec<OwnedObjectPath>) = service.call("SearchItems", &(attributes,)).await?;
if !locked.is_empty() {
let paths: Vec<ObjectPath<'_>> = locked.iter().map(|p| p.as_ref()).collect();
let (now, prompt): (Vec<OwnedObjectPath>, 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<Option<String>> {
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 { writable: false, .. } => bail!(NO_KEYRING),
Backend::File { path, writable: true } => {
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(())
}
// Deleting is allowed even read-only: it removes a plaintext secret.
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<BTreeMap<String, FileEntry>> {
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<String, FileEntry>) -> 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);
}
#[tokio::test]
async fn without_keyring_nothing_new_is_saved() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("secrets/credentials.json");
SecretStore::file(path.clone()).set("old", "https://a.example", "sk-legacy-key").await.unwrap();
let fallback = SecretStore(Backend::File { path: path.clone(), writable: false });
assert_eq!(fallback.set("new", "https://a.example", "sk-12345678").await.unwrap_err().to_string(), NO_KEYRING);
// A key from an older build stays usable and can be removed.
assert_eq!(fallback.get("old", "https://a.example").await.unwrap().as_deref(), Some("sk-legacy-key"));
fallback.delete("old").await.unwrap();
assert_eq!(fallback.get("old", "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());
}
}