mod platform;
use std::fmt;
use std::sync::Arc;
use keyring_core::{CredentialStore, Entry};
use secrecy::ExposeSecret as _;
use tr064::SecretString;
pub const SERVICE: &str = "fritz";
pub const ENV_PASSWORD: &str = "FRITZ_PASSWORD";
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("the keychain failed")]
Keychain(#[source] keyring_core::Error),
#[error("no password for {0}, run `fritz auth login` or set {ENV_PASSWORD}")]
Missing(String),
}
#[derive(Clone)]
pub struct Keychain {
store: Arc<CredentialStore>,
}
impl fmt::Debug for Keychain {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Keychain")
.field("store", &self.store.vendor())
.finish()
}
}
impl Keychain {
pub fn with_store(store: Arc<CredentialStore>) -> Self {
Self { store }
}
fn entry(&self, account: &str) -> Result<Entry, Error> {
self.store
.build(SERVICE, account, None)
.map_err(Error::Keychain)
}
pub fn get(&self, account: &str) -> Result<Option<SecretString>, Error> {
match self.entry(account)?.get_password() {
Ok(password) => Ok(Some(password.into())),
Err(keyring_core::Error::NoEntry) => Ok(None),
Err(error) => Err(Error::Keychain(error)),
}
}
pub fn set(&self, account: &str, password: &SecretString) -> Result<(), Error> {
self.entry(account)?
.set_password(password.expose_secret())
.map_err(Error::Keychain)
}
pub fn delete(&self, account: &str) -> Result<bool, Error> {
match self.entry(account)?.delete_credential() {
Ok(()) => Ok(true),
Err(keyring_core::Error::NoEntry) => Ok(false),
Err(error) => Err(Error::Keychain(error)),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
Environment,
Keychain,
}
impl fmt::Display for Source {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Environment => write!(f, "the environment variable {ENV_PASSWORD}"),
Self::Keychain => f.write_str("the keychain"),
}
}
}
pub fn password(
environment: Option<SecretString>,
keychain: Option<&Keychain>,
account: &str,
) -> Result<(SecretString, Source), Error> {
let stored = match (environment, keychain) {
(Some(password), _) => return Ok((password, Source::Environment)),
(None, Some(keychain)) => keychain.get(account)?,
(None, None) => None,
};
stored
.map(|password| (password, Source::Keychain))
.ok_or_else(|| Error::Missing(account.to_owned()))
}
#[cfg(test)]
mod tests {
use keyring_core::mock;
use super::*;
const ACCOUNT: &str = "agent@fritz.box";
fn keychain() -> Keychain {
Keychain::with_store(mock::Store::new().unwrap())
}
fn fail_next(keychain: &Keychain) {
let entry = keychain.entry(ACCOUNT).unwrap();
entry
.as_any()
.downcast_ref::<mock::Cred>()
.unwrap()
.set_error(keyring_core::Error::PlatformFailure("broken".into()));
}
#[test]
fn stores_passwords() {
let keychain = keychain();
assert!(format!("{keychain:?}").contains("Mock store"));
assert!(keychain.get(ACCOUNT).unwrap().is_none());
assert!(!keychain.delete(ACCOUNT).unwrap());
keychain.set(ACCOUNT, &"secret".into()).unwrap();
let password = keychain.get(ACCOUNT).unwrap().unwrap();
assert_eq!(password.expose_secret(), "secret");
assert!(keychain.delete(ACCOUNT).unwrap());
assert!(keychain.get(ACCOUNT).unwrap().is_none());
}
#[test]
fn reports_keychain_failures() {
let keychain = keychain();
fail_next(&keychain);
assert!(matches!(keychain.get(ACCOUNT), Err(Error::Keychain(_))));
fail_next(&keychain);
assert!(matches!(
keychain.set(ACCOUNT, &"secret".into()),
Err(Error::Keychain(_))
));
fail_next(&keychain);
assert!(matches!(keychain.delete(ACCOUNT), Err(Error::Keychain(_))));
fail_next(&keychain);
let error = password(None, Some(&keychain), ACCOUNT).unwrap_err();
assert_eq!(error.to_string(), "the keychain failed");
}
#[test]
fn prefers_the_environment() {
let keychain = keychain();
keychain.set(ACCOUNT, &"stored".into()).unwrap();
let (found, source) = password(Some("given".into()), Some(&keychain), ACCOUNT).unwrap();
assert_eq!(found.expose_secret(), "given");
assert_eq!(source, Source::Environment);
assert_eq!(
source.to_string(),
"the environment variable FRITZ_PASSWORD"
);
let (found, source) = password(None, Some(&keychain), ACCOUNT).unwrap();
assert_eq!(found.expose_secret(), "stored");
assert_eq!(source.to_string(), "the keychain");
}
#[test]
fn reports_a_missing_password() {
for keychain in [None, Some(keychain())] {
let error = password(None, keychain.as_ref(), ACCOUNT).unwrap_err();
assert_eq!(
error.to_string(),
"no password for agent@fritz.box, run `fritz auth login` or set FRITZ_PASSWORD"
);
}
}
}