kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
Documentation
//! The `SecretStore` seam: session and refresh tokens, and the software
//! device key. Never written to the SyncStore.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Mutex;

use crate::error::{Error, Result};

pub trait SecretStore: Send + Sync {
    fn get(&self, key: &str) -> Result<Option<String>>;
    fn set(&self, key: &str, value: &str) -> Result<()>;
    fn delete(&self, key: &str) -> Result<()>;
}

/// Secrets in memory only (tests, conformance, ephemeral scripts).
#[derive(Default)]
pub struct MemorySecretStore(Mutex<HashMap<String, String>>);

impl MemorySecretStore {
    pub fn new() -> MemorySecretStore {
        MemorySecretStore::default()
    }
}

impl SecretStore for MemorySecretStore {
    fn get(&self, key: &str) -> Result<Option<String>> {
        Ok(self.0.lock().unwrap().get(key).cloned())
    }
    fn set(&self, key: &str, value: &str) -> Result<()> {
        self.0.lock().unwrap().insert(key.into(), value.into());
        Ok(())
    }
    fn delete(&self, key: &str) -> Result<()> {
        self.0.lock().unwrap().remove(key);
        Ok(())
    }
}

/// Secrets as 0600 files in a directory: only where the OS has no keychain
/// (headless Linux, containers).
pub struct FileSecretStore {
    dir: PathBuf,
}

impl FileSecretStore {
    pub fn new(dir: impl Into<PathBuf>) -> Result<FileSecretStore> {
        let dir = dir.into();
        std::fs::create_dir_all(&dir).map_err(Error::storage)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
        }
        Ok(FileSecretStore { dir })
    }

    fn path(&self, key: &str) -> PathBuf {
        let safe: String =
            key.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
        self.dir.join(safe)
    }
}

impl SecretStore for FileSecretStore {
    fn get(&self, key: &str) -> Result<Option<String>> {
        match std::fs::read_to_string(self.path(key)) {
            Ok(s) => Ok(Some(s)),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(Error::storage(e)),
        }
    }

    fn set(&self, key: &str, value: &str) -> Result<()> {
        let path = self.path(key);
        let tmp = path.with_extension("tmp");
        {
            use std::io::Write;
            let mut o = std::fs::OpenOptions::new();
            o.write(true).create(true).truncate(true);
            #[cfg(unix)]
            {
                use std::os::unix::fs::OpenOptionsExt;
                o.mode(0o600);
            }
            let mut f = o.open(&tmp).map_err(Error::storage)?;
            f.write_all(value.as_bytes()).map_err(Error::storage)?;
            f.sync_all().map_err(Error::storage)?;
        }
        // Atomic replace: a rotated token pair is never half written.
        std::fs::rename(&tmp, &path).map_err(Error::storage)
    }

    fn delete(&self, key: &str) -> Result<()> {
        match std::fs::remove_file(self.path(key)) {
            Ok(()) => Ok(()),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(e) => Err(Error::storage(e)),
        }
    }
}

/// The OS keychain: macOS Keychain, Windows Credential Manager, Linux Secret Service.
#[cfg(feature = "os-keychain")]
pub struct KeychainSecretStore {
    service: String,
}

#[cfg(feature = "os-keychain")]
impl KeychainSecretStore {
    /// `service` names the app, e.g. `com.example.todos`.
    pub fn new(service: impl Into<String>) -> KeychainSecretStore {
        KeychainSecretStore { service: service.into() }
    }

    /// True when the OS keychain answers (a probe read).
    pub fn available(&self) -> bool {
        match keyring::Entry::new(&self.service, "kovlet-probe") {
            Ok(e) => matches!(e.get_password(), Ok(_) | Err(keyring::Error::NoEntry)),
            Err(_) => false,
        }
    }

    fn entry(&self, key: &str) -> Result<keyring::Entry> {
        keyring::Entry::new(&self.service, key).map_err(Error::storage)
    }
}

#[cfg(feature = "os-keychain")]
impl SecretStore for KeychainSecretStore {
    fn get(&self, key: &str) -> Result<Option<String>> {
        match self.entry(key)?.get_password() {
            Ok(s) => Ok(Some(s)),
            Err(keyring::Error::NoEntry) => Ok(None),
            Err(e) => Err(Error::storage(e)),
        }
    }
    fn set(&self, key: &str, value: &str) -> Result<()> {
        self.entry(key)?.set_password(value).map_err(Error::storage)
    }
    fn delete(&self, key: &str) -> Result<()> {
        match self.entry(key)?.delete_credential() {
            Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
            Err(e) => Err(Error::storage(e)),
        }
    }
}