1use crate::db::{
2 Attachment, AutoType, Color, CustomDataItem, History, IconId, Times, Value,
3 node::{Node, NodePtr},
4 rc_refcell_node,
5};
6use secrecy::ExposeSecret;
7use std::collections::HashMap;
8use uuid::Uuid;
9
10#[derive(Debug, Clone)]
12#[cfg_attr(feature = "serialization", derive(serde::Serialize))]
13pub struct Entry {
14 pub(crate) uuid: Uuid,
15 pub(crate) fields: HashMap<String, Value<String>>,
16 pub(crate) autotype: Option<AutoType>,
17 pub(crate) tags: Vec<String>,
18
19 pub(crate) times: Times,
20
21 pub(crate) custom_data: HashMap<String, CustomDataItem>,
22
23 pub(crate) icon_id: Option<IconId>,
24 pub(crate) custom_icon: Option<Uuid>,
25
26 pub(crate) foreground_color: Option<Color>,
27 pub(crate) background_color: Option<Color>,
28
29 pub(crate) override_url: Option<String>,
30 pub(crate) quality_check: Option<bool>,
31
32 pub attachments: HashMap<String, Attachment>,
33
34 pub(crate) history: Option<History>,
35
36 pub(crate) parent: Option<Uuid>,
37
38 pub(crate) previous_parent_group: Option<Uuid>,
39}
40
41impl Default for Entry {
42 fn default() -> Self {
43 Self {
44 uuid: Uuid::new_v4(),
45 fields: HashMap::new(),
46 autotype: None,
47 tags: Vec::new(),
48 times: Times::new(),
49 custom_data: Default::default(),
50 icon_id: Some(IconId::KEY),
51 custom_icon: None,
52 foreground_color: None,
53 background_color: None,
54 override_url: None,
55 quality_check: None,
56 attachments: HashMap::new(),
57 history: None,
58 parent: None,
59 previous_parent_group: None,
60 }
61 }
62}
63
64impl PartialEq for Entry {
65 fn eq(&self, other: &Self) -> bool {
66 self.uuid == other.uuid
67 && self.fields == other.fields
68 && self.autotype == other.autotype
69 && self.tags == other.tags
70 && self.times == other.times
71 && self.custom_data == other.custom_data
72 && self.icon_id == other.icon_id
73 && self.custom_icon == other.custom_icon
74 && self.foreground_color == other.foreground_color
75 && self.background_color == other.background_color
76 && self.override_url == other.override_url
77 && self.quality_check == other.quality_check
78 && self.attachments == other.attachments
79 && self.history == other.history
80 }
82}
83
84impl Eq for Entry {}
85
86impl Node for Entry {
87 fn duplicate(&self) -> NodePtr {
88 let mut tmp = self.clone();
89 tmp.parent = None;
90 rc_refcell_node(tmp)
91 }
92
93 fn get_uuid(&self) -> Uuid {
94 self.uuid
95 }
96
97 fn set_uuid(&mut self, uuid: Uuid) {
98 self.uuid = uuid;
99 }
100
101 fn get_title(&self) -> Option<&str> {
102 self.get("Title")
103 }
104
105 fn set_title(&mut self, title: Option<&str>) {
106 self.set_unprotected_field_pair("Title", title);
107 }
108
109 fn get_notes(&self) -> Option<&str> {
110 self.get("Notes")
111 }
112
113 fn set_notes(&mut self, notes: Option<&str>) {
114 self.set_unprotected_field_pair("Notes", notes);
115 }
116
117 fn get_icon_id(&self) -> Option<IconId> {
118 self.icon_id
119 }
120
121 fn set_icon_id(&mut self, icon_id: Option<IconId>) {
122 self.icon_id = icon_id;
123 }
124
125 fn get_custom_icon_uuid(&self) -> Option<Uuid> {
126 self.custom_icon
127 }
128
129 fn get_times(&self) -> &Times {
130 &self.times
131 }
132
133 fn get_times_mut(&mut self) -> &mut Times {
134 &mut self.times
135 }
136
137 fn get_parent(&self) -> Option<Uuid> {
138 self.parent
139 }
140
141 fn set_parent(&mut self, parent: Option<Uuid>) {
142 self.parent = parent;
143 }
144}
145
146impl Entry {
147 pub fn quality_check(&self) -> bool {
148 self.quality_check.unwrap_or(true)
149 }
150
151 pub fn previous_parent_group(&self) -> Option<Uuid> {
152 self.previous_parent_group
153 }
154
155 pub fn custom_icon_uuid(&self) -> Option<Uuid> {
156 self.custom_icon
157 }
158
159 pub fn custom_data(&self) -> &HashMap<String, CustomDataItem> {
160 &self.custom_data
161 }
162
163 pub fn custom_data_mut(&mut self) -> &mut HashMap<String, CustomDataItem> {
164 &mut self.custom_data
165 }
166
167 pub fn get_history(&self) -> &Option<History> {
168 &self.history
169 }
170
171 pub fn purge_history(&mut self) {
172 self.history = None;
173 }
174
175 pub(crate) fn set_unprotected_field_pair(&mut self, field_name: &str, field_value: Option<&str>) {
176 if let Some(field_value) = field_value {
177 let v = Value::Unprotected(field_value.to_string());
178 self.fields.insert(field_name.to_string(), v);
179 } else {
180 self.fields.remove(field_name);
181 }
182 }
183
184 pub(crate) fn set_protected_field_pair<T: AsRef<[u8]>>(&mut self, field_name: &str, field_value: Option<T>) {
185 if let Some(field_value) = field_value {
186 let value = String::from_utf8_lossy(field_value.as_ref()).into_owned();
187 let v = Value::protected(value);
188 self.fields.insert(field_name.to_string(), v);
189 } else {
190 self.fields.remove(field_name);
191 }
192 }
193
194 pub(crate) fn set_binary_field_pair<T: AsRef<[u8]>>(&mut self, field_name: &str, field_value: Option<T>) {
195 if let Some(field_value) = field_value {
196 self.attachments.insert(
197 field_name.to_string(),
198 Attachment {
199 data: Value::unprotected(field_value.as_ref().to_vec()),
200 },
201 );
202 } else {
203 self.attachments.remove(field_name);
204 }
205 }
206}
207
208impl<'a> Entry {
209 pub fn get(&'a self, key: &str) -> Option<&'a str> {
211 match self.fields.get(key) {
212 None => None,
213 Some(Value::Protected(pv)) => Some(pv.expose_secret()),
214 Some(Value::Unprotected(uv)) => Some(uv),
215 }
216 }
217
218 pub fn get_bytes(&'a self, key: &str) -> Option<&'a [u8]> {
220 self.attachments.get(key).map(|attachment| attachment.data.get().as_slice())
221 }
222
223 pub fn get_autotype(&self) -> Option<&AutoType> {
224 self.autotype.as_ref()
225 }
226
227 pub fn set_autotype(&mut self, autotype: Option<AutoType>) {
228 self.autotype = autotype;
229 }
230
231 pub fn get_tags(&self) -> &Vec<String> {
234 self.tags.as_ref()
235 }
236
237 pub fn get_tags_mut(&mut self) -> &mut Vec<String> {
238 self.tags.as_mut()
239 }
240
241 #[rustfmt::skip]
242 const EXCLUDED_FIELDS: [&'static str; 9] = ["Password", "BinaryData", "otp", "Title", "URL", "UserName", "Notes", "Additional", "BinaryDesc"];
243
244 pub fn set_additional_attribute(&mut self, key: &str, value: Option<&str>) -> crate::Result<()> {
246 if Self::EXCLUDED_FIELDS.contains(&key) {
247 return Err(format!("Cannot set additional attribute for field {key}").into());
248 }
249 self.set_unprotected_field_pair(key, value);
250 Ok(())
251 }
252
253 pub fn get_additional_attribute(&self, key: &str) -> Option<&str> {
255 if Self::EXCLUDED_FIELDS.contains(&key) {
256 return None;
257 }
258 self.get(key)
259 }
260
261 pub fn additional_attributes(&self) -> Vec<(String, String)> {
263 self.fields
264 .keys()
265 .filter(|key| !Self::EXCLUDED_FIELDS.contains(&key.as_str()))
266 .filter_map(|key| self.get(key).map(|value| (key.clone(), value.to_string())))
267 .collect()
268 }
269
270 pub fn get_username(&'a self) -> Option<&'a str> {
272 self.get("UserName")
273 }
274
275 pub fn set_username(&mut self, username: Option<&str>) {
276 self.set_unprotected_field_pair("UserName", username);
277 }
278
279 pub fn get_password(&self) -> Option<&str> {
281 self.get("Password")
282 }
283
284 pub fn set_password(&mut self, password: Option<&str>) {
285 self.set_protected_field_pair("Password", password.map(|p| p.as_bytes()));
286 }
287
288 pub fn get_url(&self) -> Option<&str> {
290 self.get("URL")
291 }
292
293 pub fn set_url(&mut self, url: Option<&str>) {
294 self.set_unprotected_field_pair("URL", url);
295 }
296
297 pub fn update_history(&mut self) -> bool {
304 if self.history.is_none() {
305 self.history = Some(History::default());
306 }
307
308 if !self.has_uncommited_changes() {
309 return false;
310 }
311
312 self.times.set_last_modification(Some(Times::now()));
313
314 let mut new_history_entry = self.clone();
315 new_history_entry.history = None;
316
317 if let Some(h) = self.history.as_mut() {
320 h.add_entry(new_history_entry);
321 }
322
323 true
324 }
325
326 pub(crate) fn has_uncommited_changes(&self) -> bool {
329 if let Some(history) = self.history.as_ref() {
330 if history.entries.is_empty() {
331 return true;
332 }
333
334 let new_times = Times::default();
335
336 let mut sanitized_entry = self.clone();
337 sanitized_entry.times = new_times.clone();
338 sanitized_entry.history.take();
339
340 let mut last_history_entry = history.entries.first().unwrap().clone();
341 last_history_entry.times = new_times;
342 last_history_entry.history.take();
343
344 if sanitized_entry.eq(&last_history_entry) {
345 return false;
346 }
347 }
348 true
349 }
350}
351
352#[cfg(test)]
353mod entry_tests {
354 use super::{Entry, Node};
355 use std::{thread, time};
356
357 #[test]
358 fn byte_values() {
359 let mut entry = Entry::default();
360 entry.set_binary_field_pair("a-bytes", Some(&[1, 2, 3]));
361
362 entry.set_unprotected_field_pair("a-unprotected", Some("asdf"));
363 entry.set_protected_field_pair("a-protected", Some("asdf".as_bytes()));
364
365 assert_eq!(entry.get_bytes("a-bytes"), Some(&[1, 2, 3][..]));
366 assert_eq!(entry.get_bytes("a-unprotected"), None);
367 assert_eq!(entry.get_bytes("a-protected"), None);
368
369 assert_eq!(entry.get("a-bytes"), None);
370
371 assert!(!entry.attachments["a-bytes"].data.is_empty());
372 entry.set_binary_field_pair::<&[u8]>("a-bytes", None);
373 assert_eq!(entry.get_bytes("a-bytes"), None);
374 }
375
376 #[test]
377 fn update_history() {
378 let mut entry = Entry::default();
379 let mut last_modification_time = entry.times.get_last_modification().unwrap();
380
381 entry.set_username(Some("user"));
382 thread::sleep(time::Duration::from_secs(1));
385
386 assert!(entry.update_history());
387 assert!(entry.history.is_some());
388 assert_eq!(entry.history.as_ref().unwrap().entries.len(), 1);
389 assert_ne!(entry.times.get_last_modification().unwrap(), last_modification_time);
390 last_modification_time = entry.times.get_last_modification().unwrap();
391 thread::sleep(time::Duration::from_secs(1));
392
393 assert!(!entry.update_history());
396 assert!(entry.history.is_some());
397 assert_eq!(entry.history.as_ref().unwrap().entries.len(), 1);
398 assert_eq!(entry.times.get_last_modification().unwrap(), last_modification_time);
399
400 entry.set_title(Some("first title"));
401
402 assert!(entry.update_history());
403 assert!(entry.history.is_some());
404 assert_eq!(entry.history.as_ref().unwrap().entries.len(), 2);
405 assert_ne!(entry.times.get_last_modification().unwrap(), last_modification_time);
406 last_modification_time = entry.times.get_last_modification().unwrap();
407 thread::sleep(time::Duration::from_secs(1));
408
409 assert!(!entry.update_history());
410 assert!(entry.history.is_some());
411 assert_eq!(entry.history.as_ref().unwrap().entries.len(), 2);
412 assert_eq!(entry.times.get_last_modification().unwrap(), last_modification_time);
413
414 entry.set_title(Some("second title"));
415
416 assert!(entry.update_history());
417 assert!(entry.history.is_some());
418 assert_eq!(entry.history.as_ref().unwrap().entries.len(), 3);
419 assert_ne!(entry.times.get_last_modification().unwrap(), last_modification_time);
420 last_modification_time = entry.times.get_last_modification().unwrap();
421 thread::sleep(time::Duration::from_secs(1));
422
423 assert!(!entry.update_history());
424 assert!(entry.history.is_some());
425 assert_eq!(entry.history.as_ref().unwrap().entries.len(), 3);
426 assert_eq!(entry.times.get_last_modification().unwrap(), last_modification_time);
427
428 let last_history_entry = entry.history.as_ref().unwrap().entries.first().unwrap();
429 assert_eq!(last_history_entry.get_title().unwrap(), "second title");
430
431 for history_entry in &entry.history.unwrap().entries {
432 assert!(history_entry.history.is_none());
433 }
434 }
435
436 #[cfg(feature = "totp")]
437 #[test]
438 fn totp() {
439 let mut entry = Entry::default();
440 entry.set_raw_otp_value(
441 Some("otpauth://totp/ACME%20Co:john.doe@email.com?secret=HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ&issuer=ACME%20Co&algorithm=SHA1&digits=6&period=30"),
442 );
443
444 assert!(entry.get_otp().is_ok());
445 }
446
447 #[cfg(feature = "serialization")]
448 #[test]
449 fn serialization() {
450 use super::Value;
451 assert_eq!(
452 serde_json::to_string(&Value::Unprotected(vec![65, 66, 67])).unwrap(),
453 "[65,66,67]".to_string()
454 );
455
456 assert_eq!(
457 serde_json::to_string(&Value::Unprotected("ABC".to_string())).unwrap(),
458 "\"ABC\"".to_string()
459 );
460
461 assert_eq!(
462 serde_json::to_string(&Value::<String>::protected("ABC")).unwrap(),
463 "\"ABC\"".to_string()
464 );
465 }
466}