Skip to main content

kanidmd_lib/server/
delete.rs

1use crate::{
2    prelude::*,
3    server::{ChangeFlag, DeleteEvent, Plugins},
4};
5use std::collections::BTreeMap;
6
7impl QueryServerWriteTransaction<'_> {
8    #[allow(clippy::cognitive_complexity)]
9    #[instrument(level = "debug", skip_all)]
10    pub fn delete(&mut self, de: &DeleteEvent) -> Result<(), OperationError> {
11        // Do you have access to view all the set members? Reduce based on your
12        // read permissions and attrs
13        // THIS IS PRETTY COMPLEX SEE THE DESIGN DOC
14        // In this case we need a search, but not INTERNAL to keep the same
15        // associated credentials.
16        // We only need to retrieve uuid though ...
17        if !de.ident.is_internal() {
18            security_info!(name = %de.ident, "delete initiator");
19        }
20
21        // Now, delete only what you can see
22        let mut pre_candidates = self
23            .impersonate_search_valid(de.filter.clone(), de.filter_orig.clone(), &de.ident)
24            .map_err(|e| {
25                admin_error!("delete: error in pre-candidate selection {:?}", e);
26                e
27            })?;
28
29        // Apply access controls to reduce the set if required.
30        // delete_allow_operation
31        let access = self.get_accesscontrols();
32        let op_allow = access
33            .delete_allow_operation(de, &pre_candidates)
34            .map_err(|e| {
35                admin_error!("Failed to check delete access {:?}", e);
36                e
37            })?;
38        if !op_allow {
39            return Err(OperationError::AccessDenied);
40        }
41
42        // Is the candidate set empty?
43        if pre_candidates.is_empty() {
44            warn!("delete: no candidates match filter");
45            debug!(delete_filter = ?de.filter);
46            return Err(OperationError::NoMatchingEntries);
47        };
48
49        if pre_candidates.iter().any(|e| e.mask_tombstone().is_none()) {
50            warn!("Refusing to delete entries which may be an attempt to bypass replication state machine.");
51            return Err(OperationError::AccessDenied);
52        }
53
54        // ======= Access Control and Invariants Checked !!! ========
55
56        // We now extend pre-candidates with anything that will be cascade-deleted.
57        let references_filt = filter!(f_or(
58            pre_candidates
59                .iter()
60                .map(|entry| { f_eq(Attribute::Refers, PartialValue::Refer(entry.get_uuid())) })
61                .collect(),
62        ));
63
64        let mut pre_cascade_delete_candidates = self
65            .internal_search(references_filt)
66            .inspect_err(|err| error!(?err, "unable to find reference entries"))?;
67
68        #[cfg(any(test, debug_assertions))]
69        {
70            use std::collections::BTreeSet;
71
72            let candidate_uuids: BTreeSet<_> =
73                pre_candidates.iter().map(|e| e.get_uuid()).collect();
74            let ref_candidate_uuids: BTreeSet<_> = pre_cascade_delete_candidates
75                .iter()
76                .map(|e| e.get_uuid())
77                .collect();
78
79            assert!(candidate_uuids.is_disjoint(&ref_candidate_uuids));
80        }
81
82        let mut cascade_delete_candidates: Vec<EntryInvalidCommitted> =
83            pre_cascade_delete_candidates
84                .iter()
85                // Invalidate and assign change id's
86                .map(|er| {
87                    er.as_ref()
88                        .clone()
89                        .invalidate(self.cid.clone(), &self.trim_cid)
90                })
91                // These entries are the ones that are being deleted by cascade, so we mark them
92                // as such.
93                .map(|mut entry| {
94                    if let Some(refer_uuid) = entry.get_ava_refer_single(Attribute::Refers) {
95                        // Stash the entry that triggered our deleted in this attribute. This
96                        // allows us to restore this linkage on revive, and also being a uuid instead
97                        // of a refers means that refint won't clean this linkage.
98                        entry.add_ava(Attribute::CascadeDeleted, Value::Uuid(refer_uuid));
99                    };
100                    entry
101                })
102                .collect();
103
104        let mut candidates: Vec<Entry<EntryInvalid, EntryCommitted>> = pre_candidates
105            .iter()
106            // Invalidate and assign change id's
107            .map(|er| {
108                er.as_ref()
109                    .clone()
110                    .invalidate(self.cid.clone(), &self.trim_cid)
111            })
112            .collect();
113
114        pre_candidates.append(&mut pre_cascade_delete_candidates);
115        candidates.append(&mut cascade_delete_candidates);
116
117        trace!(?candidates, "delete: candidates");
118
119        // If we need to build a memorial to the candidate, ask plugins now.
120        let mut memorials: BTreeMap<Uuid, EntryInitNew> = BTreeMap::new();
121
122        Plugins::run_build_memorials(self, &pre_candidates, &mut memorials, de).inspect_err(
123            |err| {
124                error!(?err, "Delete operation failed (plugin)");
125            },
126        )?;
127
128        if !memorials.is_empty() {
129            let candidates: Vec<Entry<EntryInvalid, EntryNew>> = memorials
130                .into_iter()
131                .map(|(source_uuid, mut entry)| {
132                    // First, ensure that the only class is Memorial.
133                    entry.remove_ava(&Attribute::Class);
134                    entry.set_ava_set(&Attribute::Uuid, ValueSetUuid::new(Uuid::new_v4()));
135                    entry.set_ava_set(&Attribute::InMemoriam, ValueSetUuid::new(source_uuid));
136                    entry.set_ava_set(
137                        &Attribute::Class,
138                        vs_iutf8n![EntryClass::Object.into(), EntryClass::Memorial.into()],
139                    );
140                    // Now setup replication metadata so that we can put this entry
141                    // into the invalid state.
142                    entry.assign_cid(self.cid.clone(), &self.schema)
143                })
144                .collect();
145
146            if candidates.iter().any(|e| e.mask_recycled_ts().is_none()) {
147                warn!("Refusing to create invalid entries that are attempting to bypass replication state machine.");
148                return Err(OperationError::AccessDenied);
149            }
150
151            let norm_cand = candidates
152                .into_iter()
153                .map(|e| {
154                    e.validate(&self.schema)
155                        .map_err(|e| {
156                            error!("Schema Violation in create validate {:?}", e);
157                            OperationError::SchemaViolation(e)
158                        })
159                        .map(|e| {
160                            // Then seal the changes?
161                            e.seal(&self.schema)
162                        })
163                })
164                .collect::<Result<Vec<EntrySealedNew>, _>>()?;
165
166            let _commit_cand = self
167                .be_txn
168                .create(&self.cid, norm_cand)
169                .inspect_err(|err| {
170                    error!(?err, "betxn create failure");
171                })?;
172        }
173
174        // Pre delete plugs
175        Plugins::run_pre_delete(self, &mut candidates, de).inspect_err(|err| {
176            error!(?err, "Delete operation failed (plugin)");
177        })?;
178
179        trace!(?candidates, "delete: now marking candidates as recycled");
180
181        let res: Result<Vec<Entry<EntrySealed, EntryCommitted>>, OperationError> = candidates
182            .into_iter()
183            .map(|e| {
184                e.to_recycled()
185                    .validate(&self.schema)
186                    .map_err(|e| {
187                        admin_error!(err = ?e, "Schema Violation in delete validate");
188                        OperationError::SchemaViolation(e)
189                    })
190                    // seal if it worked.
191                    .map(|e| e.seal(&self.schema))
192            })
193            .collect();
194
195        let del_cand: Vec<Entry<_, _>> = res?;
196
197        self.be_txn
198            .modify(&self.cid, &pre_candidates, &del_cand)
199            .map_err(|e| {
200                // be_txn is dropped, ie aborted here.
201                admin_error!("Delete operation failed (backend), {:?}", e);
202                e
203            })?;
204
205        // Post delete plugins
206        Plugins::run_post_delete(self, &del_cand, de).map_err(|e| {
207            admin_error!("Delete operation failed (plugin), {:?}", e);
208            e
209        })?;
210
211        // We have finished all plugs and now have a successful operation - flag if
212        // schema or acp requires reload.
213        if !self.changed_flags.contains(ChangeFlag::SCHEMA)
214            && del_cand.iter().any(|e| {
215                e.attribute_equality(Attribute::Class, &EntryClass::ClassType.into())
216                    || e.attribute_equality(Attribute::Class, &EntryClass::AttributeType.into())
217            })
218        {
219            self.changed_flags.insert(ChangeFlag::SCHEMA)
220        }
221        if !self.changed_flags.contains(ChangeFlag::ACP)
222            && del_cand.iter().any(|e| {
223                e.attribute_equality(Attribute::Class, &EntryClass::AccessControlProfile.into())
224            })
225        {
226            self.changed_flags.insert(ChangeFlag::ACP)
227        }
228
229        if !self.changed_flags.contains(ChangeFlag::APPLICATION)
230            && del_cand
231                .iter()
232                .any(|e| e.attribute_equality(Attribute::Class, &EntryClass::Application.into()))
233        {
234            self.changed_flags.insert(ChangeFlag::APPLICATION)
235        }
236
237        if !self.changed_flags.contains(ChangeFlag::OAUTH2)
238            && del_cand.iter().any(|e| {
239                e.attribute_equality(Attribute::Class, &EntryClass::OAuth2ResourceServer.into())
240            })
241        {
242            self.changed_flags.insert(ChangeFlag::OAUTH2)
243        }
244
245        if !self.changed_flags.contains(ChangeFlag::OAUTH2_CLIENT)
246            && del_cand
247                .iter()
248                .any(|e| e.attribute_equality(Attribute::Class, &EntryClass::OAuth2Client.into()))
249        {
250            self.changed_flags.insert(ChangeFlag::OAUTH2_CLIENT)
251        }
252
253        if !self.changed_flags.contains(ChangeFlag::FEATURE)
254            && del_cand
255                .iter()
256                .any(|e| e.attribute_equality(Attribute::Class, &EntryClass::Feature.into()))
257        {
258            self.changed_flags.insert(ChangeFlag::FEATURE)
259        }
260
261        if !self.changed_flags.contains(ChangeFlag::DOMAIN)
262            && del_cand
263                .iter()
264                .any(|e| e.attribute_equality(Attribute::Uuid, &PVUUID_DOMAIN_INFO))
265        {
266            self.changed_flags.insert(ChangeFlag::DOMAIN)
267        }
268
269        if !self.changed_flags.contains(ChangeFlag::SYSTEM_CONFIG)
270            && del_cand
271                .iter()
272                .any(|e| e.attribute_equality(Attribute::Uuid, &PVUUID_SYSTEM_CONFIG))
273        {
274            self.changed_flags.insert(ChangeFlag::SYSTEM_CONFIG)
275        }
276
277        if !self.changed_flags.contains(ChangeFlag::SYNC_AGREEMENT)
278            && del_cand
279                .iter()
280                .any(|e| e.attribute_equality(Attribute::Class, &EntryClass::SyncAccount.into()))
281        {
282            self.changed_flags.insert(ChangeFlag::SYNC_AGREEMENT)
283        }
284
285        if !self.changed_flags.contains(ChangeFlag::KEY_MATERIAL)
286            && del_cand.iter().any(|e| {
287                e.attribute_equality(Attribute::Class, &EntryClass::KeyProvider.into())
288                    || e.attribute_equality(Attribute::Class, &EntryClass::KeyObject.into())
289            })
290        {
291            self.changed_flags.insert(ChangeFlag::KEY_MATERIAL)
292        }
293
294        self.changed_uuid
295            .extend(del_cand.iter().map(|e| e.get_uuid()));
296
297        trace!(
298            changed = ?self.changed_flags.iter_names().collect::<Vec<_>>(),
299        );
300
301        // Send result
302        if de.ident.is_internal() {
303            trace!("Delete operation success");
304        } else {
305            admin_info!("Delete operation success");
306        }
307        Ok(())
308    }
309
310    pub fn internal_delete(
311        &mut self,
312        filter: &Filter<FilterInvalid>,
313    ) -> Result<(), OperationError> {
314        let f_valid = filter
315            .validate(self.get_schema())
316            .map_err(OperationError::SchemaViolation)?;
317        let de = DeleteEvent::new_internal(f_valid);
318        self.delete(&de)
319    }
320
321    pub fn internal_delete_uuid(&mut self, target_uuid: Uuid) -> Result<(), OperationError> {
322        let filter = filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(target_uuid)));
323        let f_valid = filter
324            .validate(self.get_schema())
325            .map_err(OperationError::SchemaViolation)?;
326        let de = DeleteEvent::new_internal(f_valid);
327        self.delete(&de)
328    }
329
330    pub fn internal_delete_uuid_if_exists(
331        &mut self,
332        target_uuid: Uuid,
333    ) -> Result<(), OperationError> {
334        let filter = filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(target_uuid)));
335        self.internal_delete_if_exists(&filter)
336    }
337
338    pub fn internal_delete_if_exists(
339        &mut self,
340        filter: &Filter<FilterInvalid>,
341    ) -> Result<(), OperationError> {
342        let f_valid = filter
343            .validate(self.get_schema())
344            .map_err(OperationError::SchemaViolation)?;
345
346        let ee = ExistsEvent::new_internal(f_valid.clone());
347        // Submit it
348        if self.exists(&ee)? {
349            let de = DeleteEvent::new_internal(f_valid);
350            self.delete(&de)?;
351        }
352        Ok(())
353    }
354
355    pub(crate) fn ident_delete_uuid(
356        &mut self,
357        ident: &Identity,
358        target_uuid: Uuid,
359    ) -> Result<(), OperationError> {
360        let filter = filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(target_uuid)));
361
362        let filter_orig = filter
363            .validate(self.get_schema())
364            .map_err(OperationError::SchemaViolation)?;
365
366        let filter = filter_orig.clone().into_ignore_hidden();
367
368        let de = DeleteEvent {
369            ident: ident.clone(),
370            filter,
371            filter_orig,
372        };
373        self.delete(&de)
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use crate::prelude::*;
380
381    #[qs_test]
382    async fn test_delete(server: &QueryServer) {
383        // Create
384        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
385
386        let e1 = entry_init!(
387            (Attribute::Class, EntryClass::Object.to_value()),
388            (Attribute::Class, EntryClass::Account.to_value()),
389            (Attribute::Class, EntryClass::Person.to_value()),
390            (Attribute::Name, Value::new_iname("testperson1")),
391            (
392                Attribute::Uuid,
393                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
394            ),
395            (Attribute::Description, Value::new_utf8s("testperson")),
396            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
397        );
398
399        let e2 = entry_init!(
400            (Attribute::Class, EntryClass::Object.to_value()),
401            (Attribute::Class, EntryClass::Account.to_value()),
402            (Attribute::Class, EntryClass::Person.to_value()),
403            (Attribute::Name, Value::new_iname("testperson2")),
404            (
405                Attribute::Uuid,
406                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63932"))
407            ),
408            (Attribute::Description, Value::new_utf8s("testperson")),
409            (Attribute::DisplayName, Value::new_utf8s("testperson2"))
410        );
411
412        let e3 = entry_init!(
413            (Attribute::Class, EntryClass::Object.to_value()),
414            (Attribute::Class, EntryClass::Account.to_value()),
415            (Attribute::Class, EntryClass::Person.to_value()),
416            (Attribute::Name, Value::new_iname("testperson3")),
417            (
418                Attribute::Uuid,
419                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63933"))
420            ),
421            (Attribute::Description, Value::new_utf8s("testperson")),
422            (Attribute::DisplayName, Value::new_utf8s("testperson3"))
423        );
424
425        let ce = CreateEvent::new_internal(vec![e1, e2, e3]);
426
427        let cr = server_txn.create(&ce);
428        assert!(cr.is_ok());
429
430        // Delete filter is syntax invalid
431        let de_inv = DeleteEvent::new_internal_invalid(filter!(f_pres(Attribute::NonExist)));
432        assert!(server_txn.delete(&de_inv).is_err());
433
434        // Delete deletes nothing
435        let de_empty = DeleteEvent::new_internal_invalid(filter!(f_eq(
436            Attribute::Uuid,
437            PartialValue::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-000000000000"))
438        )));
439        assert!(server_txn.delete(&de_empty).is_err());
440
441        // Delete matches one
442        let de_sin = DeleteEvent::new_internal_invalid(filter!(f_eq(
443            Attribute::Name,
444            PartialValue::new_iname("testperson3")
445        )));
446        assert!(server_txn.delete(&de_sin).is_ok());
447
448        // Delete matches many
449        let de_mult = DeleteEvent::new_internal_invalid(filter!(f_eq(
450            Attribute::Description,
451            PartialValue::new_utf8s("testperson")
452        )));
453        assert!(server_txn.delete(&de_mult).is_ok());
454
455        assert!(server_txn.commit().is_ok());
456    }
457}