Skip to main content

kanidmd_lib/idm/
application.rs

1use super::ldap::{LdapBoundToken, LdapSession};
2use crate::{
3    credential::apppwd::ApplicationPassword,
4    idm::{
5        account::Account,
6        event::LdapApplicationAuthEvent,
7        server::{IdmServerAuthTransaction, IdmServerProxyWriteTransaction, IdmServerTransaction},
8    },
9    prelude::*,
10    utils::readable_password_from_random,
11};
12use concread::cowcell::*;
13use hashbrown::HashMap;
14use kanidm_proto::internal::OperationError;
15use std::sync::Arc;
16use uuid::Uuid;
17
18#[derive(Clone)]
19pub(crate) struct Application {
20    pub uuid: Uuid,
21    pub name: String,
22    pub linked_group: Uuid,
23}
24
25impl Application {
26    #[cfg(test)]
27    pub(crate) fn try_from_entry_ro(
28        value: &Entry<EntrySealed, EntryCommitted>,
29        _qs: &mut QueryServerReadTransaction,
30    ) -> Result<Self, OperationError> {
31        if !value.attribute_equality(Attribute::Class, &EntryClass::Application.to_partialvalue()) {
32            return Err(OperationError::MissingClass(ENTRYCLASS_APPLICATION.into()));
33        }
34
35        let uuid = value.get_uuid();
36
37        let name = value
38            .get_ava_single_iname(Attribute::Name)
39            .map(|s| s.to_string())
40            .ok_or_else(|| OperationError::MissingAttribute(Attribute::Name))?;
41
42        let linked_group = value
43            .get_ava_single_refer(Attribute::LinkedGroup)
44            .ok_or_else(|| OperationError::MissingAttribute(Attribute::LinkedGroup))?;
45
46        Ok(Application {
47            name,
48            uuid,
49            linked_group,
50        })
51    }
52}
53
54#[derive(Clone)]
55struct LdapApplicationsInner {
56    set: HashMap<String, Application>,
57}
58
59pub struct LdapApplications {
60    inner: CowCell<LdapApplicationsInner>,
61}
62
63pub struct LdapApplicationsReadTransaction {
64    inner: CowCellReadTxn<LdapApplicationsInner>,
65}
66
67pub struct LdapApplicationsWriteTransaction<'a> {
68    inner: CowCellWriteTxn<'a, LdapApplicationsInner>,
69}
70
71impl LdapApplicationsWriteTransaction<'_> {
72    pub fn reload(&mut self, value: Vec<Arc<EntrySealedCommitted>>) -> Result<(), OperationError> {
73        let app_set: Result<HashMap<_, _>, _> = value
74            .into_iter()
75            .map(|ent| {
76                if !ent.attribute_equality(Attribute::Class, &EntryClass::Application.into()) {
77                    error!("Missing class application");
78                    return Err(OperationError::InvalidEntryState);
79                }
80
81                let uuid = ent.get_uuid();
82                let name = ent
83                    .get_ava_single_iname(Attribute::Name)
84                    .map(str::to_string)
85                    .ok_or(OperationError::InvalidValueState)?;
86
87                let linked_group = ent
88                    .get_ava_single_refer(Attribute::LinkedGroup)
89                    .ok_or(OperationError::InvalidValueState)?;
90
91                let app = Application {
92                    uuid,
93                    name: name.clone(),
94                    linked_group,
95                };
96
97                Ok((name, app))
98            })
99            .collect();
100
101        let new_inner = LdapApplicationsInner { set: app_set? };
102        self.inner.replace(new_inner);
103
104        Ok(())
105    }
106
107    pub fn commit(self) {
108        self.inner.commit();
109    }
110}
111
112impl LdapApplications {
113    pub fn read(&self) -> LdapApplicationsReadTransaction {
114        LdapApplicationsReadTransaction {
115            inner: self.inner.read(),
116        }
117    }
118
119    pub fn write(&self) -> LdapApplicationsWriteTransaction<'_> {
120        LdapApplicationsWriteTransaction {
121            inner: self.inner.write(),
122        }
123    }
124}
125
126impl TryFrom<Vec<Arc<EntrySealedCommitted>>> for LdapApplications {
127    type Error = OperationError;
128
129    fn try_from(value: Vec<Arc<EntrySealedCommitted>>) -> Result<Self, Self::Error> {
130        let apps = LdapApplications {
131            inner: CowCell::new(LdapApplicationsInner {
132                set: HashMap::new(),
133            }),
134        };
135
136        let mut apps_wr = apps.write();
137        apps_wr.reload(value)?;
138        apps_wr.commit();
139        Ok(apps)
140    }
141}
142
143impl IdmServerAuthTransaction<'_> {
144    pub async fn application_auth_ldap(
145        &mut self,
146        lae: &LdapApplicationAuthEvent,
147        ct: Duration,
148    ) -> Result<Option<LdapBoundToken>, OperationError> {
149        let usr_entry = self.get_qs_txn().internal_search_uuid(lae.target)?;
150
151        let account: Account =
152            Account::try_from_entry_ro(&usr_entry, &mut self.qs_read).map_err(|e| {
153                error!("Failed to search account {:?}", e);
154                e
155            })?;
156
157        if account.is_anonymous() {
158            return Err(OperationError::InvalidUuid);
159        }
160
161        if !account.is_within_valid_time(ct) {
162            security_info!("Account has expired or is not yet valid, not allowing to proceed");
163            return Err(OperationError::SessionExpired);
164        }
165
166        let application = self
167            .applications
168            .inner
169            .set
170            .get(&lae.application)
171            .ok_or_else(|| {
172                info!("Application {:?} not found", lae.application);
173                OperationError::NoMatchingEntries
174            })?;
175
176        // Check linked group membership
177        let is_memberof = usr_entry
178            .get_ava_refer(Attribute::MemberOf)
179            .map(|member_of_set| member_of_set.contains(&application.linked_group))
180            .unwrap_or_default();
181
182        if !is_memberof {
183            debug!(
184                "User {:?} not member of application {}:{:?} linked group {:?}",
185                account.uuid, application.name, application.uuid, application.linked_group,
186            );
187            return Ok(None);
188        }
189
190        match account.verify_application_password(application, lae.cleartext.as_str())? {
191            Some(_) => {
192                let session_id = Uuid::new_v4();
193                security_info!(
194                    "Starting session {} for {} {} with application {}:{:?}",
195                    session_id,
196                    account.spn(),
197                    account.uuid,
198                    application.name,
199                    application.uuid,
200                );
201
202                Ok(Some(LdapBoundToken {
203                    spn: account.spn().into(),
204                    session_id,
205                    effective_session: LdapSession::UnixBind(account.uuid),
206                }))
207            }
208            None => {
209                security_info!("Account does not have a configured application password.");
210                Ok(None)
211            }
212        }
213    }
214}
215
216#[derive(Debug)]
217pub struct GenerateApplicationPasswordEvent {
218    pub ident: Identity,
219    pub target: Uuid,
220    pub application: Uuid,
221    pub label: String,
222}
223
224impl GenerateApplicationPasswordEvent {
225    pub fn from_parts(
226        ident: Identity,
227        target: Uuid,
228        application: Uuid,
229        label: String,
230    ) -> Result<Self, OperationError> {
231        Ok(GenerateApplicationPasswordEvent {
232            ident,
233            target,
234            application,
235            label,
236        })
237    }
238
239    pub fn new_internal(target: Uuid, application: Uuid, label: String) -> Self {
240        GenerateApplicationPasswordEvent {
241            ident: Identity::from_internal(),
242            target,
243            application,
244            label,
245        }
246    }
247}
248
249impl IdmServerProxyWriteTransaction<'_> {
250    #[instrument(level = "debug", skip_all)]
251    pub fn generate_application_password(
252        &mut self,
253        ev: &GenerateApplicationPasswordEvent,
254    ) -> Result<(String, Uuid), OperationError> {
255        // This is intended to be read/copied by a human
256        let cleartext = readable_password_from_random();
257        let policy = self.crypto_policy();
258
259        let ap = ApplicationPassword::new(
260            ev.application,
261            ev.label.as_str(),
262            cleartext.as_str(),
263            policy,
264        )
265        .inspect_err(|err| {
266            error!(
267                ?err,
268                "Unable to generate application password. This is a BUG!!!"
269            )
270        })?;
271
272        let ap_uuid = ap.uuid;
273        let vap = Value::ApplicationPassword(ap);
274        let modlist = ModifyList::new_append(Attribute::ApplicationPassword, vap);
275
276        // Apply it
277        self.qs_write
278            .impersonate_modify(
279                // Filter as executed
280                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(ev.target))),
281                // Filter as intended (acp)
282                &filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(ev.target))),
283                &modlist,
284                // Provide the event to impersonate
285                &ev.ident,
286            )
287            .inspect_err(|err| error!(?err))
288            .map(|_| (cleartext, ap_uuid))
289    }
290
291    #[instrument(level = "debug", skip_all)]
292    pub fn application_password_delete(
293        &mut self,
294        ident: &Identity,
295        target: Uuid,
296        apppwd_id: Uuid,
297    ) -> Result<(), OperationError> {
298        let modlist = ModifyList::new_remove(
299            Attribute::ApplicationPassword,
300            PartialValue::Uuid(apppwd_id),
301        );
302
303        self.qs_write
304            .impersonate_modify(
305                // Filter as executed
306                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(target))),
307                // Filter as intended (acp)
308                &filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(target))),
309                &modlist,
310                ident,
311            )
312            .inspect_err(|err| error!(?err))
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use crate::{
319        event::CreateEvent,
320        idm::{
321            account::Account,
322            application::{Application, GenerateApplicationPasswordEvent},
323            server::IdmServerTransaction,
324            serviceaccount::{DestroyApiTokenEvent, GenerateApiTokenEvent},
325        },
326        prelude::*,
327    };
328    use compact_jwt::{dangernoverify::JwsDangerReleaseWithoutVerify, JwsVerifier};
329    use kanidm_proto::internal::ApiToken as ProtoApiToken;
330    use std::time::Duration;
331
332    const TEST_CURRENT_TIME: u64 = 6000;
333
334    // Tests it is not possible to create an application without the linked group attribute
335    #[idm_test]
336    async fn test_idm_application_no_linked_group(
337        idms: &IdmServer,
338        _idms_delayed: &mut IdmServerDelayed,
339    ) {
340        let ct = Duration::from_secs(TEST_CURRENT_TIME);
341        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
342
343        let test_entry_uuid = Uuid::new_v4();
344
345        let e1 = entry_init!(
346            (Attribute::Class, EntryClass::Object.to_value()),
347            (Attribute::Class, EntryClass::Account.to_value()),
348            (Attribute::Class, EntryClass::ServiceAccount.to_value()),
349            (Attribute::Class, EntryClass::Application.to_value()),
350            (Attribute::DisplayName, Value::new_utf8s("Application")),
351            (Attribute::Name, Value::new_iname("test_app_name")),
352            (Attribute::Uuid, Value::Uuid(test_entry_uuid)),
353            (Attribute::Description, Value::new_utf8s("test_app_desc")),
354            (
355                Attribute::DisplayName,
356                Value::new_utf8s("test_app_dispname")
357            )
358        );
359
360        let ce = CreateEvent::new_internal(vec![e1]);
361        let cr = idms_prox_write.qs_write.create(&ce);
362        assert!(cr.is_err());
363    }
364
365    // Tests creating an application with a real linked group attribute
366    #[idm_test]
367    async fn test_idm_application_linked_group(
368        idms: &IdmServer,
369        _idms_delayed: &mut IdmServerDelayed,
370    ) {
371        let test_entry_name = "test_app_name";
372        let test_entry_uuid = Uuid::new_v4();
373        let test_grp_name = "testgroup1";
374        let test_grp_uuid = Uuid::new_v4();
375
376        {
377            let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
378
379            let e1 = entry_init!(
380                (Attribute::Class, EntryClass::Object.to_value()),
381                (Attribute::Class, EntryClass::Group.to_value()),
382                (Attribute::Name, Value::new_iname(test_grp_name)),
383                (Attribute::Uuid, Value::Uuid(test_grp_uuid))
384            );
385
386            let e2 = entry_init!(
387                (Attribute::Class, EntryClass::Object.to_value()),
388                (Attribute::Class, EntryClass::Account.to_value()),
389                (Attribute::Class, EntryClass::ServiceAccount.to_value()),
390                (Attribute::Class, EntryClass::Application.to_value()),
391                (Attribute::Name, Value::new_iname(test_entry_name)),
392                (Attribute::Uuid, Value::Uuid(test_entry_uuid)),
393                (Attribute::Description, Value::new_utf8s("test_app_desc")),
394                (
395                    Attribute::DisplayName,
396                    Value::new_utf8s("test_app_dispname")
397                ),
398                (Attribute::LinkedGroup, Value::Refer(test_grp_uuid))
399            );
400
401            let ce = CreateEvent::new_internal(vec![e1, e2]);
402            let cr = idms_prox_write.qs_write.create(&ce);
403            assert!(cr.is_ok());
404
405            let cr = idms_prox_write.qs_write.commit();
406            assert!(cr.is_ok());
407        }
408
409        {
410            let mut idms_prox_read = idms.proxy_read().await.unwrap();
411            let app = idms_prox_read
412                .qs_read
413                .internal_search_uuid(test_entry_uuid)
414                .and_then(|entry| {
415                    Application::try_from_entry_ro(&entry, &mut idms_prox_read.qs_read)
416                })
417                .map_err(|e| {
418                    trace!("Error: {:?}", e);
419                    e
420                });
421            assert!(app.is_ok());
422
423            let app = app.unwrap();
424            assert_eq!(app.name, "test_app_name");
425            assert_eq!(app.uuid, test_entry_uuid);
426            assert_eq!(app.linked_group, test_grp_uuid);
427        }
428
429        // Test reference integrity. An attempt to remove a linked group blocks
430        // the group being deleted
431        {
432            let de = DeleteEvent::new_internal_invalid(filter!(f_eq(
433                Attribute::Uuid,
434                PartialValue::Uuid(test_grp_uuid)
435            )));
436            let mut idms_proxy_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
437            assert!(idms_proxy_write.qs_write.delete(&de).is_err());
438        }
439
440        {
441            let de = DeleteEvent::new_internal_invalid(filter!(f_eq(
442                Attribute::Uuid,
443                PartialValue::Uuid(test_entry_uuid)
444            )));
445            let mut idms_proxy_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
446            assert!(idms_proxy_write.qs_write.delete(&de).is_ok());
447            assert!(idms_proxy_write.qs_write.commit().is_ok());
448        }
449
450        {
451            let de = DeleteEvent::new_internal_invalid(filter!(f_eq(
452                Attribute::Uuid,
453                PartialValue::Uuid(test_grp_uuid)
454            )));
455            let mut idms_proxy_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
456            assert!(idms_proxy_write.qs_write.delete(&de).is_ok());
457            assert!(idms_proxy_write.qs_write.commit().is_ok());
458        }
459    }
460
461    #[idm_test]
462    async fn test_idm_application_delete(idms: &IdmServer, _idms_delayed: &mut IdmServerDelayed) {
463        let test_usr_name = "testuser1";
464        let test_usr_uuid = Uuid::new_v4();
465        let test_app_name = "testapp1";
466        let test_app_uuid = Uuid::new_v4();
467        let test_grp_name = "testgroup1";
468        let test_grp_uuid = Uuid::new_v4();
469
470        {
471            let ct = duration_from_epoch_now();
472            let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
473
474            let e1 = entry_init!(
475                (Attribute::Class, EntryClass::Object.to_value()),
476                (Attribute::Class, EntryClass::Account.to_value()),
477                (Attribute::Class, EntryClass::Person.to_value()),
478                (Attribute::Name, Value::new_iname(test_usr_name)),
479                (Attribute::Uuid, Value::Uuid(test_usr_uuid)),
480                (Attribute::Description, Value::new_utf8s(test_usr_name)),
481                (Attribute::DisplayName, Value::new_utf8s(test_usr_name))
482            );
483
484            let e2 = entry_init!(
485                (Attribute::Class, EntryClass::Object.to_value()),
486                (Attribute::Class, EntryClass::Group.to_value()),
487                (Attribute::Name, Value::new_iname(test_grp_name)),
488                (Attribute::Uuid, Value::Uuid(test_grp_uuid)),
489                (Attribute::Member, Value::ReferN(test_usr_uuid))
490            );
491
492            let e3 = entry_init!(
493                (Attribute::Class, EntryClass::Object.to_value()),
494                (Attribute::Class, EntryClass::Account.to_value()),
495                (Attribute::Class, EntryClass::ServiceAccount.to_value()),
496                (Attribute::Class, EntryClass::Application.to_value()),
497                (Attribute::DisplayName, Value::new_utf8s("Application")),
498                (Attribute::Name, Value::new_iname(test_app_name)),
499                (Attribute::Uuid, Value::Uuid(test_app_uuid)),
500                (Attribute::LinkedGroup, Value::Refer(test_grp_uuid))
501            );
502
503            let ce = CreateEvent::new_internal(vec![e1, e2, e3]);
504            let cr = idms_prox_write.qs_write.create(&ce);
505            assert!(cr.is_ok());
506
507            let ev = GenerateApplicationPasswordEvent {
508                ident: Identity::from_internal(),
509                target: test_usr_uuid,
510                application: test_app_uuid,
511                label: "label".to_string(),
512            };
513            idms_prox_write
514                .generate_application_password(&ev)
515                .expect("Failed to create application password");
516
517            let cr = idms_prox_write.qs_write.commit();
518            assert!(cr.is_ok());
519        }
520
521        {
522            let mut idms_prox_read = idms.proxy_read().await.unwrap();
523            let account = idms_prox_read
524                .qs_read
525                .internal_search_uuid(test_usr_uuid)
526                .and_then(|entry| Account::try_from_entry_ro(&entry, &mut idms_prox_read.qs_read))
527                .map_err(|e| {
528                    trace!("Error: {:?}", e);
529                    e
530                })
531                .expect("Failed to search for account");
532
533            assert!(account.apps_pwds.values().count() > 0);
534        }
535
536        // Test reference integrity. If app is removed linked application passwords must go
537        {
538            let de = DeleteEvent::new_internal_invalid(filter!(f_eq(
539                Attribute::Uuid,
540                PartialValue::Uuid(test_app_uuid)
541            )));
542            let mut idms_proxy_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
543            assert!(idms_proxy_write.qs_write.delete(&de).is_ok());
544            assert!(idms_proxy_write.qs_write.commit().is_ok());
545        }
546
547        {
548            let mut idms_prox_read = idms.proxy_read().await.unwrap();
549            assert!(idms_prox_read
550                .qs_read
551                .internal_search_uuid(test_app_uuid)
552                .is_err());
553        }
554
555        {
556            let mut idms_prox_read = idms.proxy_read().await.unwrap();
557            let account = idms_prox_read
558                .qs_read
559                .internal_search_uuid(test_usr_uuid)
560                .and_then(|entry| Account::try_from_entry_ro(&entry, &mut idms_prox_read.qs_read))
561                .map_err(|e| {
562                    trace!("Error: {:?}", e);
563                    e
564                })
565                .expect("Failed to search for account");
566
567            assert_eq!(account.apps_pwds.values().count(), 0);
568        }
569    }
570
571    // Test apitoken for application entries
572    #[idm_test]
573    async fn test_idm_application_api_token(
574        idms: &IdmServer,
575        _idms_delayed: &mut IdmServerDelayed,
576    ) {
577        let ct = Duration::from_secs(TEST_CURRENT_TIME);
578        let past_grc = Duration::from_secs(TEST_CURRENT_TIME + 1) + AUTH_TOKEN_GRACE_WINDOW;
579        let exp = Duration::from_secs(TEST_CURRENT_TIME + 6000);
580        let post_exp = Duration::from_secs(TEST_CURRENT_TIME + 6010);
581        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
582
583        let test_entry_uuid = Uuid::new_v4();
584        let test_group_uuid = Uuid::new_v4();
585
586        let e1 = entry_init!(
587            (Attribute::Class, EntryClass::Object.to_value()),
588            (Attribute::Class, EntryClass::Group.to_value()),
589            (Attribute::Name, Value::new_iname("test_group")),
590            (Attribute::Uuid, Value::Uuid(test_group_uuid))
591        );
592
593        let e2 = entry_init!(
594            (Attribute::Class, EntryClass::Object.to_value()),
595            (Attribute::Class, EntryClass::ServiceAccount.to_value()),
596            (Attribute::Class, EntryClass::Account.to_value()),
597            (Attribute::Class, EntryClass::Application.to_value()),
598            (Attribute::DisplayName, Value::new_utf8s("Application")),
599            (Attribute::Name, Value::new_iname("test_app_name")),
600            (Attribute::Uuid, Value::Uuid(test_entry_uuid)),
601            (Attribute::Description, Value::new_utf8s("test_app_desc")),
602            (Attribute::LinkedGroup, Value::Refer(test_group_uuid))
603        );
604
605        let ce = CreateEvent::new_internal(vec![e1, e2]);
606        let cr = idms_prox_write.qs_write.create(&ce);
607        assert!(cr.is_ok());
608
609        let gte = GenerateApiTokenEvent::new_internal(test_entry_uuid, "TestToken", Some(exp));
610
611        let api_token = idms_prox_write
612            .service_account_generate_api_token(&gte, ct)
613            .expect("failed to generate new api token");
614
615        trace!(?api_token);
616
617        // Deserialise it.
618        let jws_verifier = JwsDangerReleaseWithoutVerify::default();
619
620        let apitoken_inner = jws_verifier
621            .verify(&api_token)
622            .unwrap()
623            .from_json::<ProtoApiToken>()
624            .unwrap();
625
626        let ident = idms_prox_write
627            .validate_client_auth_info_to_ident(api_token.clone().into(), ct)
628            .expect("Unable to verify api token.");
629
630        assert_eq!(ident.get_uuid(), test_entry_uuid);
631
632        // Check the expiry
633        assert!(
634            idms_prox_write
635                .validate_client_auth_info_to_ident(api_token.clone().into(), post_exp)
636                .expect_err("Should not succeed")
637                == OperationError::SessionExpired
638        );
639
640        // Delete session
641        let dte =
642            DestroyApiTokenEvent::new_internal(apitoken_inner.account_id, apitoken_inner.token_id);
643        assert!(idms_prox_write
644            .service_account_destroy_api_token(&dte)
645            .is_ok());
646
647        // Within gracewindow?
648        // This is okay, because we are within the gracewindow.
649        let ident = idms_prox_write
650            .validate_client_auth_info_to_ident(api_token.clone().into(), ct)
651            .expect("Unable to verify api token.");
652        assert_eq!(ident.get_uuid(), test_entry_uuid);
653
654        // Past gracewindow?
655        assert!(
656            idms_prox_write
657                .validate_client_auth_info_to_ident(api_token.clone().into(), past_grc)
658                .expect_err("Should not succeed")
659                == OperationError::SessionExpired
660        );
661
662        assert!(idms_prox_write.commit().is_ok());
663    }
664}