Skip to main content

kanidmd_lib/server/
create.rs

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