1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
use super::ldap::{LdapBoundToken, LdapSession};
use crate::idm::account::Account;
use crate::idm::event::LdapApplicationAuthEvent;
use crate::idm::server::{IdmServerAuthTransaction, IdmServerTransaction};
use crate::prelude::*;
use concread::cowcell::*;
use hashbrown::HashMap;
use kanidm_proto::internal::OperationError;
use std::sync::Arc;
use uuid::Uuid;

#[derive(Clone)]
pub(crate) struct Application {
    pub uuid: Uuid,
    pub name: String,
    pub linked_group: Uuid,
}

impl Application {
    #[cfg(test)]
    pub(crate) fn try_from_entry_ro(
        value: &Entry<EntrySealed, EntryCommitted>,
        _qs: &mut QueryServerReadTransaction,
    ) -> Result<Self, OperationError> {
        if !value.attribute_equality(Attribute::Class, &EntryClass::Application.to_partialvalue()) {
            return Err(OperationError::MissingClass(ENTRYCLASS_APPLICATION.into()));
        }

        let uuid = value.get_uuid();

        let name = value
            .get_ava_single_iname(Attribute::Name)
            .map(|s| s.to_string())
            .ok_or_else(|| OperationError::MissingAttribute(Attribute::Name))?;

        let linked_group = value
            .get_ava_single_refer(Attribute::LinkedGroup)
            .ok_or_else(|| OperationError::MissingAttribute(Attribute::LinkedGroup))?;

        Ok(Application {
            name,
            uuid,
            linked_group,
        })
    }
}

#[derive(Clone)]
struct LdapApplicationsInner {
    set: HashMap<String, Application>,
}

pub struct LdapApplications {
    inner: CowCell<LdapApplicationsInner>,
}

pub struct LdapApplicationsReadTransaction {
    inner: CowCellReadTxn<LdapApplicationsInner>,
}

pub struct LdapApplicationsWriteTransaction<'a> {
    inner: CowCellWriteTxn<'a, LdapApplicationsInner>,
}

impl<'a> LdapApplicationsWriteTransaction<'a> {
    pub fn reload(&mut self, value: Vec<Arc<EntrySealedCommitted>>) -> Result<(), OperationError> {
        let app_set: Result<HashMap<_, _>, _> = value
            .into_iter()
            .map(|ent| {
                if !ent.attribute_equality(Attribute::Class, &EntryClass::Application.into()) {
                    error!("Missing class application");
                    return Err(OperationError::InvalidEntryState);
                }

                let uuid = ent.get_uuid();
                let name = ent
                    .get_ava_single_iname(Attribute::Name)
                    .map(str::to_string)
                    .ok_or(OperationError::InvalidValueState)?;

                let linked_group = ent
                    .get_ava_single_refer(Attribute::LinkedGroup)
                    .ok_or(OperationError::InvalidValueState)?;

                let app = Application {
                    uuid,
                    name: name.clone(),
                    linked_group,
                };

                Ok((name, app))
            })
            .collect();

        let new_inner = LdapApplicationsInner { set: app_set? };
        self.inner.replace(new_inner);

        Ok(())
    }

    pub fn commit(self) {
        self.inner.commit();
    }
}

impl LdapApplications {
    pub fn read(&self) -> LdapApplicationsReadTransaction {
        LdapApplicationsReadTransaction {
            inner: self.inner.read(),
        }
    }

    pub fn write(&self) -> LdapApplicationsWriteTransaction {
        LdapApplicationsWriteTransaction {
            inner: self.inner.write(),
        }
    }
}

impl TryFrom<Vec<Arc<EntrySealedCommitted>>> for LdapApplications {
    type Error = OperationError;

    fn try_from(value: Vec<Arc<EntrySealedCommitted>>) -> Result<Self, Self::Error> {
        let apps = LdapApplications {
            inner: CowCell::new(LdapApplicationsInner {
                set: HashMap::new(),
            }),
        };

        let mut apps_wr = apps.write();
        apps_wr.reload(value)?;
        apps_wr.commit();
        Ok(apps)
    }
}

impl<'a> IdmServerAuthTransaction<'a> {
    pub async fn application_auth_ldap(
        &mut self,
        lae: &LdapApplicationAuthEvent,
        ct: Duration,
    ) -> Result<Option<LdapBoundToken>, OperationError> {
        let usr_entry = self.get_qs_txn().internal_search_uuid(lae.target)?;

        let account: Account =
            Account::try_from_entry_ro(&usr_entry, &mut self.qs_read).map_err(|e| {
                error!("Failed to search account {:?}", e);
                e
            })?;

        if account.is_anonymous() {
            return Err(OperationError::InvalidUuid);
        }

        if !account.is_within_valid_time(ct) {
            security_info!("Account has expired or is not yet valid, not allowing to proceed");
            return Err(OperationError::SessionExpired);
        }

        let application = self
            .applications
            .inner
            .set
            .get(&lae.application)
            .ok_or_else(|| {
                info!("Application {:?} not found", lae.application);
                OperationError::NoMatchingEntries
            })?;

        // Check linked group membership
        let is_memberof = usr_entry
            .get_ava_refer(Attribute::MemberOf)
            .map(|member_of_set| member_of_set.contains(&application.linked_group))
            .unwrap_or_default();

        if !is_memberof {
            debug!(
                "User {:?} not member of application {}:{:?} linked group {:?}",
                account.uuid, application.name, application.uuid, application.linked_group,
            );
            return Ok(None);
        }

        match account.verify_application_password(application, lae.cleartext.as_str())? {
            Some(_) => {
                let session_id = Uuid::new_v4();
                security_info!(
                    "Starting session {} for {} {} with application {}:{:?}",
                    session_id,
                    account.spn,
                    account.uuid,
                    application.name,
                    application.uuid,
                );

                Ok(Some(LdapBoundToken {
                    spn: account.spn,
                    session_id,
                    effective_session: LdapSession::UnixBind(account.uuid),
                }))
            }
            None => {
                security_info!("Account does not have a configured application password.");
                Ok(None)
            }
        }
    }
}

#[derive(Debug)]
pub struct GenerateApplicationPasswordEvent {
    pub ident: Identity,
    pub target: Uuid,
    pub application: Uuid,
    pub label: String,
}

impl GenerateApplicationPasswordEvent {
    pub fn from_parts(
        ident: Identity,
        target: Uuid,
        application: Uuid,
        label: String,
    ) -> Result<Self, OperationError> {
        Ok(GenerateApplicationPasswordEvent {
            ident,
            target,
            application,
            label,
        })
    }

    pub fn new_internal(target: Uuid, application: Uuid, label: String) -> Self {
        GenerateApplicationPasswordEvent {
            ident: Identity::from_internal(),
            target,
            application,
            label,
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::event::CreateEvent;
    use crate::idm::account::Account;
    use crate::idm::application::Application;
    use crate::idm::application::GenerateApplicationPasswordEvent;
    use crate::idm::server::IdmServerTransaction;
    use crate::idm::serviceaccount::{DestroyApiTokenEvent, GenerateApiTokenEvent};
    use crate::prelude::*;
    use compact_jwt::{dangernoverify::JwsDangerReleaseWithoutVerify, JwsVerifier};
    use kanidm_proto::internal::ApiToken as ProtoApiToken;
    use std::time::Duration;

    const TEST_CURRENT_TIME: u64 = 6000;

    // Tests that only the correct combinations of [Account, Person, Application and
    // ServiceAccount] classes are allowed.
    #[idm_test]
    async fn test_idm_application_excludes(idms: &IdmServer, _idms_delayed: &mut IdmServerDelayed) {
        let ct = Duration::from_secs(TEST_CURRENT_TIME);
        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();

        // ServiceAccount, Application and Person not allowed together
        let test_grp_name = "testgroup1";
        let test_grp_uuid = Uuid::new_v4();
        let e1 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Group.to_value()),
            (Attribute::Name, Value::new_iname(test_grp_name)),
            (Attribute::Uuid, Value::Uuid(test_grp_uuid))
        );
        let test_entry_uuid = Uuid::new_v4();
        let e2 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Account.to_value()),
            (Attribute::Class, EntryClass::ServiceAccount.to_value()),
            (Attribute::Class, EntryClass::Application.to_value()),
            (Attribute::Class, EntryClass::Person.to_value()),
            (Attribute::Name, Value::new_iname("test_app_name")),
            (Attribute::Uuid, Value::Uuid(test_entry_uuid)),
            (Attribute::Description, Value::new_utf8s("test_app_desc")),
            (
                Attribute::DisplayName,
                Value::new_utf8s("test_app_dispname")
            ),
            (Attribute::LinkedGroup, Value::Refer(test_grp_uuid))
        );
        let ce = CreateEvent::new_internal(vec![e1, e2]);
        let cr = idms_prox_write.qs_write.create(&ce);
        assert!(cr.is_err());

        // Application and Person not allowed together
        let test_grp_name = "testgroup1";
        let test_grp_uuid = Uuid::new_v4();
        let e1 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Group.to_value()),
            (Attribute::Name, Value::new_iname(test_grp_name)),
            (Attribute::Uuid, Value::Uuid(test_grp_uuid))
        );
        let test_entry_uuid = Uuid::new_v4();
        let e2 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Account.to_value()),
            (Attribute::Class, EntryClass::Application.to_value()),
            (Attribute::Class, EntryClass::Person.to_value()),
            (Attribute::Name, Value::new_iname("test_app_name")),
            (Attribute::Uuid, Value::Uuid(test_entry_uuid)),
            (Attribute::Description, Value::new_utf8s("test_app_desc")),
            (
                Attribute::DisplayName,
                Value::new_utf8s("test_app_dispname")
            ),
            (Attribute::LinkedGroup, Value::Refer(test_grp_uuid))
        );
        let ce = CreateEvent::new_internal(vec![e1, e2]);
        let cr = idms_prox_write.qs_write.create(&ce);
        assert!(cr.is_err());

        // Supplements not satisfied, Application supplements ServiceAccount
        let test_grp_name = "testgroup1";
        let test_grp_uuid = Uuid::new_v4();
        let e1 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Group.to_value()),
            (Attribute::Name, Value::new_iname(test_grp_name)),
            (Attribute::Uuid, Value::Uuid(test_grp_uuid))
        );
        let test_entry_uuid = Uuid::new_v4();
        let e2 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Account.to_value()),
            (Attribute::Class, EntryClass::Application.to_value()),
            (Attribute::Name, Value::new_iname("test_app_name")),
            (Attribute::Uuid, Value::Uuid(test_entry_uuid)),
            (Attribute::Description, Value::new_utf8s("test_app_desc")),
            (Attribute::LinkedGroup, Value::Refer(test_grp_uuid))
        );
        let ce = CreateEvent::new_internal(vec![e1, e2]);
        let cr = idms_prox_write.qs_write.create(&ce);
        assert!(cr.is_err());

        // Supplements not satisfied, Application supplements ServiceAccount
        let test_grp_name = "testgroup1";
        let test_grp_uuid = Uuid::new_v4();
        let e1 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Group.to_value()),
            (Attribute::Name, Value::new_iname(test_grp_name)),
            (Attribute::Uuid, Value::Uuid(test_grp_uuid))
        );
        let test_entry_uuid = Uuid::new_v4();
        let e2 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Application.to_value()),
            (Attribute::Name, Value::new_iname("test_app_name")),
            (Attribute::Uuid, Value::Uuid(test_entry_uuid)),
            (Attribute::Description, Value::new_utf8s("test_app_desc")),
            (Attribute::LinkedGroup, Value::Refer(test_grp_uuid))
        );
        let ce = CreateEvent::new_internal(vec![e1, e2]);
        let cr = idms_prox_write.qs_write.create(&ce);
        assert!(cr.is_err());

        // Supplements satisfied, Application supplements ServiceAccount
        let test_grp_name = "testgroup1";
        let test_grp_uuid = Uuid::new_v4();
        let e1 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Group.to_value()),
            (Attribute::Name, Value::new_iname(test_grp_name)),
            (Attribute::Uuid, Value::Uuid(test_grp_uuid))
        );
        let test_entry_uuid = Uuid::new_v4();
        let e2 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Application.to_value()),
            (Attribute::Class, EntryClass::ServiceAccount.to_value()),
            (Attribute::Name, Value::new_iname("test_app_name")),
            (Attribute::Uuid, Value::Uuid(test_entry_uuid)),
            (Attribute::Description, Value::new_utf8s("test_app_desc")),
            (Attribute::LinkedGroup, Value::Refer(test_grp_uuid))
        );
        let ce = CreateEvent::new_internal(vec![e1, e2]);
        let cr = idms_prox_write.qs_write.create(&ce);
        assert!(cr.is_ok());
    }

    // Tests it is not possible to create an applicatin without the linked group attribute
    #[idm_test]
    async fn test_idm_application_no_linked_group(
        idms: &IdmServer,
        _idms_delayed: &mut IdmServerDelayed,
    ) {
        let ct = Duration::from_secs(TEST_CURRENT_TIME);
        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();

        let test_entry_uuid = Uuid::new_v4();

        let e1 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Account.to_value()),
            (Attribute::Class, EntryClass::ServiceAccount.to_value()),
            (Attribute::Class, EntryClass::Application.to_value()),
            (Attribute::Name, Value::new_iname("test_app_name")),
            (Attribute::Uuid, Value::Uuid(test_entry_uuid)),
            (Attribute::Description, Value::new_utf8s("test_app_desc")),
            (
                Attribute::DisplayName,
                Value::new_utf8s("test_app_dispname")
            )
        );

        let ce = CreateEvent::new_internal(vec![e1]);
        let cr = idms_prox_write.qs_write.create(&ce);
        assert!(cr.is_err());
    }

    // Tests creating an applicatin with a real linked group attribute
    #[idm_test]
    async fn test_idm_application_linked_group(
        idms: &IdmServer,
        _idms_delayed: &mut IdmServerDelayed,
    ) {
        let test_entry_name = "test_app_name";
        let test_entry_uuid = Uuid::new_v4();
        let test_grp_name = "testgroup1";
        let test_grp_uuid = Uuid::new_v4();

        {
            let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();

            let e1 = entry_init!(
                (Attribute::Class, EntryClass::Object.to_value()),
                (Attribute::Class, EntryClass::Group.to_value()),
                (Attribute::Name, Value::new_iname(test_grp_name)),
                (Attribute::Uuid, Value::Uuid(test_grp_uuid))
            );

            let e2 = entry_init!(
                (Attribute::Class, EntryClass::Object.to_value()),
                (Attribute::Class, EntryClass::Account.to_value()),
                (Attribute::Class, EntryClass::ServiceAccount.to_value()),
                (Attribute::Class, EntryClass::Application.to_value()),
                (Attribute::Name, Value::new_iname(test_entry_name)),
                (Attribute::Uuid, Value::Uuid(test_entry_uuid)),
                (Attribute::Description, Value::new_utf8s("test_app_desc")),
                (
                    Attribute::DisplayName,
                    Value::new_utf8s("test_app_dispname")
                ),
                (Attribute::LinkedGroup, Value::Refer(test_grp_uuid))
            );

            let ce = CreateEvent::new_internal(vec![e1, e2]);
            let cr = idms_prox_write.qs_write.create(&ce);
            assert!(cr.is_ok());

            let cr = idms_prox_write.qs_write.commit();
            assert!(cr.is_ok());
        }

        {
            let mut idms_prox_read = idms.proxy_read().await.unwrap();
            let app = idms_prox_read
                .qs_read
                .internal_search_uuid(test_entry_uuid)
                .and_then(|entry| {
                    Application::try_from_entry_ro(&entry, &mut idms_prox_read.qs_read)
                })
                .map_err(|e| {
                    trace!("Error: {:?}", e);
                    e
                });
            assert!(app.is_ok());

            let app = app.unwrap();
            assert_eq!(app.name, "test_app_name");
            assert_eq!(app.uuid, test_entry_uuid);
            assert_eq!(app.linked_group, test_grp_uuid);
        }

        // Test reference integrity. An attempt to remove a linked group blocks
        // the group being deleted
        {
            let de = DeleteEvent::new_internal_invalid(filter!(f_eq(
                Attribute::Uuid,
                PartialValue::Uuid(test_grp_uuid)
            )));
            let mut idms_proxy_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
            assert!(idms_proxy_write.qs_write.delete(&de).is_err());
        }

        {
            let de = DeleteEvent::new_internal_invalid(filter!(f_eq(
                Attribute::Uuid,
                PartialValue::Uuid(test_entry_uuid)
            )));
            let mut idms_proxy_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
            assert!(idms_proxy_write.qs_write.delete(&de).is_ok());
            assert!(idms_proxy_write.qs_write.commit().is_ok());
        }

        {
            let de = DeleteEvent::new_internal_invalid(filter!(f_eq(
                Attribute::Uuid,
                PartialValue::Uuid(test_grp_uuid)
            )));
            let mut idms_proxy_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
            assert!(idms_proxy_write.qs_write.delete(&de).is_ok());
            assert!(idms_proxy_write.qs_write.commit().is_ok());
        }
    }

    #[idm_test]
    async fn test_idm_application_delete(idms: &IdmServer, _idms_delayed: &mut IdmServerDelayed) {
        let test_usr_name = "testuser1";
        let test_usr_uuid = Uuid::new_v4();
        let test_app_name = "testapp1";
        let test_app_uuid = Uuid::new_v4();
        let test_grp_name = "testgroup1";
        let test_grp_uuid = Uuid::new_v4();

        {
            let ct = duration_from_epoch_now();
            let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();

            let e1 = entry_init!(
                (Attribute::Class, EntryClass::Object.to_value()),
                (Attribute::Class, EntryClass::Account.to_value()),
                (Attribute::Class, EntryClass::Person.to_value()),
                (Attribute::Name, Value::new_iname(test_usr_name)),
                (Attribute::Uuid, Value::Uuid(test_usr_uuid)),
                (Attribute::Description, Value::new_utf8s(test_usr_name)),
                (Attribute::DisplayName, Value::new_utf8s(test_usr_name))
            );

            let e2 = entry_init!(
                (Attribute::Class, EntryClass::Object.to_value()),
                (Attribute::Class, EntryClass::Group.to_value()),
                (Attribute::Name, Value::new_iname(test_grp_name)),
                (Attribute::Uuid, Value::Uuid(test_grp_uuid)),
                (Attribute::Member, Value::Refer(test_usr_uuid))
            );

            let e3 = entry_init!(
                (Attribute::Class, EntryClass::Object.to_value()),
                (Attribute::Class, EntryClass::ServiceAccount.to_value()),
                (Attribute::Class, EntryClass::Application.to_value()),
                (Attribute::Name, Value::new_iname(test_app_name)),
                (Attribute::Uuid, Value::Uuid(test_app_uuid)),
                (Attribute::LinkedGroup, Value::Refer(test_grp_uuid))
            );

            let ce = CreateEvent::new_internal(vec![e1, e2, e3]);
            let cr = idms_prox_write.qs_write.create(&ce);
            assert!(cr.is_ok());

            let ev = GenerateApplicationPasswordEvent {
                ident: Identity::from_internal(),
                target: test_usr_uuid,
                application: test_app_uuid,
                label: "label".to_string(),
            };
            idms_prox_write
                .generate_application_password(&ev)
                .expect("Failed to create application password");

            let cr = idms_prox_write.qs_write.commit();
            assert!(cr.is_ok());
        }

        {
            let mut idms_prox_read = idms.proxy_read().await.unwrap();
            let account = idms_prox_read
                .qs_read
                .internal_search_uuid(test_usr_uuid)
                .and_then(|entry| Account::try_from_entry_ro(&entry, &mut idms_prox_read.qs_read))
                .map_err(|e| {
                    trace!("Error: {:?}", e);
                    e
                })
                .expect("Failed to search for account");

            assert!(account.apps_pwds.values().count() > 0);
        }

        // Test reference integrity. If app is removed linked application passwords must go
        {
            let de = DeleteEvent::new_internal_invalid(filter!(f_eq(
                Attribute::Uuid,
                PartialValue::Uuid(test_app_uuid)
            )));
            let mut idms_proxy_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
            assert!(idms_proxy_write.qs_write.delete(&de).is_ok());
            assert!(idms_proxy_write.qs_write.commit().is_ok());
        }

        {
            let mut idms_prox_read = idms.proxy_read().await.unwrap();
            assert!(idms_prox_read
                .qs_read
                .internal_search_uuid(test_app_uuid)
                .is_err());
        }

        {
            let mut idms_prox_read = idms.proxy_read().await.unwrap();
            let account = idms_prox_read
                .qs_read
                .internal_search_uuid(test_usr_uuid)
                .and_then(|entry| Account::try_from_entry_ro(&entry, &mut idms_prox_read.qs_read))
                .map_err(|e| {
                    trace!("Error: {:?}", e);
                    e
                })
                .expect("Failed to search for account");

            assert_eq!(account.apps_pwds.values().count(), 0);
        }
    }

    // Test apitoken for application entries
    #[idm_test]
    async fn test_idm_application_api_token(
        idms: &IdmServer,
        _idms_delayed: &mut IdmServerDelayed,
    ) {
        let ct = Duration::from_secs(TEST_CURRENT_TIME);
        let past_grc = Duration::from_secs(TEST_CURRENT_TIME + 1) + AUTH_TOKEN_GRACE_WINDOW;
        let exp = Duration::from_secs(TEST_CURRENT_TIME + 6000);
        let post_exp = Duration::from_secs(TEST_CURRENT_TIME + 6010);
        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();

        let test_entry_uuid = Uuid::new_v4();
        let test_group_uuid = Uuid::new_v4();

        let e1 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Group.to_value()),
            (Attribute::Name, Value::new_iname("test_group")),
            (Attribute::Uuid, Value::Uuid(test_group_uuid))
        );

        let e2 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::ServiceAccount.to_value()),
            (Attribute::Class, EntryClass::Application.to_value()),
            (Attribute::Name, Value::new_iname("test_app_name")),
            (Attribute::Uuid, Value::Uuid(test_entry_uuid)),
            (Attribute::Description, Value::new_utf8s("test_app_desc")),
            (Attribute::LinkedGroup, Value::Refer(test_group_uuid))
        );

        let ce = CreateEvent::new_internal(vec![e1, e2]);
        let cr = idms_prox_write.qs_write.create(&ce);
        assert!(cr.is_ok());

        let gte = GenerateApiTokenEvent::new_internal(test_entry_uuid, "TestToken", Some(exp));

        let api_token = idms_prox_write
            .service_account_generate_api_token(&gte, ct)
            .expect("failed to generate new api token");

        trace!(?api_token);

        // Deserialise it.
        let jws_verifier = JwsDangerReleaseWithoutVerify::default();

        let apitoken_inner = jws_verifier
            .verify(&api_token)
            .unwrap()
            .from_json::<ProtoApiToken>()
            .unwrap();

        let ident = idms_prox_write
            .validate_client_auth_info_to_ident(api_token.clone().into(), ct)
            .expect("Unable to verify api token.");

        assert_eq!(ident.get_uuid(), Some(test_entry_uuid));

        // Check the expiry
        assert!(
            idms_prox_write
                .validate_client_auth_info_to_ident(api_token.clone().into(), post_exp)
                .expect_err("Should not succeed")
                == OperationError::SessionExpired
        );

        // Delete session
        let dte =
            DestroyApiTokenEvent::new_internal(apitoken_inner.account_id, apitoken_inner.token_id);
        assert!(idms_prox_write
            .service_account_destroy_api_token(&dte)
            .is_ok());

        // Within gracewindow?
        // This is okay, because we are within the gracewindow.
        let ident = idms_prox_write
            .validate_client_auth_info_to_ident(api_token.clone().into(), ct)
            .expect("Unable to verify api token.");
        assert_eq!(ident.get_uuid(), Some(test_entry_uuid));

        // Past gracewindow?
        assert!(
            idms_prox_write
                .validate_client_auth_info_to_ident(api_token.clone().into(), past_grc)
                .expect_err("Should not succeed")
                == OperationError::SessionExpired
        );

        assert!(idms_prox_write.commit().is_ok());
    }
}