Skip to main content

keepass/db/types/
group.rs

1use std::ops::{Deref, DerefMut};
2
3use indexmap::IndexSet;
4use thiserror::Error;
5use uuid::Uuid;
6
7use crate::{
8	Database,
9	db::{Entry, EntryId, EntryMut, EntryRef},
10};
11
12/// Unique identifier for a [Group]
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub struct GroupId(Uuid);
15
16impl Default for GroupId {
17	fn default() -> Self {
18		Self::new()
19	}
20}
21
22impl GroupId {
23	/// Generate a new random `GroupId`.
24	pub fn new() -> Self {
25		Self(Uuid::new_v4())
26	}
27
28	/// Build a `GroupId` from an existing [Uuid].
29	///
30	/// Useful when a group's identifier needs to be pinned (e.g. test fixtures or migrations).
31	/// Pair with [Group::add_group_with_id][GroupMut::add_group_with_id] to insert
32	/// a group under a chosen identifier.
33	pub const fn from_uuid(uuid: Uuid) -> Self {
34		Self(uuid)
35	}
36
37	/// Get the Uuid contained inside
38	pub fn uuid(&self) -> Uuid {
39		self.0
40	}
41}
42
43impl From<Uuid> for GroupId {
44	fn from(uuid: Uuid) -> Self {
45		Self::from_uuid(uuid)
46	}
47}
48
49impl std::fmt::Display for GroupId {
50	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51		write!(f, "{}", self.0)
52	}
53}
54
55/// A database group containing child groups and entries.
56#[derive(Debug, Eq, PartialEq, Clone)]
57pub struct Group {
58	/// Unique identifier of the group.
59	pub(crate) id: GroupId,
60
61	/// Identifier of the parent group, if any.
62	pub(crate) parent: Option<GroupId>,
63
64	/// Name of the group.
65	pub name: String,
66
67	/// Child group identifiers.
68	pub(crate) groups: IndexSet<GroupId>,
69
70	/// Entry identifiers directly contained in this group.
71	pub(crate) entries: IndexSet<EntryId>,
72}
73
74impl Group {
75	/// Get the unique identifier for this group
76	pub fn id(&self) -> GroupId {
77		self.id
78	}
79
80	pub(crate) fn with_id(id: GroupId, parent: Option<GroupId>) -> Group {
81		Group { id, parent, name: String::new(), groups: IndexSet::new(), entries: IndexSet::new() }
82	}
83
84	/// Get an iterator over the IDs of all contained groups
85	pub fn group_ids(&self) -> impl Iterator<Item = GroupId> + '_ {
86		self.groups.iter().cloned()
87	}
88
89	/// Get an iterator over the IDs of all contained entries
90	pub fn entry_ids(&self) -> impl Iterator<Item = EntryId> + '_ {
91		self.entries.iter().cloned()
92	}
93}
94
95/// Immutable reference to a [Group]. Implements [Deref] to [&Group][Group].
96#[derive(Clone)]
97pub struct GroupRef<'a> {
98	database: &'a crate::db::Database,
99	id: GroupId,
100}
101
102impl GroupRef<'_> {
103	pub(crate) fn new(database: &Database, id: GroupId) -> GroupRef<'_> {
104		GroupRef { database, id }
105	}
106
107	/// Get a contained group by ID
108	pub fn group(&self, id: GroupId) -> Option<GroupRef<'_>> {
109		self.groups.contains(&id).then(move || GroupRef::new(self.database, id))
110	}
111
112	/// Get a contained entry by ID
113	pub fn entry(&self, id: EntryId) -> Option<EntryRef<'_>> {
114		self.entries.contains(&id).then(move || EntryRef::new(self.database, id))
115	}
116
117	/// Get an iterator over all contained groups
118	pub fn groups(&self) -> impl Iterator<Item = GroupRef<'_>> + '_ {
119		self.groups.iter().map(move |id| GroupRef::new(self.database, *id))
120	}
121
122	/// Get an iterator over all contained entries
123	pub fn entries(&self) -> impl Iterator<Item = EntryRef<'_>> + '_ {
124		self.entries.iter().map(move |id| EntryRef::new(self.database, *id))
125	}
126}
127
128impl Deref for GroupRef<'_> {
129	type Target = Group;
130
131	#[allow(clippy::expect_used, clippy::missing_panics_doc)] // group existence is guaranteed
132	fn deref(&self) -> &Self::Target {
133		self.database.groups.get(&self.id).expect("GroupRef points to a non-existing group")
134	}
135}
136
137/// Mutable reference to a [Group]. Implements [DerefMut] to [&mut Group][Group]
138pub struct GroupMut<'a> {
139	database: &'a mut crate::db::Database,
140	id: GroupId,
141}
142
143impl GroupMut<'_> {
144	pub(crate) fn new(database: &mut Database, id: GroupId) -> GroupMut<'_> {
145		GroupMut { database, id }
146	}
147
148	/// Get a mutable reference to a contained group by ID
149	pub fn group_mut(&mut self, id: GroupId) -> Option<GroupMut<'_>> {
150		self.groups.contains(&id).then(move || GroupMut::new(self.database, id))
151	}
152
153	/// Get a mutable reference to a contained entry by ID
154	pub fn entry_mut(&mut self, id: EntryId) -> Option<EntryMut<'_>> {
155		self.entries.contains(&id).then(move || EntryMut::new(self.database, id))
156	}
157
158	/// Convenience method to edit the group in a closure.
159	pub fn edit(&mut self, f: impl FnOnce(&mut GroupMut<'_>)) -> &mut Self {
160		f(self);
161		self
162	}
163
164	/// Adds a new subgroup to this group and returns a mutable reference to it.
165	#[allow(clippy::missing_panics_doc)]
166	pub fn add_group(&mut self) -> GroupMut<'_> {
167		#[allow(clippy::expect_used)]
168		self.add_group_with_id(GroupId::new()).expect("fresh v4 UUID cannot collide with an existing group identifier")
169	}
170
171	/// Adds a new entry to this group and returns a mutable reference to it.
172	#[allow(clippy::missing_panics_doc)]
173	pub fn add_entry(&mut self) -> EntryMut<'_> {
174		#[allow(clippy::expect_used)]
175		self.add_entry_with_id(EntryId::new()).expect("fresh v4 UUID cannot collide with an existing entry identifier")
176	}
177	/// Adds a new entry under a caller-supplied [EntryId] and returns a mutable reference to it.
178	///
179	/// Returns [DuplicateEntryIdError] if an entry with the same identifier already
180	/// exists anywhere in the database.
181	///
182	/// # Example
183	///
184	/// ```
185	/// use keepass::db::{Database, EntryId, fields};
186	/// use uuid::uuid;
187	///
188	/// let mut db = Database::new();
189	/// let entry_id: EntryId = uuid!("00000000-0000-0000-0000-000000000001").into();
190	/// let mut root = db.root_mut();
191	/// let mut entry = root.add_entry_with_id(entry_id).unwrap();
192	/// entry.set_unprotected(fields::TITLE, "Example");
193	/// ```
194	pub fn add_entry_with_id(&mut self, id: EntryId) -> Result<EntryMut<'_>, DuplicateEntryIdError> {
195		if self.database.entries.contains_key(&id) {
196			return Err(DuplicateEntryIdError(id));
197		}
198
199		let new_entry = Entry::with_id(id, self.id);
200		self.entries.insert(id);
201		self.database.entries.insert(id, new_entry);
202
203		Ok(EntryMut::new(self.database, id))
204	}
205
206	/// Adds a new subgroup under a caller-supplied [GroupId] and returns a mutable reference to
207	/// it.
208	///
209	/// Returns [DuplicateGroupIdError] if a group with the same identifier already
210	/// exists anywhere in the database.
211	///
212	/// # Example
213	///
214	/// ```
215	/// use keepass::db::{Database, GroupId};
216	/// use uuid::uuid;
217	///
218	/// let mut db = Database::new();
219	/// let group_id: GroupId = uuid!("00000000-0000-0000-0000-000000000002").into();
220	/// db.root_mut()
221	///     .add_group_with_id(group_id)
222	///     .unwrap()
223	///     .edit(|g| g.name = "Pinned group".to_string());
224	/// ```
225	pub fn add_group_with_id(&mut self, id: GroupId) -> Result<GroupMut<'_>, DuplicateGroupIdError> {
226		if self.database.groups.contains_key(&id) {
227			return Err(DuplicateGroupIdError(id));
228		}
229
230		let new_group = Group::with_id(id, Some(self.id));
231		self.groups.insert(id);
232		self.database.groups.insert(id, new_group);
233
234		Ok(GroupMut::new(self.database, id))
235	}
236}
237
238/// Attempted to add a group with an ID that already exists in the database.
239#[derive(Debug, Error)]
240#[error("a group with ID {0} already exists in the database")]
241pub struct DuplicateGroupIdError(pub GroupId);
242
243/// Attempted to add an entry with an ID that already exists in the database.
244#[derive(Debug, Error)]
245#[error("an entry with ID {0} already exists in the database")]
246pub struct DuplicateEntryIdError(pub EntryId);
247
248impl Deref for GroupMut<'_> {
249	type Target = Group;
250
251	#[allow(clippy::expect_used, clippy::missing_panics_doc)] // group existence is guaranteed
252	fn deref(&self) -> &Self::Target {
253		self.database.groups.get(&self.id).expect("GroupMut points to a non-existing group")
254	}
255}
256
257impl DerefMut for GroupMut<'_> {
258	#[allow(clippy::expect_used, clippy::missing_panics_doc)] // group existence is guaranteed
259	fn deref_mut(&mut self) -> &mut Self::Target {
260		self.database.groups.get_mut(&self.id).expect("GroupMut points to a non-existing group")
261	}
262}
263
264#[cfg(test)]
265#[allow(clippy::unwrap_used)]
266mod group_tests {
267	use crate::Database;
268	use crate::db::fields;
269
270	#[test]
271	fn get() {
272		let mut db = Database::new();
273
274		let general_group_id = db.root_mut().add_group().edit(|g| g.name = "General".into()).id();
275		let sample_entry_id = {
276			let mut group = db.group_mut(general_group_id).unwrap();
277			let mut entry = group.add_entry();
278			entry.set_unprotected(fields::TITLE, "Sample Entry #2");
279			entry.id()
280		};
281
282		assert_eq!(db.entry(sample_entry_id).unwrap().get(fields::TITLE), Some("Sample Entry #2"));
283
284		let root = db.root();
285
286		assert!(root.group(general_group_id).is_some());
287		assert!(db.group(general_group_id).unwrap().entry(sample_entry_id).is_some());
288	}
289
290	#[test]
291	fn get_mut() {
292		let mut db = Database::new();
293
294		let general_group_id = db.root_mut().add_group().edit(|g| g.name = "General".into()).id();
295
296		let sample_entry_id = {
297			let mut group = db.group_mut(general_group_id).unwrap();
298			let mut entry = group.add_entry();
299			entry.set_unprotected(fields::TITLE, "Sample Entry #2");
300			entry.id()
301		};
302
303		assert_eq!(db.entry_mut(sample_entry_id).unwrap().get(fields::TITLE), Some("Sample Entry #2"));
304
305		assert!(db.root_mut().group_mut(general_group_id).is_some());
306
307		assert!(db.group_mut(general_group_id).unwrap().entry_mut(sample_entry_id).is_some());
308	}
309
310	#[test]
311	fn add_entry_with_id_uses_supplied_uuid() {
312		use crate::db::EntryId;
313		use uuid::uuid;
314
315		let mut db = Database::new();
316		let pinned_uuid = uuid!("00000000-0000-0000-0000-0000000000aa");
317		let pinned: EntryId = pinned_uuid.into();
318		let inserted_id = {
319			let mut root = db.root_mut();
320			let mut entry = root.add_entry_with_id(pinned).unwrap();
321			entry.set_unprotected(fields::TITLE, "pinned");
322			entry.id()
323		};
324		assert_eq!(inserted_id, pinned);
325		assert_eq!(inserted_id.uuid(), pinned_uuid);
326		assert_eq!(db.entry(pinned).unwrap().get(fields::TITLE), Some("pinned"),);
327	}
328
329	#[test]
330	fn add_entry_with_id_duplicate_returns_error() {
331		use crate::db::{DuplicateEntryIdError, EntryId};
332		use uuid::uuid;
333
334		let mut db = Database::new();
335		let pinned: EntryId = uuid!("00000000-0000-0000-0000-0000000000ab").into();
336
337		db.root_mut().add_entry_with_id(pinned).unwrap();
338
339		assert!(matches!(
340			db.root_mut().add_entry_with_id(pinned),
341			Err(DuplicateEntryIdError(eid)) if eid == pinned
342		));
343	}
344
345	#[test]
346	fn add_group_with_id_uses_supplied_uuid() {
347		use crate::db::GroupId;
348		use uuid::uuid;
349
350		let mut db = Database::new();
351		let pinned_uuid = uuid!("00000000-0000-0000-0000-0000000000ba");
352		let pinned: GroupId = pinned_uuid.into();
353
354		let inserted_id = db.root_mut().add_group_with_id(pinned).unwrap().edit(|g| g.name = "pinned".into()).id();
355
356		assert_eq!(inserted_id, pinned);
357		assert_eq!(inserted_id.uuid(), pinned_uuid);
358		assert_eq!(db.group(pinned).unwrap().name, "pinned");
359	}
360
361	#[test]
362	fn add_group_with_id_duplicate_returns_error() {
363		use crate::db::{DuplicateGroupIdError, GroupId};
364		use uuid::uuid;
365
366		let mut db = Database::new();
367		let pinned: GroupId = uuid!("00000000-0000-0000-0000-0000000000bb").into();
368
369		db.root_mut().add_group_with_id(pinned).unwrap();
370
371		assert!(matches!(
372			db.root_mut().add_group_with_id(pinned),
373			Err(DuplicateGroupIdError(gid)) if gid == pinned
374		));
375	}
376
377	#[test]
378	fn group_id_new_generates_distinct_ids() {
379		use crate::db::GroupId;
380
381		assert_ne!(GroupId::new(), GroupId::new());
382	}
383
384	#[test]
385	fn from_uuid_impls_match_constructors() {
386		use crate::db::{EntryId, GroupId};
387		use uuid::uuid;
388
389		let raw = uuid!("00000000-0000-0000-0000-0000000000cc");
390		let from_entry: EntryId = raw.into();
391		let from_entry_ctor = EntryId::from_uuid(raw);
392		assert_eq!(from_entry, from_entry_ctor);
393		assert_eq!(from_entry.uuid(), raw);
394
395		let from_group: GroupId = raw.into();
396		let from_group_ctor = GroupId::from_uuid(raw);
397		assert_eq!(from_group, from_group_ctor);
398		assert_eq!(from_group.uuid(), raw);
399	}
400}