Skip to content
1        10        20        30        40        50        60        70        80        901use crate::server_url::TwigUrl;23#[cfg(not(feature = "testing"))]4use anyhow::{Context, bail};5#[cfg(not(feature = "testing"))]6use keyring::{Entry, Error as KeyringError};78pub trait CredentialStore {9    fn check_available(&self) -> anyhow::Result<()>;10    fn get(&self, server: &TwigUrl) -> anyhow::Result<Option<String>>;11    fn put(&self, server: &TwigUrl, token: &str) -> anyhow::Result<()>;12    fn erase(&self, server: &TwigUrl) -> anyhow::Result<()>;13}1415#[derive(Default)]16#[cfg(not(feature = "testing"))]17pub struct KeyringCredentialStore;1819#[cfg(not(feature = "testing"))]20impl KeyringCredentialStore {21    fn entry(server: &TwigUrl) -> anyhow::Result<Entry> {22        Entry::new("tree", server.as_url().as_str())23            .context("Could not open the operating-system credential entry")24    }25}2627#[cfg(not(feature = "testing"))]28impl CredentialStore for KeyringCredentialStore {29    fn check_available(&self) -> anyhow::Result<()> {30        if let Err(error) = Entry::store_status() {31            bail!("The operating-system credential store is unavailable: {error}");32        }33        Ok(())34    }3536    fn get(&self, server: &TwigUrl) -> anyhow::Result<Option<String>> {37        match Self::entry(server)?.get_password() {38            Ok(token) => Ok(Some(token)),39            Err(KeyringError::NoEntry) => Ok(None),40            Err(error) => Err(error).context("Could not read the Twig token from the OS keyring"),41        }42    }4344    fn put(&self, server: &TwigUrl, token: &str) -> anyhow::Result<()> {45        Self::entry(server)?46            .set_password(token)47            .context("Could not save the Twig token in the OS keyring")48    }4950    fn erase(&self, server: &TwigUrl) -> anyhow::Result<()> {51        match Self::entry(server)?.delete_credential() {52            Ok(()) | Err(KeyringError::NoEntry) => Ok(()),53            Err(error) => Err(error).context("Could not erase the Twig token from the OS keyring"),54        }55    }56}