Skip to main content

kanidmd_lib/credential/
mod.rs

1use std::convert::TryFrom;
2
3use hashbrown::{HashMap, HashSet};
4use kanidm_proto::internal::{CredentialDetail, CredentialDetailType, OperationError};
5use time::OffsetDateTime;
6use uuid::Uuid;
7use webauthn_rs::prelude::{AuthenticationResult, Passkey, SecurityKey};
8use webauthn_rs_core::proto::{Credential as WebauthnCredential, CredentialV3};
9
10use crate::be::dbvalue::{DbBackupCodeV1, DbCred};
11
12pub mod apppwd;
13pub mod softlock;
14pub mod totp;
15
16use self::totp::TOTP_DEFAULT_STEP;
17
18use kanidm_lib_crypto::CryptoPolicy;
19
20use crate::credential::{softlock::CredSoftLockPolicy, totp::Totp};
21
22// These are in order of "relative" strength.
23/*
24#[derive(Clone, Debug)]
25pub enum Policy {
26    PasswordOnly,
27    WebauthnOnly,
28    GeneratedPassword,
29    PasswordAndWebauthn,
30}
31*/
32
33pub use kanidm_lib_crypto::Password;
34
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct BackupCodes {
37    code_set: HashSet<String>,
38}
39
40impl TryFrom<DbBackupCodeV1> for BackupCodes {
41    type Error = ();
42
43    fn try_from(value: DbBackupCodeV1) -> Result<Self, Self::Error> {
44        Ok(BackupCodes {
45            code_set: value.code_set,
46        })
47    }
48}
49
50impl BackupCodes {
51    pub fn new(code_set: HashSet<String>) -> Self {
52        BackupCodes { code_set }
53    }
54
55    pub fn verify(&self, code_chal: &str) -> bool {
56        self.code_set.contains(code_chal)
57    }
58
59    pub fn remove(&mut self, code_chal: &str) -> bool {
60        self.code_set.remove(code_chal)
61    }
62
63    pub fn to_dbbackupcodev1(&self) -> DbBackupCodeV1 {
64        DbBackupCodeV1 {
65            code_set: self.code_set.clone(),
66        }
67    }
68}
69
70#[derive(Clone, Debug, PartialEq)]
71/// This is how we store credentials in the server. An account can have many credentials, and
72/// a credential can have many factors. Only successful auth to a credential as a whole unit
73/// will succeed. For example:
74/// A: Credential { password: aaa }
75/// B: Credential { password: bbb, otp: ... }
76/// In this case, if we selected credential B, and then provided password "aaa" we would deny
77/// the auth as the password of B was incorrect. Additionally, while A only needs the "password",
78/// B requires both the password and otp to be valid.
79///
80/// In this way, each Credential provides its own password requirements and policy, and requires
81/// some metadata to support this such as it's source and strength etc.
82pub struct Credential {
83    // policy: Policy,
84    pub(crate) type_: CredentialType,
85    // Uuid of Credential, used by auth session to lock this specific credential
86    // if required.
87    pub(crate) uuid: Uuid,
88    // TODO #59: Add auth policy IE validUntil, lock state ...
89    // locked: bool
90    timestamp: OffsetDateTime,
91}
92
93#[derive(Clone, Debug, PartialEq)]
94/// The type of credential that is stored. Each of these represents a full set of 'what is required'
95/// to complete an authentication session. The reason to have these typed like this is so we can
96/// apply policy later to what classes or levels of credentials can be used. We use these types
97/// to also know what type of auth session handler to initiate.
98pub enum CredentialType {
99    // Anonymous,
100    Password(Password),
101    GeneratedPassword(Password),
102    PasswordMfa(
103        Password,
104        HashMap<String, Totp>,
105        HashMap<String, SecurityKey>,
106        Option<BackupCodes>,
107    ),
108    Webauthn(HashMap<String, Passkey>),
109}
110
111impl From<&Credential> for CredentialDetail {
112    fn from(value: &Credential) -> Self {
113        CredentialDetail {
114            uuid: value.uuid,
115            type_: match &value.type_ {
116                CredentialType::Password(_) => CredentialDetailType::Password,
117                CredentialType::GeneratedPassword(_) => CredentialDetailType::GeneratedPassword,
118                CredentialType::Webauthn(wan) => {
119                    let labels: Vec<_> = wan.keys().cloned().collect();
120                    CredentialDetailType::Passkey(labels)
121                }
122                CredentialType::PasswordMfa(_, totp, wan, backup_code) => {
123                    // Don't sort - we need these in order to match to what the user
124                    // sees so they can remove by index.
125                    let wan_labels: Vec<_> = wan.keys().cloned().collect();
126                    let totp_labels: Vec<_> = totp.keys().cloned().collect();
127
128                    CredentialDetailType::PasswordMfa(
129                        totp_labels,
130                        wan_labels,
131                        backup_code.as_ref().map(|c| c.code_set.len()).unwrap_or(0),
132                    )
133                }
134            },
135        }
136    }
137}
138
139impl TryFrom<DbCred> for Credential {
140    type Error = ();
141
142    fn try_from(value: DbCred) -> Result<Self, Self::Error> {
143        // We need to retrieve the timestamp here since not all DbCreds have one.
144        // All V1 creds will fall back to a default
145        let timestamp = value.last_changed_timestamp();
146
147        // Work out what the policy is?
148        match value {
149            DbCred::V2Password {
150                password: db_password,
151                uuid,
152                ..
153            }
154            | DbCred::Pw {
155                password: Some(db_password),
156                webauthn: _,
157                totp: _,
158                backup_code: _,
159                claims: _,
160                uuid,
161            } => {
162                let v_password = Password::try_from(db_password)?;
163                let type_ = CredentialType::Password(v_password);
164                if type_.is_valid() {
165                    Ok(Credential {
166                        type_,
167                        uuid,
168                        timestamp,
169                    })
170                } else {
171                    Err(())
172                }
173            }
174            DbCred::V2GenPassword {
175                password: db_password,
176                uuid,
177                ..
178            }
179            | DbCred::GPw {
180                password: Some(db_password),
181                webauthn: _,
182                totp: _,
183                backup_code: _,
184                claims: _,
185                uuid,
186            } => {
187                let v_password = Password::try_from(db_password)?;
188                let type_ = CredentialType::GeneratedPassword(v_password);
189                if type_.is_valid() {
190                    Ok(Credential {
191                        type_,
192                        uuid,
193                        timestamp,
194                    })
195                } else {
196                    Err(())
197                }
198            }
199            DbCred::PwMfa {
200                password: Some(db_password),
201                webauthn: maybe_db_webauthn,
202                totp,
203                backup_code,
204                claims: _,
205                uuid,
206            } => {
207                let v_password = Password::try_from(db_password)?;
208
209                let v_totp = match totp {
210                    Some(dbt) => {
211                        let l = "totp".to_string();
212                        let t = Totp::try_from(dbt)?;
213                        HashMap::from([(l, t)])
214                    }
215                    None => HashMap::default(),
216                };
217
218                let v_webauthn = match maybe_db_webauthn {
219                    Some(db_webauthn) => db_webauthn
220                        .into_iter()
221                        .map(|wc| {
222                            (
223                                wc.label,
224                                SecurityKey::from(WebauthnCredential::from(CredentialV3 {
225                                    cred_id: wc.id,
226                                    cred: wc.cred,
227                                    counter: wc.counter,
228                                    verified: wc.verified,
229                                    registration_policy: wc.registration_policy,
230                                })),
231                            )
232                        })
233                        .collect(),
234                    None => Default::default(),
235                };
236
237                let v_backup_code = match backup_code {
238                    Some(dbb) => Some(BackupCodes::try_from(dbb)?),
239                    None => None,
240                };
241
242                let type_ =
243                    CredentialType::PasswordMfa(v_password, v_totp, v_webauthn, v_backup_code);
244
245                if type_.is_valid() {
246                    Ok(Credential {
247                        type_,
248                        uuid,
249                        timestamp,
250                    })
251                } else {
252                    Err(())
253                }
254            }
255            DbCred::Wn {
256                password: _,
257                webauthn: Some(db_webauthn),
258                totp: _,
259                backup_code: _,
260                claims: _,
261                uuid,
262            } => {
263                let v_webauthn = db_webauthn
264                    .into_iter()
265                    .map(|wc| {
266                        (
267                            wc.label,
268                            Passkey::from(WebauthnCredential::from(CredentialV3 {
269                                cred_id: wc.id,
270                                cred: wc.cred,
271                                counter: wc.counter,
272                                verified: wc.verified,
273                                registration_policy: wc.registration_policy,
274                            })),
275                        )
276                    })
277                    .collect();
278
279                let type_ = CredentialType::Webauthn(v_webauthn);
280
281                if type_.is_valid() {
282                    Ok(Credential {
283                        type_,
284                        uuid,
285                        timestamp,
286                    })
287                } else {
288                    Err(())
289                }
290            }
291            DbCred::TmpWn {
292                webauthn: db_webauthn,
293                uuid,
294            } => {
295                let v_webauthn = db_webauthn.into_iter().collect();
296                let type_ = CredentialType::Webauthn(v_webauthn);
297
298                if type_.is_valid() {
299                    Ok(Credential {
300                        type_,
301                        uuid,
302                        timestamp,
303                    })
304                } else {
305                    Err(())
306                }
307            }
308            DbCred::V2PasswordMfa {
309                password: db_password,
310                totp: maybe_db_totp,
311                backup_code,
312                webauthn: db_webauthn,
313                uuid,
314            } => {
315                let v_password = Password::try_from(db_password)?;
316
317                let v_totp = match maybe_db_totp {
318                    Some(dbt) => {
319                        let l = "totp".to_string();
320                        let t = Totp::try_from(dbt)?;
321                        HashMap::from([(l, t)])
322                    }
323                    None => HashMap::default(),
324                };
325
326                let v_backup_code = match backup_code {
327                    Some(dbb) => Some(BackupCodes::try_from(dbb)?),
328                    None => None,
329                };
330
331                let v_webauthn = db_webauthn.into_iter().collect();
332
333                let type_ =
334                    CredentialType::PasswordMfa(v_password, v_totp, v_webauthn, v_backup_code);
335
336                if type_.is_valid() {
337                    Ok(Credential {
338                        type_,
339                        uuid,
340                        timestamp,
341                    })
342                } else {
343                    Err(())
344                }
345            }
346            DbCred::V3PasswordMfa {
347                password: db_password,
348                totp: db_totp,
349                backup_code,
350                webauthn: db_webauthn,
351                uuid,
352                ..
353            } => {
354                let v_password = Password::try_from(db_password)?;
355
356                let v_totp = db_totp
357                    .into_iter()
358                    .map(|(l, dbt)| Totp::try_from(dbt).map(|t| (l, t)))
359                    .collect::<Result<HashMap<_, _>, _>>()?;
360
361                let v_backup_code = match backup_code {
362                    Some(dbb) => Some(BackupCodes::try_from(dbb)?),
363                    None => None,
364                };
365
366                let v_webauthn = db_webauthn.into_iter().collect();
367
368                let type_ =
369                    CredentialType::PasswordMfa(v_password, v_totp, v_webauthn, v_backup_code);
370
371                if type_.is_valid() {
372                    Ok(Credential {
373                        type_,
374                        uuid,
375                        timestamp,
376                    })
377                } else {
378                    Err(())
379                }
380            }
381            credential => {
382                error!("Database content may be corrupt - invalid credential state");
383                debug!(%credential);
384                debug!(?credential);
385                Err(())
386            }
387        }
388    }
389}
390
391impl Credential {
392    pub fn timestamp(&self) -> OffsetDateTime {
393        self.timestamp
394    }
395
396    /// Create a new credential that contains a CredentialType::Password
397    pub fn new_password_only(
398        policy: &CryptoPolicy,
399        cleartext: &str,
400        timestamp: OffsetDateTime,
401    ) -> Result<Self, OperationError> {
402        Password::new(policy, cleartext)
403            .map_err(|e| {
404                error!(crypto_err = ?e);
405                OperationError::CryptographyError
406            })
407            .map(|password| Self::new_from_password(password, timestamp))
408    }
409
410    /// Create a new credential that contains a CredentialType::GeneratedPassword
411    pub fn new_generatedpassword_only(
412        policy: &CryptoPolicy,
413        cleartext: &str,
414        timestamp: OffsetDateTime,
415    ) -> Result<Self, OperationError> {
416        Password::new(policy, cleartext)
417            .map_err(|e| {
418                error!(crypto_err = ?e);
419                OperationError::CryptographyError
420            })
421            .map(|password| Self::new_from_generatedpassword(password, timestamp))
422    }
423
424    /// Update the state of the Password on this credential, if a password is present. If possible
425    /// this will convert the credential to a PasswordMFA in some cases, or fail in others.
426    pub fn set_password(
427        &self,
428        policy: &CryptoPolicy,
429        cleartext: &str,
430        timestamp: OffsetDateTime,
431    ) -> Result<Self, OperationError> {
432        Password::new(policy, cleartext)
433            .map_err(|e| {
434                error!(crypto_err = ?e);
435                OperationError::CryptographyError
436            })
437            .map(|pw| self.update_password(pw, timestamp))
438    }
439
440    pub fn upgrade_password(
441        &self,
442        policy: &CryptoPolicy,
443        cleartext: &str,
444    ) -> Result<Option<Self>, OperationError> {
445        let valid = self.password_ref().and_then(|pw| {
446            pw.verify(cleartext).map_err(|e| {
447                error!(crypto_err = ?e);
448                OperationError::CryptographyError
449            })
450        })?;
451
452        if valid {
453            let pw = Password::new(policy, cleartext).map_err(|e| {
454                error!(crypto_err = ?e);
455                OperationError::CryptographyError
456            })?;
457
458            // Note, during update_password we normally rotate the uuid, here we
459            // set it back to our current value. This is because we are just
460            // updating the hash value, not actually changing the password itself.
461            let mut cred = self.update_password(pw, self.timestamp);
462            cred.uuid = self.uuid;
463
464            Ok(Some(cred))
465        } else {
466            // No updates needed, password has changed.
467            Ok(None)
468        }
469    }
470
471    /// Extend this credential with another alternate webauthn credential. This is especially
472    /// useful for `PasswordMfa` where you can have many webauthn credentials and a password
473    /// generally so that one is a backup.
474    #[cfg(test)] // This method isn't used outside of tests, Should we keep the cfg?
475    pub fn append_securitykey(
476        &self,
477        label: String,
478        cred: SecurityKey,
479    ) -> Result<Self, OperationError> {
480        let type_ = match &self.type_ {
481            CredentialType::Password(pw) | CredentialType::GeneratedPassword(pw) => {
482                let mut wan = HashMap::new();
483                wan.insert(label, cred);
484                CredentialType::PasswordMfa(pw.clone(), HashMap::default(), wan, None)
485            }
486            CredentialType::PasswordMfa(pw, totp, map, backup_code) => {
487                let mut nmap = map.clone();
488                if nmap.insert(label.clone(), cred).is_some() {
489                    return Err(OperationError::InvalidAttribute(format!(
490                        "Webauthn label '{label:?}' already exists"
491                    )));
492                }
493                CredentialType::PasswordMfa(pw.clone(), totp.clone(), nmap, backup_code.clone())
494            }
495            // Ignore
496            CredentialType::Webauthn(map) => CredentialType::Webauthn(map.clone()),
497        };
498
499        // Check stuff
500        Ok(Credential {
501            type_,
502            // Rotate the credential id on any change to invalidate sessions.
503            uuid: Uuid::new_v4(),
504            // Update the timestamp to signify a changed credential
505            timestamp: self.timestamp,
506        })
507    }
508
509    /// Remove a webauthn token identified by `label` from this Credential.
510    pub fn remove_securitykey(
511        &self,
512        label: &str,
513        timestamp: OffsetDateTime,
514    ) -> Result<Self, OperationError> {
515        let type_ = match &self.type_ {
516            CredentialType::Password(_)
517            | CredentialType::GeneratedPassword(_)
518            | CredentialType::Webauthn(_) => {
519                return Err(OperationError::InvalidAttribute(
520                    "SecurityKey is not present on this credential".to_string(),
521                ));
522            }
523            CredentialType::PasswordMfa(pw, totp, map, backup_code) => {
524                let mut nmap = map.clone();
525                if nmap.remove(label).is_none() {
526                    return Err(OperationError::InvalidAttribute(format!(
527                        "Removing Webauthn token with label '{label:?}': does not exist"
528                    )));
529                }
530                if nmap.is_empty() {
531                    if !totp.is_empty() {
532                        CredentialType::PasswordMfa(
533                            pw.clone(),
534                            totp.clone(),
535                            nmap,
536                            backup_code.clone(),
537                        )
538                    } else {
539                        // Note: No need to keep backup code if it is no longer MFA
540                        CredentialType::Password(pw.clone())
541                    }
542                } else {
543                    CredentialType::PasswordMfa(pw.clone(), totp.clone(), nmap, backup_code.clone())
544                }
545            }
546        };
547
548        // Check stuff
549        Ok(Credential {
550            type_,
551            // Rotate the credential id on any change to invalidate sessions.
552            uuid: Uuid::new_v4(),
553            // Update the timestamp to signify a changed credential
554            timestamp,
555        })
556    }
557
558    #[allow(clippy::ptr_arg)]
559    /// After a successful authentication with Webauthn, we need to advance the credentials
560    /// counter value to prevent certain classes of replay attacks.
561    pub fn update_webauthn_properties(
562        &self,
563        auth_result: &AuthenticationResult,
564    ) -> Result<Option<Self>, OperationError> {
565        let type_ = match &self.type_ {
566            CredentialType::Password(_pw) | CredentialType::GeneratedPassword(_pw) => {
567                // Should not be possible!
568                // -- this does occur when we have mixed pw/passkey
569                // and we need to do an update, so we just mask this no Ok(None).
570                // return Err(OperationError::InvalidState);
571                return Ok(None);
572            }
573            CredentialType::Webauthn(map) => {
574                let mut nmap = map.clone();
575                nmap.values_mut().for_each(|pk| {
576                    pk.update_credential(auth_result);
577                });
578                CredentialType::Webauthn(nmap)
579            }
580            CredentialType::PasswordMfa(pw, totp, map, backup_code) => {
581                let mut nmap = map.clone();
582                nmap.values_mut().for_each(|sk| {
583                    sk.update_credential(auth_result);
584                });
585                CredentialType::PasswordMfa(pw.clone(), totp.clone(), nmap, backup_code.clone())
586            }
587        };
588
589        Ok(Some(Credential {
590            type_,
591            // Rotate the credential id on any change to invalidate sessions.
592            uuid: Uuid::new_v4(),
593            timestamp: self.timestamp,
594        }))
595    }
596
597    /// Get a reference to the contained webuthn credentials, if any.
598    pub fn securitykey_ref(&self) -> Result<&HashMap<String, SecurityKey>, OperationError> {
599        match &self.type_ {
600            CredentialType::Webauthn(_)
601            | CredentialType::Password(_)
602            | CredentialType::GeneratedPassword(_) => Err(OperationError::InvalidAccountState(
603                "non-webauthn cred type?".to_string(),
604            )),
605            CredentialType::PasswordMfa(_, _, map, _) => Ok(map),
606        }
607    }
608
609    pub fn passkey_ref(&self) -> Result<&HashMap<String, Passkey>, OperationError> {
610        match &self.type_ {
611            CredentialType::PasswordMfa(_, _, _, _)
612            | CredentialType::Password(_)
613            | CredentialType::GeneratedPassword(_) => Err(OperationError::InvalidAccountState(
614                "non-webauthn cred type?".to_string(),
615            )),
616            CredentialType::Webauthn(map) => Ok(map),
617        }
618    }
619
620    /// Get a reference to the contained password, if any.
621    pub fn password_ref(&self) -> Result<&Password, OperationError> {
622        match &self.type_ {
623            CredentialType::Password(pw)
624            | CredentialType::GeneratedPassword(pw)
625            | CredentialType::PasswordMfa(pw, _, _, _) => Ok(pw),
626            CredentialType::Webauthn(_) => Err(OperationError::InvalidAccountState(
627                "non-password cred type?".to_string(),
628            )),
629        }
630    }
631
632    pub fn is_mfa(&self) -> bool {
633        match &self.type_ {
634            CredentialType::Password(_) | CredentialType::GeneratedPassword(_) => false,
635            CredentialType::PasswordMfa(..) | CredentialType::Webauthn(_) => true,
636        }
637    }
638
639    #[cfg(test)]
640    pub fn verify_password(&self, cleartext: &str) -> Result<bool, OperationError> {
641        self.password_ref().and_then(|pw| {
642            pw.verify(cleartext).map_err(|e| {
643                error!(crypto_err = ?e);
644                OperationError::CryptographyError
645            })
646        })
647    }
648
649    /// Extract this credential into it's Serialisable Database form, ready for persistence.
650    pub fn to_db_valuev1(&self) -> DbCred {
651        let uuid = self.uuid;
652        match &self.type_ {
653            CredentialType::Password(pw) => DbCred::V2Password {
654                password: pw.to_dbpasswordv1(),
655                uuid,
656                timestamp: self.timestamp,
657            },
658            CredentialType::GeneratedPassword(pw) => DbCred::V2GenPassword {
659                password: pw.to_dbpasswordv1(),
660                uuid,
661                timestamp: self.timestamp,
662            },
663            CredentialType::PasswordMfa(pw, totp, map, backup_code) => DbCred::V3PasswordMfa {
664                password: pw.to_dbpasswordv1(),
665                totp: totp
666                    .iter()
667                    .map(|(l, t)| (l.clone(), t.to_dbtotpv1()))
668                    .collect(),
669                backup_code: backup_code.as_ref().map(|b| b.to_dbbackupcodev1()),
670                webauthn: map.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
671                uuid,
672                timestamp: self.timestamp,
673            },
674            CredentialType::Webauthn(map) => DbCred::TmpWn {
675                webauthn: map.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
676                uuid,
677            },
678        }
679    }
680
681    pub(crate) fn update_password(&self, pw: Password, timestamp: OffsetDateTime) -> Self {
682        let type_ = match &self.type_ {
683            CredentialType::Password(_) | CredentialType::GeneratedPassword(_) => {
684                CredentialType::Password(pw)
685            }
686            CredentialType::PasswordMfa(_, totp, wan, backup_code) => {
687                CredentialType::PasswordMfa(pw, totp.clone(), wan.clone(), backup_code.clone())
688            }
689            // Ignore
690            CredentialType::Webauthn(wan) => CredentialType::Webauthn(wan.clone()),
691        };
692        Credential {
693            type_,
694            // Rotate the credential id on any change to invalidate sessions.
695            uuid: Uuid::new_v4(),
696            // Update the timestamp to signify a changed credential
697            timestamp,
698        }
699    }
700
701    // We don't make totp accessible from outside the crate for now.
702    pub(crate) fn append_totp(&self, label: String, totp: Totp, timestamp: OffsetDateTime) -> Self {
703        let type_ = match &self.type_ {
704            CredentialType::Password(pw) | CredentialType::GeneratedPassword(pw) => {
705                CredentialType::PasswordMfa(
706                    pw.clone(),
707                    HashMap::from([(label, totp)]),
708                    HashMap::new(),
709                    None,
710                )
711            }
712            CredentialType::PasswordMfa(pw, totps, wan, backup_code) => {
713                let mut totps = totps.clone();
714                let replaced = totps.insert(label, totp).is_none();
715                debug_assert!(replaced);
716
717                CredentialType::PasswordMfa(pw.clone(), totps, wan.clone(), backup_code.clone())
718            }
719            CredentialType::Webauthn(wan) => {
720                debug_assert!(false);
721                CredentialType::Webauthn(wan.clone())
722            }
723        };
724        Credential {
725            type_,
726            // Rotate the credential id on any change to invalidate sessions.
727            uuid: Uuid::new_v4(),
728            // Update the timestamp to signify a changed credential
729            timestamp,
730        }
731    }
732
733    pub(crate) fn remove_totp(&self, label: &str, timestamp: OffsetDateTime) -> Self {
734        let type_ = match &self.type_ {
735            CredentialType::PasswordMfa(pw, totp, wan, backup_code) => {
736                let mut totp = totp.clone();
737                let removed = totp.remove(label).is_some();
738                debug_assert!(removed);
739
740                if wan.is_empty() && totp.is_empty() {
741                    // Note: No need to keep backup code if it is no longer MFA
742                    CredentialType::Password(pw.clone())
743                } else {
744                    CredentialType::PasswordMfa(pw.clone(), totp, wan.clone(), backup_code.clone())
745                }
746            }
747            _ => self.type_.clone(),
748        };
749        Credential {
750            type_,
751            // Rotate the credential id on any change to invalidate sessions.
752            uuid: Uuid::new_v4(),
753            // Update the timestamp to signify a changed credential
754            timestamp,
755        }
756    }
757
758    pub(crate) fn has_totp_by_name(&self, label: &str) -> bool {
759        match &self.type_ {
760            CredentialType::PasswordMfa(_, totp, _, _) => totp.contains_key(label),
761            _ => false,
762        }
763    }
764
765    pub(crate) fn new_from_generatedpassword(pw: Password, timestamp: OffsetDateTime) -> Self {
766        Credential {
767            type_: CredentialType::GeneratedPassword(pw),
768            uuid: Uuid::new_v4(),
769            timestamp,
770        }
771    }
772
773    pub(crate) fn new_from_password(pw: Password, timestamp: OffsetDateTime) -> Self {
774        Credential {
775            type_: CredentialType::Password(pw),
776            uuid: Uuid::new_v4(),
777            timestamp,
778        }
779    }
780
781    pub(crate) fn softlock_policy(&self) -> CredSoftLockPolicy {
782        match &self.type_ {
783            CredentialType::Password(_pw) | CredentialType::GeneratedPassword(_pw) => {
784                CredSoftLockPolicy::Password
785            }
786            CredentialType::PasswordMfa(_pw, totp, wan, _) => {
787                // For backup code, use totp/wan policy (whatever is available)
788                if !totp.is_empty() {
789                    // What's the min step?
790                    let min_step = totp
791                        .iter()
792                        .map(|(_, t)| t.step)
793                        .min()
794                        .unwrap_or(TOTP_DEFAULT_STEP);
795                    CredSoftLockPolicy::Totp(min_step)
796                } else if !wan.is_empty() {
797                    CredSoftLockPolicy::Webauthn
798                } else {
799                    CredSoftLockPolicy::Password
800                }
801            }
802            CredentialType::Webauthn(_wan) => CredSoftLockPolicy::Webauthn,
803        }
804    }
805
806    pub(crate) fn update_backup_code(
807        &self,
808        backup_codes: BackupCodes,
809        timestamp: OffsetDateTime,
810    ) -> Result<Self, OperationError> {
811        match &self.type_ {
812            CredentialType::PasswordMfa(pw, totp, wan, _) => Ok(Credential {
813                type_: CredentialType::PasswordMfa(
814                    pw.clone(),
815                    totp.clone(),
816                    wan.clone(),
817                    Some(backup_codes),
818                ),
819                // Rotate the credential id on any change to invalidate sessions.
820                uuid: Uuid::new_v4(),
821                // Update the timestamp to signify a changed credential
822                timestamp,
823            }),
824            _ => Err(OperationError::InvalidAccountState(
825                "Non-MFA credential type".to_string(),
826            )),
827        }
828    }
829
830    pub(crate) fn invalidate_backup_code(
831        self,
832        code_to_remove: &str,
833    ) -> Result<Self, OperationError> {
834        match self.type_ {
835            CredentialType::PasswordMfa(pw, totp, wan, opt_backup_codes) => {
836                match opt_backup_codes {
837                    Some(mut backup_codes) => {
838                        backup_codes.remove(code_to_remove);
839                        Ok(Credential {
840                            type_: CredentialType::PasswordMfa(pw, totp, wan, Some(backup_codes)),
841                            // Don't rotate uuid here since this is a consumption of a backup
842                            // code.
843                            uuid: self.uuid,
844                            timestamp: self.timestamp,
845                        })
846                    }
847                    _ => Err(OperationError::InvalidAccountState(
848                        "backup code does not exist".to_string(),
849                    )),
850                }
851            }
852            _ => Err(OperationError::InvalidAccountState(
853                "Non-MFA credential type".to_string(),
854            )),
855        }
856    }
857
858    pub(crate) fn remove_backup_code(
859        &self,
860        timestamp: OffsetDateTime,
861    ) -> Result<Self, OperationError> {
862        match &self.type_ {
863            CredentialType::PasswordMfa(pw, totp, wan, _) => Ok(Credential {
864                type_: CredentialType::PasswordMfa(pw.clone(), totp.clone(), wan.clone(), None),
865                // Rotate the credential id on any change to invalidate sessions.
866                uuid: Uuid::new_v4(),
867                // Update the timestamp to signify a changed credential
868                timestamp,
869            }),
870            _ => Err(OperationError::InvalidAccountState(
871                "Non-MFA credential type".to_string(),
872            )),
873        }
874    }
875}
876
877impl CredentialType {
878    fn is_valid(&self) -> bool {
879        match self {
880            CredentialType::Password(_) | CredentialType::GeneratedPassword(_) => true,
881            CredentialType::PasswordMfa(_, m_totp, webauthn, _) => {
882                !m_totp.is_empty() || !webauthn.is_empty() // ignore backup code (it should only be a complement for totp/webauth)
883            }
884            CredentialType::Webauthn(webauthn) => !webauthn.is_empty(),
885        }
886    }
887}
888
889#[cfg(test)]
890mod tests {
891    use std::time::Duration;
892
893    use crate::credential::{
894        totp::{Totp, TOTP_DEFAULT_STEP},
895        Credential,
896    };
897    use kanidm_lib_crypto::{CryptoPolicy, Password};
898    use time::OffsetDateTime;
899
900    #[test]
901    fn test_credential_timestamp_updated_on_totp_append() {
902        let pw = Password::new(&CryptoPolicy::minimum(), "test_password")
903            .expect("Failed to create password");
904        let original_cred = Credential::new_from_password(pw, OffsetDateTime::UNIX_EPOCH);
905        let original_timestamp = original_cred.timestamp;
906
907        let totp = Totp::generate_secure(TOTP_DEFAULT_STEP);
908        let updated_cred = original_cred.append_totp(
909            "test_totp".to_string(),
910            totp,
911            OffsetDateTime::UNIX_EPOCH + Duration::from_millis(10),
912        );
913
914        // Verify timestamp was updated
915        assert!(updated_cred.timestamp > original_timestamp);
916        assert_ne!(original_cred.uuid, updated_cred.uuid);
917    }
918
919    #[test]
920    fn test_credential_timestamp_updated_on_totp_remove() {
921        let pw = Password::new(&CryptoPolicy::minimum(), "test_password")
922            .expect("Failed to create password");
923        let cred = Credential::new_from_password(pw, OffsetDateTime::UNIX_EPOCH);
924
925        let totp = Totp::generate_secure(TOTP_DEFAULT_STEP);
926        let cred_with_totp = cred.append_totp(
927            "test_totp".to_string(),
928            totp,
929            OffsetDateTime::UNIX_EPOCH + Duration::from_millis(10),
930        );
931        let timestamp_after_append = cred_with_totp.timestamp;
932
933        let cred_removed = cred_with_totp.remove_totp(
934            "test_totp",
935            OffsetDateTime::UNIX_EPOCH + Duration::from_millis(20),
936        );
937
938        // Verify timestamp was updated
939        assert!(cred_removed.timestamp > timestamp_after_append);
940        assert_ne!(cred_with_totp.uuid, cred_removed.uuid);
941    }
942
943    #[test]
944    fn test_credential_timestamp_updated_on_password_change() {
945        let original_cred = Credential::new_password_only(
946            &CryptoPolicy::minimum(),
947            "original_password",
948            OffsetDateTime::UNIX_EPOCH,
949        )
950        .expect("Failed to create credential");
951        let original_timestamp = original_cred.timestamp;
952
953        let updated_cred = original_cred
954            .set_password(
955                &CryptoPolicy::minimum(),
956                "new_password",
957                OffsetDateTime::UNIX_EPOCH + Duration::from_millis(10),
958            )
959            .expect("Failed to update password");
960
961        // Verify timestamp was updated
962        assert!(updated_cred.timestamp > original_timestamp);
963        assert_ne!(original_cred.uuid, updated_cred.uuid);
964    }
965
966    #[test]
967    fn test_credential_timestamp_preserved_on_password_upgrade() {
968        let original_cred = Credential::new_password_only(
969            &CryptoPolicy::minimum(),
970            "test_password",
971            OffsetDateTime::UNIX_EPOCH,
972        )
973        .expect("Failed to create credential");
974        let original_timestamp = original_cred.timestamp;
975        let original_uuid = original_cred.uuid;
976
977        // Password upgrade should preserve UUID and timestamp since it's just
978        // updating the hash algorithm, not actually changing the password
979        let maybe_upgraded = original_cred
980            .upgrade_password(&CryptoPolicy::minimum(), "test_password")
981            .expect("Failed to upgrade password");
982
983        if let Some(upgraded_cred) = maybe_upgraded {
984            // UUID should be preserved during upgrade (unlike other operations)
985            assert_eq!(original_uuid, upgraded_cred.uuid);
986            // Timestamp should be updated to reflect the upgrade
987            assert!(upgraded_cred.timestamp >= original_timestamp);
988        }
989    }
990
991    #[test]
992    fn test_credential_timestamp_on_mfa_operations() {
993        use crate::credential::BackupCodes;
994        use hashbrown::HashSet;
995
996        let pw = Password::new(&CryptoPolicy::minimum(), "test_password")
997            .expect("Failed to create password");
998        let cred = Credential::new_from_password(pw, OffsetDateTime::UNIX_EPOCH);
999
1000        // Add TOTP to make it MFA
1001        let totp = Totp::generate_secure(TOTP_DEFAULT_STEP);
1002        let mfa_cred = cred.append_totp(
1003            "test_totp".to_string(),
1004            totp,
1005            OffsetDateTime::UNIX_EPOCH + Duration::from_millis(10),
1006        );
1007        let mfa_timestamp = mfa_cred.timestamp;
1008
1009        // Add backup codes
1010        let backup_codes =
1011            BackupCodes::new(HashSet::from(["code1".to_string(), "code2".to_string()]));
1012        let cred_with_backup = mfa_cred
1013            .update_backup_code(
1014                backup_codes,
1015                OffsetDateTime::UNIX_EPOCH + Duration::from_millis(20),
1016            )
1017            .expect("Failed to add backup codes");
1018
1019        // Verify timestamp was updated
1020        assert!(cred_with_backup.timestamp > mfa_timestamp);
1021        assert_ne!(mfa_cred.uuid, cred_with_backup.uuid);
1022
1023        // Remove backup codes
1024        let cred_removed_backup = cred_with_backup
1025            .remove_backup_code(OffsetDateTime::UNIX_EPOCH + Duration::from_millis(30))
1026            .expect("Failed to remove backup codes");
1027
1028        // Verify timestamp was updated again
1029        assert!(cred_removed_backup.timestamp > cred_with_backup.timestamp);
1030        assert_ne!(cred_with_backup.uuid, cred_removed_backup.uuid);
1031    }
1032}