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 get_username(&'a self) -> Option<&'a str> {
263 self.get("UserName")
264 }
265
266 pub fn set_username(&mut self, username: Option<&str>) {
267 self.set_unprotected_field_pair("UserName", username);
268 }
269
270 pub fn get_password(&self) -> Option<&str> {
272 self.get("Password")
273 }
274
275 pub fn set_password(&mut self, password: Option<&str>) {
276 self.set_protected_field_pair("Password", password.map(|p| p.as_bytes()));
277 }
278
279 pub fn get_url(&self) -> Option<&str> {
281 self.get("URL")
282 }
283
284 pub fn set_url(&mut self, url: Option<&str>) {
285 self.set_unprotected_field_pair("URL", url);
286 }
287
288 pub fn update_history(&mut self) -> bool {
295 if self.history.is_none() {
296 self.history = Some(History::default());
297 }
298
299 if !self.has_uncommited_changes() {
300 return false;
301 }
302
303 self.times.set_last_modification(Some(Times::now()));
304
305 let mut new_history_entry = self.clone();
306 new_history_entry.history = None;
307
308 if let Some(h) = self.history.as_mut() {
311 h.add_entry(new_history_entry);
312 }
313
314 true
315 }
316
317 pub(crate) fn has_uncommited_changes(&self) -> bool {
320 if let Some(history) = self.history.as_ref() {
321 if history.entries.is_empty() {
322 return true;
323 }
324
325 let new_times = Times::default();
326
327 let mut sanitized_entry = self.clone();
328 sanitized_entry.times = new_times.clone();
329 sanitized_entry.history.take();
330
331 let mut last_history_entry = history.entries.first().unwrap().clone();
332 last_history_entry.times = new_times;
333 last_history_entry.history.take();
334
335 if sanitized_entry.eq(&last_history_entry) {
336 return false;
337 }
338 }
339 true
340 }
341}
342
343#[cfg(test)]
344mod entry_tests {
345 use super::{Entry, Node};
346 use std::{thread, time};
347
348 #[test]
349 fn byte_values() {
350 let mut entry = Entry::default();
351 entry.set_binary_field_pair("a-bytes", Some(&[1, 2, 3]));
352
353 entry.set_unprotected_field_pair("a-unprotected", Some("asdf"));
354 entry.set_protected_field_pair("a-protected", Some("asdf".as_bytes()));
355
356 assert_eq!(entry.get_bytes("a-bytes"), Some(&[1, 2, 3][..]));
357 assert_eq!(entry.get_bytes("a-unprotected"), None);
358 assert_eq!(entry.get_bytes("a-protected"), None);
359
360 assert_eq!(entry.get("a-bytes"), None);
361
362 assert!(!entry.attachments["a-bytes"].data.is_empty());
363 entry.set_binary_field_pair::<&[u8]>("a-bytes", None);
364 assert_eq!(entry.get_bytes("a-bytes"), None);
365 }
366
367 #[test]
368 fn update_history() {
369 let mut entry = Entry::default();
370 let mut last_modification_time = entry.times.get_last_modification().unwrap();
371
372 entry.set_username(Some("user"));
373 thread::sleep(time::Duration::from_secs(1));
376
377 assert!(entry.update_history());
378 assert!(entry.history.is_some());
379 assert_eq!(entry.history.as_ref().unwrap().entries.len(), 1);
380 assert_ne!(entry.times.get_last_modification().unwrap(), last_modification_time);
381 last_modification_time = entry.times.get_last_modification().unwrap();
382 thread::sleep(time::Duration::from_secs(1));
383
384 assert!(!entry.update_history());
387 assert!(entry.history.is_some());
388 assert_eq!(entry.history.as_ref().unwrap().entries.len(), 1);
389 assert_eq!(entry.times.get_last_modification().unwrap(), last_modification_time);
390
391 entry.set_title(Some("first title"));
392
393 assert!(entry.update_history());
394 assert!(entry.history.is_some());
395 assert_eq!(entry.history.as_ref().unwrap().entries.len(), 2);
396 assert_ne!(entry.times.get_last_modification().unwrap(), last_modification_time);
397 last_modification_time = entry.times.get_last_modification().unwrap();
398 thread::sleep(time::Duration::from_secs(1));
399
400 assert!(!entry.update_history());
401 assert!(entry.history.is_some());
402 assert_eq!(entry.history.as_ref().unwrap().entries.len(), 2);
403 assert_eq!(entry.times.get_last_modification().unwrap(), last_modification_time);
404
405 entry.set_title(Some("second title"));
406
407 assert!(entry.update_history());
408 assert!(entry.history.is_some());
409 assert_eq!(entry.history.as_ref().unwrap().entries.len(), 3);
410 assert_ne!(entry.times.get_last_modification().unwrap(), last_modification_time);
411 last_modification_time = entry.times.get_last_modification().unwrap();
412 thread::sleep(time::Duration::from_secs(1));
413
414 assert!(!entry.update_history());
415 assert!(entry.history.is_some());
416 assert_eq!(entry.history.as_ref().unwrap().entries.len(), 3);
417 assert_eq!(entry.times.get_last_modification().unwrap(), last_modification_time);
418
419 let last_history_entry = entry.history.as_ref().unwrap().entries.first().unwrap();
420 assert_eq!(last_history_entry.get_title().unwrap(), "second title");
421
422 for history_entry in &entry.history.unwrap().entries {
423 assert!(history_entry.history.is_none());
424 }
425 }
426
427 #[cfg(feature = "totp")]
428 #[test]
429 fn totp() {
430 let mut entry = Entry::default();
431 entry.set_raw_otp_value(
432 Some("otpauth://totp/ACME%20Co:john.doe@email.com?secret=HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ&issuer=ACME%20Co&algorithm=SHA1&digits=6&period=30"),
433 );
434
435 assert!(entry.get_otp().is_ok());
436 }
437
438 #[cfg(feature = "serialization")]
439 #[test]
440 fn serialization() {
441 use super::Value;
442 assert_eq!(
443 serde_json::to_string(&Value::Unprotected(vec![65, 66, 67])).unwrap(),
444 "[65,66,67]".to_string()
445 );
446
447 assert_eq!(
448 serde_json::to_string(&Value::Unprotected("ABC".to_string())).unwrap(),
449 "\"ABC\"".to_string()
450 );
451
452 assert_eq!(
453 serde_json::to_string(&Value::<String>::protected("ABC")).unwrap(),
454 "\"ABC\"".to_string()
455 );
456 }
457}