keyring_core/sample/credential.rs
1use std::any::Any;
2use std::collections::HashMap;
3use std::sync::Arc;
4
5use dashmap::DashMap;
6use serde::{Deserialize, Serialize};
7use uuid::Uuid;
8
9use super::store::{CredValue, Store};
10use crate::attributes::parse_attributes;
11use crate::{Credential, Entry, Error, Result, api::CredentialApi};
12
13/// Credentials are specified by a pair of service name and username.
14#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
15pub struct CredId {
16 /// The service name.
17 pub service: String,
18 /// The username.
19 pub user: String,
20}
21
22/// Each of these keys specifies a specific credential in the store.
23///
24/// For each credential ID, the store maintains a list of all the
25/// credentials associated with that ID. The first in that list
26/// (element 0) is the credential _specified_ by the ID, so it's
27/// the one that's auto-created if there are no credentials with
28/// that ID in the store and a password is set. All keys with
29/// indices higher than 0 are wrappers for a specific credential,
30/// but they do not _specify_ a credential.
31#[derive(Clone)]
32pub struct CredKey {
33 /// The store that holds this credential.
34 pub store: Arc<Store>,
35 /// The service and user pair for this credential.
36 pub id: CredId,
37 /// The UUID of the credential this key wraps, if any.
38 pub uuid: Option<String>,
39}
40
41impl std::fmt::Debug for CredKey {
42 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 f.debug_struct("CredKey")
44 .field("id", &self.id)
45 .field("uuid", &self.uuid)
46 .finish()
47 }
48}
49
50impl CredKey {
51 /// This is the boilerplate for all credential-reading/updating calls.
52 ///
53 /// It makes sure there is just one credential and, if so, it reads/updates it.
54 /// If there is no credential, it returns a NoEntry error.
55 /// If there are multiple credentials, it returns an ambiguous error.
56 ///
57 /// It knows about the difference between specifiers and wrappers
58 /// and acts accordingly.
59 pub fn with_unique_pair<T, F>(&self, f: F) -> Result<T>
60 where
61 F: FnOnce(&String, &mut CredValue) -> T,
62 {
63 match self.uuid.as_ref() {
64 // this is a wrapper, look for the cred, and if found get it, else fail
65 Some(key) => match self.store.creds.get(&self.id) {
66 None => Err(Error::NoEntry),
67 Some(pair) => match pair.value().get_mut(key) {
68 None => Err(Error::NoEntry),
69 Some(mut cred) => {
70 let (key, val) = cred.pair_mut();
71 Ok(f(key, val))
72 }
73 },
74 },
75 // this is a specifier
76 None => {
77 match self.store.creds.get(&self.id) {
78 // there are no matching creds
79 None => Err(Error::NoEntry),
80 // this is a specifier: check for ambiguity and get if not
81 Some(pair) => {
82 let creds = pair.value();
83 match creds.len() {
84 // no matching cred, can't read or update
85 0 => Err(Error::NoEntry),
86 // just one current cred, get it
87 1 => {
88 let mut first = creds.iter_mut().next().unwrap();
89 let (key, val) = first.pair_mut();
90 Ok(f(key, val))
91 }
92 // more than one cred - ambiguous!
93 _ => {
94 let mut entries: Vec<Entry> = vec![];
95 for cred in creds.iter() {
96 let key = CredKey {
97 store: self.store.clone(),
98 id: self.id.clone(),
99 uuid: Some(cred.key().clone()),
100 };
101 entries.push(Entry::new_with_credential(Arc::new(key)));
102 }
103 Err(Error::Ambiguous(entries))
104 }
105 }
106 }
107 }
108 }
109 }
110 }
111
112 /// A simpler form of boilerplate which just looks at the cred's value
113 pub fn with_unique_cred<T, F>(&self, f: F) -> Result<T>
114 where
115 F: FnOnce(&mut CredValue) -> T,
116 {
117 self.with_unique_pair(|_, cred| f(cred))
118 }
119
120 /// This returns the UUID of the sole credential for this cred.
121 pub fn get_uuid(&self) -> Result<String> {
122 self.with_unique_pair(|uuid, _| uuid.to_string())
123 }
124
125 /// This returns the comment of the sole credential for this cred.
126 pub fn get_comment(&self) -> Result<Option<String>> {
127 self.with_unique_pair(|_, cred| cred.comment.clone())
128 }
129}
130
131impl CredentialApi for CredKey {
132 /// See the API docs.
133 fn set_secret(&self, secret: &[u8]) -> Result<()> {
134 let result = self.with_unique_cred(|cred| cred.secret = secret.to_vec());
135 match result {
136 Ok(_) => Ok(()),
137 // a specifier with no credential: create the cred
138 Err(Error::NoEntry) if self.uuid.is_none() => {
139 let value = CredValue::new(secret);
140 let creds = DashMap::new();
141 creds.insert(Uuid::new_v4().to_string(), value);
142 self.store.creds.insert(self.id.clone(), creds);
143 Ok(())
144 }
145 // a wrapper with no cred or an ambiguous spec
146 Err(e) => Err(e),
147 }
148 }
149
150 /// See the API docs.
151 fn get_secret(&self) -> Result<Vec<u8>> {
152 self.with_unique_cred(|cred| cred.secret.clone())
153 }
154
155 /// See the API docs.
156 ///
157 /// The possible attributes on credentials in this store are `uuid`, `comment`,
158 /// and `creation-date`.
159 fn get_attributes(&self) -> Result<HashMap<String, String>> {
160 self.with_unique_pair(|uuid, cred| get_attrs(uuid, cred))
161 }
162
163 /// See the API docs.
164 ///
165 /// Only the `comment` attribute can be updated.
166 fn update_attributes(&self, attrs: &HashMap<&str, &str>) -> Result<()> {
167 parse_attributes(&["comment"], Some(attrs))?;
168 self.with_unique_cred(|cred| update_attrs(cred, attrs))
169 }
170
171 /// See the API docs.
172 fn delete_credential(&self) -> Result<()> {
173 let result = self.with_unique_cred(|_| ());
174 match result {
175 // there is exactly one matching cred, delete it
176 Ok(_) => {
177 match self.uuid.as_ref() {
178 // this is a wrapper, delete the credential key from the map
179 Some(uuid) => {
180 self.store.creds.get(&self.id).unwrap().value().remove(uuid);
181 Ok(())
182 }
183 // this is a specifier, and there's only credential, delete the map
184 None => {
185 self.store.creds.remove(&self.id);
186 Ok(())
187 }
188 }
189 }
190 // there's no cred or many creds, return the error
191 Err(e) => Err(e),
192 }
193 }
194
195 /// See the API docs.
196 ///
197 /// This always returns a new wrapper, even if this is already a wrapper,
198 /// because that's just as easy to do once we've checked the error conditions.
199 fn get_credential(&self) -> Result<Option<Arc<Credential>>> {
200 let result = self.get_uuid();
201 match result {
202 Ok(uuid) => Ok(Some(Arc::new(CredKey {
203 store: self.store.clone(),
204 id: self.id.clone(),
205 uuid: Some(uuid),
206 }))),
207 Err(e) => Err(e),
208 }
209 }
210
211 /// See the API docs.
212 fn get_specifiers(&self) -> Option<(String, String)> {
213 Some((self.id.service.clone(), self.id.user.clone()))
214 }
215
216 /// See the API docs.
217 fn as_any(&self) -> &dyn Any {
218 self
219 }
220
221 /// See the API docs.
222 fn debug_fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223 std::fmt::Debug::fmt(self, f)
224 }
225}
226
227/// get the attributes on a credential
228///
229/// This is a helper function used by get_attributes
230pub fn get_attrs(uuid: &str, cred: &CredValue) -> HashMap<String, String> {
231 let mut attrs = HashMap::new();
232 attrs.insert("uuid".to_string(), uuid.to_string());
233 if let Some(date) = &cred.creation_date {
234 attrs.insert("creation-date".to_string(), date.to_string());
235 }
236 if let Some(comment) = &cred.comment {
237 attrs.insert("comment".to_string(), comment.to_string());
238 };
239 attrs
240}
241
242/// update the attributes on a credential
243///
244/// This is a helper function used by update_attributes
245pub fn update_attrs(cred: &mut CredValue, attrs: &HashMap<&str, &str>) {
246 if let Some(comment) = attrs.get("comment") {
247 cred.comment = Some(comment.to_string());
248 }
249}