Skip to main content

kanidmd_lib/server/
modify.rs

1use std::sync::Arc;
2
3use super::ChangeFlag;
4use crate::{plugins::Plugins, prelude::*};
5
6pub(crate) struct ModifyPartial<'a> {
7    pub norm_cand: Vec<Entry<EntrySealed, EntryCommitted>>,
8    pub pre_candidates: Vec<Arc<Entry<EntrySealed, EntryCommitted>>>,
9    pub me: &'a ModifyEvent,
10}
11
12impl QueryServerWriteTransaction<'_> {
13    #[instrument(level = "debug", skip_all)]
14    pub fn modify(&mut self, me: &ModifyEvent) -> Result<(), OperationError> {
15        let mp = self.modify_pre_apply(me)?;
16        if let Some(mp) = mp {
17            self.modify_apply(mp)
18        } else {
19            // No action to apply, the pre-apply said nothing to be done.
20            Ok(())
21        }
22    }
23
24    /// SAFETY: This is unsafe because you need to be careful about how you handle and check
25    /// the Ok(None) case which occurs during internal operations, and that you DO NOT re-order
26    /// and call multiple pre-applies at the same time, else you can cause DB corruption.
27    #[instrument(level = "debug", skip_all)]
28    pub(crate) fn modify_pre_apply<'x>(
29        &mut self,
30        me: &'x ModifyEvent,
31    ) -> Result<Option<ModifyPartial<'x>>, OperationError> {
32        trace!(?me);
33
34        // Get the candidates.
35        // Modify applies a modlist to a filter, so we need to internal search
36        // then apply.
37        if !me.ident.is_internal() {
38            security_info!(name = %me.ident, "modify initiator");
39        }
40
41        // Validate input.
42
43        // Is the modlist non zero?
44        if me.modlist.is_empty() {
45            request_error!("modify: empty modify request");
46            return Err(OperationError::EmptyRequest);
47        }
48
49        // Is the modlist valid?
50        // This is now done in the event transform
51
52        // Is the filter invalid to schema?
53        // This is now done in the event transform
54
55        // This also checks access controls due to use of the impersonation.
56        let pre_candidates = self
57            .impersonate_search_valid(me.filter.clone(), me.filter_orig.clone(), &me.ident)
58            .map_err(|e| {
59                admin_error!("modify: error in pre-candidate selection {:?}", e);
60                e
61            })?;
62
63        if pre_candidates.is_empty() {
64            if me.ident.is_internal() {
65                trace!(
66                    "modify_pre_apply: no candidates match filter ... continuing {:?}",
67                    me.filter
68                );
69                return Ok(None);
70            } else {
71                request_error!(
72                    "modify: no candidates match filter, failure {:?}",
73                    me.filter
74                );
75                return Err(OperationError::NoMatchingEntries);
76            }
77        };
78
79        trace!("modify_pre_apply: pre_candidates -> {:?}", pre_candidates);
80        trace!("modify_pre_apply: modlist -> {:?}", me.modlist);
81
82        // Are we allowed to make the changes we want to?
83        // modify_allow_operation
84        let access = self.get_accesscontrols();
85        let op_allow = access
86            .modify_allow_operation(me, &pre_candidates)
87            .map_err(|e| {
88                admin_error!("Unable to check modify access {:?}", e);
89                e
90            })?;
91        if !op_allow {
92            return Err(OperationError::AccessDenied);
93        }
94
95        // Clone a set of writeables.
96        // Apply the modlist -> Remember, we have a set of origs
97        // and the new modified ents.
98        let mut candidates: Vec<Entry<EntryInvalid, EntryCommitted>> = pre_candidates
99            .iter()
100            .map(|er| {
101                er.as_ref()
102                    .clone()
103                    .invalidate(self.cid.clone(), &self.trim_cid)
104            })
105            .collect();
106
107        candidates.iter_mut().try_for_each(|er| {
108            er.apply_modlist(&me.modlist).inspect_err(|_e| {
109                error!("Modification failed for {:?}", er.get_uuid());
110            })
111        })?;
112
113        trace!("modify: candidates -> {:?}", candidates);
114
115        // Did any of the candidates now become masked?
116        if std::iter::zip(
117            pre_candidates
118                .iter()
119                .map(|e| e.mask_recycled_ts().is_none()),
120            candidates.iter().map(|e| e.mask_recycled_ts().is_none()),
121        )
122        .any(|(a, b)| a != b)
123        {
124            admin_warn!("Refusing to apply modifications that are attempting to bypass replication state machine.");
125            return Err(OperationError::AccessDenied);
126        }
127
128        // Pre mod plugins
129        Plugins::run_pre_modify(self, &pre_candidates, &mut candidates, me).map_err(|e| {
130            admin_error!("Pre-Modify operation failed (plugin), {:?}", e);
131            e
132        })?;
133
134        // NOTE: There is a potential optimisation here, where if
135        // candidates == pre-candidates, then we don't need to store anything
136        // because we effectively just did an assert. However, like all
137        // optimisations, this could be premature - so we for now, just
138        // do the CORRECT thing and recommit as we may find later we always
139        // want to add CSN's or other.
140
141        let res: Result<Vec<EntrySealedCommitted>, OperationError> = candidates
142            .into_iter()
143            .map(|entry| {
144                entry
145                    .validate(&self.schema)
146                    .map_err(|e| {
147                        admin_error!("Schema Violation in validation of modify_pre_apply {:?}", e);
148                        OperationError::SchemaViolation(e)
149                    })
150                    .map(|entry| entry.seal(&self.schema))
151            })
152            .collect();
153
154        let norm_cand: Vec<Entry<_, _>> = res?;
155
156        Ok(Some(ModifyPartial {
157            norm_cand,
158            pre_candidates,
159            me,
160        }))
161    }
162
163    #[instrument(level = "debug", skip_all)]
164    pub(crate) fn modify_apply(&mut self, mp: ModifyPartial<'_>) -> Result<(), OperationError> {
165        let ModifyPartial {
166            norm_cand,
167            pre_candidates,
168            me,
169        } = mp;
170
171        // Backend Modify
172        self.be_txn
173            .modify(&self.cid, &pre_candidates, &norm_cand)
174            .map_err(|e| {
175                admin_error!("Modify operation failed (backend), {:?}", e);
176                e
177            })?;
178
179        // Post Plugins
180        //
181        // memberOf actually wants the pre cand list and the norm_cand list to see what
182        // changed. Could be optimised, but this is correct still ...
183        Plugins::run_post_modify(self, &pre_candidates, &norm_cand, me).map_err(|e| {
184            admin_error!("Post-Modify operation failed (plugin), {:?}", e);
185            e
186        })?;
187
188        // We have finished all plugs and now have a successful operation - flag if
189        // schema or acp requires reload. Remember, this is a modify, so we need to check
190        // pre and post cands.
191
192        if !self.changed_flags.contains(ChangeFlag::SCHEMA)
193            && norm_cand
194                .iter()
195                .chain(pre_candidates.iter().map(|e| e.as_ref()))
196                .any(|e| {
197                    e.attribute_equality(Attribute::Class, &EntryClass::ClassType.into())
198                        || e.attribute_equality(Attribute::Class, &EntryClass::AttributeType.into())
199                })
200        {
201            self.changed_flags.insert(ChangeFlag::SCHEMA)
202        }
203
204        if !self.changed_flags.contains(ChangeFlag::ACP)
205            && norm_cand
206                .iter()
207                .chain(pre_candidates.iter().map(|e| e.as_ref()))
208                .any(|e| {
209                    e.attribute_equality(Attribute::Class, &EntryClass::AccessControlProfile.into())
210                })
211        {
212            self.changed_flags.insert(ChangeFlag::ACP)
213        }
214
215        if !self.changed_flags.contains(ChangeFlag::APPLICATION)
216            && norm_cand
217                .iter()
218                .chain(pre_candidates.iter().map(|e| e.as_ref()))
219                .any(|e| e.attribute_equality(Attribute::Class, &EntryClass::Application.into()))
220        {
221            self.changed_flags.insert(ChangeFlag::APPLICATION)
222        }
223
224        if !self.changed_flags.contains(ChangeFlag::OAUTH2)
225            && norm_cand
226                .iter()
227                .zip(pre_candidates.iter().map(|e| e.as_ref()))
228                .any(|(post, pre)| {
229                    // This is in the modify path only - because sessions can update the RS
230                    // this can trigger reloads of all the oauth2 clients. That would make
231                    // client credentials grant pretty expensive in these cases. To avoid this
232                    // we check if "anything else" beside the oauth2session changed in this
233                    // txn.
234                    (post.attribute_equality(
235                        Attribute::Class,
236                        &EntryClass::OAuth2ResourceServer.into(),
237                    ) || pre.attribute_equality(
238                        Attribute::Class,
239                        &EntryClass::OAuth2ResourceServer.into(),
240                    )) && post
241                        .entry_changed_excluding_attribute(Attribute::OAuth2Session, &self.cid)
242                })
243        {
244            self.changed_flags.insert(ChangeFlag::OAUTH2)
245        }
246
247        if !self.changed_flags.contains(ChangeFlag::OAUTH2_CLIENT)
248            && norm_cand
249                .iter()
250                .zip(pre_candidates.iter().map(|e| e.as_ref()))
251                .any(|(post, pre)| {
252                    post.attribute_equality(Attribute::Class, &EntryClass::OAuth2Client.into())
253                        || pre
254                            .attribute_equality(Attribute::Class, &EntryClass::OAuth2Client.into())
255                })
256        {
257            self.changed_flags.insert(ChangeFlag::OAUTH2_CLIENT)
258        }
259
260        if !self.changed_flags.contains(ChangeFlag::FEATURE)
261            && norm_cand
262                .iter()
263                .zip(pre_candidates.iter().map(|e| e.as_ref()))
264                .any(|(post, pre)| {
265                    post.attribute_equality(Attribute::Class, &EntryClass::Feature.into())
266                        || pre.attribute_equality(Attribute::Class, &EntryClass::Feature.into())
267                })
268        {
269            self.changed_flags.insert(ChangeFlag::FEATURE)
270        }
271
272        if !self.changed_flags.contains(ChangeFlag::DOMAIN)
273            && norm_cand
274                .iter()
275                .chain(pre_candidates.iter().map(|e| e.as_ref()))
276                .any(|e| e.attribute_equality(Attribute::Uuid, &PVUUID_DOMAIN_INFO))
277        {
278            self.changed_flags.insert(ChangeFlag::DOMAIN)
279        }
280
281        if !self.changed_flags.contains(ChangeFlag::SYSTEM_CONFIG)
282            && norm_cand
283                .iter()
284                .chain(pre_candidates.iter().map(|e| e.as_ref()))
285                .any(|e| e.attribute_equality(Attribute::Uuid, &PVUUID_SYSTEM_CONFIG))
286        {
287            self.changed_flags.insert(ChangeFlag::SYSTEM_CONFIG)
288        }
289
290        if !self.changed_flags.contains(ChangeFlag::SYNC_AGREEMENT)
291            && norm_cand
292                .iter()
293                .chain(pre_candidates.iter().map(|e| e.as_ref()))
294                .any(|e| e.attribute_equality(Attribute::Class, &EntryClass::SyncAccount.into()))
295        {
296            self.changed_flags.insert(ChangeFlag::SYNC_AGREEMENT)
297        }
298
299        if !self.changed_flags.contains(ChangeFlag::KEY_MATERIAL)
300            && norm_cand
301                .iter()
302                .chain(pre_candidates.iter().map(|e| e.as_ref()))
303                .any(|e| {
304                    e.attribute_equality(Attribute::Class, &EntryClass::KeyProvider.into())
305                        || e.attribute_equality(Attribute::Class, &EntryClass::KeyObject.into())
306                })
307        {
308            self.changed_flags.insert(ChangeFlag::KEY_MATERIAL)
309        }
310
311        self.changed_uuid.extend(
312            norm_cand
313                .iter()
314                .map(|e| e.get_uuid())
315                .chain(pre_candidates.iter().map(|e| e.get_uuid())),
316        );
317
318        trace!(
319            changed = ?self.changed_flags.iter_names().collect::<Vec<_>>(),
320        );
321
322        // return
323        if me.ident.is_internal() {
324            trace!("Modify operation success");
325        } else {
326            admin_info!("Modify operation success");
327        }
328        Ok(())
329    }
330}
331
332impl QueryServerWriteTransaction<'_> {
333    /// Used in conjunction with internal_apply_writable, to get a pre/post
334    /// pair, where post is pre-configured with metadata to allow
335    /// modificiation before submit back to internal_apply_writable
336    #[instrument(level = "debug", skip_all)]
337    pub(crate) fn internal_search_writeable(
338        &mut self,
339        filter: &Filter<FilterInvalid>,
340    ) -> Result<Vec<EntryTuple>, OperationError> {
341        let f_valid = filter
342            .validate(self.get_schema())
343            .map_err(OperationError::SchemaViolation)?;
344        let se = SearchEvent::new_internal(f_valid);
345        self.search(&se).map(|vs| {
346            vs.into_iter()
347                .map(|e| {
348                    let writeable = e
349                        .as_ref()
350                        .clone()
351                        .invalidate(self.cid.clone(), &self.trim_cid);
352                    (e, writeable)
353                })
354                .collect()
355        })
356    }
357
358    /// Allows writing batches of modified entries without going through
359    /// the modlist path. This allows more efficient batch transformations
360    /// such as memberof, but at the expense that YOU must guarantee you
361    /// uphold all other plugin and state rules that are important. You
362    /// probably want modify instead.
363    #[allow(clippy::needless_pass_by_value)]
364    #[instrument(level = "debug", skip_all)]
365    pub(crate) fn internal_apply_writable(
366        &mut self,
367        candidate_tuples: Vec<(Arc<EntrySealedCommitted>, EntryInvalidCommitted)>,
368    ) -> Result<(), OperationError> {
369        if candidate_tuples.is_empty() {
370            // No action needed.
371            return Ok(());
372        }
373
374        let (pre_candidates, candidates): (
375            Vec<Arc<EntrySealedCommitted>>,
376            Vec<EntryInvalidCommitted>,
377        ) = candidate_tuples.into_iter().unzip();
378
379        /*
380        let mut pre_candidates = Vec::with_capacity(candidate_tuples.len());
381        let mut candidates = Vec::with_capacity(candidate_tuples.len());
382
383        for (pre, post) in candidate_tuples.into_iter() {
384            pre_candidates.push(pre);
385            candidates.push(post);
386        }
387        */
388
389        let res: Result<Vec<Entry<EntrySealed, EntryCommitted>>, OperationError> = candidates
390            .into_iter()
391            .map(|e| {
392                e.validate(&self.schema)
393                    .map_err(|e| {
394                        admin_error!(
395                            "Schema Violation in internal_apply_writable validate: {:?}",
396                            e
397                        );
398                        OperationError::SchemaViolation(e)
399                    })
400                    .map(|e| e.seal(&self.schema))
401            })
402            .collect();
403
404        let norm_cand: Vec<Entry<_, _>> = res?;
405
406        if cfg!(debug_assertions) || cfg!(test) {
407            pre_candidates
408                .iter()
409                .zip(norm_cand.iter())
410                .try_for_each(|(pre, post)| {
411                    if pre.get_uuid() == post.get_uuid() {
412                        Ok(())
413                    } else {
414                        admin_error!("modify - cand sets not correctly aligned");
415                        Err(OperationError::InvalidRequestState)
416                    }
417                })?;
418        }
419
420        // Backend Modify
421        self.be_txn
422            .modify(&self.cid, &pre_candidates, &norm_cand)
423            .map_err(|e| {
424                admin_error!("Modify operation failed (backend), {:?}", e);
425                e
426            })?;
427
428        if !self.changed_flags.contains(ChangeFlag::SCHEMA)
429            && norm_cand
430                .iter()
431                .chain(pre_candidates.iter().map(|e| e.as_ref()))
432                .any(|e| {
433                    e.attribute_equality(Attribute::Class, &EntryClass::ClassType.into())
434                        || e.attribute_equality(Attribute::Class, &EntryClass::AttributeType.into())
435                })
436        {
437            self.changed_flags.insert(ChangeFlag::SCHEMA)
438        }
439
440        if !self.changed_flags.contains(ChangeFlag::ACP)
441            && norm_cand
442                .iter()
443                .chain(pre_candidates.iter().map(|e| e.as_ref()))
444                .any(|e| {
445                    e.attribute_equality(Attribute::Class, &EntryClass::AccessControlProfile.into())
446                })
447        {
448            self.changed_flags.insert(ChangeFlag::ACP)
449        }
450
451        if !self.changed_flags.contains(ChangeFlag::APPLICATION)
452            && norm_cand
453                .iter()
454                .chain(pre_candidates.iter().map(|e| e.as_ref()))
455                .any(|e| e.attribute_equality(Attribute::Class, &EntryClass::Application.into()))
456        {
457            self.changed_flags.insert(ChangeFlag::APPLICATION)
458        }
459
460        if !self.changed_flags.contains(ChangeFlag::OAUTH2)
461            && norm_cand.iter().any(|e| {
462                e.attribute_equality(Attribute::Class, &EntryClass::OAuth2ResourceServer.into())
463            })
464        {
465            self.changed_flags.insert(ChangeFlag::OAUTH2)
466        }
467
468        if !self.changed_flags.contains(ChangeFlag::OAUTH2_CLIENT)
469            && norm_cand
470                .iter()
471                .any(|e| e.attribute_equality(Attribute::Class, &EntryClass::OAuth2Client.into()))
472        {
473            self.changed_flags.insert(ChangeFlag::OAUTH2_CLIENT)
474        }
475
476        if !self.changed_flags.contains(ChangeFlag::FEATURE)
477            && norm_cand
478                .iter()
479                .any(|e| e.attribute_equality(Attribute::Class, &EntryClass::Feature.into()))
480        {
481            self.changed_flags.insert(ChangeFlag::FEATURE)
482        }
483
484        if !self.changed_flags.contains(ChangeFlag::DOMAIN)
485            && norm_cand
486                .iter()
487                .any(|e| e.attribute_equality(Attribute::Uuid, &PVUUID_DOMAIN_INFO))
488        {
489            self.changed_flags.insert(ChangeFlag::DOMAIN)
490        }
491        if !self.changed_flags.contains(ChangeFlag::SYSTEM_CONFIG)
492            && norm_cand
493                .iter()
494                .any(|e| e.attribute_equality(Attribute::Uuid, &PVUUID_SYSTEM_CONFIG))
495        {
496            self.changed_flags.insert(ChangeFlag::DOMAIN)
497        }
498
499        self.changed_uuid.extend(
500            norm_cand
501                .iter()
502                .map(|e| e.get_uuid())
503                .chain(pre_candidates.iter().map(|e| e.get_uuid())),
504        );
505
506        trace!(
507            changed = ?self.changed_flags.iter_names().collect::<Vec<_>>(),
508        );
509
510        trace!("Modify operation success");
511        Ok(())
512    }
513
514    #[instrument(level = "debug", skip_all)]
515    pub fn internal_modify(
516        &mut self,
517        filter: &Filter<FilterInvalid>,
518        modlist: &ModifyList<ModifyInvalid>,
519    ) -> Result<(), OperationError> {
520        let f_valid = filter
521            .validate(self.get_schema())
522            .map_err(OperationError::SchemaViolation)?;
523        let m_valid = modlist
524            .validate(self.get_schema())
525            .map_err(OperationError::SchemaViolation)?;
526        let me = ModifyEvent::new_internal(f_valid, m_valid);
527        self.modify(&me)
528    }
529
530    pub fn internal_modify_uuid(
531        &mut self,
532        target_uuid: Uuid,
533        modlist: &ModifyList<ModifyInvalid>,
534    ) -> Result<(), OperationError> {
535        let filter = filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(target_uuid)));
536        let f_valid = filter
537            .validate(self.get_schema())
538            .map_err(OperationError::SchemaViolation)?;
539        let m_valid = modlist
540            .validate(self.get_schema())
541            .map_err(OperationError::SchemaViolation)?;
542        let me = ModifyEvent::new_internal(f_valid, m_valid);
543        self.modify(&me)
544    }
545
546    pub fn impersonate_modify_valid(
547        &mut self,
548        f_valid: Filter<FilterValid>,
549        f_intent_valid: Filter<FilterValid>,
550        m_valid: ModifyList<ModifyValid>,
551        event: &Identity,
552    ) -> Result<(), OperationError> {
553        let me = ModifyEvent::new_impersonate(event, f_valid, f_intent_valid, m_valid);
554        self.modify(&me)
555    }
556
557    pub fn impersonate_modify(
558        &mut self,
559        filter: &Filter<FilterInvalid>,
560        filter_intent: &Filter<FilterInvalid>,
561        modlist: &ModifyList<ModifyInvalid>,
562        event: &Identity,
563    ) -> Result<(), OperationError> {
564        let f_valid = filter.validate(self.get_schema()).map_err(|e| {
565            admin_error!("filter Schema Invalid {:?}", e);
566            OperationError::SchemaViolation(e)
567        })?;
568        let f_intent_valid = filter_intent.validate(self.get_schema()).map_err(|e| {
569            admin_error!("f_intent Schema Invalid {:?}", e);
570            OperationError::SchemaViolation(e)
571        })?;
572        let m_valid = modlist.validate(self.get_schema()).map_err(|e| {
573            admin_error!("modlist Schema Invalid {:?}", e);
574            OperationError::SchemaViolation(e)
575        })?;
576        self.impersonate_modify_valid(f_valid, f_intent_valid, m_valid, event)
577    }
578
579    pub fn impersonate_modify_gen_event(
580        &mut self,
581        filter: &Filter<FilterInvalid>,
582        filter_intent: &Filter<FilterInvalid>,
583        modlist: &ModifyList<ModifyInvalid>,
584        event: &Identity,
585    ) -> Result<ModifyEvent, OperationError> {
586        let f_valid = filter.validate(self.get_schema()).map_err(|e| {
587            admin_error!("filter Schema Invalid {:?}", e);
588            OperationError::SchemaViolation(e)
589        })?;
590        let f_intent_valid = filter_intent.validate(self.get_schema()).map_err(|e| {
591            admin_error!("f_intent Schema Invalid {:?}", e);
592            OperationError::SchemaViolation(e)
593        })?;
594        let m_valid = modlist.validate(self.get_schema()).map_err(|e| {
595            admin_error!("modlist Schema Invalid {:?}", e);
596            OperationError::SchemaViolation(e)
597        })?;
598        Ok(ModifyEvent::new_impersonate(
599            event,
600            f_valid,
601            f_intent_valid,
602            m_valid,
603        ))
604    }
605}
606
607#[cfg(test)]
608mod tests {
609    use crate::{credential::Credential, prelude::*};
610    use kanidm_lib_crypto::CryptoPolicy;
611    use time::OffsetDateTime;
612
613    #[qs_test]
614    async fn test_modify(server: &QueryServer) {
615        // Create an object
616        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
617
618        let e1 = entry_init!(
619            (Attribute::Class, EntryClass::Object.to_value()),
620            (Attribute::Class, EntryClass::Account.to_value()),
621            (Attribute::Class, EntryClass::Person.to_value()),
622            (Attribute::Name, Value::new_iname("testperson1")),
623            (
624                Attribute::Uuid,
625                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
626            ),
627            (Attribute::Description, Value::new_utf8s("testperson1")),
628            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
629        );
630
631        let e2 = entry_init!(
632            (Attribute::Class, EntryClass::Object.to_value()),
633            (Attribute::Class, EntryClass::Account.to_value()),
634            (Attribute::Class, EntryClass::Person.to_value()),
635            (Attribute::Name, Value::new_iname("testperson2")),
636            (
637                Attribute::Uuid,
638                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63932"))
639            ),
640            (Attribute::Description, Value::new_utf8s("testperson2")),
641            (Attribute::DisplayName, Value::new_utf8s("testperson2"))
642        );
643
644        let ce = CreateEvent::new_internal(vec![e1, e2]);
645
646        let cr = server_txn.create(&ce);
647        assert!(cr.is_ok());
648
649        // Empty Modlist (filter is valid)
650        let me_emp = ModifyEvent::new_internal_invalid(
651            filter!(f_pres(Attribute::Class)),
652            ModifyList::new_list(vec![]),
653        );
654        assert_eq!(
655            server_txn.modify(&me_emp),
656            Err(OperationError::EmptyRequest)
657        );
658
659        let idm_admin = server_txn.internal_search_uuid(UUID_IDM_ADMIN).unwrap();
660
661        // Mod changes no objects
662        let me_nochg = ModifyEvent::new_impersonate_entry(
663            idm_admin,
664            filter!(f_eq(
665                Attribute::Name,
666                PartialValue::new_iname("flarbalgarble")
667            )),
668            ModifyList::new_list(vec![Modify::Present(
669                Attribute::Description,
670                Value::from("anusaosu"),
671            )]),
672        );
673        assert_eq!(
674            server_txn.modify(&me_nochg),
675            Err(OperationError::NoMatchingEntries)
676        );
677
678        // TODO: can we can this, since the filter's defined as an enum now
679        // Filter is invalid to schema - to check this due to changes in the way events are
680        // handled, we put this via the internal modify function to get the modlist
681        // checked for us. Normal server operation doesn't allow weird bypasses like
682        // this.
683        // let r_inv_1 = server_txn.internal_modify(
684        //     &filter!(f_eq(
685        //         Attribute::TestAttr,
686        //         PartialValue::new_iname("Flarbalgarble")
687        //     )),
688        //     &ModifyList::new_list(vec![Modify::Present(
689        //         Attribute::Description.into(),
690        //         Value::from("anusaosu"),
691        //     )]),
692        // );
693        // assert!(
694        //     r_inv_1
695        //         == Err(OperationError::SchemaViolation(
696        //             SchemaError::InvalidAttribute("tnanuanou".to_string())
697        //         ))
698        // );
699
700        // Mod is invalid to schema
701        let me_inv_m = ModifyEvent::new_internal_invalid(
702            filter!(f_pres(Attribute::Class)),
703            ModifyList::new_list(vec![Modify::Present(
704                Attribute::NonExist,
705                Value::from("anusaosu"),
706            )]),
707        );
708        assert!(
709            server_txn.modify(&me_inv_m)
710                == Err(OperationError::SchemaViolation(
711                    SchemaError::InvalidAttribute(Attribute::NonExist.to_string())
712                ))
713        );
714
715        // Mod single object
716        let me_sin = ModifyEvent::new_internal_invalid(
717            filter!(f_eq(
718                Attribute::Name,
719                PartialValue::new_iname("testperson2")
720            )),
721            ModifyList::new_list(vec![
722                Modify::Purged(Attribute::Description),
723                Modify::Present(Attribute::Description, Value::from("anusaosu")),
724            ]),
725        );
726        assert!(server_txn.modify(&me_sin).is_ok());
727
728        // Mod multiple object
729        let me_mult = ModifyEvent::new_internal_invalid(
730            filter!(f_or!([
731                f_eq(Attribute::Name, PartialValue::new_iname("testperson1")),
732                f_eq(Attribute::Name, PartialValue::new_iname("testperson2")),
733            ])),
734            ModifyList::new_list(vec![
735                Modify::Purged(Attribute::Description),
736                Modify::Present(Attribute::Description, Value::from("anusaosu")),
737            ]),
738        );
739        assert!(server_txn.modify(&me_mult).is_ok());
740
741        assert!(server_txn.commit().is_ok());
742    }
743
744    #[qs_test]
745    async fn test_modify_assert(server: &QueryServer) {
746        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
747
748        let t_uuid = Uuid::new_v4();
749        let r_uuid = Uuid::new_v4();
750
751        assert!(server_txn
752            .internal_create(vec![entry_init!(
753                (Attribute::Class, EntryClass::Object.to_value()),
754                (Attribute::Uuid, Value::Uuid(t_uuid))
755            ),])
756            .is_ok());
757
758        // This assertion will FAIL
759        assert!(matches!(
760            server_txn.internal_modify_uuid(
761                t_uuid,
762                &ModifyList::new_list(vec![
763                    m_assert(Attribute::Uuid, &PartialValue::Uuid(r_uuid)),
764                    m_pres(Attribute::Description, &Value::Utf8("test".into()))
765                ])
766            ),
767            Err(OperationError::ModifyAssertionFailed)
768        ));
769
770        // This assertion will PASS
771        assert!(server_txn
772            .internal_modify_uuid(
773                t_uuid,
774                &ModifyList::new_list(vec![
775                    m_assert(Attribute::Uuid, &PartialValue::Uuid(t_uuid)),
776                    m_pres(Attribute::Description, &Value::Utf8("test".into()))
777                ])
778            )
779            .is_ok());
780    }
781
782    #[qs_test]
783    async fn test_modify_invalid_class(server: &QueryServer) {
784        // Test modifying an entry and adding an extra class, that would cause the entry
785        // to no longer conform to schema.
786        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
787
788        let e1 = entry_init!(
789            (Attribute::Class, EntryClass::Object.to_value()),
790            (Attribute::Class, EntryClass::Account.to_value()),
791            (Attribute::Class, EntryClass::Person.to_value()),
792            (Attribute::Name, Value::new_iname("testperson1")),
793            (
794                Attribute::Uuid,
795                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
796            ),
797            (Attribute::Description, Value::new_utf8s("testperson1")),
798            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
799        );
800
801        let ce = CreateEvent::new_internal(vec![e1]);
802
803        let cr = server_txn.create(&ce);
804        assert!(cr.is_ok());
805
806        // Add class but no values
807        let me_sin = ModifyEvent::new_internal_invalid(
808            filter!(f_eq(
809                Attribute::Name,
810                PartialValue::new_iname("testperson1")
811            )),
812            ModifyList::new_list(vec![Modify::Present(
813                Attribute::Class,
814                EntryClass::SystemInfo.to_value(),
815            )]),
816        );
817        assert!(server_txn.modify(&me_sin).is_err());
818
819        /*
820        // No longer applies, since multi-value is a property of the syntax now so
821        // invalid Values won't work on inserts.
822
823        // Add multivalue where not valid
824        let me_sin = ModifyEvent::new_internal_invalid(
825            filter!(f_eq(
826                Attribute::Name,
827                PartialValue::new_iname("testperson1")
828            )),
829            ModifyList::new_list(vec![Modify::Present(
830                Attribute::Name,
831                Value::new_inamen("testpersonx"),
832            )]),
833        );
834        assert!(server_txn.modify(&me_sin).is_err());
835        */
836
837        // add class and valid values?
838        let me_sin = ModifyEvent::new_internal_invalid(
839            filter!(f_eq(
840                Attribute::Name,
841                PartialValue::new_iname("testperson1")
842            )),
843            ModifyList::new_list(vec![
844                Modify::Present(Attribute::Class, EntryClass::SystemInfo.to_value()),
845                // Modify::Present(Attribute::Domain.into(), Value::new_iutf8("domain.name")),
846                Modify::Present(Attribute::Version, Value::new_uint32(1)),
847            ]),
848        );
849        assert!(server_txn.modify(&me_sin).is_ok());
850
851        // Replace a value
852        let me_sin = ModifyEvent::new_internal_invalid(
853            filter!(f_eq(
854                Attribute::Name,
855                PartialValue::new_iname("testperson1")
856            )),
857            ModifyList::new_list(vec![
858                Modify::Purged(Attribute::Name),
859                Modify::Present(Attribute::Name, Value::new_iname("testpersonx")),
860            ]),
861        );
862        assert!(server_txn.modify(&me_sin).is_ok());
863    }
864
865    #[qs_test]
866    async fn test_modify_password_only(server: &QueryServer) {
867        let e1 = entry_init!(
868            (Attribute::Class, EntryClass::Object.to_value()),
869            (Attribute::Class, EntryClass::Person.to_value()),
870            (Attribute::Class, EntryClass::Account.to_value()),
871            (Attribute::Name, Value::new_iname("testperson1")),
872            (
873                Attribute::Uuid,
874                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
875            ),
876            (Attribute::Description, Value::new_utf8s("testperson1")),
877            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
878        );
879        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
880        // Add the entry. Today we have no syntax to take simple str to a credential
881        // but honestly, that's probably okay :)
882        let ce = CreateEvent::new_internal(vec![e1]);
883        let cr = server_txn.create(&ce);
884        assert!(cr.is_ok());
885
886        // Build the credential.
887        let p = CryptoPolicy::minimum();
888        let cred =
889            Credential::new_password_only(&p, "test_password", OffsetDateTime::UNIX_EPOCH).unwrap();
890        let v_cred = Value::new_credential("primary", cred);
891        assert!(v_cred.validate());
892
893        // now modify and provide a primary credential.
894        let me_inv_m = ModifyEvent::new_internal_invalid(
895            filter!(f_eq(
896                Attribute::Name,
897                PartialValue::new_iname("testperson1")
898            )),
899            ModifyList::new_list(vec![Modify::Present(Attribute::PrimaryCredential, v_cred)]),
900        );
901        // go!
902        assert!(server_txn.modify(&me_inv_m).is_ok());
903
904        // assert it exists and the password checks out
905        let test_ent = server_txn
906            .internal_search_uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
907            .expect("failed");
908        // get the primary ava
909        let cred_ref = test_ent
910            .get_ava_single_credential(Attribute::PrimaryCredential)
911            .expect("Failed");
912        // do a pw check.
913        assert!(cred_ref.verify_password("test_password").unwrap());
914    }
915
916    #[qs_test]
917    async fn test_modify_name_self_write(server: &QueryServer) {
918        let user_uuid = uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930");
919        let e1 = entry_init!(
920            (Attribute::Class, EntryClass::Object.to_value()),
921            (Attribute::Class, EntryClass::Person.to_value()),
922            (Attribute::Class, EntryClass::Account.to_value()),
923            (Attribute::Name, Value::new_iname("testperson1")),
924            (Attribute::Uuid, Value::Uuid(user_uuid)),
925            (Attribute::Description, Value::new_utf8s("testperson1")),
926            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
927        );
928        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
929
930        assert!(server_txn.internal_create(vec![e1]).is_ok());
931
932        // Impersonate the user.
933
934        let testperson_entry = server_txn.internal_search_uuid(user_uuid).unwrap();
935
936        let user_ident = Identity::from_impersonate_entry_readwrite(testperson_entry);
937
938        // Can we change ourself?
939        let me_inv_m = ModifyEvent::new_impersonate_identity(
940            user_ident,
941            filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(user_uuid),)),
942            ModifyList::new_list(vec![
943                Modify::Purged(Attribute::Name),
944                Modify::Present(Attribute::Name, Value::new_iname("test_person_renamed")),
945                Modify::Purged(Attribute::DisplayName),
946                Modify::Present(
947                    Attribute::DisplayName,
948                    Value::Utf8("test_person_renamed".into()),
949                ),
950                Modify::Purged(Attribute::LegalName),
951                Modify::Present(
952                    Attribute::LegalName,
953                    Value::Utf8("test_person_renamed".into()),
954                ),
955            ]),
956        );
957
958        // Modify success.
959        assert!(server_txn.modify(&me_inv_m).is_ok());
960
961        // Alter the deal.
962        let modify_remove_person = ModifyEvent::new_internal_invalid(
963            filter!(f_eq(
964                Attribute::Uuid,
965                PartialValue::Uuid(UUID_IDM_PEOPLE_SELF_NAME_WRITE),
966            )),
967            ModifyList::new_list(vec![Modify::Purged(Attribute::Member)]),
968        );
969
970        assert!(server_txn.modify(&modify_remove_person).is_ok());
971
972        // Reload the users identity which will cause the memberships to be reflected now.
973        let testperson_entry = server_txn.internal_search_uuid(user_uuid).unwrap();
974
975        let user_ident = Identity::from_impersonate_entry_readwrite(testperson_entry);
976
977        let me_inv_m = ModifyEvent::new_impersonate_identity(
978            user_ident,
979            filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(user_uuid),)),
980            ModifyList::new_list(vec![
981                Modify::Purged(Attribute::Name),
982                Modify::Present(Attribute::Name, Value::new_iname("test_person_renamed")),
983                Modify::Purged(Attribute::DisplayName),
984                Modify::Present(
985                    Attribute::DisplayName,
986                    Value::Utf8("test_person_renamed".into()),
987                ),
988                Modify::Purged(Attribute::LegalName),
989                Modify::Present(
990                    Attribute::LegalName,
991                    Value::Utf8("test_person_renamed".into()),
992                ),
993            ]),
994        );
995
996        // The modification must now fail.
997        assert_eq!(
998            server_txn.modify(&me_inv_m),
999            Err(OperationError::AccessDenied)
1000        );
1001    }
1002}