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
22pub 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)]
71pub struct Credential {
83 pub(crate) type_: CredentialType,
85 pub(crate) uuid: Uuid,
88 timestamp: OffsetDateTime,
91}
92
93#[derive(Clone, Debug, PartialEq)]
94pub enum CredentialType {
99 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 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 let timestamp = value.last_changed_timestamp();
146
147 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 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 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 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 let mut cred = self.update_password(pw, self.timestamp);
462 cred.uuid = self.uuid;
463
464 Ok(Some(cred))
465 } else {
466 Ok(None)
468 }
469 }
470
471 #[cfg(test)] 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 CredentialType::Webauthn(map) => CredentialType::Webauthn(map.clone()),
497 };
498
499 Ok(Credential {
501 type_,
502 uuid: Uuid::new_v4(),
504 timestamp: self.timestamp,
506 })
507 }
508
509 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 CredentialType::Password(pw.clone())
541 }
542 } else {
543 CredentialType::PasswordMfa(pw.clone(), totp.clone(), nmap, backup_code.clone())
544 }
545 }
546 };
547
548 Ok(Credential {
550 type_,
551 uuid: Uuid::new_v4(),
553 timestamp,
555 })
556 }
557
558 #[allow(clippy::ptr_arg)]
559 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 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 uuid: Uuid::new_v4(),
593 timestamp: self.timestamp,
594 }))
595 }
596
597 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 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 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 CredentialType::Webauthn(wan) => CredentialType::Webauthn(wan.clone()),
691 };
692 Credential {
693 type_,
694 uuid: Uuid::new_v4(),
696 timestamp,
698 }
699 }
700
701 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 uuid: Uuid::new_v4(),
728 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 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 uuid: Uuid::new_v4(),
753 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 if !totp.is_empty() {
789 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 uuid: Uuid::new_v4(),
821 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 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 uuid: Uuid::new_v4(),
867 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() }
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 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 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 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 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 assert_eq!(original_uuid, upgraded_cred.uuid);
986 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 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 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 assert!(cred_with_backup.timestamp > mfa_timestamp);
1021 assert_ne!(mfa_cred.uuid, cred_with_backup.uuid);
1022
1023 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 assert!(cred_removed_backup.timestamp > cred_with_backup.timestamp);
1030 assert_ne!(cred_with_backup.uuid, cred_removed_backup.uuid);
1031 }
1032}