Skip to main content

keepass/db/types/
entry.rs

1use std::{
2	collections::HashMap,
3	ops::{Deref, DerefMut},
4};
5
6use uuid::Uuid;
7
8use crate::{
9	Database,
10	db::{GroupId, Times, Value, fields},
11};
12
13/// Unique identifier for an [Entry]
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub struct EntryId(Uuid);
16
17impl Default for EntryId {
18	fn default() -> Self {
19		Self::new()
20	}
21}
22
23impl EntryId {
24	/// Generate a new random `EntryId`.
25	pub fn new() -> Self {
26		Self(Uuid::new_v4())
27	}
28
29	/// Build an `EntryId` from an existing [Uuid].
30	///
31	/// Useful when an entry's identifier needs to be pinned (e.g. test fixtures or migrations).
32	/// Pair with [Group::add_entry_with_id][crate::db::GroupMut::add_entry_with_id] to insert
33	/// an entry under a chosen identifier.
34	pub const fn from_uuid(uuid: Uuid) -> Self {
35		Self(uuid)
36	}
37
38	/// Get the Uuid contained inside
39	pub fn uuid(&self) -> Uuid {
40		self.0
41	}
42}
43
44impl From<Uuid> for EntryId {
45	fn from(uuid: Uuid) -> Self {
46		Self::from_uuid(uuid)
47	}
48}
49
50/// A database entry containing key-value fields.
51#[derive(Debug, Eq, PartialEq, Clone)]
52pub struct Entry {
53	/// Unique identifier of this entry.
54	pub(crate) id: EntryId,
55
56	/// Parent group identifier.
57	pub(crate) parent: GroupId,
58
59	/// Key-value fields, including username, password, URL, and notes.
60	///
61	/// Common field names are available in [crate::db::fields].
62	pub fields: HashMap<String, Value<String>>,
63
64	/// Entry timestamps.
65	pub times: Times,
66}
67
68impl Entry {
69	pub(crate) fn with_id(id: EntryId, parent: GroupId) -> Self {
70		Self { id, parent, fields: HashMap::new(), times: Times::new() }
71	}
72
73	/// Get the unique identifier for the [Entry]
74	pub fn id(&self) -> EntryId {
75		self.id
76	}
77
78	/// Get a field by name, taking care of unprotecting Protected values automatically
79	pub fn get(&self, key: &str) -> Option<&str> {
80		self.fields.get(key).map(|v| v.as_str())
81	}
82
83	/// Set a field's value by name
84	pub fn set(&mut self, key: impl Into<String>, value: Value<String>) {
85		self.fields.insert(key.into(), value);
86	}
87
88	/// Set a field's unprotected value by name
89	pub fn set_unprotected(&mut self, key: impl Into<String>, value: impl Into<String>) {
90		self.set(key, Value::unprotected(value));
91	}
92
93	/// Set an unprotected field only if its value or protection differs.
94	/// Returns true if the field was changed.
95	pub fn update_unprotected(&mut self, key: &str, value: &str) -> bool {
96		if self.fields.get(key).is_some_and(|current| {
97			!current.is_protected() && current.get() == value
98		}) {
99			return false;
100		}
101
102		self.set(key, Value::unprotected(value.to_owned()));
103		true
104	}
105
106	/// Set a protected field only if its value or protection differs.
107	/// Returns true if the field was changed.
108	pub fn update_protected(&mut self, key: &str, value: &str) -> bool {
109		if self.fields.get(key).is_some_and(|current| {
110			current.is_protected() && current.get() == value
111		}) {
112			return false;
113		}
114
115		self.set(key, Value::protected(value.to_owned()));
116		true
117	}
118
119	/// Set a field's protected value by name
120	pub fn set_protected(&mut self, key: impl Into<String>, value: impl Into<String>) {
121		self.set(key, Value::protected(value));
122	}
123
124	/// Convenience method for getting the raw value of the 'otp' field
125	pub fn get_raw_otp_value(&self) -> Option<&str> {
126		self.get(fields::OTP)
127	}
128
129	/// Convenience method for getting the value of the 'Title' field
130	pub fn get_title(&self) -> Option<&str> {
131		self.get(fields::TITLE)
132	}
133
134	/// Convenience method for getting the value of the 'UserName' field
135	pub fn get_username(&self) -> Option<&str> {
136		self.get(fields::USERNAME)
137	}
138
139	/// Convenience method for getting the value of the 'Password' field
140	pub fn get_password(&self) -> Option<&str> {
141		self.get(fields::PASSWORD)
142	}
143
144	/// Convenience method for getting the value of the 'URL' field
145	pub fn get_url(&self) -> Option<&str> {
146		self.get(fields::URL)
147	}
148}
149
150impl std::fmt::Display for EntryId {
151	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152		write!(f, "{}", self.0)
153	}
154}
155
156/// An immutable reference to an [Entry]. Implements [Deref] to [&Entry][Entry].
157pub struct EntryRef<'a> {
158	database: &'a Database,
159	id: EntryId,
160}
161
162impl EntryRef<'_> {
163	pub(crate) fn new(database: &Database, id: EntryId) -> EntryRef<'_> {
164		EntryRef { database, id }
165	}
166}
167
168impl Deref for EntryRef<'_> {
169	type Target = Entry;
170
171	#[allow(clippy::expect_used, clippy::missing_panics_doc)] // entry existence is guaranteed
172	fn deref(&self) -> &Self::Target {
173		// UNWRAP safety: EntryRef can only be constructed with a valid EntryId
174		self.database.entries.get(&self.id).expect("Entry not found")
175	}
176}
177
178/// A mutable reference to an [Entry]. Implements [DerefMut] to [&mut Entry][Entry].
179pub struct EntryMut<'a> {
180	database: &'a mut Database,
181	id: EntryId,
182}
183
184impl EntryMut<'_> {
185	pub(crate) fn new(database: &mut Database, id: EntryId) -> EntryMut<'_> {
186		EntryMut { database, id }
187	}
188
189	/// Remove this entry from the database
190	#[allow(clippy::expect_used, clippy::missing_panics_doc)] // the entry and parent should always be found
191	pub fn remove(self) {
192		let entry = self.database.entries.remove(&self.id).expect("Entry not found");
193		self.database.group_mut(entry.parent).expect("Parent group not found").entries.shift_remove(&self.id);
194	}
195}
196
197impl Deref for EntryMut<'_> {
198	type Target = Entry;
199
200	#[allow(clippy::expect_used, clippy::missing_panics_doc)] // entry existence is guaranteed
201	fn deref(&self) -> &Self::Target {
202		// UNWRAP safety: EntryMut can only be constructed with a valid EntryId
203		self.database.entries.get(&self.id).expect("Entry not found")
204	}
205}
206
207impl DerefMut for EntryMut<'_> {
208	#[allow(clippy::expect_used, clippy::missing_panics_doc)] // entry existence is guaranteed
209	fn deref_mut(&mut self) -> &mut Self::Target {
210		// UNWRAP safety: EntryMut can only be constructed with a valid EntryId
211		self.database.entries.get_mut(&self.id).expect("Entry not found")
212	}
213}
214
215#[cfg(test)]
216#[allow(clippy::unwrap_used)]
217mod tests {
218	use super::EntryId;
219
220	#[test]
221	fn entry_id_new_generates_distinct_ids() {
222		assert_ne!(EntryId::new(), EntryId::new());
223	}
224
225	#[test]
226	fn update_fields_only_when_changed() {
227		use super::Entry;
228		use crate::db::GroupId;
229
230		let mut entry = Entry::with_id(EntryId::new(), GroupId::new());
231
232		assert!(entry.update_protected("Password", "secret"));
233		assert!(!entry.update_protected("Password", "secret"));
234		assert!(entry.fields["Password"].is_protected());
235
236		assert!(entry.update_protected("Password", "new-secret"));
237		assert_eq!(entry.get("Password"), Some("new-secret"));
238
239		assert!(entry.update_unprotected("Password", "new-secret"));
240		assert!(!entry.fields["Password"].is_protected());
241
242		assert!(!entry.update_unprotected("Password", "new-secret"));
243
244		assert!(entry.update_protected("Password", "new-secret"));
245		assert!(entry.fields["Password"].is_protected());
246	}
247}