1use crate::prelude::*;
2use crate::server::CreateEvent;
3use crate::server::{ChangeFlag, Plugins};
4
5impl QueryServerWriteTransaction<'_> {
6 #[instrument(level = "debug", skip_all)]
7 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 let candidates: Vec<Entry<EntryInit, EntryNew>> = ce.entries.clone();
26
27 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 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 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 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 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 e.seal(&self.schema)
74 })
75 })
76 .collect::<Result<Vec<EntrySealedNew>, _>>()?;
77
78 Plugins::run_pre_create(self, &norm_cand, ce).map_err(|e| {
82 admin_error!("Create operation failed (plugin), {:?}", e);
83 e
84 })?;
85
86 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 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 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 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 idm_admin = server_txn
204 .internal_search_uuid(UUID_IDM_ADMIN)
205 .expect("failed");
206
207 let se1 = SearchEvent::new_impersonate_entry(idm_admin, filt);
208
209 let mut e = entry_init!(
210 (Attribute::Class, EntryClass::Object.to_value()),
211 (Attribute::Class, EntryClass::Person.to_value()),
212 (Attribute::Class, EntryClass::Account.to_value()),
213 (Attribute::Name, Value::new_iname("testperson")),
214 (
215 Attribute::Spn,
216 Value::new_spn_str("testperson", "example.com")
217 ),
218 (
219 Attribute::Uuid,
220 Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
221 ),
222 (Attribute::Description, Value::new_utf8s("testperson")),
223 (Attribute::DisplayName, Value::new_utf8s("testperson"))
224 );
225
226 let ce = CreateEvent::new_internal(vec![e.clone()]);
227
228 let r1 = server_txn.search(&se1).expect("search failure");
229 assert!(r1.is_empty());
230
231 let cr = server_txn.create(&ce);
232 assert!(cr.is_ok());
233
234 let r2 = server_txn.search(&se1).expect("search failure");
235 debug!("--> {:?}", r2);
236 assert_eq!(r2.len(), 1);
237
238 e.add_ava(Attribute::Class, EntryClass::MemberOf.into());
240 e.add_ava(Attribute::MemberOf, Value::Refer(UUID_IDM_ALL_PERSONS));
241 e.add_ava(
242 Attribute::DirectMemberOf,
243 Value::Refer(UUID_IDM_ALL_PERSONS),
244 );
245 e.add_ava(Attribute::MemberOf, Value::Refer(UUID_IDM_ALL_ACCOUNTS));
246 e.add_ava(
247 Attribute::DirectMemberOf,
248 Value::Refer(UUID_IDM_ALL_ACCOUNTS),
249 );
250 e.add_ava(
252 Attribute::MemberOf,
253 Value::Refer(UUID_IDM_PEOPLE_SELF_NAME_WRITE),
254 );
255 e.add_ava(
257 Attribute::NameHistory,
258 Value::AuditLogString(server_txn.get_txn_cid().clone(), "testperson".to_string()),
259 );
260 let key = r2
262 .first()
263 .unwrap()
264 .get_ava_single_eckey_private(Attribute::IdVerificationEcKey)
265 .unwrap();
266
267 e.add_ava(
268 Attribute::IdVerificationEcKey,
269 Value::EcKeyPrivate(key.clone()),
270 );
271
272 let expected = vec![Arc::new(e.into_sealed_committed())];
273
274 error!("{:#?}", r2);
275 error!("{:#?}", expected);
276
277 assert_eq!(r2, expected);
278
279 assert!(server_txn.commit().is_ok());
280 }
281
282 #[qs_pair_test]
283 async fn test_pair_create_user(server_a: &QueryServer, server_b: &QueryServer) {
284 let mut server_a_txn = server_a.write(duration_from_epoch_now()).await.unwrap();
285 let mut server_b_txn = server_b.write(duration_from_epoch_now()).await.unwrap();
286
287 let filt = filter!(f_eq(Attribute::Name, PartialValue::new_iname("testperson")));
289
290 let idm_admin = server_a_txn
291 .internal_search_uuid(UUID_IDM_ADMIN)
292 .expect("failed");
293 let se_a = SearchEvent::new_impersonate_entry(idm_admin, filt.clone());
294
295 let idm_admin = server_b_txn
297 .internal_search_uuid(UUID_IDM_ADMIN)
298 .expect("failed");
299 let se_b = SearchEvent::new_impersonate_entry(idm_admin, filt);
300
301 let e = entry_init!(
302 (Attribute::Class, EntryClass::Person.to_value()),
303 (Attribute::Class, EntryClass::Account.to_value()),
304 (Attribute::Name, Value::new_iname("testperson")),
305 (Attribute::Description, Value::new_utf8s("testperson")),
306 (Attribute::DisplayName, Value::new_utf8s("testperson"))
307 );
308
309 let cr = server_a_txn.internal_create(vec![e.clone()]);
310 assert!(cr.is_ok());
311
312 let r1 = server_a_txn.search(&se_a).expect("search failure");
313 assert!(!r1.is_empty());
314
315 let r2 = server_b_txn.search(&se_b).expect("search failure");
317 assert!(r2.is_empty());
318
319 let cr = server_b_txn.internal_create(vec![e]);
320 assert!(cr.is_ok());
321
322 let r2 = server_b_txn.search(&se_b).expect("search failure");
324 assert!(!r2.is_empty());
325
326 assert!(server_a_txn.commit().is_ok());
327 assert!(server_b_txn.commit().is_ok());
328 }
329}