kanidmd_lib/server/
create.rs

1use crate::prelude::*;
2use crate::server::CreateEvent;
3use crate::server::{ChangeFlag, Plugins};
4
5impl QueryServerWriteTransaction<'_> {
6    #[instrument(level = "debug", skip_all)]
7    /// The create event is a raw, read only representation of the request
8    /// that was made to us, including information about the identity
9    /// performing the request.
10    pub fn create(&mut self, ce: &CreateEvent) -> Result<Option<Vec<Uuid>>, OperationError> {
11        if !ce.ident.is_internal() {
12            security_info!(name = %ce.ident, "create initiator");
13        }
14
15        if ce.entries.is_empty() {
16            request_error!("create: empty create request");
17            return Err(OperationError::EmptyRequest);
18        }
19
20        // TODO #67: Do we need limits on number of creates, or do we constraint
21        // based on request size in the frontend?
22
23        // Copy the entries to a writeable form, this involves assigning a
24        // change id so we can track what's happening.
25        let candidates: Vec<Entry<EntryInit, EntryNew>> = ce.entries.clone();
26
27        // Do we have rights to perform these creates?
28        // create_allow_operation
29        let access = self.get_accesscontrols();
30        let op_allow = access
31            .create_allow_operation(ce, &candidates)
32            .map_err(|e| {
33                admin_error!("Failed to check create access {:?}", e);
34                e
35            })?;
36        if !op_allow {
37            return Err(OperationError::AccessDenied);
38        }
39
40        // Before we assign replication metadata, we need to assert these entries
41        // are valid to create within the set of replication transitions. This
42        // means they *can not* be recycled or tombstones!
43        if candidates.iter().any(|e| e.mask_recycled_ts().is_none()) {
44            admin_warn!("Refusing to create invalid entries that are attempting to bypass replication state machine.");
45            return Err(OperationError::AccessDenied);
46        }
47
48        // Assign our replication metadata now, since we can proceed with this operation.
49        let mut candidates: Vec<Entry<EntryInvalid, EntryNew>> = candidates
50            .into_iter()
51            .map(|e| e.assign_cid(self.cid.clone(), &self.schema))
52            .collect();
53
54        // run any pre plugins, giving them the list of mutable candidates.
55        // pre-plugins are defined here in their correct order of calling!
56        // I have no intent to make these dynamic or configurable.
57        Plugins::run_pre_create_transform(self, &mut candidates, ce).map_err(|e| {
58            admin_error!("Create operation failed (pre_transform plugin), {:?}", e);
59            e
60        })?;
61
62        // Now, normalise AND validate!
63        let norm_cand = candidates
64            .into_iter()
65            .map(|e| {
66                e.validate(&self.schema)
67                    .map_err(|e| {
68                        admin_error!("Schema Violation in create validate {:?}", e);
69                        OperationError::SchemaViolation(e)
70                    })
71                    .map(|e| {
72                        // Then seal the changes?
73                        e.seal(&self.schema)
74                    })
75            })
76            .collect::<Result<Vec<EntrySealedNew>, _>>()?;
77
78        // Run any pre-create plugins now with schema validated entries.
79        // This is important for normalisation of certain types i.e. class
80        // or attributes for these checks.
81        Plugins::run_pre_create(self, &norm_cand, ce).map_err(|e| {
82            admin_error!("Create operation failed (plugin), {:?}", e);
83            e
84        })?;
85
86        // We may change from ce.entries later to something else?
87        let commit_cand = self.be_txn.create(&self.cid, norm_cand).map_err(|e| {
88            admin_error!("betxn create failure {:?}", e);
89            e
90        })?;
91
92        // Run any post plugins
93        Plugins::run_post_create(self, &commit_cand, ce).map_err(|e| {
94            admin_error!("Create operation failed (post plugin), {:?}", e);
95            e
96        })?;
97
98        // We have finished all plugins and now have a successful operation - flag if
99        // schema or acp requires reload.
100        if !self.changed_flags.contains(ChangeFlag::SCHEMA)
101            && commit_cand.iter().any(|e| {
102                e.attribute_equality(Attribute::Class, &EntryClass::ClassType.into())
103                    || e.attribute_equality(Attribute::Class, &EntryClass::AttributeType.into())
104            })
105        {
106            self.changed_flags.insert(ChangeFlag::SCHEMA)
107        }
108        if !self.changed_flags.contains(ChangeFlag::ACP)
109            && commit_cand.iter().any(|e| {
110                e.attribute_equality(Attribute::Class, &EntryClass::AccessControlProfile.into())
111            })
112        {
113            self.changed_flags.insert(ChangeFlag::ACP)
114        }
115
116        if !self.changed_flags.contains(ChangeFlag::APPLICATION)
117            && commit_cand
118                .iter()
119                .any(|e| e.attribute_equality(Attribute::Class, &EntryClass::Application.into()))
120        {
121            self.changed_flags.insert(ChangeFlag::APPLICATION)
122        }
123
124        if !self.changed_flags.contains(ChangeFlag::OAUTH2)
125            && commit_cand.iter().any(|e| {
126                e.attribute_equality(Attribute::Class, &EntryClass::OAuth2ResourceServer.into())
127            })
128        {
129            self.changed_flags.insert(ChangeFlag::OAUTH2)
130        }
131        if !self.changed_flags.contains(ChangeFlag::DOMAIN)
132            && commit_cand
133                .iter()
134                .any(|e| e.attribute_equality(Attribute::Uuid, &PVUUID_DOMAIN_INFO))
135        {
136            self.changed_flags.insert(ChangeFlag::DOMAIN)
137        }
138        if !self.changed_flags.contains(ChangeFlag::SYSTEM_CONFIG)
139            && commit_cand
140                .iter()
141                .any(|e| e.attribute_equality(Attribute::Uuid, &PVUUID_SYSTEM_CONFIG))
142        {
143            self.changed_flags.insert(ChangeFlag::SYSTEM_CONFIG)
144        }
145
146        if !self.changed_flags.contains(ChangeFlag::SYNC_AGREEMENT)
147            && commit_cand
148                .iter()
149                .any(|e| e.attribute_equality(Attribute::Class, &EntryClass::SyncAccount.into()))
150        {
151            self.changed_flags.insert(ChangeFlag::SYNC_AGREEMENT)
152        }
153
154        if !self.changed_flags.contains(ChangeFlag::KEY_MATERIAL)
155            && commit_cand.iter().any(|e| {
156                e.attribute_equality(Attribute::Class, &EntryClass::KeyProvider.into())
157                    || e.attribute_equality(Attribute::Class, &EntryClass::KeyObject.into())
158            })
159        {
160            self.changed_flags.insert(ChangeFlag::KEY_MATERIAL)
161        }
162
163        self.changed_uuid
164            .extend(commit_cand.iter().map(|e| e.get_uuid()));
165
166        trace!(
167            changed = ?self.changed_flags.iter_names().collect::<Vec<_>>(),
168        );
169
170        // We are complete, finalise logging and return
171
172        if ce.ident.is_internal() {
173            trace!("Create operation success");
174        } else {
175            admin_info!("Create operation success");
176        }
177
178        if ce.return_created_uuids {
179            Ok(Some(commit_cand.iter().map(|e| e.get_uuid()).collect()))
180        } else {
181            Ok(None)
182        }
183    }
184
185    pub fn internal_create(
186        &mut self,
187        entries: Vec<Entry<EntryInit, EntryNew>>,
188    ) -> Result<(), OperationError> {
189        let ce = CreateEvent::new_internal(entries);
190        self.create(&ce).map(|_| ())
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use crate::prelude::*;
197    use std::sync::Arc;
198
199    #[qs_test]
200    async fn test_create_user(server: &QueryServer) {
201        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
202        let filt = filter!(f_eq(Attribute::Name, PartialValue::new_iname("testperson")));
203        let admin = server_txn.internal_search_uuid(UUID_ADMIN).expect("failed");
204
205        let se1 = SearchEvent::new_impersonate_entry(admin, filt);
206
207        let mut e = entry_init!(
208            (Attribute::Class, EntryClass::Object.to_value()),
209            (Attribute::Class, EntryClass::Person.to_value()),
210            (Attribute::Class, EntryClass::Account.to_value()),
211            (Attribute::Name, Value::new_iname("testperson")),
212            (
213                Attribute::Spn,
214                Value::new_spn_str("testperson", "example.com")
215            ),
216            (
217                Attribute::Uuid,
218                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
219            ),
220            (Attribute::Description, Value::new_utf8s("testperson")),
221            (Attribute::DisplayName, Value::new_utf8s("testperson"))
222        );
223
224        let ce = CreateEvent::new_internal(vec![e.clone()]);
225
226        let r1 = server_txn.search(&se1).expect("search failure");
227        assert!(r1.is_empty());
228
229        let cr = server_txn.create(&ce);
230        assert!(cr.is_ok());
231
232        let r2 = server_txn.search(&se1).expect("search failure");
233        debug!("--> {:?}", r2);
234        assert_eq!(r2.len(), 1);
235
236        // We apply some member-of in the server now, so we add these before we seal.
237        e.add_ava(Attribute::Class, EntryClass::MemberOf.into());
238        e.add_ava(Attribute::MemberOf, Value::Refer(UUID_IDM_ALL_PERSONS));
239        e.add_ava(
240            Attribute::DirectMemberOf,
241            Value::Refer(UUID_IDM_ALL_PERSONS),
242        );
243        e.add_ava(Attribute::MemberOf, Value::Refer(UUID_IDM_ALL_ACCOUNTS));
244        e.add_ava(
245            Attribute::DirectMemberOf,
246            Value::Refer(UUID_IDM_ALL_ACCOUNTS),
247        );
248        // Indirectly via all persons
249        e.add_ava(
250            Attribute::MemberOf,
251            Value::Refer(UUID_IDM_PEOPLE_SELF_NAME_WRITE),
252        );
253        // we also add the name_history ava!
254        e.add_ava(
255            Attribute::NameHistory,
256            Value::AuditLogString(server_txn.get_txn_cid().clone(), "testperson".to_string()),
257        );
258        // this is kinda ugly but since ecdh keys are generated we don't have any other way
259        let key = r2
260            .first()
261            .unwrap()
262            .get_ava_single_eckey_private(Attribute::IdVerificationEcKey)
263            .unwrap();
264
265        e.add_ava(
266            Attribute::IdVerificationEcKey,
267            Value::EcKeyPrivate(key.clone()),
268        );
269
270        let expected = vec![Arc::new(e.into_sealed_committed())];
271
272        assert_eq!(r2, expected);
273
274        assert!(server_txn.commit().is_ok());
275    }
276
277    #[qs_pair_test]
278    async fn test_pair_create_user(server_a: &QueryServer, server_b: &QueryServer) {
279        let mut server_a_txn = server_a.write(duration_from_epoch_now()).await.unwrap();
280        let mut server_b_txn = server_b.write(duration_from_epoch_now()).await.unwrap();
281
282        // Create on server a
283        let filt = filter!(f_eq(Attribute::Name, PartialValue::new_iname("testperson")));
284
285        let admin = server_a_txn
286            .internal_search_uuid(UUID_ADMIN)
287            .expect("failed");
288        let se_a = SearchEvent::new_impersonate_entry(admin, filt.clone());
289
290        let admin = server_b_txn
291            .internal_search_uuid(UUID_ADMIN)
292            .expect("failed");
293        let se_b = SearchEvent::new_impersonate_entry(admin, filt);
294
295        let e = entry_init!(
296            (Attribute::Class, EntryClass::Person.to_value()),
297            (Attribute::Class, EntryClass::Account.to_value()),
298            (Attribute::Name, Value::new_iname("testperson")),
299            (Attribute::Description, Value::new_utf8s("testperson")),
300            (Attribute::DisplayName, Value::new_utf8s("testperson"))
301        );
302
303        let cr = server_a_txn.internal_create(vec![e.clone()]);
304        assert!(cr.is_ok());
305
306        let r1 = server_a_txn.search(&se_a).expect("search failure");
307        assert!(!r1.is_empty());
308
309        // Not on sb
310        let r2 = server_b_txn.search(&se_b).expect("search failure");
311        assert!(r2.is_empty());
312
313        let cr = server_b_txn.internal_create(vec![e]);
314        assert!(cr.is_ok());
315
316        // Now is present
317        let r2 = server_b_txn.search(&se_b).expect("search failure");
318        assert!(!r2.is_empty());
319
320        assert!(server_a_txn.commit().is_ok());
321        assert!(server_b_txn.commit().is_ok());
322    }
323}