mod split;
use std::collections::HashMap;
use std::sync::{Mutex, MutexGuard};
use zeroize::Zeroizing;
use crate::Secret;
use crate::vault::lock;
use split::Limits;
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("The credential store is unavailable. Unlock your system keychain and try again.")]
pub struct KeychainError;
const LIMITS: Option<Limits> = if cfg!(windows) {
Some(Limits::WINDOWS)
} else {
None
};
static SPLIT: Mutex<()> = Mutex::new(());
pub struct Keychain {
service: String,
}
impl Keychain {
pub fn new(service: impl Into<String>) -> Self {
Self {
service: service.into(),
}
}
pub fn load(&self, account: &str) -> Result<Option<Secret>, KeychainError> {
let _split = serialise();
split::load(&System(&self.service), LIMITS, account).map(|value| value.map(Secret::new))
}
pub fn save(&self, account: &str, secret: &Secret) -> Result<(), KeychainError> {
let _split = serialise();
split::save(&System(&self.service), LIMITS, account, secret.expose())
}
pub fn delete(&self, account: &str) -> Result<(), KeychainError> {
let _split = serialise();
split::delete(&System(&self.service), LIMITS, account)
}
}
fn serialise() -> Option<MutexGuard<'static, ()>> {
LIMITS.map(|_| lock(&SPLIT))
}
enum Item {
Text(String),
Bytes(Zeroizing<Vec<u8>>),
}
trait Store {
fn service(&self) -> &str;
fn get(&self, account: &str) -> Result<Option<Item>, KeychainError>;
fn set_text(&self, account: &str, value: &str) -> Result<(), KeychainError>;
fn set_bytes(&self, account: &str, value: &[u8]) -> Result<(), KeychainError>;
fn delete(&self, account: &str) -> Result<(), KeychainError>;
fn find(&self, pattern: &str) -> Result<Vec<String>, KeychainError>;
}
struct System<'a>(&'a str);
impl Store for System<'_> {
fn service(&self) -> &str {
self.0
}
fn get(&self, account: &str) -> Result<Option<Item>, KeychainError> {
item(entry(self.0, account)?.get_password())
}
fn set_text(&self, account: &str, value: &str) -> Result<(), KeychainError> {
entry(self.0, account)?
.set_password(value)
.map_err(|_| KeychainError)
}
fn set_bytes(&self, account: &str, value: &[u8]) -> Result<(), KeychainError> {
entry(self.0, account)?
.set_secret(value)
.map_err(|_| KeychainError)
}
fn delete(&self, account: &str) -> Result<(), KeychainError> {
optional(entry(self.0, account)?.delete_credential()).map(|_| ())
}
fn find(&self, pattern: &str) -> Result<Vec<String>, KeychainError> {
keyring::v1::Entry::store_status()
.as_ref()
.map_err(|_| KeychainError)?;
let found = keyring_core::Entry::search(&HashMap::from([("pattern", pattern)]))
.map_err(|_| KeychainError)?;
Ok(found
.iter()
.filter_map(|entry| target_of(entry.get_attributes()))
.collect())
}
}
fn entry(service: &str, account: &str) -> Result<keyring::v1::Entry, KeychainError> {
keyring::v1::Entry::new(service, account).map_err(|_| KeychainError)
}
fn item(result: keyring::v1::Result<String>) -> Result<Option<Item>, KeychainError> {
match result {
Ok(text) => Ok(Some(Item::Text(text))),
Err(keyring::v1::Error::BadEncoding(bytes)) => Ok(Some(Item::Bytes(Zeroizing::new(bytes)))),
Err(keyring::v1::Error::NoEntry) => Ok(None),
Err(_) => Err(KeychainError),
}
}
fn optional<T>(result: keyring::v1::Result<T>) -> Result<Option<T>, KeychainError> {
match result {
Ok(value) => Ok(Some(value)),
Err(keyring::v1::Error::NoEntry) => Ok(None),
Err(_) => Err(KeychainError),
}
}
fn target_of(attributes: keyring::v1::Result<HashMap<String, String>>) -> Option<String> {
attributes.ok()?.remove("target_name")
}
#[cfg(test)]
mod tests;