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<(), 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 Ok(())
178 }
179
180 pub fn internal_create(
181 &mut self,
182 entries: Vec<Entry<EntryInit, EntryNew>>,
183 ) -> Result<(), OperationError> {
184 let ce = CreateEvent::new_internal(entries);
185 self.create(&ce)
186 }
187}
188
189#[cfg(test)]
190mod tests {
191 use crate::prelude::*;
192 use std::sync::Arc;
193
194 #[qs_test]
195 async fn test_create_user(server: &QueryServer) {
196 let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
197 let filt = filter!(f_eq(Attribute::Name, PartialValue::new_iname("testperson")));
198 let admin = server_txn.internal_search_uuid(UUID_ADMIN).expect("failed");
199
200 let se1 = SearchEvent::new_impersonate_entry(admin, filt);
201
202 let mut e = entry_init!(
203 (Attribute::Class, EntryClass::Object.to_value()),
204 (Attribute::Class, EntryClass::Person.to_value()),
205 (Attribute::Class, EntryClass::Account.to_value()),
206 (Attribute::Name, Value::new_iname("testperson")),
207 (
208 Attribute::Spn,
209 Value::new_spn_str("testperson", "example.com")
210 ),
211 (
212 Attribute::Uuid,
213 Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
214 ),
215 (Attribute::Description, Value::new_utf8s("testperson")),
216 (Attribute::DisplayName, Value::new_utf8s("testperson"))
217 );
218
219 let ce = CreateEvent::new_internal(vec![e.clone()]);
220
221 let r1 = server_txn.search(&se1).expect("search failure");
222 assert!(r1.is_empty());
223
224 let cr = server_txn.create(&ce);
225 assert!(cr.is_ok());
226
227 let r2 = server_txn.search(&se1).expect("search failure");
228 debug!("--> {:?}", r2);
229 assert_eq!(r2.len(), 1);
230
231 e.add_ava(Attribute::Class, EntryClass::MemberOf.into());
233 e.add_ava(Attribute::MemberOf, Value::Refer(UUID_IDM_ALL_PERSONS));
234 e.add_ava(
235 Attribute::DirectMemberOf,
236 Value::Refer(UUID_IDM_ALL_PERSONS),
237 );
238 e.add_ava(Attribute::MemberOf, Value::Refer(UUID_IDM_ALL_ACCOUNTS));
239 e.add_ava(
240 Attribute::DirectMemberOf,
241 Value::Refer(UUID_IDM_ALL_ACCOUNTS),
242 );
243 e.add_ava(
245 Attribute::MemberOf,
246 Value::Refer(UUID_IDM_PEOPLE_SELF_NAME_WRITE),
247 );
248 e.add_ava(
250 Attribute::NameHistory,
251 Value::AuditLogString(server_txn.get_txn_cid().clone(), "testperson".to_string()),
252 );
253 let key = r2
255 .first()
256 .unwrap()
257 .get_ava_single_eckey_private(Attribute::IdVerificationEcKey)
258 .unwrap();
259
260 e.add_ava(
261 Attribute::IdVerificationEcKey,
262 Value::EcKeyPrivate(key.clone()),
263 );
264
265 let expected = vec![Arc::new(e.into_sealed_committed())];
266
267 assert_eq!(r2, expected);
268
269 assert!(server_txn.commit().is_ok());
270 }
271
272 #[qs_pair_test]
273 async fn test_pair_create_user(server_a: &QueryServer, server_b: &QueryServer) {
274 let mut server_a_txn = server_a.write(duration_from_epoch_now()).await.unwrap();
275 let mut server_b_txn = server_b.write(duration_from_epoch_now()).await.unwrap();
276
277 let filt = filter!(f_eq(Attribute::Name, PartialValue::new_iname("testperson")));
279
280 let admin = server_a_txn
281 .internal_search_uuid(UUID_ADMIN)
282 .expect("failed");
283 let se_a = SearchEvent::new_impersonate_entry(admin, filt.clone());
284
285 let admin = server_b_txn
286 .internal_search_uuid(UUID_ADMIN)
287 .expect("failed");
288 let se_b = SearchEvent::new_impersonate_entry(admin, filt);
289
290 let e = entry_init!(
291 (Attribute::Class, EntryClass::Person.to_value()),
292 (Attribute::Class, EntryClass::Account.to_value()),
293 (Attribute::Name, Value::new_iname("testperson")),
294 (Attribute::Description, Value::new_utf8s("testperson")),
295 (Attribute::DisplayName, Value::new_utf8s("testperson"))
296 );
297
298 let cr = server_a_txn.internal_create(vec![e.clone()]);
299 assert!(cr.is_ok());
300
301 let r1 = server_a_txn.search(&se_a).expect("search failure");
302 assert!(!r1.is_empty());
303
304 let r2 = server_b_txn.search(&se_b).expect("search failure");
306 assert!(r2.is_empty());
307
308 let cr = server_b_txn.internal_create(vec![e]);
309 assert!(cr.is_ok());
310
311 let r2 = server_b_txn.search(&se_b).expect("search failure");
313 assert!(!r2.is_empty());
314
315 assert!(server_a_txn.commit().is_ok());
316 assert!(server_b_txn.commit().is_ok());
317 }
318}