Skip to main content

kanidmd_lib/idm/
account_signup.rs

1use crate::{
2    idm::server::{IdmServerProxyReadTransaction, IdmServerProxyWriteTransaction},
3    prelude::*,
4    utils::readable_password_from_random,
5};
6use crypto_glue::{s256::Sha256, traits::Digest};
7use kanidm_proto::v1::OutboundMessage;
8
9pub struct AccountSignupRequestEvent {
10    // Who initiated this? By default I think
11    // this will be an internal identity?
12    pub ident: Identity,
13    username: String,
14    display_name: String,
15    email: String,
16}
17
18impl AccountSignupRequestEvent {
19    pub fn new(username: String, display_name: String, email: String) -> Self {
20        Self {
21            ident: Identity::account_request(),
22            username,
23            display_name,
24            email,
25        }
26    }
27}
28
29pub struct AccountSignupVerifyEvent {
30    pub ident: Identity,
31    intent_id: String,
32}
33
34impl AccountSignupVerifyEvent {
35    pub fn new(intent_id: String) -> Self {
36        Self {
37            ident: Identity::account_request(),
38            intent_id,
39        }
40    }
41}
42
43impl IdmServerProxyWriteTransaction<'_> {
44    pub fn account_signup_request(
45        &mut self,
46        asre: AccountSignupRequestEvent,
47    ) -> Result<(), OperationError> {
48        // If the feature is not enabled, error.
49        if !self.qs_write.get_feature_account_signup_config().enabled {
50            warn!("Attempt to perform account signup while feature is disabled.");
51            return Err(OperationError::AS0001FeatureDisabled);
52        }
53
54        // Generates a new account signup request entry that needs further processing.
55        // It needs a "delete after" tag.
56
57        let AccountSignupRequestEvent {
58            ident,
59            username,
60            display_name,
61            email,
62        } = asre;
63
64        let curtime_odt = self.qs_write.get_curtime_odt();
65        let delete_after_odt = curtime_odt + DEFAULT_ACCOUNT_SIGNUP_RETENTION;
66
67        let intent_id = readable_password_from_random();
68        // We treat this like pkce - we store a sha256, and the requestor has to present the plaintext
69        // code to accept the request.
70        let intent_sha256 = Sha256::digest(intent_id.as_bytes());
71
72        let account_signup_entry = EntryInitNew::from_iter([
73            (
74                Attribute::Class,
75                ValueSetIutf8N::new(EntryClass::AccountSignupRequest.into()) as ValueSet,
76            ),
77            (Attribute::Name, ValueSetIname::new(&username) as ValueSet),
78            (
79                Attribute::DisplayName,
80                ValueSetUtf8::new(display_name) as ValueSet,
81            ),
82            (
83                Attribute::Mail,
84                ValueSetEmailAddress::new(email.clone()) as ValueSet,
85            ),
86            (
87                Attribute::DeleteAfter,
88                ValueSetDateTime::new(delete_after_odt),
89            ),
90            (
91                Attribute::S256,
92                ValueSetSha256::new(intent_sha256) as ValueSet,
93            ),
94        ]);
95
96        // Create
97        let ce = CreateEvent {
98            ident,
99            entries: vec![account_signup_entry],
100            return_created_uuids: false,
101        };
102
103        self.qs_write.create(&ce)?;
104
105        let message = OutboundMessage::AccountSignupRequestV1 {
106            username,
107            intent_id,
108            expiry_time: delete_after_odt,
109        };
110
111        let mail_ident = Identity::message_queue();
112
113        let _message_id = self.qs_write.queue_message(&mail_ident, message, email)?;
114
115        Ok(())
116    }
117
118    pub fn account_signup_request_verify(
119        &mut self,
120        asre: AccountSignupVerifyEvent,
121    ) -> Result<Uuid, OperationError> {
122        // If the feature is not enabled, error.
123        if !self.qs_write.get_feature_account_signup_config().enabled {
124            warn!("Attempt to perform account signup while feature is disabled.");
125            return Err(OperationError::AS0002FeatureDisabled);
126        }
127
128        let AccountSignupVerifyEvent { ident, intent_id } = asre;
129
130        let intent_sha256 = Sha256::digest(intent_id.as_bytes());
131
132        let filter = filter_all!(f_and(vec![
133            f_eq(Attribute::Class, EntryClass::AccountSignupRequest.into()),
134            f_eq(Attribute::S256, intent_sha256.into())
135        ]));
136
137        let signup_entry = self.qs_write.ident_search_single(&ident, filter)?;
138
139        debug!(?signup_entry);
140
141        // Delete the signup request.
142        self.qs_write
143            .ident_delete_uuid(&ident, signup_entry.get_uuid())?;
144
145        // Create the account, with the values from the request.
146        let attr_iter = signup_entry.get_ava_iter().filter_map(|(a, vs)| match a {
147            Attribute::Name | Attribute::DisplayName | Attribute::Mail => {
148                Some((a.clone(), vs.clone()))
149            }
150            _ => None,
151        });
152
153        let account_entry = EntryInitNew::from_iter(
154            std::iter::once((
155                Attribute::Class,
156                vs_iutf8n!(
157                    EntryClass::Object.as_str(),
158                    EntryClass::Account.as_str(),
159                    EntryClass::Person.as_str()
160                ),
161            ))
162            .chain(attr_iter),
163        );
164
165        // Create
166        let ce = CreateEvent {
167            ident,
168            entries: vec![account_entry],
169            return_created_uuids: true,
170        };
171
172        let created_uuids = self.qs_write.create(&ce)?;
173
174        created_uuids
175            .and_then(|v| v.first().copied())
176            .ok_or(OperationError::AS0006InvalidState)
177    }
178}
179
180pub struct AccountSignupDisplayEvent {
181    pub ident: Identity,
182    intent_id: String,
183}
184
185#[derive(Debug)]
186pub struct AccountSignupDisplay {
187    pub username: String,
188    pub display_name: String,
189}
190
191impl AccountSignupDisplayEvent {
192    pub fn new(intent_id: String) -> Self {
193        Self {
194            ident: Identity::account_request(),
195            intent_id,
196        }
197    }
198}
199
200impl IdmServerProxyReadTransaction<'_> {
201    pub fn account_signup_display(
202        &mut self,
203        asde: AccountSignupDisplayEvent,
204    ) -> Result<AccountSignupDisplay, OperationError> {
205        // If the feature is not enabled, error.
206        if !self.qs_read.get_feature_account_signup_config().enabled {
207            warn!("Attempt to perform account signup while feature is disabled.");
208            return Err(OperationError::AS0003FeatureDisabled);
209        }
210
211        let AccountSignupDisplayEvent { ident, intent_id } = asde;
212
213        let intent_sha256 = Sha256::digest(intent_id.as_bytes());
214
215        let filter = filter_all!(f_and(vec![
216            f_eq(Attribute::Class, EntryClass::AccountSignupRequest.into()),
217            f_eq(Attribute::S256, intent_sha256.into())
218        ]));
219
220        let signup_entry = self.qs_read.ident_search_single(&ident, filter)?;
221
222        debug!(?signup_entry);
223
224        let username = signup_entry
225            .get_ava_single_iname(Attribute::Name)
226            .map(String::from)
227            .ok_or_else(|| {
228                error!("account signup request missing attribute Name");
229                OperationError::AS0004InvalidState
230            })?;
231
232        let display_name = signup_entry
233            .get_ava_single_utf8(Attribute::DisplayName)
234            .map(String::from)
235            .ok_or_else(|| {
236                error!("account signup request missing attribute DisplayName");
237                OperationError::AS0005InvalidState
238            })?;
239
240        // Return just the details needed
241        Ok(AccountSignupDisplay {
242            username,
243            display_name,
244        })
245    }
246}
247
248#[cfg(test)]
249mod tests {
250    use super::{AccountSignupDisplayEvent, AccountSignupRequestEvent, AccountSignupVerifyEvent};
251    use crate::prelude::*;
252    use kanidm_proto::v1::OutboundMessage;
253
254    const TESTPERSON_NAME: &str = "testperson";
255    const TESTPERSON_DISPLAY_NAME: &str = "Test Personington";
256    const TESTPERSON_EMAIL: &str = "testperson@example.com";
257
258    #[idm_test]
259    async fn test_account_signup_request_feature_disable(
260        idms: &IdmServer,
261        _idms_delayed: &mut IdmServerDelayed,
262    ) {
263        // If the feature is disabled, the request implicitly fails.
264        let ct = duration_from_epoch_now();
265        let mut write_txn = idms.proxy_write(ct).await.unwrap();
266
267        let account_signup_req = AccountSignupRequestEvent {
268            ident: Identity::account_request(),
269            username: TESTPERSON_NAME.into(),
270            display_name: TESTPERSON_DISPLAY_NAME.into(),
271            email: TESTPERSON_EMAIL.into(),
272        };
273
274        let result = write_txn
275            .account_signup_request(account_signup_req)
276            .unwrap_err();
277
278        assert_eq!(result, OperationError::AS0001FeatureDisabled);
279
280        // Even though we don't have a real intent id here, the feature
281        // check always denies first.
282        let account_signup_verify = AccountSignupVerifyEvent {
283            ident: Identity::account_request(),
284            intent_id: String::default(),
285        };
286
287        let result = write_txn
288            .account_signup_request_verify(account_signup_verify)
289            .unwrap_err();
290
291        assert_eq!(result, OperationError::AS0002FeatureDisabled);
292
293        assert!(write_txn.commit().is_ok());
294
295        let mut read_txn = idms.proxy_read().await.unwrap();
296
297        let account_signup_display = AccountSignupDisplayEvent {
298            ident: Identity::account_request(),
299            intent_id: String::default(),
300        };
301
302        let result = read_txn
303            .account_signup_display(account_signup_display)
304            .unwrap_err();
305
306        assert_eq!(result, OperationError::AS0003FeatureDisabled);
307    }
308
309    #[idm_test]
310    async fn test_account_signup_request_basic(
311        idms: &IdmServer,
312        _idms_delayed: &mut IdmServerDelayed,
313    ) {
314        // Enable the feature.
315        let ct = duration_from_epoch_now();
316        let mut write_txn = idms.proxy_write(ct).await.unwrap();
317
318        write_txn
319            .qs_write
320            .internal_batch_modify(
321                [(
322                    UUID_ACCOUNT_SIGNUP_FEATURE,
323                    ModifyList::from_iter([(Attribute::Enabled, Some(vs_bool!(true) as ValueSet))]),
324                )]
325                .into_iter(),
326            )
327            .unwrap();
328
329        write_txn.qs_write.reload().unwrap();
330
331        // Create a new request.
332        let account_signup_req = AccountSignupRequestEvent {
333            ident: Identity::account_request(),
334            username: TESTPERSON_NAME.into(),
335            display_name: TESTPERSON_DISPLAY_NAME.into(),
336            email: TESTPERSON_EMAIL.into(),
337        };
338
339        write_txn
340            .account_signup_request(account_signup_req)
341            .unwrap();
342
343        // Since there are no validation rules in place, it should immediately succeed.
344
345        // Validate the person
346
347        // TODO: Validate the message in the delayed queue
348        let idm_admin_identity = write_txn
349            .qs_write
350            .impersonate_uuid_as_readwrite_identity(UUID_IDM_ADMIN)
351            .expect("Failed to retrieve identity");
352
353        let filter = filter!(f_and(vec![
354            f_eq(Attribute::Class, EntryClass::OutboundMessage.into()),
355            f_eq(
356                Attribute::MailDestination,
357                PartialValue::EmailAddress(TESTPERSON_EMAIL.into())
358            )
359        ]));
360
361        let mut entries = write_txn
362            .qs_write
363            .impersonate_search(filter.clone(), filter, &idm_admin_identity)
364            .expect("Unable to search message queue");
365
366        assert_eq!(entries.len(), 1);
367        let message_entry = entries.pop().unwrap();
368
369        let message = message_entry
370            .get_ava_set(Attribute::MessageTemplate)
371            .and_then(|vs| vs.as_message())
372            .unwrap();
373
374        let intent_id = match message {
375            OutboundMessage::AccountSignupRequestV1 {
376                username,
377                intent_id,
378                ..
379            } => {
380                assert_eq!(username, TESTPERSON_NAME);
381                intent_id.clone()
382            }
383            _ => panic!("Wrong message type!"),
384        };
385
386        assert!(write_txn.commit().is_ok());
387
388        // Verify we can read the display information.
389
390        let mut read_txn = idms.proxy_read().await.unwrap();
391
392        let account_signup_display = AccountSignupDisplayEvent {
393            ident: Identity::account_request(),
394            intent_id: intent_id.clone(),
395        };
396
397        let account_details = read_txn
398            .account_signup_display(account_signup_display)
399            .expect("Failed to view signup request");
400
401        assert_eq!(&account_details.username, TESTPERSON_NAME);
402        assert_eq!(&account_details.display_name, TESTPERSON_DISPLAY_NAME);
403
404        drop(read_txn);
405
406        // Now use the intent_id to complete the signup.
407        let mut write_txn = idms.proxy_write(ct).await.unwrap();
408
409        let account_signup_verify = AccountSignupVerifyEvent {
410            ident: Identity::account_request(),
411            intent_id,
412        };
413
414        let _result = write_txn
415            .account_signup_request_verify(account_signup_verify)
416            .expect("Unable to process account signup verification");
417
418        assert!(write_txn.commit().is_ok());
419    }
420}