kanidm 1.1.0-alpha

Kanidm Server Library and Binary
Documentation
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
use crate::audit::AuditScope;
use crate::constants::{AUTH_SESSION_TIMEOUT, MFAREG_SESSION_TIMEOUT, PW_MIN_LENGTH};
use crate::constants::{UUID_ANONYMOUS, UUID_SYSTEM_CONFIG};
use crate::event::{AuthEvent, AuthEventStep, AuthResult};
use crate::idm::account::Account;
use crate::idm::authsession::AuthSession;
use crate::idm::event::{
    GeneratePasswordEvent, GenerateTOTPEvent, LdapAuthEvent, PasswordChangeEvent,
    RadiusAuthTokenEvent, RegenerateRadiusSecretEvent, UnixGroupTokenEvent,
    UnixPasswordChangeEvent, UnixUserAuthEvent, UnixUserTokenEvent, VerifyTOTPEvent,
};
use crate::idm::mfareg::{MfaRegCred, MfaRegNext, MfaRegSession, MfaReqInit, MfaReqStep};
use crate::idm::radius::RadiusAccount;
use crate::idm::unix::{UnixGroup, UnixUserAccount};
use crate::ldap::LdapBoundToken;
use crate::server::QueryServerReadTransaction;
use crate::server::{QueryServer, QueryServerTransaction, QueryServerWriteTransaction};
use crate::utils::{password_from_random, readable_password_from_random, uuid_from_duration, SID};
use crate::value::PartialValue;

use kanidm_proto::v1::AuthState;
use kanidm_proto::v1::OperationError;
use kanidm_proto::v1::RadiusAuthToken;
// use kanidm_proto::v1::TOTPSecret as ProtoTOTPSecret;
use kanidm_proto::v1::SetCredentialResponse;
use kanidm_proto::v1::UnixGroupToken;
use kanidm_proto::v1::UnixUserToken;

use concread::collections::bptree::*;
use rand::prelude::*;
use std::time::Duration;
use uuid::Uuid;

pub struct IdmServer {
    // There is a good reason to keep this single thread - it
    // means that limits to sessions can be easily applied and checked to
    // variaous accounts, and we have a good idea of how to structure the
    // in memory caches related to locking.
    sessions: BptreeMap<Uuid, AuthSession>,
    // Keep a set of inprogress mfa registrations
    mfareg_sessions: BptreeMap<Uuid, MfaRegSession>,
    // Need a reference to the query server.
    qs: QueryServer,
}

pub struct IdmServerWriteTransaction<'a> {
    // Contains methods that require writes, but in the context of writing to
    // the idm in memory structures (maybe the query server too). This is
    // things like authentication
    sessions: BptreeMapWriteTxn<'a, Uuid, AuthSession>,
    pub qs_read: QueryServerReadTransaction<'a>,
    // thread/server id
    sid: SID,
}

pub struct IdmServerProxyReadTransaction<'a> {
    // This contains read-only methods, like getting users, groups
    // and other structured content.
    pub qs_read: QueryServerReadTransaction<'a>,
}

pub struct IdmServerProxyWriteTransaction<'a> {
    // This does NOT take any read to the memory content, allowing safe
    // qs operations to occur through this interface.
    pub qs_write: QueryServerWriteTransaction<'a>,
    // Associate to an event origin ID, which has a TS and a UUID instead
    mfareg_sessions: BptreeMapWriteTxn<'a, Uuid, MfaRegSession>,
    sid: SID,
}

impl IdmServer {
    // TODO #59: Make number of authsessions configurable!!!
    pub fn new(qs: QueryServer) -> IdmServer {
        IdmServer {
            sessions: BptreeMap::new(),
            mfareg_sessions: BptreeMap::new(),
            qs,
        }
    }

    pub fn write(&self) -> IdmServerWriteTransaction {
        let mut sid = [0; 4];
        let mut rng = StdRng::from_entropy();
        rng.fill(&mut sid);

        IdmServerWriteTransaction {
            sessions: self.sessions.write(),
            // qs: &self.qs,
            qs_read: self.qs.read(),
            sid,
        }
    }

    pub fn proxy_read(&self) -> IdmServerProxyReadTransaction {
        IdmServerProxyReadTransaction {
            qs_read: self.qs.read(),
        }
    }

    pub fn proxy_write(&self, ts: Duration) -> IdmServerProxyWriteTransaction {
        let mut sid = [0; 4];
        let mut rng = StdRng::from_entropy();
        rng.fill(&mut sid);

        IdmServerProxyWriteTransaction {
            mfareg_sessions: self.mfareg_sessions.write(),
            qs_write: self.qs.write(ts),
            sid,
        }
    }
}

impl<'a> IdmServerWriteTransaction<'a> {
    #[cfg(test)]
    pub fn is_sessionid_present(&self, sessionid: &Uuid) -> bool {
        self.sessions.contains_key(sessionid)
    }

    pub fn expire_auth_sessions(&mut self, ct: Duration) {
        // ct is current time - sub the timeout. and then split.
        let expire = ct - Duration::from_secs(AUTH_SESSION_TIMEOUT);
        let split_at = uuid_from_duration(expire, self.sid);
        // Removes older sessions in place.
        self.sessions.split_off_lt(&split_at);
        // expired will now be dropped, and can't be used by future sessions.
    }

    pub fn auth(
        &mut self,
        au: &mut AuditScope,
        ae: &AuthEvent,
        ct: Duration,
    ) -> Result<AuthResult, OperationError> {
        ltrace!(au, "Received -> {:?}", ae);

        // Match on the auth event, to see what we need to do.

        match &ae.step {
            AuthEventStep::Init(init) => {
                lperf_segment!(au, "idm::server::auth<Init>", || {
                    // Allocate a session id, based on current time.
                    let sessionid = uuid_from_duration(ct, self.sid);

                    // Begin the auth procedure!
                    // Start a read
                    //
                    // Actually we may not need this - at the time we issue the auth-init
                    // we could generate the uat, the nonce and cache hashes in memory,
                    // then this can just be fully without a txn.
                    //
                    // We do need a txn so that we can process/search and claims
                    // or related based on the quality of the provided auth steps
                    //
                    // We *DO NOT* need a write though, because I think that lock outs
                    // and rate limits are *per server* and *in memory* only.
                    //
                    // Check anything needed? Get the current auth-session-id from request
                    // because it associates to the nonce's etc which were all cached.
                    let euuid = self.qs_read.name_to_uuid(au, init.name.as_str())?;

                    // Get the first / single entry we expect here ....
                    let entry = self.qs_read.internal_search_uuid(au, &euuid)?;

                    lsecurity!(
                        au,
                        "Initiating Authentication Session for ... {:?}: {:?}",
                        euuid,
                        entry
                    );

                    // Now, convert the Entry to an account - this gives us some stronger
                    // typing and functionality so we can assess what auth types can
                    // continue, and helps to keep non-needed entry specific data
                    // out of the LRU.
                    let account = Account::try_from_entry_ro(au, entry, &mut self.qs_read)?;
                    let auth_session = AuthSession::new(au, account, init.appid.clone());

                    // Get the set of mechanisms that can proceed. This is tied
                    // to the session so that it can mutate state and have progression
                    // of what's next, or ordering.
                    let next_mech = auth_session.valid_auth_mechs();

                    // If we have a session of the same id, return an error (despite how
                    // unlikely this is ...
                    lperf_segment!(au, "idm::server::auth<Init> -> sessions", || {
                        if self.sessions.contains_key(&sessionid) {
                            Err(OperationError::InvalidSessionState)
                        } else {
                            self.sessions.insert(sessionid, auth_session);
                            // Debugging: ensure we really inserted ...
                            debug_assert!(self.sessions.get(&sessionid).is_some());
                            Ok(())
                        }
                    })?;

                    Ok(AuthResult {
                        sessionid,
                        state: AuthState::Continue(next_mech),
                    })
                })
            }
            AuthEventStep::Creds(creds) => {
                lperf_segment!(au, "idm::server::auth<Creds>", || {
                    // Do we have a session?
                    let auth_session = self
                        .sessions
                        // Why is the session missing?
                        .get_mut(&creds.sessionid)
                        .ok_or_else(|| {
                            ladmin_error!(au, "Invalid Session State (no present session uuid)");
                            OperationError::InvalidSessionState
                        })?;
                    // Process the credentials here as required.
                    // Basically throw them at the auth_session and see what
                    // falls out.
                    auth_session
                        .validate_creds(au, &creds.creds, &ct)
                        .map(|aus| {
                            AuthResult {
                                // Is this right?
                                sessionid: creds.sessionid,
                                state: aus,
                            }
                        })
                })
            }
        }
    }

    pub fn auth_unix(
        &mut self,
        au: &mut AuditScope,
        uae: &UnixUserAuthEvent,
        _ct: Duration,
    ) -> Result<Option<UnixUserToken>, OperationError> {
        // TODO #59: Implement soft lock checking for unix creds here!

        // Get the entry/target we are working on.
        let account = self
            .qs_read
            .internal_search_uuid(au, &uae.target)
            .and_then(|account_entry| {
                UnixUserAccount::try_from_entry_ro(au, account_entry, &mut self.qs_read)
            })
            .map_err(|e| {
                ladmin_error!(au, "Failed to start auth unix -> {:?}", e);
                e
            })?;

        // Validate the unix_pw - this checks the account/cred lock states.
        account.verify_unix_credential(au, uae.cleartext.as_str())
    }

    pub fn auth_ldap(
        &mut self,
        au: &mut AuditScope,
        lae: LdapAuthEvent,
        _ct: Duration,
    ) -> Result<Option<LdapBoundToken>, OperationError> {
        // TODO #59: Implement soft lock checking for unix creds here!

        let account_entry = self
            .qs_read
            .internal_search_uuid(au, &lae.target)
            .map_err(|e| {
                ladmin_error!(au, "Failed to start auth ldap -> {:?}", e);
                e
            })?;
        /* !!! This would probably be better if we DIDN'T use the Unix/Account types ... ? */

        // if anonymous
        if lae.target == *UUID_ANONYMOUS {
            // TODO: #59 We should have checked if anonymous was locked by now!
            let account = Account::try_from_entry_ro(au, account_entry, &mut self.qs_read)?;
            Ok(Some(LdapBoundToken {
                spn: account.spn,
                uuid: *UUID_ANONYMOUS,
                effective_uuid: *UUID_ANONYMOUS,
            }))
        } else {
            let account = UnixUserAccount::try_from_entry_ro(au, account_entry, &mut self.qs_read)?;
            if account
                .verify_unix_credential(au, lae.cleartext.as_str())?
                .is_some()
            {
                Ok(Some(LdapBoundToken {
                    spn: account.spn,
                    uuid: account.uuid,
                    effective_uuid: *UUID_ANONYMOUS,
                }))
            } else {
                Ok(None)
            }
        }
    }

    pub fn commit(self, au: &mut AuditScope) -> Result<(), OperationError> {
        lperf_trace_segment!(au, "idm::server::IdmServerWriteTransaction::commit", || {
            self.sessions.commit();
            Ok(())
        })
    }
}

impl<'a> IdmServerProxyReadTransaction<'a> {
    pub fn get_radiusauthtoken(
        &mut self,
        au: &mut AuditScope,
        rate: &RadiusAuthTokenEvent,
    ) -> Result<RadiusAuthToken, OperationError> {
        let account = self
            .qs_read
            .impersonate_search_ext_uuid(au, &rate.target, &rate.event)
            .and_then(|account_entry| {
                RadiusAccount::try_from_entry_reduced(au, account_entry, &mut self.qs_read)
            })
            .map_err(|e| {
                ladmin_error!(au, "Failed to start radius auth token {:?}", e);
                e
            })?;

        account.to_radiusauthtoken()
    }

    pub fn get_unixusertoken(
        &mut self,
        au: &mut AuditScope,
        uute: &UnixUserTokenEvent,
    ) -> Result<UnixUserToken, OperationError> {
        let account = self
            .qs_read
            .impersonate_search_ext_uuid(au, &uute.target, &uute.event)
            .and_then(|account_entry| {
                UnixUserAccount::try_from_entry_reduced(au, account_entry, &mut self.qs_read)
            })
            .map_err(|e| {
                ladmin_error!(au, "Failed to start unix user token -> {:?}", e);
                e
            })?;

        account.to_unixusertoken()
    }

    pub fn get_unixgrouptoken(
        &mut self,
        au: &mut AuditScope,
        uute: &UnixGroupTokenEvent,
    ) -> Result<UnixGroupToken, OperationError> {
        let group = self
            .qs_read
            .impersonate_search_ext_uuid(au, &uute.target, &uute.event)
            .and_then(UnixGroup::try_from_entry_reduced)
            .map_err(|e| {
                ladmin_error!(au, "Failed to start unix group token {:?}", e);
                e
            })?;
        group.to_unixgrouptoken()
    }
}

impl<'a> IdmServerProxyWriteTransaction<'a> {
    pub fn expire_mfareg_sessions(&mut self, ct: Duration) {
        // ct is current time - sub the timeout. and then split.
        let expire = ct - Duration::from_secs(MFAREG_SESSION_TIMEOUT);
        let split_at = uuid_from_duration(expire, self.sid);
        // Removes older sessions in place.
        self.mfareg_sessions.split_off_lt(&split_at);
        // expired will now be dropped, and can't be used by future sessions.
    }

    fn check_password_quality(
        &mut self,
        au: &mut AuditScope,
        cleartext: &str,
        related_inputs: &[&str],
    ) -> Result<(), OperationError> {
        // password strength and badlisting is always global, rather than per-pw-policy.
        // pw-policy as check on the account is about requirements for mfa for example.
        //

        // is the password at least 10 char?
        if cleartext.len() < PW_MIN_LENGTH {
            return Err(OperationError::PasswordTooShort(PW_MIN_LENGTH));
        }

        // does the password pass zxcvbn?

        let entropy = zxcvbn::zxcvbn(cleartext, related_inputs).map_err(|e| {
            ladmin_error!(au, "zxcvbn check failure (password empty?) {:?}", e);
            OperationError::PasswordEmpty
        })?;

        // check account pwpolicy (for 3 or 4)? Do we need pw strength beyond this
        // or should we be enforcing mfa instead
        if entropy.score() < 3 {
            // The password is too week as per:
            // https://docs.rs/zxcvbn/2.0.0/zxcvbn/struct.Entropy.html
            let feedback: zxcvbn::feedback::Feedback = entropy
                .feedback()
                .as_ref()
                .ok_or(OperationError::InvalidState)
                .map(|v| v.clone())
                .map_err(|e| {
                    lsecurity!(au, "zxcvbn returned no feedback when score < 3");
                    e
                })?;

            lsecurity!(au, "pw feedback -> {:?}", feedback);

            // return Err(OperationError::PasswordTooWeak(feedback))
            return Err(OperationError::PasswordTooWeak);
        }

        // check a password badlist to eliminate more content
        // we check the password as "lower case" to help eliminate possibilities
        let lc_password = PartialValue::new_iutf8s(cleartext);
        let badlist_entry = self
            .qs_write
            .internal_search_uuid(au, &UUID_SYSTEM_CONFIG)
            .map_err(|e| {
                ladmin_error!(au, "Failed to retrieve system configuration {:?}", e);
                e
            })?;
        if badlist_entry.attribute_value_pres("badlist_password", &lc_password) {
            lsecurity!(au, "Password found in badlist, rejecting");
            Err(OperationError::PasswordBadListed)
        } else {
            Ok(())
        }
    }

    fn target_to_account(
        &mut self,
        au: &mut AuditScope,
        target: &Uuid,
    ) -> Result<Account, OperationError> {
        // Get the account
        let account = self
            .qs_write
            .internal_search_uuid(au, target)
            .and_then(|account_entry| {
                Account::try_from_entry_rw(au, account_entry, &mut self.qs_write)
            })
            .map_err(|e| {
                ladmin_error!(au, "Failed to search account {:?}", e);
                e
            })?;
        // Ask if tis all good - this step checks pwpolicy and such

        // Deny the change if the account is anonymous!
        if account.is_anonymous() {
            Err(OperationError::SystemProtectedObject)
        } else {
            Ok(account)
        }
    }

    pub fn set_account_password(
        &mut self,
        au: &mut AuditScope,
        pce: &PasswordChangeEvent,
    ) -> Result<(), OperationError> {
        let account = self.target_to_account(au, &pce.target)?;
        // Ask if tis all good - this step checks pwpolicy and such

        // Question: Is it a security issue to reveal pw policy checks BEFORE permission is
        // determined over the credential modification?
        //
        // I don't think so - because we should only be showing how STRONG the pw is ...

        // Get related inputs, such as account name, email, etc.
        let related_inputs: Vec<&str> = vec![
            account.name.as_str(),
            account.displayname.as_str(),
            account.spn.as_str(),
        ];

        self.check_password_quality(au, pce.cleartext.as_str(), related_inputs.as_slice())
            .map_err(|e| {
                lrequest_error!(au, "check_password_quality -> {:?}", e);
                e
            })?;

        // it returns a modify
        let modlist = account
            .gen_password_mod(pce.cleartext.as_str(), &pce.appid)
            .map_err(|e| {
                ladmin_error!(au, "Failed to generate password mod {:?}", e);
                e
            })?;
        ltrace!(au, "processing change {:?}", modlist);
        // given the new credential generate a modify
        // We use impersonate here to get the event from ae
        self.qs_write
            .impersonate_modify(
                au,
                // Filter as executed
                filter!(f_eq("uuid", PartialValue::new_uuidr(&pce.target))),
                // Filter as intended (acp)
                filter_all!(f_eq("uuid", PartialValue::new_uuidr(&pce.target))),
                modlist,
                &pce.event,
            )
            .map_err(|e| {
                lrequest_error!(au, "error -> {:?}", e);
                e
            })?;

        Ok(())
    }

    pub fn set_unix_account_password(
        &mut self,
        au: &mut AuditScope,
        pce: &UnixPasswordChangeEvent,
    ) -> Result<(), OperationError> {
        // Get the account
        let account = self
            .qs_write
            .internal_search_uuid(au, &pce.target)
            .and_then(|account_entry| {
                // Assert the account is unix and valid.
                UnixUserAccount::try_from_entry_rw(au, account_entry, &mut self.qs_write)
            })
            .map_err(|e| {
                ladmin_error!(au, "Failed to start set unix account password {:?}", e);
                e
            })?;
        // Ask if tis all good - this step checks pwpolicy and such

        // Deny the change if the account is anonymous!
        if account.is_anonymous() {
            return Err(OperationError::SystemProtectedObject);
        }

        // Get related inputs, such as account name, email, etc.
        let related_inputs: Vec<&str> = vec![
            account.name.as_str(),
            account.displayname.as_str(),
            account.spn.as_str(),
        ];

        self.check_password_quality(au, pce.cleartext.as_str(), related_inputs.as_slice())
            .map_err(|e| {
                ladmin_error!(au, "Failed to checked password quality {:?}", e);
                e
            })?;

        // it returns a modify
        let modlist = account
            .gen_password_mod(pce.cleartext.as_str())
            .map_err(|e| {
                ladmin_error!(au, "Unable to generate password change modlist {:?}", e);
                e
            })?;
        ltrace!(au, "processing change {:?}", modlist);
        // given the new credential generate a modify
        // We use impersonate here to get the event from ae
        self.qs_write
            .impersonate_modify(
                au,
                // Filter as executed
                filter!(f_eq("uuid", PartialValue::new_uuidr(&pce.target))),
                // Filter as intended (acp)
                filter_all!(f_eq("uuid", PartialValue::new_uuidr(&pce.target))),
                modlist,
                &pce.event,
            )
            .map_err(|e| {
                lrequest_error!(au, "error -> {:?}", e);
                e
            })
            .map(|_| ())
    }

    pub fn recover_account(
        &mut self,
        au: &mut AuditScope,
        name: String,
        cleartext: String,
    ) -> Result<(), OperationError> {
        // name to uuid
        let target = self.qs_write.name_to_uuid(au, name.as_str()).map_err(|e| {
            ladmin_error!(au, "name to uuid failed {:?}", e);
            e
        })?;
        // internal pce.
        let pce = PasswordChangeEvent::new_internal(&target, cleartext.as_str(), None);
        // now set_account_password.
        self.set_account_password(au, &pce)
    }

    pub fn generate_account_password(
        &mut self,
        au: &mut AuditScope,
        gpe: &GeneratePasswordEvent,
    ) -> Result<String, OperationError> {
        let account = self.target_to_account(au, &gpe.target)?;
        // Ask if tis all good - this step checks pwpolicy and such

        // Generate a new random, long pw.
        // Because this is generated, we can bypass policy checks!
        let cleartext = password_from_random();

        // check a password badlist - even if generated, we still don't want to
        // reuse something that has been disclosed.

        // it returns a modify
        let modlist = account
            .gen_password_mod(cleartext.as_str(), &gpe.appid)
            .map_err(|e| {
                ladmin_error!(au, "Unable to generate password mod {:?}", e);
                e
            })?;

        ltrace!(au, "processing change {:?}", modlist);
        // given the new credential generate a modify
        // We use impersonate here to get the event from ae
        self.qs_write
            .impersonate_modify(
                au,
                // Filter as executed
                filter!(f_eq("uuid", PartialValue::new_uuidr(&gpe.target))),
                // Filter as intended (acp)
                filter_all!(f_eq("uuid", PartialValue::new_uuidr(&gpe.target))),
                modlist,
                // Provide the event to impersonate
                &gpe.event,
            )
            .map(|_| cleartext)
            .map_err(|e| {
                ladmin_error!(au, "Failed to generate account password {:?}", e);
                e
            })
    }

    pub fn regenerate_radius_secret(
        &mut self,
        au: &mut AuditScope,
        rrse: &RegenerateRadiusSecretEvent,
    ) -> Result<String, OperationError> {
        let account = self.target_to_account(au, &rrse.target)?;

        // Difference to the password above, this is intended to be read/copied
        // by a human wiath a keyboard in some cases.
        let cleartext = readable_password_from_random();

        // Create a modlist from the change.
        let modlist = account
            .regenerate_radius_secret_mod(cleartext.as_str())
            .map_err(|e| {
                ladmin_error!(au, "Unable to generate radius secret mod {:?}", e);
                e
            })?;
        ltrace!(au, "processing change {:?}", modlist);

        // Apply it.
        self.qs_write
            .impersonate_modify(
                au,
                // Filter as executed
                filter!(f_eq("uuid", PartialValue::new_uuidr(&rrse.target))),
                // Filter as intended (acp)
                filter_all!(f_eq("uuid", PartialValue::new_uuidr(&rrse.target))),
                modlist,
                // Provide the event to impersonate
                &rrse.event,
            )
            .map_err(|e| {
                lrequest_error!(au, "error -> {:?}", e);
                e
            })
            .map(|_| cleartext)
    }

    pub fn generate_account_totp(
        &mut self,
        au: &mut AuditScope,
        gte: &GenerateTOTPEvent,
        ct: Duration,
    ) -> Result<SetCredentialResponse, OperationError> {
        let account = self.target_to_account(au, &gte.target)?;
        let sessionid = uuid_from_duration(ct, self.sid);

        let origin = (&gte.event.origin).into();
        let label = gte.label.clone();
        let (session, next) = MfaRegSession::new(origin, account, MfaReqInit::TOTP(label))
            .map_err(|e| {
                ladmin_error!(au, "Unable to start totp MfaRegSession {:?}", e);
                e
            })?;

        let next = next.to_proto(&sessionid);

        // Add session to tree
        self.mfareg_sessions.insert(sessionid, session);
        ltrace!(au, "Start mfa reg session -> {:?}", sessionid);
        Ok(next)
    }

    pub fn verify_account_totp(
        &mut self,
        au: &mut AuditScope,
        vte: &VerifyTOTPEvent,
        ct: Duration,
    ) -> Result<SetCredentialResponse, OperationError> {
        let sessionid = vte.session;
        let origin = (&vte.event.origin).into();
        let chal = vte.chal;

        ltrace!(au, "Attempting to find mfareg_session -> {:?}", sessionid);

        let (next, opt_cred) = self
            .mfareg_sessions
            .get_mut(&sessionid)
            .ok_or(OperationError::InvalidRequestState)
            .and_then(|session| {
                session.step(&origin, &vte.target, MfaReqStep::TOTPVerify(chal), &ct)
            })
            .map_err(|e| {
                ladmin_error!(au, "Failed to verify totp {:?}", e);
                e
            })?;

        if let (MfaRegNext::Success, Some(MfaRegCred::TOTP(token))) = (&next, opt_cred) {
            // Purge the session.
            let session = self
                .mfareg_sessions
                .remove(&sessionid)
                .expect("Session within transaction vanished!");
            // reg the token
            let modlist = session.account.gen_totp_mod(token).map_err(|e| {
                ladmin_error!(au, "Failed to gen totp mod {:?}", e);
                e
            })?;
            // Perform the mod
            self.qs_write
                .impersonate_modify(
                    au,
                    // Filter as executed
                    filter!(f_eq("uuid", PartialValue::new_uuidr(&session.account.uuid))),
                    // Filter as intended (acp)
                    filter_all!(f_eq("uuid", PartialValue::new_uuidr(&session.account.uuid))),
                    modlist,
                    &vte.event,
                )
                .map_err(|e| {
                    ladmin_error!(au, "verify_account_totp {:?}", e);
                    e
                })?;
        };

        let next = next.to_proto(&sessionid);
        Ok(next)
    }

    pub fn commit(self, au: &mut AuditScope) -> Result<(), OperationError> {
        lperf_trace_segment!(au, "idm::server::IdmServerWriteTransaction::commit", || {
            self.mfareg_sessions.commit();
            self.qs_write.commit(au)
        })
    }
}

// Need tests of the sessions and the auth ...

#[cfg(test)]
mod tests {
    use crate::constants::{
        AUTH_SESSION_TIMEOUT, MFAREG_SESSION_TIMEOUT, UUID_ADMIN, UUID_ANONYMOUS,
    };
    use crate::credential::totp::TOTP;
    use crate::credential::Credential;
    use crate::entry::{Entry, EntryInit, EntryNew};
    use crate::event::{AuthEvent, AuthResult, CreateEvent, ModifyEvent};
    use crate::idm::event::{
        GenerateTOTPEvent, PasswordChangeEvent, RadiusAuthTokenEvent, RegenerateRadiusSecretEvent,
        UnixGroupTokenEvent, UnixPasswordChangeEvent, UnixUserAuthEvent, UnixUserTokenEvent,
        VerifyTOTPEvent,
    };
    use crate::modify::{Modify, ModifyList};
    use crate::value::{PartialValue, Value};
    use kanidm_proto::v1::OperationError;
    use kanidm_proto::v1::SetCredentialResponse;
    use kanidm_proto::v1::{AuthAllowed, AuthState};

    use crate::audit::AuditScope;
    use crate::idm::server::IdmServer;
    use crate::server::QueryServer;
    use crate::utils::duration_from_epoch_now;
    use std::time::Duration;
    use uuid::Uuid;

    const TEST_PASSWORD: &'static str = "ntaoeuntnaoeuhraohuercahu😍";
    const TEST_PASSWORD_INC: &'static str = "ntaoentu nkrcgaeunhibwmwmqj;k wqjbkx ";
    const TEST_CURRENT_TIME: u64 = 6000;
    const TEST_CURRENT_EXPIRE: u64 = TEST_CURRENT_TIME + AUTH_SESSION_TIMEOUT + 1;

    #[test]
    fn test_idm_anonymous_auth() {
        run_idm_test!(|_qs: &QueryServer, idms: &IdmServer, au: &mut AuditScope| {
            let sid = {
                // Start and test anonymous auth.
                let mut idms_write = idms.write();
                // Send the initial auth event for initialising the session
                let anon_init = AuthEvent::anonymous_init();
                // Expect success
                let r1 = idms_write.auth(au, &anon_init, Duration::from_secs(TEST_CURRENT_TIME));
                /* Some weird lifetime shit happens here ... */

                let sid = match r1 {
                    Ok(ar) => {
                        let AuthResult { sessionid, state } = ar;
                        match state {
                            AuthState::Continue(mut conts) => {
                                // Should only be one auth mech
                                assert!(conts.len() == 1);
                                // And it should be anonymous
                                let m = conts.pop().expect("Should not fail");
                                assert!(m == AuthAllowed::Anonymous);
                            }
                            _ => {
                                error!(
                                    "A critical error has occured! We have a non-continue result!"
                                );
                                panic!();
                            }
                        };
                        // Now pass back the sessionid, we are good to continue.
                        sessionid
                    }
                    Err(e) => {
                        // Should not occur!
                        error!("A critical error has occured! {:?}", e);
                        panic!();
                    }
                };

                debug!("sessionid is ==> {:?}", sid);

                idms_write.commit(au).expect("Must not fail");

                sid
            };
            {
                let mut idms_write = idms.write();
                // Now send the anonymous request, given the session id.
                let anon_step = AuthEvent::cred_step_anonymous(sid);

                // Expect success
                let r2 = idms_write.auth(au, &anon_step, Duration::from_secs(TEST_CURRENT_TIME));
                debug!("r2 ==> {:?}", r2);

                match r2 {
                    Ok(ar) => {
                        let AuthResult {
                            sessionid: _,
                            state,
                        } = ar;
                        match state {
                            AuthState::Success(_uat) => {
                                // Check the uat.
                            }
                            _ => {
                                error!(
                                    "A critical error has occured! We have a non-succcess result!"
                                );
                                panic!();
                            }
                        }
                    }
                    Err(e) => {
                        error!("A critical error has occured! {:?}", e);
                        // Should not occur!
                        panic!();
                    }
                };

                idms_write.commit(au).expect("Must not fail");
            }
        });
    }

    // Test sending anonymous but with no session init.
    #[test]
    fn test_idm_anonymous_auth_invalid_states() {
        run_idm_test!(|_qs: &QueryServer, idms: &IdmServer, au: &mut AuditScope| {
            {
                let mut idms_write = idms.write();
                let sid = Uuid::new_v4();
                let anon_step = AuthEvent::cred_step_anonymous(sid);

                // Expect failure
                let r2 = idms_write.auth(au, &anon_step, Duration::from_secs(TEST_CURRENT_TIME));
                debug!("r2 ==> {:?}", r2);

                match r2 {
                    Ok(_) => {
                        error!("Auth state machine not correctly enforced!");
                        panic!();
                    }
                    Err(e) => match e {
                        OperationError::InvalidSessionState => {}
                        _ => panic!(),
                    },
                };
            }
        })
    }

    fn init_admin_w_password(
        au: &mut AuditScope,
        qs: &QueryServer,
        pw: &str,
    ) -> Result<(), OperationError> {
        let cred = Credential::new_password_only(pw);
        let v_cred = Value::new_credential("primary", cred);
        let qs_write = qs.write(duration_from_epoch_now());

        // now modify and provide a primary credential.
        let me_inv_m = unsafe {
            ModifyEvent::new_internal_invalid(
                filter!(f_eq("name", PartialValue::new_iname("admin"))),
                ModifyList::new_list(vec![Modify::Present(
                    "primary_credential".to_string(),
                    v_cred,
                )]),
            )
        };
        // go!
        assert!(qs_write.modify(au, &me_inv_m).is_ok());

        qs_write.commit(au)
    }

    fn init_admin_authsession_sid(idms: &IdmServer, au: &mut AuditScope) -> Uuid {
        let mut idms_write = idms.write();
        let admin_init = AuthEvent::named_init("admin");

        let r1 = idms_write.auth(au, &admin_init, Duration::from_secs(TEST_CURRENT_TIME));
        let ar = r1.unwrap();
        let AuthResult { sessionid, state } = ar;

        match state {
            AuthState::Continue(_) => {}
            _ => {
                error!("Sessions was not initialised");
                panic!();
            }
        };

        idms_write.commit(au).expect("Must not fail");

        sessionid
    }

    #[test]
    fn test_idm_simple_password_auth() {
        run_idm_test!(|qs: &QueryServer, idms: &IdmServer, au: &mut AuditScope| {
            init_admin_w_password(au, qs, TEST_PASSWORD).expect("Failed to setup admin account");
            let sid = init_admin_authsession_sid(idms, au);

            let mut idms_write = idms.write();
            let anon_step = AuthEvent::cred_step_password(sid, TEST_PASSWORD);

            // Expect success
            let r2 = idms_write.auth(au, &anon_step, Duration::from_secs(TEST_CURRENT_TIME));
            debug!("r2 ==> {:?}", r2);

            match r2 {
                Ok(ar) => {
                    let AuthResult {
                        sessionid: _,
                        state,
                    } = ar;
                    match state {
                        AuthState::Success(_uat) => {
                            // Check the uat.
                        }
                        _ => {
                            error!("A critical error has occured! We have a non-succcess result!");
                            panic!();
                        }
                    }
                }
                Err(e) => {
                    error!("A critical error has occured! {:?}", e);
                    // Should not occur!
                    panic!();
                }
            };

            idms_write.commit(au).expect("Must not fail");
        })
    }

    #[test]
    fn test_idm_simple_password_spn_auth() {
        run_idm_test!(|qs: &QueryServer, idms: &IdmServer, au: &mut AuditScope| {
            init_admin_w_password(au, qs, TEST_PASSWORD).expect("Failed to setup admin account");
            let mut idms_write = idms.write();
            let admin_init = AuthEvent::named_init("admin@example.com");

            let r1 = idms_write.auth(au, &admin_init, Duration::from_secs(TEST_CURRENT_TIME));
            let ar = r1.unwrap();
            let AuthResult { sessionid, state } = ar;

            match state {
                AuthState::Continue(_) => {}
                _ => {
                    error!("Sessions was not initialised");
                    panic!();
                }
            };

            idms_write.commit(au).expect("Must not fail");

            let sid = sessionid;

            let mut idms_write = idms.write();
            let anon_step = AuthEvent::cred_step_password(sid, TEST_PASSWORD);

            // Expect success
            let r2 = idms_write.auth(au, &anon_step, Duration::from_secs(TEST_CURRENT_TIME));
            debug!("r2 ==> {:?}", r2);

            match r2 {
                Ok(ar) => {
                    let AuthResult {
                        sessionid: _,
                        state,
                    } = ar;
                    match state {
                        AuthState::Success(_uat) => {
                            // Check the uat.
                        }
                        _ => {
                            error!("A critical error has occured! We have a non-succcess result!");
                            panic!();
                        }
                    }
                }
                Err(e) => {
                    error!("A critical error has occured! {:?}", e);
                    // Should not occur!
                    panic!();
                }
            };

            idms_write.commit(au).expect("Must not fail");
        })
    }

    #[test]
    fn test_idm_simple_password_invalid() {
        run_idm_test!(|qs: &QueryServer, idms: &IdmServer, au: &mut AuditScope| {
            init_admin_w_password(au, qs, TEST_PASSWORD).expect("Failed to setup admin account");
            let sid = init_admin_authsession_sid(idms, au);
            let mut idms_write = idms.write();
            let anon_step = AuthEvent::cred_step_password(sid, TEST_PASSWORD_INC);

            // Expect success
            let r2 = idms_write.auth(au, &anon_step, Duration::from_secs(TEST_CURRENT_TIME));
            debug!("r2 ==> {:?}", r2);

            match r2 {
                Ok(ar) => {
                    let AuthResult {
                        sessionid: _,
                        state,
                    } = ar;
                    match state {
                        AuthState::Denied(_reason) => {
                            // Check the uat.
                        }
                        _ => {
                            error!("A critical error has occured! We have a non-denied result!");
                            panic!();
                        }
                    }
                }
                Err(e) => {
                    error!("A critical error has occured! {:?}", e);
                    // Should not occur!
                    panic!();
                }
            };

            idms_write.commit(au).expect("Must not fail");
        })
    }

    #[test]
    fn test_idm_simple_password_reset() {
        run_idm_test!(|_qs: &QueryServer, idms: &IdmServer, au: &mut AuditScope| {
            let pce = PasswordChangeEvent::new_internal(&UUID_ADMIN, TEST_PASSWORD, None);

            let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now());
            assert!(idms_prox_write.set_account_password(au, &pce).is_ok());
            assert!(idms_prox_write.set_account_password(au, &pce).is_ok());
            assert!(idms_prox_write.commit(au).is_ok());
        })
    }

    #[test]
    fn test_idm_anonymous_set_password_denied() {
        run_idm_test!(|_qs: &QueryServer, idms: &IdmServer, au: &mut AuditScope| {
            let pce = PasswordChangeEvent::new_internal(&UUID_ANONYMOUS, TEST_PASSWORD, None);

            let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now());
            assert!(idms_prox_write.set_account_password(au, &pce).is_err());
            assert!(idms_prox_write.commit(au).is_ok());
        })
    }

    #[test]
    fn test_idm_session_expire() {
        run_idm_test!(|qs: &QueryServer, idms: &IdmServer, au: &mut AuditScope| {
            init_admin_w_password(au, qs, TEST_PASSWORD).expect("Failed to setup admin account");
            let sid = init_admin_authsession_sid(idms, au);
            let mut idms_write = idms.write();
            assert!(idms_write.is_sessionid_present(&sid));
            // Expire like we are currently "now". Should not affect our session.
            idms_write.expire_auth_sessions(Duration::from_secs(TEST_CURRENT_TIME));
            assert!(idms_write.is_sessionid_present(&sid));
            // Expire as though we are in the future.
            idms_write.expire_auth_sessions(Duration::from_secs(TEST_CURRENT_EXPIRE));
            assert!(!idms_write.is_sessionid_present(&sid));
            assert!(idms_write.commit(au).is_ok());
            let idms_write = idms.write();
            assert!(!idms_write.is_sessionid_present(&sid));
        })
    }

    #[test]
    fn test_idm_regenerate_radius_secret() {
        run_idm_test!(|_qs: &QueryServer, idms: &IdmServer, au: &mut AuditScope| {
            let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now());
            let rrse = RegenerateRadiusSecretEvent::new_internal(UUID_ADMIN.clone());

            // Generates a new credential when none exists
            let r1 = idms_prox_write
                .regenerate_radius_secret(au, &rrse)
                .expect("Failed to reset radius credential 1");
            // Regenerates and overwrites the radius credential
            let r2 = idms_prox_write
                .regenerate_radius_secret(au, &rrse)
                .expect("Failed to reset radius credential 2");
            assert!(r1 != r2);
        })
    }

    #[test]
    fn test_idm_radiusauthtoken() {
        run_idm_test!(|_qs: &QueryServer, idms: &IdmServer, au: &mut AuditScope| {
            let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now());
            let rrse = RegenerateRadiusSecretEvent::new_internal(UUID_ADMIN.clone());
            let r1 = idms_prox_write
                .regenerate_radius_secret(au, &rrse)
                .expect("Failed to reset radius credential 1");
            idms_prox_write.commit(au).expect("failed to commit");

            let mut idms_prox_read = idms.proxy_read();
            let rate = RadiusAuthTokenEvent::new_internal(UUID_ADMIN.clone());
            let tok_r = idms_prox_read
                .get_radiusauthtoken(au, &rate)
                .expect("Failed to generate radius auth token");

            // view the token?
            assert!(r1 == tok_r.secret);
        })
    }

    #[test]
    fn test_idm_simple_password_reject_weak() {
        run_idm_test!(|_qs: &QueryServer, idms: &IdmServer, au: &mut AuditScope| {
            // len check
            let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now());

            let pce = PasswordChangeEvent::new_internal(&UUID_ADMIN, "password", None);
            let e = idms_prox_write.set_account_password(au, &pce);
            assert!(e.is_err());

            // zxcvbn check
            let pce = PasswordChangeEvent::new_internal(&UUID_ADMIN, "password1234", None);
            let e = idms_prox_write.set_account_password(au, &pce);
            assert!(e.is_err());

            // Check the "name" checking works too (I think admin may hit a common pw rule first)
            let pce = PasswordChangeEvent::new_internal(&UUID_ADMIN, "admin_nta", None);
            let e = idms_prox_write.set_account_password(au, &pce);
            assert!(e.is_err());

            // Check that the demo badlist password is rejected.
            let pce = PasswordChangeEvent::new_internal(
                &UUID_ADMIN,
                "demo_badlist_shohfie3aeci2oobur0aru9uushah6EiPi2woh4hohngoighaiRuepieN3ongoo1",
                None,
            );
            let e = idms_prox_write.set_account_password(au, &pce);
            assert!(e.is_err());

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

    #[test]
    fn test_idm_unixusertoken() {
        run_idm_test!(|_qs: &QueryServer, idms: &IdmServer, au: &mut AuditScope| {
            let idms_prox_write = idms.proxy_write(duration_from_epoch_now());
            // Modify admin to have posixaccount
            let me_posix = unsafe {
                ModifyEvent::new_internal_invalid(
                    filter!(f_eq("name", PartialValue::new_iname("admin"))),
                    ModifyList::new_list(vec![
                        Modify::Present("class".to_string(), Value::new_class("posixaccount")),
                        Modify::Present("gidnumber".to_string(), Value::new_uint32(2001)),
                    ]),
                )
            };
            assert!(idms_prox_write.qs_write.modify(au, &me_posix).is_ok());
            // Add a posix group that has the admin as a member.
            let e: Entry<EntryInit, EntryNew> = Entry::unsafe_from_entry_str(
                r#"{
                "attrs": {
                    "class": ["object", "group", "posixgroup"],
                    "name": ["testgroup"],
                    "uuid": ["01609135-a1c4-43d5-966b-a28227644445"],
                    "description": ["testgroup"],
                    "member": ["00000000-0000-0000-0000-000000000000"]
                }
            }"#,
            );

            let ce = CreateEvent::new_internal(vec![e.clone()]);

            assert!(idms_prox_write.qs_write.create(au, &ce).is_ok());

            idms_prox_write.commit(au).expect("failed to commit");

            let mut idms_prox_read = idms.proxy_read();

            let ugte = UnixGroupTokenEvent::new_internal(
                Uuid::parse_str("01609135-a1c4-43d5-966b-a28227644445")
                    .expect("failed to parse uuid"),
            );
            let tok_g = idms_prox_read
                .get_unixgrouptoken(au, &ugte)
                .expect("Failed to generate unix group token");

            assert!(tok_g.name == "testgroup");
            assert!(tok_g.spn == "testgroup@example.com");

            let uute = UnixUserTokenEvent::new_internal(UUID_ADMIN.clone());
            let tok_r = idms_prox_read
                .get_unixusertoken(au, &uute)
                .expect("Failed to generate unix user token");

            assert!(tok_r.name == "admin");
            assert!(tok_r.spn == "admin@example.com");
            assert!(tok_r.groups.len() == 2);
            assert!(tok_r.groups[0].name == "admin");
            assert!(tok_r.groups[1].name == "testgroup");

            // Show we can get the admin as a unix group token too
            let ugte = UnixGroupTokenEvent::new_internal(
                Uuid::parse_str("00000000-0000-0000-0000-000000000000")
                    .expect("failed to parse uuid"),
            );
            let tok_g = idms_prox_read
                .get_unixgrouptoken(au, &ugte)
                .expect("Failed to generate unix group token");

            assert!(tok_g.name == "admin");
            assert!(tok_g.spn == "admin@example.com");
        })
    }

    #[test]
    fn test_idm_simple_unix_password_reset() {
        run_idm_test!(|_qs: &QueryServer, idms: &IdmServer, au: &mut AuditScope| {
            let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now());
            // make the admin a valid posix account
            let me_posix = unsafe {
                ModifyEvent::new_internal_invalid(
                    filter!(f_eq("name", PartialValue::new_iname("admin"))),
                    ModifyList::new_list(vec![
                        Modify::Present("class".to_string(), Value::new_class("posixaccount")),
                        Modify::Present("gidnumber".to_string(), Value::new_uint32(2001)),
                    ]),
                )
            };
            assert!(idms_prox_write.qs_write.modify(au, &me_posix).is_ok());

            let pce = UnixPasswordChangeEvent::new_internal(&UUID_ADMIN, TEST_PASSWORD);

            assert!(idms_prox_write.set_unix_account_password(au, &pce).is_ok());
            assert!(idms_prox_write.set_unix_account_password(au, &pce).is_ok());
            assert!(idms_prox_write.commit(au).is_ok());

            let mut idms_write = idms.write();
            // Check auth verification of the password

            let uuae_good = UnixUserAuthEvent::new_internal(&UUID_ADMIN, TEST_PASSWORD);
            let a1 = idms_write.auth_unix(au, &uuae_good, Duration::from_secs(TEST_CURRENT_TIME));
            match a1 {
                Ok(Some(_tok)) => {}
                _ => assert!(false),
            };
            // Check bad password
            let uuae_bad = UnixUserAuthEvent::new_internal(&UUID_ADMIN, TEST_PASSWORD_INC);
            let a2 = idms_write.auth_unix(au, &uuae_bad, Duration::from_secs(TEST_CURRENT_TIME));
            match a2 {
                Ok(None) => {}
                _ => assert!(false),
            };
            assert!(idms_write.commit(au).is_ok());

            // Check deleting the password
            let idms_prox_write = idms.proxy_write(duration_from_epoch_now());
            let me_purge_up = unsafe {
                ModifyEvent::new_internal_invalid(
                    filter!(f_eq("name", PartialValue::new_iname("admin"))),
                    ModifyList::new_list(vec![Modify::Purged("unix_password".to_string())]),
                )
            };
            assert!(idms_prox_write.qs_write.modify(au, &me_purge_up).is_ok());
            assert!(idms_prox_write.commit(au).is_ok());

            // And auth should now fail due to the lack of PW material
            let mut idms_write = idms.write();
            let a3 = idms_write.auth_unix(au, &uuae_good, Duration::from_secs(TEST_CURRENT_TIME));
            match a3 {
                Ok(None) => {}
                _ => assert!(false),
            };
            assert!(idms_write.commit(au).is_ok());
        })
    }

    #[test]
    fn test_idm_totp_registration() {
        run_idm_test!(|_qs: &QueryServer, idms: &IdmServer, au: &mut AuditScope| {
            let ct = duration_from_epoch_now();
            let expire = Duration::from_secs(ct.as_secs() + MFAREG_SESSION_TIMEOUT + 2);
            let mut idms_prox_write = idms.proxy_write(ct.clone());

            // verify with no session (fail)
            let vte1 = VerifyTOTPEvent::new_internal(UUID_ADMIN.clone(), Uuid::new_v4(), 0);

            match idms_prox_write.verify_account_totp(au, &vte1, ct.clone()) {
                Err(e) => {
                    assert!(e == OperationError::InvalidRequestState);
                }
                _ => panic!(),
            };

            // reg, expire session, attempt verify (fail)
            let gte1 = GenerateTOTPEvent::new_internal(UUID_ADMIN.clone());

            let res = idms_prox_write
                .generate_account_totp(au, &gte1, ct.clone())
                .unwrap();
            let sesid = match res {
                SetCredentialResponse::TOTPCheck(id, _) => id,
                _ => panic!("invalid state!"),
            };
            idms_prox_write.expire_mfareg_sessions(expire.clone());

            let vte2 = VerifyTOTPEvent::new_internal(UUID_ADMIN.clone(), sesid, 0);

            match idms_prox_write.verify_account_totp(au, &vte1, ct.clone()) {
                Err(e) => {
                    assert!(e == OperationError::InvalidRequestState);
                }
                _ => panic!(),
            };

            // == Test TOTP on account with no password (fail)
            let res = idms_prox_write
                .generate_account_totp(au, &gte1, ct.clone())
                .unwrap();
            let (sesid, tok) = match res {
                SetCredentialResponse::TOTPCheck(id, tok) => (id, tok),
                _ => panic!("invalid state!"),
            };
            // get the correct otp
            let r_tok: TOTP = tok.into();
            let chal = r_tok
                .do_totp_duration_from_epoch(&ct)
                .expect("Failed to do totp?");
            // attempt the verify
            let vte3 = VerifyTOTPEvent::new_internal(UUID_ADMIN.clone(), sesid, chal);

            match idms_prox_write.verify_account_totp(au, &vte3, ct.clone()) {
                Err(e) => assert!(e == OperationError::InvalidState),
                _ => panic!(),
            };

            // Expire the session to allow it to reset.
            idms_prox_write.expire_mfareg_sessions(expire.clone());

            // Set a password.
            let pce = PasswordChangeEvent::new_internal(&UUID_ADMIN, TEST_PASSWORD, None);
            assert!(idms_prox_write.set_account_password(au, &pce).is_ok());

            // == reg, but change the event source part way in the process (failure)
            let res = idms_prox_write
                .generate_account_totp(au, &gte1, ct.clone())
                .unwrap();
            let (sesid, tok) = match res {
                SetCredentialResponse::TOTPCheck(id, tok) => (id, tok),
                _ => panic!("invalid state!"),
            };
            // get the correct otp
            let r_tok: TOTP = tok.into();
            let chal = r_tok
                .do_totp_duration_from_epoch(&ct)
                .expect("Failed to do totp?");
            // attempt the verify
            let vte3 = VerifyTOTPEvent::new_internal(UUID_ANONYMOUS.clone(), sesid, chal);

            match idms_prox_write.verify_account_totp(au, &vte3, ct.clone()) {
                Err(e) => assert!(e == OperationError::InvalidRequestState),
                _ => panic!(),
            };

            // == reg, verify w_ incorrect totp (fail)
            let res = idms_prox_write
                .generate_account_totp(au, &gte1, ct.clone())
                .unwrap();
            let (_sesid, _tok) = match res {
                SetCredentialResponse::TOTPCheck(id, tok) => (id, tok),
                _ => panic!("invalid state!"),
            };

            // We can reuse the OTP/Vte2 from before, since we want the invalid otp.
            match idms_prox_write.verify_account_totp(au, &vte2, ct.clone()) {
                // On failure we get back another attempt to setup the token.
                Ok(SetCredentialResponse::TOTPCheck(_id, _tok)) => {}
                _ => panic!(),
            };
            idms_prox_write.expire_mfareg_sessions(expire.clone());

            // Turn the pts into an otp
            // == reg, verify w_ correct totp (success)
            let res = idms_prox_write
                .generate_account_totp(au, &gte1, ct.clone())
                .unwrap();
            let (sesid, tok) = match res {
                SetCredentialResponse::TOTPCheck(id, tok) => (id, tok),
                _ => panic!("invalid state!"),
            };
            // We can't reuse the OTP/Vte from before, since the token seed changes
            let r_tok: TOTP = tok.into();
            let chal = r_tok
                .do_totp_duration_from_epoch(&ct)
                .expect("Failed to do totp?");
            // attempt the verify
            let vte3 = VerifyTOTPEvent::new_internal(UUID_ADMIN.clone(), sesid, chal);

            match idms_prox_write.verify_account_totp(au, &vte3, ct.clone()) {
                Ok(SetCredentialResponse::Success) => {}
                _ => panic!(),
            };
            idms_prox_write.expire_mfareg_sessions(expire.clone());

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