1pub mod command;
7mod platform;
8
9use std::fmt;
10use std::sync::Arc;
11
12use keyring_core::{CredentialStore, Entry};
13use secrecy::ExposeSecret as _;
14use tr064::SecretString;
15
16pub const SERVICE: &str = "fritz";
18
19pub const ENV_PASSWORD: &str = "FRITZ_PASSWORD";
21
22#[derive(Debug, thiserror::Error)]
24pub enum Error {
25 #[error("the keychain failed")]
27 Keychain(#[source] keyring_core::Error),
28 #[error(transparent)]
30 Command(#[from] command::Error),
31 #[error("no password for {0}, run `fritz auth login` or set {ENV_PASSWORD}")]
33 Missing(String),
34}
35
36#[derive(Clone)]
38pub struct Keychain {
39 store: Arc<CredentialStore>,
40}
41
42impl fmt::Debug for Keychain {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 f.debug_struct("Keychain")
45 .field("store", &self.store.vendor())
46 .finish()
47 }
48}
49
50impl Keychain {
51 pub fn with_store(store: Arc<CredentialStore>) -> Self {
53 Self { store }
54 }
55
56 fn entry(&self, account: &str) -> Result<Entry, Error> {
57 self.store
58 .build(SERVICE, account, None)
59 .map_err(Error::Keychain)
60 }
61
62 pub fn get(&self, account: &str) -> Result<Option<SecretString>, Error> {
64 match self.entry(account)?.get_password() {
65 Ok(password) => Ok(Some(password.into())),
66 Err(keyring_core::Error::NoEntry) => Ok(None),
67 Err(error) => Err(Error::Keychain(error)),
68 }
69 }
70
71 pub fn set(&self, account: &str, password: &SecretString) -> Result<(), Error> {
73 self.entry(account)?
74 .set_password(password.expose_secret())
75 .map_err(Error::Keychain)
76 }
77
78 pub fn delete(&self, account: &str) -> Result<bool, Error> {
80 match self.entry(account)?.delete_credential() {
81 Ok(()) => Ok(true),
82 Err(keyring_core::Error::NoEntry) => Ok(false),
83 Err(error) => Err(Error::Keychain(error)),
84 }
85 }
86}
87
88#[derive(Debug, Clone, PartialEq, Eq)]
90pub enum Source {
91 Environment,
93 Command(String),
95 Keychain,
97}
98
99impl fmt::Display for Source {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 match self {
102 Self::Environment => write!(f, "the environment variable {ENV_PASSWORD}"),
103 Self::Command(name) => write!(f, "the command `{name}`"),
104 Self::Keychain => f.write_str("the keychain"),
105 }
106 }
107}
108
109pub fn password(
112 environment: Option<SecretString>,
113 keychain: Option<&Keychain>,
114 account: &str,
115) -> Result<(SecretString, Source), Error> {
116 let stored = match (environment, keychain) {
117 (Some(password), _) => return Ok((password, Source::Environment)),
118 (None, Some(keychain)) => keychain.get(account)?,
119 (None, None) => None,
120 };
121 stored
122 .map(|password| (password, Source::Keychain))
123 .ok_or_else(|| Error::Missing(account.to_owned()))
124}
125
126#[cfg(test)]
127mod tests {
128 use keyring_core::mock;
129
130 use super::*;
131
132 const ACCOUNT: &str = "agent@fritz.box";
133
134 fn keychain() -> Keychain {
135 Keychain::with_store(mock::Store::new().unwrap())
136 }
137
138 fn fail_next(keychain: &Keychain) {
140 let entry = keychain.entry(ACCOUNT).unwrap();
141 entry
142 .as_any()
143 .downcast_ref::<mock::Cred>()
144 .unwrap()
145 .set_error(keyring_core::Error::PlatformFailure("broken".into()));
146 }
147
148 #[test]
149 fn stores_passwords() {
150 let keychain = keychain();
151 assert!(format!("{keychain:?}").contains("Mock store"));
152 assert!(keychain.get(ACCOUNT).unwrap().is_none());
153 assert!(!keychain.delete(ACCOUNT).unwrap());
154
155 keychain.set(ACCOUNT, &"secret".into()).unwrap();
156 let password = keychain.get(ACCOUNT).unwrap().unwrap();
157 assert_eq!(password.expose_secret(), "secret");
158 assert!(keychain.delete(ACCOUNT).unwrap());
159 assert!(keychain.get(ACCOUNT).unwrap().is_none());
160 }
161
162 #[test]
163 fn reports_keychain_failures() {
164 let keychain = keychain();
165 fail_next(&keychain);
166 assert!(matches!(keychain.get(ACCOUNT), Err(Error::Keychain(_))));
167 fail_next(&keychain);
168 assert!(matches!(
169 keychain.set(ACCOUNT, &"secret".into()),
170 Err(Error::Keychain(_))
171 ));
172 fail_next(&keychain);
173 assert!(matches!(keychain.delete(ACCOUNT), Err(Error::Keychain(_))));
174 fail_next(&keychain);
175 let error = password(None, Some(&keychain), ACCOUNT).unwrap_err();
176 assert_eq!(error.to_string(), "the keychain failed");
177 }
178
179 #[test]
180 fn prefers_the_environment() {
181 let keychain = keychain();
182 keychain.set(ACCOUNT, &"stored".into()).unwrap();
183
184 let (found, source) = password(Some("given".into()), Some(&keychain), ACCOUNT).unwrap();
185 assert_eq!(found.expose_secret(), "given");
186 assert_eq!(source, Source::Environment);
187 assert_eq!(
188 source.to_string(),
189 "the environment variable FRITZ_PASSWORD"
190 );
191
192 let (found, source) = password(None, Some(&keychain), ACCOUNT).unwrap();
193 assert_eq!(found.expose_secret(), "stored");
194 assert_eq!(source.to_string(), "the keychain");
195 assert_eq!(
196 Source::Command("op".to_owned()).to_string(),
197 "the command `op`"
198 );
199 }
200
201 #[test]
202 fn reports_a_missing_password() {
203 for keychain in [None, Some(keychain())] {
204 let error = password(None, keychain.as_ref(), ACCOUNT).unwrap_err();
205 assert_eq!(
206 error.to_string(),
207 "no password for agent@fritz.box, run `fritz auth login` or set FRITZ_PASSWORD"
208 );
209 }
210 }
211}