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
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::fmt;
use uuid::Uuid;
use webauthn_rs::proto::{
    CreationChallengeResponse, PublicKeyCredential, RegisterPublicKeyCredential,
    RequestChallengeResponse,
};

// These proto implementations are here because they have public definitions

/* ===== errors ===== */

#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SchemaError {
    NotImplemented,
    NoClassFound,
    InvalidClass(Vec<String>),
    MissingMustAttribute(Vec<String>),
    InvalidAttribute(String),
    InvalidAttributeSyntax(String),
    AttributeNotValidForClass(String),
    EmptyFilter,
    Corrupted,
    PhantomAttribute(String),
}

#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum PluginError {
    AttrUnique(String),
    Base(String),
    ReferentialIntegrity(String),
    PasswordImport(String),
    Oauth2Secrets,
}

#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ConsistencyError {
    Unknown,
    // Class, Attribute
    SchemaClassMissingAttribute(String, String),
    SchemaClassPhantomAttribute(String, String),
    SchemaUuidNotUnique(Uuid),
    QueryServerSearchFailure,
    EntryUuidCorrupt(u64),
    UuidIndexCorrupt(String),
    UuidNotUnique(String),
    RefintNotUpheld(u64),
    MemberOfInvalid(u64),
    InvalidAttributeType(String),
    DuplicateUniqueAttribute(String),
    InvalidSpn(u64),
    SqliteIntegrityFailure,
    BackendAllIdsSync,
    BackendIndexSync,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "lowercase")]
pub enum PasswordFeedback {
    // https://docs.rs/zxcvbn/latest/zxcvbn/feedback/enum.Suggestion.html
    UseAFewWordsAvoidCommonPhrases,
    NoNeedForSymbolsDigitsOrUppercaseLetters,
    AddAnotherWordOrTwo,
    CapitalizationDoesntHelpVeryMuch,
    AllUppercaseIsAlmostAsEasyToGuessAsAllLowercase,
    ReversedWordsArentMuchHarderToGuess,
    PredictableSubstitutionsDontHelpVeryMuch,
    UseALongerKeyboardPatternWithMoreTurns,
    AvoidRepeatedWordsAndCharacters,
    AvoidSequences,
    AvoidRecentYears,
    AvoidYearsThatAreAssociatedWithYou,
    AvoidDatesAndYearsThatAreAssociatedWithYou,
    // https://docs.rs/zxcvbn/latest/zxcvbn/feedback/enum.Warning.html
    StraightRowsOfKeysAreEasyToGuess,
    ShortKeyboardPatternsAreEasyToGuess,
    RepeatsLikeAaaAreEasyToGuess,
    RepeatsLikeAbcAbcAreOnlySlightlyHarderToGuess,
    ThisIsATop10Password,
    ThisIsATop100Password,
    ThisIsACommonPassword,
    ThisIsSimilarToACommonlyUsedPassword,
    SequencesLikeAbcAreEasyToGuess,
    RecentYearsAreEasyToGuess,
    AWordByItselfIsEasyToGuess,
    DatesAreOftenEasyToGuess,
    NamesAndSurnamesByThemselvesAreEasyToGuess,
    CommonNamesAndSurnamesAreEasyToGuess,
    // Custom
    TooShort(usize),
    BadListed,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "lowercase")]
pub enum OperationError {
    SessionExpired,
    EmptyRequest,
    Backend,
    NoMatchingEntries,
    NoMatchingAttributes,
    CorruptedEntry(u64),
    CorruptedIndex(String),
    ConsistencyError(Vec<Result<(), ConsistencyError>>),
    SchemaViolation(SchemaError),
    Plugin(PluginError),
    FilterGeneration,
    FilterUuidResolution,
    InvalidAttributeName(String),
    InvalidAttribute(String),
    InvalidDbState,
    InvalidCacheState,
    InvalidValueState,
    InvalidEntryId,
    InvalidRequestState,
    InvalidState,
    InvalidEntryState,
    InvalidUuid,
    InvalidReplChangeId,
    InvalidAcpState(String),
    InvalidSchemaState(String),
    InvalidAccountState(String),
    BackendEngine,
    SqliteError, //(RusqliteError)
    FsError,
    SerdeJsonError,
    SerdeCborError,
    AccessDenied,
    NotAuthenticated,
    NotAuthorised,
    InvalidAuthState(String),
    InvalidSessionState,
    SystemProtectedObject,
    SystemProtectedAttribute,
    PasswordQuality(Vec<PasswordFeedback>),
    CryptographyError,
    ResourceLimit,
    QueueDisconnected,
    Webauthn,
    Wait(time::OffsetDateTime),
}

impl PartialEq for OperationError {
    fn eq(&self, other: &Self) -> bool {
        // We do this to avoid InvalidPassword being checked as it's not
        // derive PartialEq. Generally we only use the PartialEq for TESTING
        // anyway.
        std::mem::discriminant(self) == std::mem::discriminant(other)
    }
}

/* ===== higher level types ===== */
// These are all types that are conceptually layers ontop of entry and
// friends. They allow us to process more complex requests and provide
// domain specific fields for the purposes of IDM, over the normal
// entry/ava/filter types. These related deeply to schema.

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Group {
    pub name: String,
    pub uuid: String,
}

impl fmt::Display for Group {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[ name: {}, ", self.name)?;
        write!(f, "uuid: {} ]", self.uuid)
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Claim {
    pub name: String,
    pub uuid: String,
    // These can be ephemeral, or shortlived in a session.
    // some may even need requesting.
    // pub expiry: DateTime
}

/*
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Application {
    pub name: String,
    pub uuid: String,
}
*/

#[derive(Debug, Serialize, Deserialize, Clone, Ord, PartialOrd, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum AuthType {
    Anonymous,
    UnixPassword,
    Password,
    GeneratedPassword,
    Webauthn,
    PasswordMfa,
    // PasswordWebauthn,
    // WebauthnVerified,
    // PasswordWebauthnVerified,
}

impl fmt::Display for AuthType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AuthType::Anonymous => write!(f, "anonymous"),
            AuthType::UnixPassword => write!(f, "unixpassword"),
            AuthType::Password => write!(f, "password"),
            AuthType::GeneratedPassword => write!(f, "generatedpassword"),
            AuthType::Webauthn => write!(f, "webauthn"),
            AuthType::PasswordMfa => write!(f, "passwordmfa"),
        }
    }
}

/// The currently authenticated user, and any required metadata for them
/// to properly authorise them. This is similar in nature to oauth and the krb
/// PAC/PAD structures. Currently we only use this internally, but we should
/// consider making it "parseable" by the client so they can have per-session
/// group/authorisation data.
///
/// This structure and how it works will *very much* change over time from this
/// point onward!
///
/// It's likely that this must have a relationship to the server's user structure
/// and to the Entry so that filters or access controls can be applied.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "lowercase")]
pub struct UserAuthToken {
    pub session_id: Uuid,
    pub auth_type: AuthType,
    // When this token should be considered expired. Interpretation
    // may depend on the client application.
    pub expiry: time::OffsetDateTime,
    pub uuid: Uuid,
    // pub name: String,
    pub displayname: String,
    pub spn: String,
    pub mail_primary: Option<String>,
    // pub groups: Vec<Group>,
    // Should we just retrieve these inside the server instead of in the uat?
    // or do we want per-session limit capabilities?
    pub lim_uidx: bool,
    pub lim_rmax: usize,
    pub lim_pmax: usize,
    pub lim_fmax: usize,
}

impl fmt::Display for UserAuthToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // writeln!(f, "name: {}", self.name)?;
        writeln!(f, "spn: {}", self.spn)?;
        writeln!(f, "uuid: {}", self.uuid)?;
        /*
        writeln!(f, "display: {}", self.displayname)?;
        for group in &self.groups {
            writeln!(f, "group: {:?}", group.name)?;
        }
        for claim in &self.claims {
            writeln!(f, "claim: {:?}", claim)?;
        }
        */
        writeln!(f, "token expiry: {}", self.expiry)
    }
}

// UAT will need a downcast to Entry, which adds in the claims to the entry
// for the purpose of filtering.

// This is similar to uat, but omits claims (they have no role in radius), and adds
// the radius secret field.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct RadiusAuthToken {
    pub name: String,
    pub displayname: String,
    pub uuid: String,
    pub secret: String,
    pub groups: Vec<Group>,
}

impl fmt::Display for RadiusAuthToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "name: {}", self.name)?;
        writeln!(f, "displayname: {}", self.displayname)?;
        writeln!(f, "uuid: {}", self.uuid)?;
        writeln!(f, "secret: {}", self.secret)?;
        self.groups
            .iter()
            .try_for_each(|g| writeln!(f, "group: {}", g))
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UnixGroupToken {
    pub name: String,
    pub spn: String,
    pub uuid: String,
    pub gidnumber: u32,
}

impl fmt::Display for UnixGroupToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[ spn: {}, ", self.spn)?;
        write!(f, "gidnumber: {} ", self.gidnumber)?;
        write!(f, "name: {}, ", self.name)?;
        write!(f, "uuid: {} ]", self.uuid)
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GroupUnixExtend {
    pub gidnumber: Option<u32>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UnixUserToken {
    pub name: String,
    pub spn: String,
    pub displayname: String,
    pub gidnumber: u32,
    pub uuid: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shell: Option<String>,
    pub groups: Vec<UnixGroupToken>,
    pub sshkeys: Vec<String>,
    // The default value of bool is false.
    #[serde(default)]
    pub valid: bool,
}

impl fmt::Display for UnixUserToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "---")?;
        writeln!(f, "spn: {}", self.spn)?;
        writeln!(f, "name: {}", self.name)?;
        writeln!(f, "displayname: {}", self.displayname)?;
        writeln!(f, "uuid: {}", self.uuid)?;
        match &self.shell {
            Some(s) => writeln!(f, "shell: {}", s)?,
            None => writeln!(f, "shell: <none>")?,
        }
        self.sshkeys
            .iter()
            .try_for_each(|s| writeln!(f, "ssh_publickey: {}", s))?;
        self.groups
            .iter()
            .try_for_each(|g| writeln!(f, "group: {}", g))
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AccountUnixExtend {
    pub gidnumber: Option<u32>,
    pub shell: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AccountPersonSet {
    pub mail: Option<Vec<String>>,
    pub legalname: Option<String>,
}

/*
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AccountOrgPersonExtend {
    pub mail: String,
}
*/

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub enum CredentialDetailType {
    Password,
    GeneratedPassword,
    Webauthn(Vec<String>),
    /// totp, webauthn
    PasswordMfa(bool, Vec<String>, usize),
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CredentialDetail {
    pub uuid: Uuid,
    pub claims: Vec<String>,
    pub type_: CredentialDetailType,
}

impl fmt::Display for CredentialDetail {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "uuid: {}", self.uuid)?;
        /*
        writeln!(f, "claims:")?;
        for claim in &self.claims {
            writeln!(f, " * {}", claim)?;
        }
        */
        match &self.type_ {
            CredentialDetailType::Password => writeln!(f, "password: set"),
            CredentialDetailType::GeneratedPassword => writeln!(f, "generated password: set"),
            CredentialDetailType::Webauthn(labels) => {
                if labels.is_empty() {
                    writeln!(f, "webauthn: no authenticators")
                } else {
                    writeln!(f, "webauthn:")?;
                    for label in labels {
                        writeln!(f, " * {}", label)?;
                    }
                    write!(f, "")
                }
            }
            CredentialDetailType::PasswordMfa(totp, labels, backup_code) => {
                writeln!(f, "password: set")?;
                if *totp {
                    writeln!(f, "totp: enabled")?;
                } else {
                    writeln!(f, "totp: disabled")?;
                }
                if *backup_code > 0 {
                    writeln!(f, "backup_code: enabled")?;
                } else {
                    writeln!(f, "backup_code: disabled")?;
                }
                if labels.is_empty() {
                    writeln!(f, "webauthn: no authenticators")
                } else {
                    writeln!(f, "webauthn:")?;
                    for label in labels {
                        writeln!(f, " * {}", label)?;
                    }
                    write!(f, "")
                }
            }
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CredentialStatus {
    pub creds: Vec<CredentialDetail>,
}

impl fmt::Display for CredentialStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for cred in &self.creds {
            writeln!(f, "---")?;
            cred.fmt(f)?;
        }
        writeln!(f, "---")
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BackupCodesView {
    // Or use SetCredentialResponse::BackupCodes?
    pub backup_codes: Vec<String>,
}

/* ===== low level proto types ===== */

// ProtoEntry vs Entry
// There is a good future reason for this seperation. It allows changing
// the in memory server core entry type, without affecting the protoEntry type
//

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
pub struct Entry {
    pub attrs: BTreeMap<String, Vec<String>>,
}

impl fmt::Display for Entry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "---")?;
        self.attrs
            .iter()
            .try_for_each(|(k, vs)| vs.iter().try_for_each(|v| writeln!(f, "{}: {}", k, v)))
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
#[serde(rename_all = "lowercase")]
pub enum Filter {
    // This is attr - value
    #[serde(alias = "Eq")]
    Eq(String, String),
    #[serde(alias = "Sub")]
    Sub(String, String),
    #[serde(alias = "Pres")]
    Pres(String),
    #[serde(alias = "Or")]
    Or(Vec<Filter>),
    #[serde(alias = "And")]
    And(Vec<Filter>),
    #[serde(alias = "AndNot")]
    AndNot(Box<Filter>),
    #[serde(rename = "self", alias = "Self")]
    SelfUuid,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "lowercase")]
pub enum Modify {
    Present(String, String),
    Removed(String, String),
    Purged(String),
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ModifyList {
    pub mods: Vec<Modify>,
}

impl ModifyList {
    pub fn new_list(mods: Vec<Modify>) -> Self {
        ModifyList { mods }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SearchRequest {
    pub filter: Filter,
}

impl SearchRequest {
    pub fn new(filter: Filter) -> Self {
        SearchRequest { filter }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SearchResponse {
    pub entries: Vec<Entry>,
}

impl SearchResponse {
    pub fn new(entries: Vec<Entry>) -> Self {
        SearchResponse { entries }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CreateRequest {
    pub entries: Vec<Entry>,
}

impl CreateRequest {
    pub fn new(entries: Vec<Entry>) -> Self {
        CreateRequest { entries }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct DeleteRequest {
    pub filter: Filter,
}

impl DeleteRequest {
    pub fn new(filter: Filter) -> Self {
        DeleteRequest { filter }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ModifyRequest {
    // Probably needs a modlist?
    pub filter: Filter,
    pub modlist: ModifyList,
}

impl ModifyRequest {
    pub fn new(filter: Filter, modlist: ModifyList) -> Self {
        ModifyRequest { filter, modlist }
    }
}

// Login is a multi-step process potentially. First the client says who they
// want to request
//
// we respond with a set of possible authentications that can proceed, and perhaps
// we indicate which options must/may?
//
// The client can then step and negotiate each.
//
// This continues until a LoginSuccess, or LoginFailure is returned.
//
// On loginSuccess, we send a cookie, and that allows the token to be
// generated. The cookie can be shared between servers.
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AuthCredential {
    Anonymous,
    Password(String),
    Totp(u32),
    Webauthn(PublicKeyCredential),
    BackupCode(String),
}

impl fmt::Debug for AuthCredential {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            AuthCredential::Anonymous => write!(fmt, "Anonymous"),
            AuthCredential::Password(_) => write!(fmt, "Password(_)"),
            AuthCredential::Totp(_) => write!(fmt, "TOTP(_)"),
            AuthCredential::Webauthn(_) => write!(fmt, "Webauthn(_)"),
            AuthCredential::BackupCode(_) => write!(fmt, "BackupCode(_)"),
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialOrd, Ord)]
#[serde(rename_all = "lowercase")]
pub enum AuthMech {
    Anonymous,
    Password,
    PasswordMfa,
    Webauthn,
    // WebauthnVerified,
    // PasswordWebauthnVerified
}

impl PartialEq for AuthMech {
    fn eq(&self, other: &Self) -> bool {
        std::mem::discriminant(self) == std::mem::discriminant(other)
    }
}

impl fmt::Display for AuthMech {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AuthMech::Anonymous => write!(f, "Anonymous (no credentials)"),
            AuthMech::Password => write!(f, "Passwold Only"),
            AuthMech::PasswordMfa => write!(f, "TOTP or Token, and Password"),
            AuthMech::Webauthn => write!(f, "Webauthn Token"),
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AuthStep {
    // name
    Init(String),
    // We want to talk to you like this.
    Begin(AuthMech),
    // Step
    Cred(AuthCredential),
    // Should we have a "finalise" type to attempt to finish based on
    // what we have given?
}

// Request auth for identity X with roles Y?
#[derive(Debug, Serialize, Deserialize)]
pub struct AuthRequest {
    pub step: AuthStep,
}

// Respond with the list of auth types and nonce, etc.
// It can also contain a denied, or success.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "lowercase")]
pub enum AuthAllowed {
    Anonymous,
    BackupCode,
    Password,
    Totp,
    Webauthn(RequestChallengeResponse),
}

impl PartialEq for AuthAllowed {
    fn eq(&self, other: &Self) -> bool {
        std::mem::discriminant(self) == std::mem::discriminant(other)
    }
}

impl Eq for AuthAllowed {}

impl Ord for AuthAllowed {
    fn cmp(&self, other: &Self) -> Ordering {
        if self.eq(other) {
            Ordering::Equal
        } else {
            // Relies on the fact that match is executed in order!
            match (self, other) {
                (AuthAllowed::Anonymous, _) => Ordering::Less,
                (_, AuthAllowed::Anonymous) => Ordering::Greater,
                (AuthAllowed::Password, _) => Ordering::Less,
                (_, AuthAllowed::Password) => Ordering::Greater,
                (AuthAllowed::BackupCode, _) => Ordering::Less,
                (_, AuthAllowed::BackupCode) => Ordering::Greater,
                (AuthAllowed::Totp, _) => Ordering::Less,
                (_, AuthAllowed::Totp) => Ordering::Greater,
                (AuthAllowed::Webauthn(_), _) => Ordering::Less,
                // Unreachable
                // (_, AuthAllowed::Webauthn(_)) => Ordering::Greater,
            }
        }
    }
}

impl PartialOrd for AuthAllowed {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl fmt::Display for AuthAllowed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AuthAllowed::Anonymous => write!(f, "Anonymous (no credentials)"),
            AuthAllowed::Password => write!(f, "Password"),
            AuthAllowed::BackupCode => write!(f, "Backup Code"),
            AuthAllowed::Totp => write!(f, "TOTP"),
            AuthAllowed::Webauthn(_) => write!(f, "Webauthn Token"),
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AuthState {
    // You need to select how you want to talk to me.
    Choose(Vec<AuthMech>),
    // Continue to auth, allowed mechanisms/challenges listed.
    Continue(Vec<AuthAllowed>),
    // Something was bad, your session is terminated and no cookie.
    Denied(String),
    // Everything is good, your bearer header has been issued and is within
    // the result.
    Success(String),
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AuthResponse {
    pub sessionid: Uuid,
    pub state: AuthState,
}

// Types needed for setting credentials
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SetCredentialRequest {
    Password(String),
    GeneratePassword,
    TotpGenerate,
    TotpVerify(Uuid, u32),
    TotpAcceptSha1(Uuid),
    TotpRemove,
    // Start the rego.
    WebauthnBegin(String),
    // Finish it.
    WebauthnRegister(Uuid, RegisterPublicKeyCredential),
    // Remove
    WebauthnRemove(String),
    BackupCodeGenerate,
    BackupCodeRemove,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TotpAlgo {
    Sha1,
    Sha256,
    Sha512,
}

impl fmt::Display for TotpAlgo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            TotpAlgo::Sha1 => write!(f, "SHA1"),
            TotpAlgo::Sha256 => write!(f, "SHA256"),
            TotpAlgo::Sha512 => write!(f, "SHA512"),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TotpSecret {
    pub accountname: String,
    /// User-facing name of the system, issuer of the TOTP
    pub issuer: String,
    pub secret: Vec<u8>,
    pub algo: TotpAlgo,
    pub step: u64,
}

impl TotpSecret {
    /// <https://github.com/google/google-authenticator/wiki/Key-Uri-Format>
    pub fn to_uri(&self) -> String {
        // label = accountname / issuer (“:” / “%3A”) *”%20” accountname
        // This is already done server side but paranoia is good!
        let accountname = self
            .accountname
            .replace(':', "")
            .replace("%3A", "")
            .replace(' ', "%20");
        let issuer = self
            .issuer
            .replace(':', "")
            .replace("%3A", "")
            .replace(' ', "%20");
        let label = format!("{}:{}", issuer, accountname);
        let algo = self.algo.to_string();
        let secret = self.get_secret();
        let period = self.step;
        format!(
            "otpauth://totp/{}?secret={}&issuer={}&algorithm={}&digits=6&period={}",
            label, secret, issuer, algo, period
        )
    }

    pub fn get_secret(&self) -> String {
        base32::encode(base32::Alphabet::RFC4648 { padding: false }, &self.secret)
    }
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SetCredentialResponse {
    Success,
    Token(String),
    TotpCheck(Uuid, TotpSecret),
    TotpInvalidSha1(Uuid),
    WebauthnCreateChallenge(Uuid, CreationChallengeResponse),
    BackupCodes(Vec<String>),
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CUIntentToken {
    pub token: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CUSessionToken {
    pub token: String,
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CURequest {
    PrimaryRemove,
    Password(String),
    CancelMFAReg,
    TotpGenerate,
    TotpVerify(u32),
    TotpAcceptSha1,
    TotpRemove,
    BackupCodeGenerate,
    BackupCodeRemove,
}

impl fmt::Debug for CURequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let t = match self {
            CURequest::PrimaryRemove => "CURequest::PrimaryRemove",
            CURequest::Password(_) => "CURequest::Password",
            CURequest::CancelMFAReg => "CURequest::CancelMFAReg",
            CURequest::TotpGenerate => "CURequest::TotpGenerate",
            CURequest::TotpVerify(_) => "CURequest::TotpVerify",
            CURequest::TotpAcceptSha1 => "CURequest::TotpAcceptSha1",
            CURequest::TotpRemove => "CURequest::TotpRemove",
            CURequest::BackupCodeGenerate => "CURequest::BackupCodeGenerate",
            CURequest::BackupCodeRemove => "CURequest::BackupCodeRemove",
        };
        writeln!(f, "{}", t)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CURegState {
    // Nothing in progress.
    None,
    TotpCheck(TotpSecret),
    TotpTryAgain,
    TotpInvalidSha1,
    BackupCodes(Vec<String>),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CUStatus {
    pub spn: String,
    pub displayname: String,
    pub can_commit: bool,
    pub primary: Option<CredentialDetail>,
    pub mfaregstate: CURegState,
}

/* Recycle Requests area */

// Only two actions on recycled is possible. Search and Revive.

/*
pub struct SearchRecycledRequest {
    pub filter: Filter,
}

impl SearchRecycledRequest {
    pub fn new(filter: Filter) -> Self {
        SearchRecycledRequest { filter }
    }
}
*/

// Need a search response here later.

/*
pub struct ReviveRecycledRequest {
    pub filter: Filter,
}

impl ReviveRecycledRequest {
    pub fn new(filter: Filter) -> Self {
        ReviveRecycledRequest { filter }
    }
}
*/

// This doesn't need seralise because it's only accessed via a "get".
/*
#[derive(Debug, Default)]
pub struct WhoamiRequest {}

impl WhoamiRequest {
    pub fn new() -> Self {
        Default::default()
    }
}
*/

#[derive(Debug, Serialize, Deserialize)]
pub struct WhoamiResponse {
    // Should we just embed the entry? Or destructure it?
    pub youare: Entry,
    pub uat: UserAuthToken,
}

impl WhoamiResponse {
    pub fn new(e: Entry, uat: UserAuthToken) -> Self {
        WhoamiResponse { youare: e, uat }
    }
}

// Simple string value provision.
#[derive(Debug, Serialize, Deserialize)]
pub struct SingleStringRequest {
    pub value: String,
}

impl SingleStringRequest {
    pub fn new(s: String) -> Self {
        SingleStringRequest { value: s }
    }
}
// Use OperationResponse here ...

#[cfg(test)]
mod tests {
    use crate::v1::Filter as ProtoFilter;
    use crate::v1::{TotpAlgo, TotpSecret};

    #[test]
    fn test_protofilter_simple() {
        let pf: ProtoFilter = ProtoFilter::Pres("class".to_string());

        println!("{:?}", serde_json::to_string(&pf).expect("JSON failure"));
    }

    #[test]
    fn totp_to_string() {
        let totp = TotpSecret {
            accountname: "william".to_string(),
            issuer: "blackhats".to_string(),
            secret: vec![0xaa, 0xbb, 0xcc, 0xdd],
            step: 30,
            algo: TotpAlgo::Sha256,
        };
        let s = totp.to_uri();
        assert!(s == "otpauth://totp/blackhats:william?secret=VK54ZXI&issuer=blackhats&algorithm=SHA256&digits=6&period=30");

        // check that invalid issuer/accounts are cleaned up.
        let totp = TotpSecret {
            accountname: "william:%3A".to_string(),
            issuer: "blackhats australia".to_string(),
            secret: vec![0xaa, 0xbb, 0xcc, 0xdd],
            step: 30,
            algo: TotpAlgo::Sha256,
        };
        let s = totp.to_uri();
        assert!(s == "otpauth://totp/blackhats%20australia:william?secret=VK54ZXI&issuer=blackhats%20australia&algorithm=SHA256&digits=6&period=30");
    }
}