1use super::accountpolicy::ResolvedAccountPolicy;
2use crate::{
3 credential::{
4 totp::{Totp, TOTP_DEFAULT_STEP},
5 BackupCodes, Credential,
6 },
7 idm::{
8 account::Account,
9 server::{IdmServerCredUpdateTransaction, IdmServerProxyWriteTransaction},
10 },
11 prelude::*,
12 server::access::Access,
13 utils::{backup_code_from_random, readable_password_from_random, utf8_len, uuid_from_duration},
14 value::{CredUpdateSessionPerms, CredentialType, IntentTokenState, LABEL_RE},
15};
16use compact_jwt::{compact::JweCompact, jwe::JweBuilder};
17use core::ops::Deref;
18use hashbrown::HashSet;
19use kanidm_proto::{
20 internal::{
21 CUCredState, CUExtPortal, CURegState, CURegWarning, CUStatus, CredentialDetail,
22 PasskeyDetail, PasswordFeedback, TotpSecret,
23 },
24 v1::OutboundMessage,
25};
26use serde::{Deserialize, Serialize};
27use sshkey_attest::proto::PublicKey as SshPublicKey;
28use std::{
29 collections::BTreeMap,
30 fmt::{self, Display},
31 sync::{Arc, Mutex},
32 time::Duration,
33};
34use time::OffsetDateTime;
35use webauthn_rs::prelude::{
36 AttestedPasskey as AttestedPasskeyV4, AttestedPasskeyRegistration, CreationChallengeResponse,
37 Passkey as PasskeyV4, PasskeyRegistration, RegisterPublicKeyCredential, WebauthnError,
38};
39use zxcvbn::{zxcvbn, Score};
40
41const MAXIMUM_CRED_UPDATE_TTL: Duration = Duration::from_secs(900);
44const MINIMUM_INTENT_TTL: Duration = Duration::from_secs(300);
46const DEFAULT_INTENT_TTL: Duration = Duration::from_secs(3600);
48const MAXIMUM_INTENT_TTL: Duration = Duration::from_secs(86400);
50
51#[derive(Debug)]
52pub enum PasswordQuality {
53 TooShort(u32),
54 TooLong(u32),
55 BadListed,
56 DontReusePasswords,
57 Feedback(Vec<PasswordFeedback>),
58}
59
60#[derive(Clone, Debug)]
61pub struct CredentialUpdateIntentToken {
62 pub intent_id: String,
63 pub expiry_time: OffsetDateTime,
64}
65
66#[derive(Clone, Debug)]
67pub struct CredentialUpdateIntentTokenExchange {
68 pub intent_id: String,
69}
70
71impl From<CredentialUpdateIntentToken> for CredentialUpdateIntentTokenExchange {
72 fn from(tok: CredentialUpdateIntentToken) -> Self {
73 CredentialUpdateIntentTokenExchange {
74 intent_id: tok.intent_id,
75 }
76 }
77}
78
79#[derive(Serialize, Deserialize, Debug)]
80struct CredentialUpdateSessionTokenInner {
81 pub sessionid: Uuid,
82 pub max_ttl: Duration,
84}
85
86#[derive(Debug)]
87pub struct CredentialUpdateSessionToken {
88 pub token_enc: JweCompact,
89}
90
91#[derive(Clone)]
93enum MfaRegState {
94 None,
95 TotpInit(Totp),
96 TotpTryAgain(Totp),
97 TotpNameTryAgain(Totp, String),
98 TotpInvalidSha1(Totp, Totp, String),
99 Passkey(Box<CreationChallengeResponse>, PasskeyRegistration),
100 #[allow(dead_code)]
101 AttestedPasskey(Box<CreationChallengeResponse>, AttestedPasskeyRegistration),
102}
103
104impl fmt::Debug for MfaRegState {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 let t = match self {
107 MfaRegState::None => "MfaRegState::None",
108 MfaRegState::TotpInit(_) => "MfaRegState::TotpInit",
109 MfaRegState::TotpTryAgain(_) => "MfaRegState::TotpTryAgain",
110 MfaRegState::TotpNameTryAgain(_, _) => "MfaRegState::TotpNameTryAgain",
111 MfaRegState::TotpInvalidSha1(_, _, _) => "MfaRegState::TotpInvalidSha1",
112 MfaRegState::Passkey(_, _) => "MfaRegState::Passkey",
113 MfaRegState::AttestedPasskey(_, _) => "MfaRegState::AttestedPasskey",
114 };
115 write!(f, "{t}")
116 }
117}
118
119#[derive(Debug, Clone, Copy)]
120enum CredentialState {
121 Modifiable,
122 DeleteOnly,
123 AccessDeny,
124 PolicyDeny,
125 }
127
128impl From<CredentialState> for CUCredState {
129 fn from(val: CredentialState) -> CUCredState {
130 match val {
131 CredentialState::Modifiable => CUCredState::Modifiable,
132 CredentialState::DeleteOnly => CUCredState::DeleteOnly,
133 CredentialState::AccessDeny => CUCredState::AccessDeny,
134 CredentialState::PolicyDeny => CUCredState::PolicyDeny,
135 }
137 }
138}
139
140#[derive(Clone)]
141pub(crate) struct CredentialUpdateSession {
142 issuer: String,
143 account: Account,
145 resolved_account_policy: ResolvedAccountPolicy,
147 intent_token_id: Option<String>,
149
150 ext_cred_portal: CUExtPortal,
152
153 dirty: bool,
155
156 primary_state: CredentialState,
158 primary: Option<Credential>,
159
160 unixcred: Option<Credential>,
162 unixcred_state: CredentialState,
163
164 sshkeys: BTreeMap<String, SshPublicKey>,
166 sshkeys_state: CredentialState,
167
168 passkeys: BTreeMap<Uuid, (String, PasskeyV4)>,
170 passkeys_state: CredentialState,
171
172 attested_passkeys: BTreeMap<Uuid, (String, AttestedPasskeyV4)>,
174 attested_passkeys_state: CredentialState,
175
176 mfaregstate: MfaRegState,
178}
179
180impl fmt::Debug for CredentialUpdateSession {
181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 let primary: Option<CredentialDetail> = self.primary.as_ref().map(|c| c.into());
183 let passkeys: Vec<PasskeyDetail> = self
184 .passkeys
185 .iter()
186 .map(|(uuid, (tag, _pk))| PasskeyDetail {
187 tag: tag.clone(),
188 uuid: *uuid,
189 })
190 .collect();
191 let attested_passkeys: Vec<PasskeyDetail> = self
192 .attested_passkeys
193 .iter()
194 .map(|(uuid, (tag, _pk))| PasskeyDetail {
195 tag: tag.clone(),
196 uuid: *uuid,
197 })
198 .collect();
199 f.debug_struct("CredentialUpdateSession")
200 .field("account.spn", &self.account.spn())
201 .field("account.unix", &self.account.unix_extn().is_some())
202 .field("resolved_account_policy", &self.resolved_account_policy)
203 .field("intent_token_id", &self.intent_token_id)
204 .field("primary.detail()", &primary)
205 .field("primary.state", &self.primary_state)
206 .field("passkeys.list()", &passkeys)
207 .field("passkeys.state", &self.passkeys_state)
208 .field("attested_passkeys.list()", &attested_passkeys)
209 .field("attested_passkeys.state", &self.attested_passkeys_state)
210 .field("mfaregstate", &self.mfaregstate)
211 .finish()
212 }
213}
214
215impl CredentialUpdateSession {
216 fn can_commit(&self) -> (bool, Vec<CredentialUpdateSessionStatusWarnings>) {
218 let mut warnings = Vec::with_capacity(0);
219 let mut can_commit = true;
220
221 let cred_type_min = self.resolved_account_policy.credential_policy();
222
223 debug!(?cred_type_min);
224
225 match cred_type_min {
226 CredentialType::Any => {}
227 CredentialType::External | CredentialType::Mfa => {
228 if self
229 .primary
230 .as_ref()
231 .map(|cred| !cred.is_mfa())
232 .unwrap_or(false)
235 {
236 can_commit = false;
237 warnings.push(CredentialUpdateSessionStatusWarnings::MfaRequired);
238 }
239 }
240 CredentialType::Passkey => {
241 if self.primary.is_some() {
244 can_commit = false;
245 warnings.push(CredentialUpdateSessionStatusWarnings::PasskeyRequired);
246 }
247 }
248 CredentialType::AttestedPasskey => {
249 if !self.passkeys.is_empty() || self.primary.is_some() {
251 can_commit = false;
252 warnings.push(CredentialUpdateSessionStatusWarnings::AttestedPasskeyRequired);
253 }
254 }
255 CredentialType::AttestedResidentkey => {
256 if !self.attested_passkeys.is_empty()
258 || !self.passkeys.is_empty()
259 || self.primary.is_some()
260 {
261 can_commit = false;
262 warnings
263 .push(CredentialUpdateSessionStatusWarnings::AttestedResidentKeyRequired);
264 }
265 }
266 CredentialType::Invalid => {
267 can_commit = false;
269 warnings.push(CredentialUpdateSessionStatusWarnings::Unsatisfiable)
270 }
271 }
272
273 if let Some(att_ca_list) = self.resolved_account_policy.webauthn_attestation_ca_list() {
274 if att_ca_list.is_empty() {
275 warnings
276 .push(CredentialUpdateSessionStatusWarnings::WebauthnAttestationUnsatisfiable)
277 }
278 }
279
280 if can_commit
282 && self.attested_passkeys.is_empty()
283 && self.passkeys.is_empty()
284 && self.primary.is_none()
285 {
286 can_commit = false;
288 warnings.push(CredentialUpdateSessionStatusWarnings::NoValidCredentials)
289 }
290
291 (can_commit, warnings)
292 }
293}
294
295pub enum MfaRegStateStatus {
296 None,
298 TotpCheck(TotpSecret),
299 TotpTryAgain,
300 TotpNameTryAgain(String),
301 TotpInvalidSha1,
302 BackupCodes(HashSet<String>),
303 Passkey(CreationChallengeResponse),
304 AttestedPasskey(CreationChallengeResponse),
305}
306
307impl fmt::Debug for MfaRegStateStatus {
308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309 let t = match self {
310 MfaRegStateStatus::None => "MfaRegStateStatus::None",
311 MfaRegStateStatus::TotpCheck(_) => "MfaRegStateStatus::TotpCheck",
312 MfaRegStateStatus::TotpTryAgain => "MfaRegStateStatus::TotpTryAgain",
313 MfaRegStateStatus::TotpNameTryAgain(_) => "MfaRegStateStatus::TotpNameTryAgain",
314 MfaRegStateStatus::TotpInvalidSha1 => "MfaRegStateStatus::TotpInvalidSha1",
315 MfaRegStateStatus::BackupCodes(_) => "MfaRegStateStatus::BackupCodes",
316 MfaRegStateStatus::Passkey(_) => "MfaRegStateStatus::Passkey",
317 MfaRegStateStatus::AttestedPasskey(_) => "MfaRegStateStatus::AttestedPasskey",
318 };
319 write!(f, "{t}")
320 }
321}
322
323#[derive(Debug, PartialEq, Eq, Clone, Copy)]
324pub enum CredentialUpdateSessionStatusWarnings {
325 MfaRequired,
326 PasskeyRequired,
327 AttestedPasskeyRequired,
328 AttestedResidentKeyRequired,
329 Unsatisfiable,
330 WebauthnAttestationUnsatisfiable,
331 WebauthnUserVerificationRequired,
332 NoValidCredentials,
333}
334
335impl Display for CredentialUpdateSessionStatusWarnings {
336 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
337 write!(f, "{self:?}")
338 }
339}
340
341impl From<CredentialUpdateSessionStatusWarnings> for CURegWarning {
342 fn from(val: CredentialUpdateSessionStatusWarnings) -> CURegWarning {
343 match val {
344 CredentialUpdateSessionStatusWarnings::MfaRequired => CURegWarning::MfaRequired,
345 CredentialUpdateSessionStatusWarnings::PasskeyRequired => CURegWarning::PasskeyRequired,
346 CredentialUpdateSessionStatusWarnings::AttestedPasskeyRequired => {
347 CURegWarning::AttestedPasskeyRequired
348 }
349 CredentialUpdateSessionStatusWarnings::AttestedResidentKeyRequired => {
350 CURegWarning::AttestedResidentKeyRequired
351 }
352 CredentialUpdateSessionStatusWarnings::Unsatisfiable => CURegWarning::Unsatisfiable,
353 CredentialUpdateSessionStatusWarnings::WebauthnAttestationUnsatisfiable => {
354 CURegWarning::WebauthnAttestationUnsatisfiable
355 }
356 CredentialUpdateSessionStatusWarnings::WebauthnUserVerificationRequired => {
357 CURegWarning::WebauthnUserVerificationRequired
358 }
359 CredentialUpdateSessionStatusWarnings::NoValidCredentials => {
360 CURegWarning::NoValidCredentials
361 }
362 }
363 }
364}
365
366#[derive(Debug)]
367pub struct CredentialUpdateSessionStatus {
368 spn: String,
369 displayname: String,
371 ext_cred_portal: CUExtPortal,
372 mfaregstate: MfaRegStateStatus,
374 can_commit: bool,
375 warnings: Vec<CredentialUpdateSessionStatusWarnings>,
377 dirty: bool,
379
380 primary: Option<CredentialDetail>,
381 primary_state: CredentialState,
382 passkeys: Vec<PasskeyDetail>,
383 passkeys_state: CredentialState,
384 attested_passkeys: Vec<PasskeyDetail>,
385 attested_passkeys_state: CredentialState,
386 attested_passkeys_allowed_devices: Vec<String>,
387
388 unixcred: Option<CredentialDetail>,
389 unixcred_state: CredentialState,
390
391 sshkeys: BTreeMap<String, SshPublicKey>,
392 sshkeys_state: CredentialState,
393}
394
395impl CredentialUpdateSessionStatus {
396 pub fn append_ephemeral_warning(&mut self, warning: CredentialUpdateSessionStatusWarnings) {
400 self.warnings.push(warning)
401 }
402
403 pub fn can_commit(&self) -> bool {
404 self.can_commit
405 }
406
407 pub fn mfaregstate(&self) -> &MfaRegStateStatus {
408 &self.mfaregstate
409 }
410}
411
412#[allow(clippy::from_over_into)]
415impl Into<CUStatus> for CredentialUpdateSessionStatus {
416 fn into(self) -> CUStatus {
417 CUStatus {
418 spn: self.spn,
419 displayname: self.displayname,
420 ext_cred_portal: self.ext_cred_portal,
421 mfaregstate: match self.mfaregstate {
422 MfaRegStateStatus::None => CURegState::None,
423 MfaRegStateStatus::TotpCheck(c) => CURegState::TotpCheck(c),
424 MfaRegStateStatus::TotpTryAgain => CURegState::TotpTryAgain,
425 MfaRegStateStatus::TotpNameTryAgain(label) => CURegState::TotpNameTryAgain(label),
426 MfaRegStateStatus::TotpInvalidSha1 => CURegState::TotpInvalidSha1,
427 MfaRegStateStatus::BackupCodes(s) => {
428 CURegState::BackupCodes(s.into_iter().collect())
429 }
430 MfaRegStateStatus::Passkey(r) => CURegState::Passkey(r),
431 MfaRegStateStatus::AttestedPasskey(r) => CURegState::AttestedPasskey(r),
432 },
433 can_commit: self.can_commit,
434 warnings: self.warnings.into_iter().map(|w| w.into()).collect(),
435 dirty: self.dirty,
436 primary: self.primary,
437 primary_state: self.primary_state.into(),
438 passkeys: self.passkeys,
439 passkeys_state: self.passkeys_state.into(),
440 attested_passkeys: self.attested_passkeys,
441 attested_passkeys_state: self.attested_passkeys_state.into(),
442 attested_passkeys_allowed_devices: self.attested_passkeys_allowed_devices,
443 unixcred: self.unixcred,
444 unixcred_state: self.unixcred_state.into(),
445 sshkeys: self.sshkeys,
446 sshkeys_state: self.sshkeys_state.into(),
447 }
448 }
449}
450
451impl From<&CredentialUpdateSession> for CredentialUpdateSessionStatus {
452 fn from(session: &CredentialUpdateSession) -> Self {
453 let (can_commit, warnings) = session.can_commit();
454
455 let attested_passkeys_allowed_devices: Vec<String> = session
456 .resolved_account_policy
457 .webauthn_attestation_ca_list()
458 .iter()
459 .flat_map(|att_ca_list: &&webauthn_rs::prelude::AttestationCaList| {
460 att_ca_list.cas().values().flat_map(|ca| {
461 ca.aaguids()
462 .values()
463 .map(|device| device.description_en().to_string())
464 })
465 })
466 .collect();
467
468 CredentialUpdateSessionStatus {
469 spn: session.account.spn().into(),
470 displayname: session.account.displayname.clone(),
471 ext_cred_portal: session.ext_cred_portal.clone(),
472 can_commit,
473 warnings,
474 dirty: session.dirty,
475 primary: session.primary.as_ref().map(|c| c.into()),
476 primary_state: session.primary_state,
477 passkeys: session
478 .passkeys
479 .iter()
480 .map(|(uuid, (tag, _pk))| PasskeyDetail {
481 tag: tag.clone(),
482 uuid: *uuid,
483 })
484 .collect(),
485 passkeys_state: session.passkeys_state,
486 attested_passkeys: session
487 .attested_passkeys
488 .iter()
489 .map(|(uuid, (tag, _pk))| PasskeyDetail {
490 tag: tag.clone(),
491 uuid: *uuid,
492 })
493 .collect(),
494 attested_passkeys_state: session.attested_passkeys_state,
495 attested_passkeys_allowed_devices,
496
497 unixcred: session.unixcred.as_ref().map(|c| c.into()),
498 unixcred_state: session.unixcred_state,
499
500 sshkeys: session.sshkeys.clone(),
501 sshkeys_state: session.sshkeys_state,
502
503 mfaregstate: match &session.mfaregstate {
504 MfaRegState::None => MfaRegStateStatus::None,
505 MfaRegState::TotpInit(token) => MfaRegStateStatus::TotpCheck(
506 token.to_proto(session.account.spn(), session.issuer.as_str()),
507 ),
508 MfaRegState::TotpNameTryAgain(_, name) => {
509 MfaRegStateStatus::TotpNameTryAgain(name.clone())
510 }
511 MfaRegState::TotpTryAgain(_) => MfaRegStateStatus::TotpTryAgain,
512 MfaRegState::TotpInvalidSha1(_, _, _) => MfaRegStateStatus::TotpInvalidSha1,
513 MfaRegState::Passkey(r, _) => MfaRegStateStatus::Passkey(r.as_ref().clone()),
514 MfaRegState::AttestedPasskey(r, _) => {
515 MfaRegStateStatus::AttestedPasskey(r.as_ref().clone())
516 }
517 },
518 }
519 }
520}
521
522pub(crate) type CredentialUpdateSessionMutex = Arc<Mutex<CredentialUpdateSession>>;
523
524pub struct InitCredentialUpdateIntentEvent {
525 pub ident: Identity,
527 pub target: Uuid,
529 pub max_ttl: Option<Duration>,
531}
532
533impl InitCredentialUpdateIntentEvent {
534 pub fn new(ident: Identity, target: Uuid, max_ttl: Option<Duration>) -> Self {
535 Self {
536 ident,
537 target,
538 max_ttl,
539 }
540 }
541
542 pub fn new_ident_account_request(target: Uuid) -> Self {
543 Self {
544 ident: Identity::account_request(),
545 target,
546 max_ttl: Some(Duration::from_secs(60)),
547 }
548 }
549
550 #[cfg(test)]
551 pub fn new_impersonate_entry(
552 e: std::sync::Arc<Entry<EntrySealed, EntryCommitted>>,
553 target: Uuid,
554 max_ttl: Duration,
555 ) -> Self {
556 let ident = Identity::from_impersonate_entry_readwrite(e);
557 Self {
558 ident,
559 target,
560 max_ttl: Some(max_ttl),
561 }
562 }
563}
564
565pub struct CredentialUpdateAccountRecovery {
566 pub email: String,
568 pub max_ttl: Option<Duration>,
570}
571
572pub struct InitCredentialUpdateIntentSendEvent {
573 pub ident: Identity,
575 pub target: Uuid,
577 pub max_ttl: Option<Duration>,
579 pub email: Option<String>,
581}
582
583pub struct InitCredentialUpdateEvent {
584 pub ident: Identity,
585 pub target: Uuid,
586}
587
588impl InitCredentialUpdateEvent {
589 pub fn new(ident: Identity, target: Uuid) -> Self {
590 InitCredentialUpdateEvent { ident, target }
591 }
592
593 #[cfg(test)]
594 pub fn new_impersonate_entry(e: std::sync::Arc<Entry<EntrySealed, EntryCommitted>>) -> Self {
595 let ident = Identity::from_impersonate_entry_readwrite(e);
596 let target = ident.get_uuid();
597 InitCredentialUpdateEvent { ident, target }
598 }
599}
600
601impl IdmServerProxyWriteTransaction<'_> {
602 fn validate_init_credential_update(
603 &mut self,
604 target: Uuid,
605 ident: &Identity,
606 ) -> Result<(Account, ResolvedAccountPolicy, CredUpdateSessionPerms), OperationError> {
607 let entry = self.qs_write.internal_search_uuid(target)?;
608
609 security_info!(
610 %target,
611 "Initiating Credential Update Session",
612 );
613
614 if ident.access_scope() != AccessScope::ReadWrite {
617 security_access!(
618 ?ident,
619 "denied ❌ - identity access scope is not permitted to modify"
620 );
621 return Err(OperationError::AccessDenied);
622 }
623
624 let (account, resolved_account_policy) =
626 Account::try_from_entry_with_policy(entry.as_ref(), &mut self.qs_write)?;
627
628 let effective_perms = self
629 .qs_write
630 .get_accesscontrols()
631 .effective_permission_check(
632 ident,
633 Some(btreeset![
634 Attribute::PrimaryCredential,
635 Attribute::PassKeys,
636 Attribute::AttestedPasskeys,
637 Attribute::UnixPassword,
638 Attribute::SshPublicKey
639 ]),
640 &[entry],
641 )?;
642
643 let eperm = effective_perms.first().ok_or_else(|| {
644 error!("Effective Permission check returned no results");
645 OperationError::InvalidState
646 })?;
647
648 if eperm.target != account.uuid {
652 error!("Effective Permission check target differs from requested entry uuid");
653 return Err(OperationError::InvalidEntryState);
654 }
655
656 let eperm_search_primary_cred = match &eperm.search {
657 Access::Deny => false,
658 Access::Grant => true,
659 Access::Allow(attrs) => attrs.contains(&Attribute::PrimaryCredential),
660 };
661
662 let eperm_mod_primary_cred = match &eperm.modify_pres {
663 Access::Deny => false,
664 Access::Grant => true,
665 Access::Allow(attrs) => attrs.contains(&Attribute::PrimaryCredential),
666 };
667
668 let eperm_rem_primary_cred = match &eperm.modify_rem {
669 Access::Deny => false,
670 Access::Grant => true,
671 Access::Allow(attrs) => attrs.contains(&Attribute::PrimaryCredential),
672 };
673
674 let primary_can_edit =
675 eperm_search_primary_cred && eperm_mod_primary_cred && eperm_rem_primary_cred;
676
677 let eperm_search_passkeys = match &eperm.search {
678 Access::Deny => false,
679 Access::Grant => true,
680 Access::Allow(attrs) => attrs.contains(&Attribute::PassKeys),
681 };
682
683 let eperm_mod_passkeys = match &eperm.modify_pres {
684 Access::Deny => false,
685 Access::Grant => true,
686 Access::Allow(attrs) => attrs.contains(&Attribute::PassKeys),
687 };
688
689 let eperm_rem_passkeys = match &eperm.modify_rem {
690 Access::Deny => false,
691 Access::Grant => true,
692 Access::Allow(attrs) => attrs.contains(&Attribute::PassKeys),
693 };
694
695 let passkeys_can_edit = eperm_search_passkeys && eperm_mod_passkeys && eperm_rem_passkeys;
696
697 let eperm_search_attested_passkeys = match &eperm.search {
698 Access::Deny => false,
699 Access::Grant => true,
700 Access::Allow(attrs) => attrs.contains(&Attribute::AttestedPasskeys),
701 };
702
703 let eperm_mod_attested_passkeys = match &eperm.modify_pres {
704 Access::Deny => false,
705 Access::Grant => true,
706 Access::Allow(attrs) => attrs.contains(&Attribute::AttestedPasskeys),
707 };
708
709 let eperm_rem_attested_passkeys = match &eperm.modify_rem {
710 Access::Deny => false,
711 Access::Grant => true,
712 Access::Allow(attrs) => attrs.contains(&Attribute::AttestedPasskeys),
713 };
714
715 let attested_passkeys_can_edit = eperm_search_attested_passkeys
716 && eperm_mod_attested_passkeys
717 && eperm_rem_attested_passkeys;
718
719 let eperm_search_unixcred = match &eperm.search {
720 Access::Deny => false,
721 Access::Grant => true,
722 Access::Allow(attrs) => attrs.contains(&Attribute::UnixPassword),
723 };
724
725 let eperm_mod_unixcred = match &eperm.modify_pres {
726 Access::Deny => false,
727 Access::Grant => true,
728 Access::Allow(attrs) => attrs.contains(&Attribute::UnixPassword),
729 };
730
731 let eperm_rem_unixcred = match &eperm.modify_rem {
732 Access::Deny => false,
733 Access::Grant => true,
734 Access::Allow(attrs) => attrs.contains(&Attribute::UnixPassword),
735 };
736
737 let unixcred_can_edit = account.unix_extn().is_some()
738 && eperm_search_unixcred
739 && eperm_mod_unixcred
740 && eperm_rem_unixcred;
741
742 let eperm_search_sshpubkey = match &eperm.search {
743 Access::Deny => false,
744 Access::Grant => true,
745 Access::Allow(attrs) => attrs.contains(&Attribute::SshPublicKey),
746 };
747
748 let eperm_mod_sshpubkey = match &eperm.modify_pres {
749 Access::Deny => false,
750 Access::Grant => true,
751 Access::Allow(attrs) => attrs.contains(&Attribute::SshPublicKey),
752 };
753
754 let eperm_rem_sshpubkey = match &eperm.modify_rem {
755 Access::Deny => false,
756 Access::Grant => true,
757 Access::Allow(attrs) => attrs.contains(&Attribute::SshPublicKey),
758 };
759
760 let sshpubkey_can_edit = account.unix_extn().is_some()
761 && eperm_search_sshpubkey
762 && eperm_mod_sshpubkey
763 && eperm_rem_sshpubkey;
764
765 let ext_cred_portal_can_view = if let Some(sync_parent_uuid) = account.sync_parent_uuid {
766 let entry = self.qs_write.internal_search_uuid(sync_parent_uuid)?;
768
769 let effective_perms = self
770 .qs_write
771 .get_accesscontrols()
772 .effective_permission_check(
773 ident,
774 Some(btreeset![Attribute::SyncCredentialPortal]),
775 &[entry],
776 )?;
777
778 let eperm = effective_perms.first().ok_or_else(|| {
779 admin_error!("Effective Permission check returned no results");
780 OperationError::InvalidState
781 })?;
782
783 match &eperm.search {
784 Access::Deny => false,
785 Access::Grant => true,
786 Access::Allow(attrs) => attrs.contains(&Attribute::SyncCredentialPortal),
787 }
788 } else {
789 false
790 };
791
792 if !(primary_can_edit
794 || passkeys_can_edit
795 || attested_passkeys_can_edit
796 || ext_cred_portal_can_view
797 || sshpubkey_can_edit
798 || unixcred_can_edit)
799 {
800 error!("Unable to proceed with credential update intent - at least one type of credential must be modifiable or visible.");
801 Err(OperationError::NotAuthorised)
802 } else {
803 security_info!(%primary_can_edit, %passkeys_can_edit, %unixcred_can_edit, %sshpubkey_can_edit, %ext_cred_portal_can_view, "Proceeding");
804 Ok((
805 account,
806 resolved_account_policy,
807 CredUpdateSessionPerms {
808 ext_cred_portal_can_view,
809 passkeys_can_edit,
810 attested_passkeys_can_edit,
811 primary_can_edit,
812 unixcred_can_edit,
813 sshpubkey_can_edit,
814 },
815 ))
816 }
817 }
818
819 fn create_credupdate_session(
820 &mut self,
821 sessionid: Uuid,
822 intent_token_id: Option<String>,
823 account: Account,
824 resolved_account_policy: ResolvedAccountPolicy,
825 perms: CredUpdateSessionPerms,
826 ct: Duration,
827 ) -> Result<(CredentialUpdateSessionToken, CredentialUpdateSessionStatus), OperationError> {
828 let ext_cred_portal_can_view = perms.ext_cred_portal_can_view;
829
830 let cred_type_min = resolved_account_policy.credential_policy();
831
832 let passkey_attestation_required = resolved_account_policy
836 .webauthn_attestation_ca_list()
837 .is_some();
838
839 let primary_state = if cred_type_min > CredentialType::Mfa {
840 CredentialState::PolicyDeny
841 } else if perms.primary_can_edit {
842 CredentialState::Modifiable
843 } else {
844 CredentialState::AccessDeny
845 };
846
847 let passkeys_state =
848 if cred_type_min > CredentialType::Passkey || passkey_attestation_required {
849 CredentialState::PolicyDeny
850 } else if perms.passkeys_can_edit {
851 CredentialState::Modifiable
852 } else {
853 CredentialState::AccessDeny
854 };
855
856 let attested_passkeys_state = if cred_type_min > CredentialType::AttestedPasskey {
857 CredentialState::PolicyDeny
858 } else if perms.attested_passkeys_can_edit {
859 if passkey_attestation_required {
860 CredentialState::Modifiable
861 } else {
862 CredentialState::DeleteOnly
864 }
865 } else {
866 CredentialState::AccessDeny
867 };
868
869 let unixcred_state = if account.unix_extn().is_none() {
870 CredentialState::PolicyDeny
871 } else if perms.unixcred_can_edit {
872 CredentialState::Modifiable
873 } else {
874 CredentialState::AccessDeny
875 };
876
877 let sshkeys_state = if perms.sshpubkey_can_edit {
878 CredentialState::Modifiable
879 } else {
880 CredentialState::AccessDeny
881 };
882
883 let primary = if matches!(primary_state, CredentialState::Modifiable) {
885 account.primary.clone()
886 } else {
887 None
888 };
889
890 let passkeys = if matches!(passkeys_state, CredentialState::Modifiable) {
891 account.passkeys.clone()
892 } else {
893 BTreeMap::default()
894 };
895
896 let unixcred: Option<Credential> = if matches!(unixcred_state, CredentialState::Modifiable)
897 {
898 account.unix_extn().and_then(|uext| uext.ucred()).cloned()
899 } else {
900 None
901 };
902
903 let sshkeys = if matches!(sshkeys_state, CredentialState::Modifiable) {
904 account.sshkeys().clone()
905 } else {
906 BTreeMap::default()
907 };
908
909 let attested_passkeys = if matches!(attested_passkeys_state, CredentialState::Modifiable)
913 || matches!(attested_passkeys_state, CredentialState::DeleteOnly)
914 {
915 if let Some(att_ca_list) = resolved_account_policy.webauthn_attestation_ca_list() {
916 let mut attested_passkeys = BTreeMap::default();
917
918 for (uuid, (label, apk)) in account.attested_passkeys.iter() {
919 match apk.verify_attestation(att_ca_list) {
920 Ok(_) => {
921 attested_passkeys.insert(*uuid, (label.clone(), apk.clone()));
923 }
924 Err(e) => {
925 warn!(eclass=?e, emsg=%e, "credential no longer meets attestation criteria");
926 }
927 }
928 }
929
930 attested_passkeys
931 } else {
932 account.attested_passkeys.clone()
936 }
937 } else {
938 BTreeMap::default()
939 };
940
941 let ext_cred_portal = match (account.sync_parent_uuid, ext_cred_portal_can_view) {
943 (Some(sync_parent_uuid), true) => {
944 let sync_entry = self.qs_write.internal_search_uuid(sync_parent_uuid)?;
945 sync_entry
946 .get_ava_single_url(Attribute::SyncCredentialPortal)
947 .cloned()
948 .map(CUExtPortal::Some)
949 .unwrap_or(CUExtPortal::Hidden)
950 }
951 (Some(_), false) => CUExtPortal::Hidden,
952 (None, _) => CUExtPortal::None,
953 };
954
955 let issuer = self.qs_write.get_domain_display_name().to_string();
957
958 let session = CredentialUpdateSession {
960 account,
961 resolved_account_policy,
962 issuer,
963 intent_token_id,
964 ext_cred_portal,
965 primary,
966 primary_state,
967 unixcred,
968 unixcred_state,
969 sshkeys,
970 sshkeys_state,
971 passkeys,
972 passkeys_state,
973 attested_passkeys,
974 attested_passkeys_state,
975 mfaregstate: MfaRegState::None,
976 dirty: false,
977 };
978
979 let max_ttl = ct + MAXIMUM_CRED_UPDATE_TTL;
980
981 let token = CredentialUpdateSessionTokenInner { sessionid, max_ttl };
982
983 let token_data = serde_json::to_vec(&token).map_err(|e| {
984 admin_error!(err = ?e, "Unable to encode token data");
985 OperationError::SerdeJsonError
986 })?;
987
988 let token_jwe = JweBuilder::from(token_data).build();
989
990 let token_enc = self
991 .qs_write
992 .get_domain_key_object_handle()?
993 .jwe_a128gcm_encrypt(&token_jwe, ct)?;
994
995 let status: CredentialUpdateSessionStatus = (&session).into();
996
997 let session = Arc::new(Mutex::new(session));
998
999 self.expire_credential_update_sessions(ct);
1003
1004 self.cred_update_sessions.insert(sessionid, session);
1006 trace!("cred_update_sessions.insert - {}", sessionid);
1007
1008 Ok((CredentialUpdateSessionToken { token_enc }, status))
1010 }
1011
1012 pub fn credential_update_account_recovery(
1013 &mut self,
1014 event: CredentialUpdateAccountRecovery,
1015 ct: Duration,
1016 ) -> Result<Uuid, OperationError> {
1017 if !self.qs_write.domain_info().allow_account_recovery() {
1018 error!("Account Recovery is Disabled, Rejecting Attempt");
1019 return Err(OperationError::CU0010AccountRecoveryDisabled);
1020 }
1021
1022 let ident = Identity::account_request();
1025
1026 let filter = filter!(f_eq(
1028 Attribute::Mail,
1029 PartialValue::EmailAddress(event.email.clone())
1030 ));
1031
1032 let mut entries = self
1033 .qs_write
1034 .impersonate_search(filter.clone(), filter, &ident)?;
1035
1036 let entry = entries
1037 .pop()
1038 .and_then(|entry| entries.is_empty().then_some(entry))
1039 .ok_or(OperationError::CU0009AccountEmailNotFound)?;
1040
1041 let target = entry.get_uuid();
1042
1043 let target_ident = Identity::from_impersonate_entry_readwrite(entry);
1052
1053 let (account, _resolved_account_policy, perms) =
1054 self.validate_init_credential_update(target, &target_ident)?;
1055
1056 self.process_credential_update_send(&account, event.max_ttl, perms, event.email, ct)
1059 }
1060
1061 #[instrument(level = "debug", skip_all)]
1062 pub fn init_credential_update_intent_send(
1063 &mut self,
1064 event: InitCredentialUpdateIntentSendEvent,
1065 ct: Duration,
1066 ) -> Result<Uuid, OperationError> {
1067 let (account, _resolved_account_policy, perms) =
1068 self.validate_init_credential_update(event.target, &event.ident)?;
1069
1070 let to_email = if let Some(to_email) = event.email {
1073 account.mail().contains(&to_email)
1074 .then_some(to_email)
1075 .ok_or_else(|| {
1076 error!(spn = %account.spn(), "Requested email address is not present on account, unable to send credential reset.");
1077 OperationError::CU0007AccountEmailNotFound
1078 })
1079 } else {
1080 let maybe_to_email = account.mail_primary().map(String::from);
1081
1082 maybe_to_email.ok_or_else(|| {
1083 error!(spn = %account.spn(), "account does not have a primary email address, unable to send credential reset.");
1084 OperationError::CU0008AccountMissingEmail
1085 })
1086 }?;
1087
1088 self.process_credential_update_send(&account, event.max_ttl, perms, to_email, ct)
1089 }
1090
1091 fn process_credential_update_send(
1092 &mut self,
1093 account: &Account,
1094 max_ttl: Option<Duration>,
1095 perms: CredUpdateSessionPerms,
1096 to_email: String,
1097 ct: Duration,
1098 ) -> Result<Uuid, OperationError> {
1099 let (intent_id, expiry_time) =
1101 self.build_credential_update_intent(max_ttl, account, perms, ct)?;
1102
1103 let display_name = account.display_name().to_owned();
1105
1106 let message = OutboundMessage::CredentialResetV1 {
1107 display_name,
1108 intent_id,
1109 expiry_time,
1110 };
1111
1112 let ident = Identity::message_queue();
1113
1114 self.qs_write.queue_message(
1115 &ident, message, to_email,
1118 )
1119 }
1120
1121 #[instrument(level = "debug", skip_all)]
1122 pub fn init_credential_update_intent(
1123 &mut self,
1124 event: &InitCredentialUpdateIntentEvent,
1125 ct: Duration,
1126 ) -> Result<CredentialUpdateIntentToken, OperationError> {
1127 let (account, _resolved_account_policy, perms) =
1128 self.validate_init_credential_update(event.target, &event.ident)?;
1129
1130 let (intent_id, expiry_time) =
1135 self.build_credential_update_intent(event.max_ttl, &account, perms, ct)?;
1136
1137 Ok(CredentialUpdateIntentToken {
1138 intent_id,
1139 expiry_time,
1140 })
1141 }
1142
1143 fn build_credential_update_intent(
1144 &mut self,
1145 max_ttl: Option<Duration>,
1146 account: &Account,
1147 perms: CredUpdateSessionPerms,
1148 ct: Duration,
1149 ) -> Result<(String, OffsetDateTime), OperationError> {
1150 let mttl = max_ttl.unwrap_or(DEFAULT_INTENT_TTL);
1154 let clamped_mttl = mttl.clamp(MINIMUM_INTENT_TTL, MAXIMUM_INTENT_TTL);
1155 debug!(?clamped_mttl, "clamped update intent validity");
1156 let max_ttl = ct + clamped_mttl;
1158
1159 let expiry_time = OffsetDateTime::UNIX_EPOCH + max_ttl;
1161
1162 let intent_id = readable_password_from_random();
1163
1164 let mut modlist = ModifyList::new_append(
1170 Attribute::CredentialUpdateIntentToken,
1171 Value::IntentToken(
1172 intent_id.clone(),
1173 IntentTokenState::Valid { max_ttl, perms },
1174 ),
1175 );
1176
1177 account
1179 .credential_update_intent_tokens
1180 .iter()
1181 .for_each(|(existing_intent_id, state)| {
1182 let max_ttl = match state {
1183 IntentTokenState::Valid { max_ttl, perms: _ }
1184 | IntentTokenState::InProgress {
1185 max_ttl,
1186 perms: _,
1187 session_id: _,
1188 session_ttl: _,
1189 }
1190 | IntentTokenState::Consumed { max_ttl } => *max_ttl,
1191 };
1192
1193 if ct >= max_ttl {
1194 modlist.push_mod(Modify::Removed(
1195 Attribute::CredentialUpdateIntentToken,
1196 PartialValue::IntentToken(existing_intent_id.clone()),
1197 ));
1198 }
1199 });
1200
1201 self.qs_write
1202 .internal_modify(
1203 &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(account.uuid))),
1205 &modlist,
1206 )
1207 .inspect_err(|err| {
1208 error!(?err);
1209 })
1210 .map(|_| (intent_id, expiry_time))
1211 }
1212
1213 #[instrument(level = "debug", skip_all)]
1214 pub fn revoke_credential_update_intent(
1215 &mut self,
1216 token: CredentialUpdateIntentTokenExchange,
1217 _current_time: Duration,
1218 ) -> Result<(), OperationError> {
1219 let CredentialUpdateIntentTokenExchange { intent_id } = token;
1220 let entries = self.qs_write.internal_search(filter!(f_eq(
1227 Attribute::CredentialUpdateIntentToken,
1228 PartialValue::IntentToken(intent_id.clone())
1229 )))?;
1230
1231 let batch_mod = entries
1233 .iter()
1234 .filter_map(|entry| {
1235 let intenttokens = entry
1236 .get_ava_set(Attribute::CredentialUpdateIntentToken)
1237 .and_then(|vs| vs.as_intenttoken_map());
1238
1239 let Some(intenttoken) = intenttokens.and_then(|m| m.get(&intent_id)) else {
1241 debug_assert!(false);
1242 return None;
1243 };
1244
1245 let max_ttl = match intenttoken {
1246 IntentTokenState::Consumed { max_ttl: _ } => return None,
1248 IntentTokenState::InProgress { max_ttl, .. }
1250 | IntentTokenState::Valid { max_ttl, .. } => *max_ttl,
1251 };
1252
1253 let entry_uuid = entry.get_uuid();
1254
1255 let mut modlist = ModifyList::new();
1256
1257 modlist.push_mod(Modify::Removed(
1258 Attribute::CredentialUpdateIntentToken,
1259 PartialValue::IntentToken(intent_id.clone()),
1260 ));
1261
1262 modlist.push_mod(Modify::Present(
1263 Attribute::CredentialUpdateIntentToken,
1264 Value::IntentToken(intent_id.clone(), IntentTokenState::Consumed { max_ttl }),
1265 ));
1266
1267 Some((entry_uuid, modlist))
1268 })
1269 .collect::<Vec<_>>();
1270
1271 self.qs_write.internal_batch_modify(batch_mod.into_iter())
1272 }
1273
1274 pub fn exchange_intent_credential_update(
1275 &mut self,
1276 token: CredentialUpdateIntentTokenExchange,
1277 current_time: Duration,
1278 ) -> Result<(CredentialUpdateSessionToken, CredentialUpdateSessionStatus), OperationError> {
1279 let CredentialUpdateIntentTokenExchange { intent_id } = token;
1280
1281 let mut vs = self.qs_write.internal_search(filter!(f_eq(
1291 Attribute::CredentialUpdateIntentToken,
1292 PartialValue::IntentToken(intent_id.clone())
1293 )))?;
1294
1295 let entry = match vs.pop() {
1296 Some(entry) => {
1297 if vs.is_empty() {
1298 entry
1300 } else {
1301 let matched_uuids = std::iter::once(entry.get_uuid())
1303 .chain(vs.iter().map(|e| e.get_uuid()))
1304 .collect::<Vec<_>>();
1305
1306 security_error!("Multiple entries had identical intent_id - for safety, rejecting the use of this intent_id! {:?}", matched_uuids);
1307
1308 return Err(OperationError::InvalidState);
1333 }
1334 }
1335 None => {
1336 security_info!(
1337 "Rejecting Update Session - Intent Token does not exist (replication delay?)",
1338 );
1339 return Err(OperationError::Wait(
1340 OffsetDateTime::UNIX_EPOCH + (current_time + Duration::from_secs(150)),
1341 ));
1342 }
1343 };
1344
1345 let (account, resolved_account_policy) =
1347 Account::try_from_entry_with_policy(entry.as_ref(), &mut self.qs_write)?;
1348
1349 let (max_ttl, perms) = match account.credential_update_intent_tokens.get(&intent_id) {
1353 Some(IntentTokenState::Consumed { max_ttl: _ }) => {
1354 security_info!(
1355 %entry,
1356 %account.uuid,
1357 "Rejecting Update Session - Intent Token has already been exchanged",
1358 );
1359 return Err(OperationError::SessionExpired);
1360 }
1361 Some(IntentTokenState::InProgress {
1362 max_ttl,
1363 perms,
1364 session_id,
1365 session_ttl,
1366 }) => {
1367 if current_time > *session_ttl {
1368 security_info!(
1370 %entry,
1371 %account.uuid,
1372 "Initiating Credential Update Session - Previous session {} has expired", session_id
1373 );
1374 } else {
1375 security_info!(
1385 %entry,
1386 %account.uuid,
1387 "Initiating Update Session - Intent Token was in use {} - this will be invalidated.", session_id
1388 );
1389 };
1390 (*max_ttl, *perms)
1391 }
1392 Some(IntentTokenState::Valid { max_ttl, perms }) => (*max_ttl, *perms),
1393 None => {
1394 admin_error!("Corruption may have occurred - index yielded an entry for intent_id, but the entry does not contain that intent_id");
1395 return Err(OperationError::InvalidState);
1396 }
1397 };
1398
1399 if current_time >= max_ttl {
1400 security_info!(?current_time, ?max_ttl, %account.uuid, "intent has expired");
1401 return Err(OperationError::SessionExpired);
1402 }
1403
1404 security_info!(
1405 %entry,
1406 %account.uuid,
1407 "Initiating Credential Update Session",
1408 );
1409
1410 let session_id = uuid_from_duration(current_time + MAXIMUM_CRED_UPDATE_TTL, self.sid);
1420
1421 let mut modlist = ModifyList::new();
1422
1423 modlist.push_mod(Modify::Removed(
1424 Attribute::CredentialUpdateIntentToken,
1425 PartialValue::IntentToken(intent_id.clone()),
1426 ));
1427 modlist.push_mod(Modify::Present(
1428 Attribute::CredentialUpdateIntentToken,
1429 Value::IntentToken(
1430 intent_id.clone(),
1431 IntentTokenState::InProgress {
1432 max_ttl,
1433 perms,
1434 session_id,
1435 session_ttl: current_time + MAXIMUM_CRED_UPDATE_TTL,
1436 },
1437 ),
1438 ));
1439
1440 self.qs_write
1441 .internal_modify(
1442 &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(account.uuid))),
1444 &modlist,
1445 )
1446 .map_err(|e| {
1447 request_error!(error = ?e);
1448 e
1449 })?;
1450
1451 self.create_credupdate_session(
1455 session_id,
1456 Some(intent_id),
1457 account,
1458 resolved_account_policy,
1459 perms,
1460 current_time,
1461 )
1462 }
1463
1464 #[instrument(level = "debug", skip_all)]
1465 pub fn init_credential_update(
1466 &mut self,
1467 event: &InitCredentialUpdateEvent,
1468 current_time: Duration,
1469 ) -> Result<(CredentialUpdateSessionToken, CredentialUpdateSessionStatus), OperationError> {
1470 let (account, resolved_account_policy, perms) =
1471 self.validate_init_credential_update(event.target, &event.ident)?;
1472
1473 let sessionid = uuid_from_duration(current_time + MAXIMUM_CRED_UPDATE_TTL, self.sid);
1477
1478 self.create_credupdate_session(
1480 sessionid,
1481 None,
1482 account,
1483 resolved_account_policy,
1484 perms,
1485 current_time,
1486 )
1487 }
1488
1489 #[instrument(level = "trace", skip(self))]
1490 pub fn expire_credential_update_sessions(&mut self, ct: Duration) {
1491 let before = self.cred_update_sessions.len();
1492 let split_at = uuid_from_duration(ct, self.sid);
1493 trace!(?split_at, "expiring less than");
1494 self.cred_update_sessions.split_off_lt(&split_at);
1495 let removed = before - self.cred_update_sessions.len();
1496 trace!(?removed);
1497 }
1498
1499 fn credential_update_commit_common(
1501 &mut self,
1502 cust: &CredentialUpdateSessionToken,
1503 ct: Duration,
1504 ) -> Result<
1505 (
1506 ModifyList<ModifyInvalid>,
1507 CredentialUpdateSession,
1508 CredentialUpdateSessionTokenInner,
1509 ),
1510 OperationError,
1511 > {
1512 let session_token: CredentialUpdateSessionTokenInner = self
1513 .qs_write
1514 .get_domain_key_object_handle()?
1515 .jwe_decrypt(&cust.token_enc)
1516 .map_err(|e| {
1517 admin_error!(?e, "Failed to decrypt credential update session request");
1518 OperationError::SessionExpired
1519 })
1520 .and_then(|data| {
1521 data.from_json().map_err(|e| {
1522 admin_error!(err = ?e, "Failed to deserialise credential update session request");
1523 OperationError::SerdeJsonError
1524 })
1525 })?;
1526
1527 if ct >= session_token.max_ttl {
1528 trace!(?ct, ?session_token.max_ttl);
1529 security_info!(%session_token.sessionid, "session expired");
1530 return Err(OperationError::SessionExpired);
1531 }
1532
1533 let session_handle = self.cred_update_sessions.remove(&session_token.sessionid)
1534 .ok_or_else(|| {
1535 admin_error!("No such sessionid exists on this server - may be due to a load balancer failover or replay? {:?}", session_token.sessionid);
1536 OperationError::InvalidState
1537 })?;
1538
1539 let session = session_handle
1540 .try_lock()
1541 .map(|guard| (*guard).clone())
1542 .map_err(|_| {
1543 admin_error!("Session already locked, unable to proceed.");
1544 OperationError::InvalidState
1545 })?;
1546
1547 trace!(?session);
1548
1549 let modlist = ModifyList::new();
1550
1551 Ok((modlist, session, session_token))
1552 }
1553
1554 pub fn commit_credential_update(
1555 &mut self,
1556 cust: &CredentialUpdateSessionToken,
1557 ct: Duration,
1558 ) -> Result<(), OperationError> {
1559 let (mut modlist, session, session_token) =
1560 self.credential_update_commit_common(cust, ct)?;
1561
1562 let can_commit = session.can_commit();
1564 if !can_commit.0 {
1565 let commit_failure_reasons = can_commit
1566 .1
1567 .iter()
1568 .map(|e| e.to_string())
1569 .collect::<Vec<String>>()
1570 .join(", ");
1571 admin_error!(
1572 "Session is unable to commit due to: {}",
1573 commit_failure_reasons
1574 );
1575 return Err(OperationError::CU0004SessionInconsistent);
1576 }
1577
1578 let entry = self.qs_write.internal_search_uuid(session.account.uuid)?;
1581 let account = Account::try_from_entry_rw(entry.as_ref(), &mut self.qs_write)?;
1582
1583 if let Some(intent_token_id) = &session.intent_token_id {
1593 let max_ttl = match account.credential_update_intent_tokens.get(intent_token_id) {
1594 Some(IntentTokenState::InProgress {
1595 max_ttl,
1596 perms: _,
1597 session_id,
1598 session_ttl: _,
1599 }) => {
1600 if *session_id != session_token.sessionid {
1601 security_info!("Session originated from an intent token, but the intent token has initiated a conflicting second update session. Refusing to commit changes.");
1602 return Err(OperationError::CU0005IntentTokenConflict);
1603 } else {
1604 *max_ttl
1605 }
1606 }
1607 Some(IntentTokenState::Consumed { max_ttl: _ })
1608 | Some(IntentTokenState::Valid {
1609 max_ttl: _,
1610 perms: _,
1611 })
1612 | None => {
1613 security_info!("Session originated from an intent token, but the intent token has transitioned to an invalid state. Refusing to commit changes.");
1614 return Err(OperationError::CU0006IntentTokenInvalidated);
1615 }
1616 };
1617
1618 modlist.push_mod(Modify::Removed(
1619 Attribute::CredentialUpdateIntentToken,
1620 PartialValue::IntentToken(intent_token_id.clone()),
1621 ));
1622 modlist.push_mod(Modify::Present(
1623 Attribute::CredentialUpdateIntentToken,
1624 Value::IntentToken(
1625 intent_token_id.clone(),
1626 IntentTokenState::Consumed { max_ttl },
1627 ),
1628 ));
1629 };
1630
1631 let mut cred_changed: Option<OffsetDateTime> = None;
1632
1633 match session.unixcred_state {
1634 CredentialState::DeleteOnly | CredentialState::Modifiable => {
1635 modlist.push_mod(Modify::Purged(Attribute::UnixPassword));
1636
1637 if let Some(ncred) = &session.unixcred {
1638 let vcred = Value::new_credential("unix", ncred.clone());
1639 modlist.push_mod(Modify::Present(Attribute::UnixPassword, vcred));
1640 cred_changed = Some(ncred.timestamp());
1641 }
1642 }
1643 CredentialState::PolicyDeny => {
1644 modlist.push_mod(Modify::Purged(Attribute::UnixPassword));
1645 }
1646 CredentialState::AccessDeny => {}
1647 };
1648
1649 if cred_changed.is_none()
1651 && session
1652 .resolved_account_policy
1653 .allow_primary_cred_fallback()
1654 != Some(true)
1655 {
1656 cred_changed = Some(OffsetDateTime::UNIX_EPOCH);
1658 }
1659
1660 match session.primary_state {
1661 CredentialState::Modifiable => {
1662 modlist.push_mod(Modify::Purged(Attribute::PrimaryCredential));
1663 if let Some(ncred) = &session.primary {
1664 let vcred = Value::new_credential("primary", ncred.clone());
1665 modlist.push_mod(Modify::Present(Attribute::PrimaryCredential, vcred));
1666
1667 cred_changed.get_or_insert(ncred.timestamp());
1668 };
1669 }
1670 CredentialState::DeleteOnly | CredentialState::PolicyDeny => {
1671 modlist.push_mod(Modify::Purged(Attribute::PrimaryCredential));
1672 }
1673 CredentialState::AccessDeny => {}
1674 };
1675
1676 cred_changed.get_or_insert(OffsetDateTime::UNIX_EPOCH);
1677
1678 if let Some(timestamp) = cred_changed {
1679 modlist.push_mod(Modify::Purged(Attribute::PasswordChangedTime));
1680 modlist.push_mod(Modify::Present(
1681 Attribute::PasswordChangedTime,
1682 Value::DateTime(timestamp),
1683 ));
1684 }
1685
1686 match session.passkeys_state {
1687 CredentialState::DeleteOnly | CredentialState::Modifiable => {
1688 modlist.push_mod(Modify::Purged(Attribute::PassKeys));
1689 session.passkeys.iter().for_each(|(uuid, (tag, pk))| {
1692 let v_pk = Value::Passkey(*uuid, tag.clone(), pk.clone());
1693 modlist.push_mod(Modify::Present(Attribute::PassKeys, v_pk));
1694 });
1695 }
1696 CredentialState::PolicyDeny => {
1697 modlist.push_mod(Modify::Purged(Attribute::PassKeys));
1698 }
1699 CredentialState::AccessDeny => {}
1700 };
1701
1702 match session.attested_passkeys_state {
1703 CredentialState::DeleteOnly | CredentialState::Modifiable => {
1704 modlist.push_mod(Modify::Purged(Attribute::AttestedPasskeys));
1705 session
1708 .attested_passkeys
1709 .iter()
1710 .for_each(|(uuid, (tag, pk))| {
1711 let v_pk = Value::AttestedPasskey(*uuid, tag.clone(), pk.clone());
1712 modlist.push_mod(Modify::Present(Attribute::AttestedPasskeys, v_pk));
1713 });
1714 }
1715 CredentialState::PolicyDeny => {
1716 modlist.push_mod(Modify::Purged(Attribute::AttestedPasskeys));
1717 }
1718 CredentialState::AccessDeny => {}
1720 };
1721
1722 match session.sshkeys_state {
1723 CredentialState::DeleteOnly | CredentialState::Modifiable => {
1724 modlist.push_mod(Modify::Purged(Attribute::SshPublicKey));
1725 for (tag, pk) in &session.sshkeys {
1726 let v_sk = Value::SshKey(tag.clone(), pk.clone());
1727 modlist.push_mod(Modify::Present(Attribute::SshPublicKey, v_sk));
1728 }
1729 }
1730 CredentialState::PolicyDeny => {
1731 modlist.push_mod(Modify::Purged(Attribute::SshPublicKey));
1732 }
1733 CredentialState::AccessDeny => {}
1734 };
1735
1736 trace!(?modlist, "processing change");
1738
1739 if modlist.is_empty() {
1740 trace!("no changes to apply");
1741 Ok(())
1742 } else {
1743 self.qs_write
1744 .internal_modify(
1745 &filter!(f_eq(
1747 Attribute::Uuid,
1748 PartialValue::Uuid(session.account.uuid)
1749 )),
1750 &modlist,
1751 )
1752 .map_err(|e| {
1753 request_error!(error = ?e);
1754 e
1755 })
1756 }
1757 }
1758
1759 pub fn cancel_credential_update(
1760 &mut self,
1761 cust: &CredentialUpdateSessionToken,
1762 ct: Duration,
1763 ) -> Result<(), OperationError> {
1764 let (mut modlist, session, session_token) =
1765 self.credential_update_commit_common(cust, ct)?;
1766
1767 if let Some(intent_token_id) = &session.intent_token_id {
1769 let entry = self.qs_write.internal_search_uuid(session.account.uuid)?;
1770 let account = Account::try_from_entry_rw(entry.as_ref(), &mut self.qs_write)?;
1771
1772 let (max_ttl, perms) = match account
1773 .credential_update_intent_tokens
1774 .get(intent_token_id)
1775 {
1776 Some(IntentTokenState::InProgress {
1777 max_ttl,
1778 perms,
1779 session_id,
1780 session_ttl: _,
1781 }) => {
1782 if *session_id != session_token.sessionid {
1783 security_info!("Session originated from an intent token, but the intent token has initiated a conflicting second update session. Refusing to commit changes.");
1784 return Err(OperationError::InvalidState);
1785 } else {
1786 (*max_ttl, *perms)
1787 }
1788 }
1789 Some(IntentTokenState::Consumed { max_ttl: _ })
1790 | Some(IntentTokenState::Valid {
1791 max_ttl: _,
1792 perms: _,
1793 })
1794 | None => {
1795 security_info!("Session originated from an intent token, but the intent token has transitioned to an invalid state. Refusing to commit changes.");
1796 return Err(OperationError::InvalidState);
1797 }
1798 };
1799
1800 modlist.push_mod(Modify::Removed(
1801 Attribute::CredentialUpdateIntentToken,
1802 PartialValue::IntentToken(intent_token_id.clone()),
1803 ));
1804 modlist.push_mod(Modify::Present(
1805 Attribute::CredentialUpdateIntentToken,
1806 Value::IntentToken(
1807 intent_token_id.clone(),
1808 IntentTokenState::Valid { max_ttl, perms },
1809 ),
1810 ));
1811 };
1812
1813 if !modlist.is_empty() {
1815 trace!(?modlist, "processing change");
1816
1817 self.qs_write
1818 .internal_modify(
1819 &filter!(f_eq(
1821 Attribute::Uuid,
1822 PartialValue::Uuid(session.account.uuid)
1823 )),
1824 &modlist,
1825 )
1826 .map_err(|e| {
1827 request_error!(error = ?e);
1828 e
1829 })
1830 } else {
1831 Ok(())
1832 }
1833 }
1834}
1835
1836impl IdmServerCredUpdateTransaction<'_> {
1837 #[cfg(test)]
1838 pub fn get_origin(&self) -> &Url {
1839 &self.webauthn.get_allowed_origins()[0]
1840 }
1841
1842 fn get_current_session(
1843 &self,
1844 cust: &CredentialUpdateSessionToken,
1845 ct: Duration,
1846 ) -> Result<CredentialUpdateSessionMutex, OperationError> {
1847 let session_token: CredentialUpdateSessionTokenInner = self
1848 .qs_read
1849 .get_domain_key_object_handle()?
1850 .jwe_decrypt(&cust.token_enc)
1851 .map_err(|e| {
1852 admin_error!(?e, "Failed to decrypt credential update session request");
1853 OperationError::SessionExpired
1854 })
1855 .and_then(|data| {
1856 data.from_json().map_err(|e| {
1857 admin_error!(err = ?e, "Failed to deserialise credential update session request");
1858 OperationError::SerdeJsonError
1859 })
1860 })?;
1861
1862 if ct >= session_token.max_ttl {
1864 trace!(?ct, ?session_token.max_ttl);
1865 security_info!(%session_token.sessionid, "session expired");
1866 return Err(OperationError::SessionExpired);
1867 }
1868
1869 self.cred_update_sessions.get(&session_token.sessionid)
1870 .ok_or_else(|| {
1871 admin_error!("No such sessionid exists on this server - may be due to a load balancer failover or token replay? {}", session_token.sessionid);
1872 OperationError::InvalidState
1873 })
1874 .cloned()
1875 }
1876
1877 pub fn credential_update_status(
1880 &self,
1881 cust: &CredentialUpdateSessionToken,
1882 ct: Duration,
1883 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
1884 let session_handle = self.get_current_session(cust, ct)?;
1885 let session = session_handle.try_lock().map_err(|_| {
1886 admin_error!("Session already locked, unable to proceed.");
1887 OperationError::InvalidState
1888 })?;
1889 trace!(?session);
1890
1891 let status: CredentialUpdateSessionStatus = session.deref().into();
1892 Ok(status)
1893 }
1894
1895 #[instrument(level = "trace", skip(self))]
1896 fn check_password_quality(
1897 &self,
1898 cleartext: &str,
1899 resolved_account_policy: &ResolvedAccountPolicy,
1900 related_inputs: &[&str],
1901 radius_secret: Option<&str>,
1902 ) -> Result<(), PasswordQuality> {
1903 let pw_min_length = resolved_account_policy.pw_min_length();
1908 let pw_max_length = resolved_account_policy.pw_max_length();
1909
1910 let pw_graphemes = utf8_len(cleartext);
1911
1912 if pw_graphemes < pw_min_length as usize {
1913 return Err(PasswordQuality::TooShort(pw_min_length));
1914 } else if pw_graphemes > pw_max_length as usize {
1915 return Err(PasswordQuality::TooLong(pw_max_length));
1916 };
1917
1918 if let Some(some_radius_secret) = radius_secret {
1919 if cleartext.contains(some_radius_secret) {
1920 return Err(PasswordQuality::DontReusePasswords);
1921 }
1922 }
1923
1924 for related in related_inputs {
1928 if cleartext.contains(related) {
1929 return Err(PasswordQuality::Feedback(vec![
1930 PasswordFeedback::NamesAndSurnamesByThemselvesAreEasyToGuess,
1931 PasswordFeedback::AvoidDatesAndYearsThatAreAssociatedWithYou,
1932 ]));
1933 }
1934 }
1935
1936 let entropy = zxcvbn(cleartext, related_inputs);
1938
1939 if entropy.score() < Score::Four {
1941 let feedback: zxcvbn::feedback::Feedback =
1944 entropy.feedback().cloned().ok_or_else(|| {
1945 security_info!("zxcvbn returned no feedback when score < 3");
1946 PasswordQuality::Feedback(vec![
1948 PasswordFeedback::UseAFewWordsAvoidCommonPhrases,
1949 PasswordFeedback::AddAnotherWordOrTwo,
1950 PasswordFeedback::NoNeedForSymbolsDigitsOrUppercaseLetters,
1951 ])
1952 })?;
1953
1954 security_info!(?feedback, "pw quality feedback");
1955
1956 let feedback: Vec<_> = feedback
1957 .suggestions()
1958 .iter()
1959 .map(|s| {
1960 match s {
1961 zxcvbn::feedback::Suggestion::UseAFewWordsAvoidCommonPhrases => {
1962 PasswordFeedback::UseAFewWordsAvoidCommonPhrases
1963 }
1964 zxcvbn::feedback::Suggestion::NoNeedForSymbolsDigitsOrUppercaseLetters => {
1965 PasswordFeedback::NoNeedForSymbolsDigitsOrUppercaseLetters
1966 }
1967 zxcvbn::feedback::Suggestion::AddAnotherWordOrTwo => {
1968 PasswordFeedback::AddAnotherWordOrTwo
1969 }
1970 zxcvbn::feedback::Suggestion::CapitalizationDoesntHelpVeryMuch => {
1971 PasswordFeedback::CapitalizationDoesntHelpVeryMuch
1972 }
1973 zxcvbn::feedback::Suggestion::AllUppercaseIsAlmostAsEasyToGuessAsAllLowercase => {
1974 PasswordFeedback::AllUppercaseIsAlmostAsEasyToGuessAsAllLowercase
1975 }
1976 zxcvbn::feedback::Suggestion::ReversedWordsArentMuchHarderToGuess => {
1977 PasswordFeedback::ReversedWordsArentMuchHarderToGuess
1978 }
1979 zxcvbn::feedback::Suggestion::PredictableSubstitutionsDontHelpVeryMuch => {
1980 PasswordFeedback::PredictableSubstitutionsDontHelpVeryMuch
1981 }
1982 zxcvbn::feedback::Suggestion::UseALongerKeyboardPatternWithMoreTurns => {
1983 PasswordFeedback::UseALongerKeyboardPatternWithMoreTurns
1984 }
1985 zxcvbn::feedback::Suggestion::AvoidRepeatedWordsAndCharacters => {
1986 PasswordFeedback::AvoidRepeatedWordsAndCharacters
1987 }
1988 zxcvbn::feedback::Suggestion::AvoidSequences => {
1989 PasswordFeedback::AvoidSequences
1990 }
1991 zxcvbn::feedback::Suggestion::AvoidRecentYears => {
1992 PasswordFeedback::AvoidRecentYears
1993 }
1994 zxcvbn::feedback::Suggestion::AvoidYearsThatAreAssociatedWithYou => {
1995 PasswordFeedback::AvoidYearsThatAreAssociatedWithYou
1996 }
1997 zxcvbn::feedback::Suggestion::AvoidDatesAndYearsThatAreAssociatedWithYou => {
1998 PasswordFeedback::AvoidDatesAndYearsThatAreAssociatedWithYou
1999 }
2000 }
2001 })
2002 .chain(feedback.warning().map(|w| match w {
2003 zxcvbn::feedback::Warning::StraightRowsOfKeysAreEasyToGuess => {
2004 PasswordFeedback::StraightRowsOfKeysAreEasyToGuess
2005 }
2006 zxcvbn::feedback::Warning::ShortKeyboardPatternsAreEasyToGuess => {
2007 PasswordFeedback::ShortKeyboardPatternsAreEasyToGuess
2008 }
2009 zxcvbn::feedback::Warning::RepeatsLikeAaaAreEasyToGuess => {
2010 PasswordFeedback::RepeatsLikeAaaAreEasyToGuess
2011 }
2012 zxcvbn::feedback::Warning::RepeatsLikeAbcAbcAreOnlySlightlyHarderToGuess => {
2013 PasswordFeedback::RepeatsLikeAbcAbcAreOnlySlightlyHarderToGuess
2014 }
2015 zxcvbn::feedback::Warning::ThisIsATop10Password => {
2016 PasswordFeedback::ThisIsATop10Password
2017 }
2018 zxcvbn::feedback::Warning::ThisIsATop100Password => {
2019 PasswordFeedback::ThisIsATop100Password
2020 }
2021 zxcvbn::feedback::Warning::ThisIsACommonPassword => {
2022 PasswordFeedback::ThisIsACommonPassword
2023 }
2024 zxcvbn::feedback::Warning::ThisIsSimilarToACommonlyUsedPassword => {
2025 PasswordFeedback::ThisIsSimilarToACommonlyUsedPassword
2026 }
2027 zxcvbn::feedback::Warning::SequencesLikeAbcAreEasyToGuess => {
2028 PasswordFeedback::SequencesLikeAbcAreEasyToGuess
2029 }
2030 zxcvbn::feedback::Warning::RecentYearsAreEasyToGuess => {
2031 PasswordFeedback::RecentYearsAreEasyToGuess
2032 }
2033 zxcvbn::feedback::Warning::AWordByItselfIsEasyToGuess => {
2034 PasswordFeedback::AWordByItselfIsEasyToGuess
2035 }
2036 zxcvbn::feedback::Warning::DatesAreOftenEasyToGuess => {
2037 PasswordFeedback::DatesAreOftenEasyToGuess
2038 }
2039 zxcvbn::feedback::Warning::NamesAndSurnamesByThemselvesAreEasyToGuess => {
2040 PasswordFeedback::NamesAndSurnamesByThemselvesAreEasyToGuess
2041 }
2042 zxcvbn::feedback::Warning::CommonNamesAndSurnamesAreEasyToGuess => {
2043 PasswordFeedback::CommonNamesAndSurnamesAreEasyToGuess
2044 }
2045 }))
2046 .collect();
2047
2048 return Err(PasswordQuality::Feedback(feedback));
2049 }
2050
2051 if self
2055 .qs_read
2056 .pw_badlist()
2057 .contains(&cleartext.to_lowercase())
2058 {
2059 security_info!("Password found in badlist, rejecting");
2060 Err(PasswordQuality::BadListed)
2061 } else {
2062 Ok(())
2063 }
2064 }
2065
2066 #[instrument(level = "trace", skip(cust, self))]
2067 pub fn credential_check_password_quality(
2068 &self,
2069 cust: &CredentialUpdateSessionToken,
2070 ct: Duration,
2071 pw: &str,
2072 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2073 let session_handle = self.get_current_session(cust, ct)?;
2074 let session = session_handle.try_lock().map_err(|_| {
2075 admin_error!("Session already locked, unable to proceed.");
2076 OperationError::InvalidState
2077 })?;
2078 trace!(?session);
2079
2080 self.check_password_quality(
2081 pw,
2082 &session.resolved_account_policy,
2083 session.account.related_inputs().as_slice(),
2084 session.account.radius_secret.as_deref(),
2085 )
2086 .map_err(|e| match e {
2087 PasswordQuality::TooShort(sz) => {
2088 OperationError::PasswordQuality(vec![PasswordFeedback::TooShort(sz)])
2089 }
2090 PasswordQuality::TooLong(sz) => {
2091 OperationError::PasswordQuality(vec![PasswordFeedback::TooLong(sz)])
2092 }
2093 PasswordQuality::BadListed => {
2094 OperationError::PasswordQuality(vec![PasswordFeedback::BadListed])
2095 }
2096 PasswordQuality::DontReusePasswords => {
2097 OperationError::PasswordQuality(vec![PasswordFeedback::DontReusePasswords])
2098 }
2099 PasswordQuality::Feedback(feedback) => OperationError::PasswordQuality(feedback),
2100 })?;
2101
2102 Ok(session.deref().into())
2103 }
2104
2105 #[instrument(level = "trace", skip(cust, self))]
2106 pub fn credential_primary_set_password(
2107 &self,
2108 cust: &CredentialUpdateSessionToken,
2109 ct: Duration,
2110 pw: &str,
2111 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2112 let session_handle = self.get_current_session(cust, ct)?;
2113 let mut session = session_handle.try_lock().map_err(|_| {
2114 admin_error!("Session already locked, unable to proceed.");
2115 OperationError::InvalidState
2116 })?;
2117 trace!(?session);
2118
2119 if !matches!(session.primary_state, CredentialState::Modifiable) {
2120 error!("Session does not have permission to modify primary credential");
2121 return Err(OperationError::AccessDenied);
2122 };
2123
2124 let timestamp = OffsetDateTime::UNIX_EPOCH + ct;
2125
2126 self.check_password_quality(
2127 pw,
2128 &session.resolved_account_policy,
2129 session.account.related_inputs().as_slice(),
2130 session.account.radius_secret.as_deref(),
2131 )
2132 .map_err(|e| match e {
2133 PasswordQuality::TooShort(sz) => {
2134 OperationError::PasswordQuality(vec![PasswordFeedback::TooShort(sz)])
2135 }
2136 PasswordQuality::TooLong(sz) => {
2137 OperationError::PasswordQuality(vec![PasswordFeedback::TooLong(sz)])
2138 }
2139 PasswordQuality::BadListed => {
2140 OperationError::PasswordQuality(vec![PasswordFeedback::BadListed])
2141 }
2142 PasswordQuality::DontReusePasswords => {
2143 OperationError::PasswordQuality(vec![PasswordFeedback::DontReusePasswords])
2144 }
2145 PasswordQuality::Feedback(feedback) => OperationError::PasswordQuality(feedback),
2146 })?;
2147
2148 let ncred = match &session.primary {
2149 Some(primary) => {
2150 primary.set_password(self.crypto_policy, pw, timestamp)?
2152 }
2153 None => Credential::new_password_only(self.crypto_policy, pw, timestamp)?,
2154 };
2155
2156 session.dirty = true;
2157 session.primary = Some(ncred);
2158 Ok(session.deref().into())
2159 }
2160
2161 pub fn credential_primary_init_totp(
2162 &self,
2163 cust: &CredentialUpdateSessionToken,
2164 ct: Duration,
2165 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2166 let session_handle = self.get_current_session(cust, ct)?;
2167 let mut session = session_handle.try_lock().map_err(|_| {
2168 admin_error!("Session already locked, unable to proceed.");
2169 OperationError::InvalidState
2170 })?;
2171 trace!(?session);
2172
2173 if !matches!(session.primary_state, CredentialState::Modifiable) {
2174 error!("Session does not have permission to modify primary credential");
2175 return Err(OperationError::AccessDenied);
2176 };
2177
2178 if !matches!(session.mfaregstate, MfaRegState::None) {
2180 debug!("Clearing incomplete mfareg");
2181 }
2182
2183 let totp_token = Totp::generate_secure(TOTP_DEFAULT_STEP);
2185
2186 session.mfaregstate = MfaRegState::TotpInit(totp_token);
2187 Ok(session.deref().into())
2189 }
2190
2191 pub fn credential_primary_check_totp(
2192 &self,
2193 cust: &CredentialUpdateSessionToken,
2194 ct: Duration,
2195 totp_chal: u32,
2196 label: &str,
2197 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2198 let session_handle = self.get_current_session(cust, ct)?;
2199 let mut session = session_handle.try_lock().map_err(|_| {
2200 admin_error!("Session already locked, unable to proceed.");
2201 OperationError::InvalidState
2202 })?;
2203 trace!(?session);
2204
2205 if !matches!(session.primary_state, CredentialState::Modifiable) {
2206 error!("Session does not have permission to modify primary credential");
2207 return Err(OperationError::AccessDenied);
2208 };
2209
2210 let timestamp = OffsetDateTime::UNIX_EPOCH + ct;
2211
2212 match &session.mfaregstate {
2214 MfaRegState::TotpInit(totp_token)
2215 | MfaRegState::TotpTryAgain(totp_token)
2216 | MfaRegState::TotpNameTryAgain(totp_token, _)
2217 | MfaRegState::TotpInvalidSha1(totp_token, _, _) => {
2218 if session
2219 .primary
2220 .as_ref()
2221 .map(|cred| cred.has_totp_by_name(label))
2222 .unwrap_or_default()
2223 || label.trim().is_empty()
2224 || !Value::validate_str_escapes(label)
2225 {
2226 session.mfaregstate =
2228 MfaRegState::TotpNameTryAgain(totp_token.clone(), label.into());
2229 return Ok(session.deref().into());
2230 }
2231
2232 if totp_token.verify(totp_chal, ct) {
2233 let ncred = session
2235 .primary
2236 .as_ref()
2237 .map(|cred| {
2238 cred.append_totp(label.to_string(), totp_token.clone(), timestamp)
2239 })
2240 .ok_or_else(|| {
2241 admin_error!("A TOTP was added, but no primary credential stub exists");
2242 OperationError::InvalidState
2243 })?;
2244
2245 session.dirty = true;
2246 session.primary = Some(ncred);
2247
2248 session.mfaregstate = MfaRegState::None;
2250 Ok(session.deref().into())
2251 } else {
2252 let token_sha1 = totp_token.clone().downgrade_to_legacy();
2256
2257 if token_sha1.verify(totp_chal, ct) {
2258 session.mfaregstate = MfaRegState::TotpInvalidSha1(
2261 totp_token.clone(),
2262 token_sha1,
2263 label.to_string(),
2264 );
2265 Ok(session.deref().into())
2266 } else {
2267 session.mfaregstate = MfaRegState::TotpTryAgain(totp_token.clone());
2269 Ok(session.deref().into())
2270 }
2271 }
2272 }
2273 _ => Err(OperationError::InvalidRequestState),
2274 }
2275 }
2276
2277 pub fn credential_primary_accept_sha1_totp(
2278 &self,
2279 cust: &CredentialUpdateSessionToken,
2280 ct: Duration,
2281 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2282 let session_handle = self.get_current_session(cust, ct)?;
2283 let mut session = session_handle.try_lock().map_err(|_| {
2284 admin_error!("Session already locked, unable to proceed.");
2285 OperationError::InvalidState
2286 })?;
2287 trace!(?session);
2288
2289 if !matches!(session.primary_state, CredentialState::Modifiable) {
2290 error!("Session does not have permission to modify primary credential");
2291 return Err(OperationError::AccessDenied);
2292 };
2293
2294 let timestamp = OffsetDateTime::UNIX_EPOCH + ct;
2295
2296 match &session.mfaregstate {
2298 MfaRegState::TotpInvalidSha1(_, token_sha1, label) => {
2299 let ncred = session
2301 .primary
2302 .as_ref()
2303 .map(|cred| cred.append_totp(label.to_string(), token_sha1.clone(), timestamp))
2304 .ok_or_else(|| {
2305 admin_error!("A TOTP was added, but no primary credential stub exists");
2306 OperationError::InvalidState
2307 })?;
2308
2309 security_info!("A SHA1 TOTP credential was accepted");
2310
2311 session.dirty = true;
2312 session.primary = Some(ncred);
2313
2314 session.mfaregstate = MfaRegState::None;
2316 Ok(session.deref().into())
2317 }
2318 _ => Err(OperationError::InvalidRequestState),
2319 }
2320 }
2321
2322 pub fn credential_primary_remove_totp(
2323 &self,
2324 cust: &CredentialUpdateSessionToken,
2325 ct: Duration,
2326 label: &str,
2327 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2328 let session_handle = self.get_current_session(cust, ct)?;
2329 let mut session = session_handle.try_lock().map_err(|_| {
2330 admin_error!("Session already locked, unable to proceed.");
2331 OperationError::InvalidState
2332 })?;
2333 trace!(?session);
2334
2335 if !matches!(session.primary_state, CredentialState::Modifiable) {
2336 error!("Session does not have permission to modify primary credential");
2337 return Err(OperationError::AccessDenied);
2338 };
2339
2340 if !matches!(session.mfaregstate, MfaRegState::None) {
2341 admin_info!("Invalid TOTP state, another update is in progress");
2342 return Err(OperationError::InvalidState);
2343 }
2344
2345 let timestamp = OffsetDateTime::UNIX_EPOCH + ct;
2346
2347 let ncred = session
2348 .primary
2349 .as_ref()
2350 .map(|cred| cred.remove_totp(label, timestamp))
2351 .ok_or_else(|| {
2352 admin_error!("Try to remove TOTP, but no primary credential stub exists");
2353 OperationError::InvalidState
2354 })?;
2355
2356 session.dirty = true;
2357 session.primary = Some(ncred);
2358
2359 session.mfaregstate = MfaRegState::None;
2361 Ok(session.deref().into())
2362 }
2363
2364 pub fn credential_primary_init_backup_codes(
2365 &self,
2366 cust: &CredentialUpdateSessionToken,
2367 ct: Duration,
2368 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2369 let session_handle = self.get_current_session(cust, ct)?;
2370 let mut session = session_handle.try_lock().map_err(|_| {
2371 error!("Session already locked, unable to proceed.");
2372 OperationError::InvalidState
2373 })?;
2374 trace!(?session);
2375
2376 if !matches!(session.primary_state, CredentialState::Modifiable) {
2377 error!("Session does not have permission to modify primary credential");
2378 return Err(OperationError::AccessDenied);
2379 };
2380
2381 let timestamp = OffsetDateTime::UNIX_EPOCH + ct;
2382
2383 let codes = backup_code_from_random();
2386
2387 let ncred = session
2388 .primary
2389 .as_ref()
2390 .ok_or_else(|| {
2391 error!("Tried to add backup codes, but no primary credential stub exists");
2392 OperationError::InvalidState
2393 })
2394 .and_then(|cred|
2395 cred.update_backup_code(BackupCodes::new(codes.clone()), timestamp)
2396 .map_err(|_| {
2397 error!("Tried to add backup codes, but MFA is not enabled on this credential yet");
2398 OperationError::InvalidState
2399 })
2400 )
2401 ?;
2402
2403 session.dirty = true;
2404 session.primary = Some(ncred);
2405
2406 Ok(session.deref().into()).map(|mut status: CredentialUpdateSessionStatus| {
2407 status.mfaregstate = MfaRegStateStatus::BackupCodes(codes);
2408 status
2409 })
2410 }
2411
2412 pub fn credential_primary_remove_backup_codes(
2413 &self,
2414 cust: &CredentialUpdateSessionToken,
2415 ct: Duration,
2416 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2417 let session_handle = self.get_current_session(cust, ct)?;
2418 let mut session = session_handle.try_lock().map_err(|_| {
2419 admin_error!("Session already locked, unable to proceed.");
2420 OperationError::InvalidState
2421 })?;
2422 trace!(?session);
2423
2424 if !matches!(session.primary_state, CredentialState::Modifiable) {
2425 error!("Session does not have permission to modify primary credential");
2426 return Err(OperationError::AccessDenied);
2427 };
2428
2429 let timestamp = OffsetDateTime::UNIX_EPOCH + ct;
2430
2431 let ncred = session
2432 .primary
2433 .as_ref()
2434 .ok_or_else(|| {
2435 admin_error!("Tried to add backup codes, but no primary credential stub exists");
2436 OperationError::InvalidState
2437 })
2438 .and_then(|cred|
2439 cred.remove_backup_code(timestamp)
2440 .map_err(|_| {
2441 admin_error!("Tried to remove backup codes, but MFA is not enabled on this credential yet");
2442 OperationError::InvalidState
2443 })
2444 )
2445 ?;
2446
2447 session.dirty = true;
2448 session.primary = Some(ncred);
2449
2450 Ok(session.deref().into())
2451 }
2452
2453 pub fn credential_primary_delete(
2454 &self,
2455 cust: &CredentialUpdateSessionToken,
2456 ct: Duration,
2457 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2458 let session_handle = self.get_current_session(cust, ct)?;
2459 let mut session = session_handle.try_lock().map_err(|_| {
2460 admin_error!("Session already locked, unable to proceed.");
2461 OperationError::InvalidState
2462 })?;
2463 trace!(?session);
2464
2465 if !(matches!(session.primary_state, CredentialState::Modifiable)
2466 || matches!(session.primary_state, CredentialState::DeleteOnly))
2467 {
2468 error!("Session does not have permission to modify primary credential");
2469 return Err(OperationError::AccessDenied);
2470 };
2471
2472 session.dirty = true;
2473 session.primary = None;
2474 Ok(session.deref().into())
2475 }
2476
2477 pub fn credential_passkey_init(
2478 &self,
2479 cust: &CredentialUpdateSessionToken,
2480 ct: Duration,
2481 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2482 let session_handle = self.get_current_session(cust, ct)?;
2483 let mut session = session_handle.try_lock().map_err(|_| {
2484 admin_error!("Session already locked, unable to proceed.");
2485 OperationError::InvalidState
2486 })?;
2487 trace!(?session);
2488
2489 if !matches!(session.passkeys_state, CredentialState::Modifiable) {
2490 error!("Session does not have permission to modify passkeys");
2491 return Err(OperationError::AccessDenied);
2492 };
2493
2494 if !matches!(session.mfaregstate, MfaRegState::None) {
2495 debug!("Clearing incomplete mfareg");
2496 }
2497
2498 let (ccr, pk_reg) = self
2499 .webauthn
2500 .start_passkey_registration(
2501 session.account.uuid,
2502 session.account.spn(),
2503 &session.account.displayname,
2504 session.account.existing_credential_id_list(),
2505 )
2506 .map_err(|e| {
2507 error!(eclass=?e, emsg=%e, "Unable to start passkey registration");
2508 OperationError::Webauthn
2509 })?;
2510
2511 session.mfaregstate = MfaRegState::Passkey(Box::new(ccr), pk_reg);
2512 Ok(session.deref().into())
2514 }
2515
2516 pub fn credential_passkey_finish(
2517 &self,
2518 cust: &CredentialUpdateSessionToken,
2519 ct: Duration,
2520 label: String,
2521 reg: &RegisterPublicKeyCredential,
2522 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2523 let session_handle = self.get_current_session(cust, ct)?;
2524 let mut session = session_handle.try_lock().map_err(|_| {
2525 admin_error!("Session already locked, unable to proceed.");
2526 OperationError::InvalidState
2527 })?;
2528 trace!(?session);
2529
2530 if !matches!(session.passkeys_state, CredentialState::Modifiable) {
2531 error!("Session does not have permission to modify passkeys");
2532 return Err(OperationError::AccessDenied);
2533 };
2534
2535 match &session.mfaregstate {
2536 MfaRegState::Passkey(_ccr, pk_reg) => {
2537 let reg_result = self.webauthn.finish_passkey_registration(reg, pk_reg);
2538
2539 session.mfaregstate = MfaRegState::None;
2541
2542 match reg_result {
2543 Ok(passkey) => {
2544 let pk_id = Uuid::new_v4();
2545
2546 session.dirty = true;
2547 session.passkeys.insert(pk_id, (label, passkey));
2548
2549 let cu_status: CredentialUpdateSessionStatus = session.deref().into();
2550 Ok(cu_status)
2551 }
2552 Err(WebauthnError::UserNotVerified) => {
2553 let mut cu_status: CredentialUpdateSessionStatus = session.deref().into();
2554 cu_status.append_ephemeral_warning(
2555 CredentialUpdateSessionStatusWarnings::WebauthnUserVerificationRequired,
2556 );
2557 Ok(cu_status)
2558 }
2559 Err(err) => {
2560 error!(eclass=?err, emsg=%err, "Unable to complete passkey registration");
2561 Err(OperationError::CU0002WebauthnRegistrationError)
2562 }
2563 }
2564 }
2565 invalid_state => {
2566 warn!(?invalid_state);
2567 Err(OperationError::InvalidRequestState)
2568 }
2569 }
2570 }
2571
2572 pub fn credential_passkey_remove(
2573 &self,
2574 cust: &CredentialUpdateSessionToken,
2575 ct: Duration,
2576 uuid: Uuid,
2577 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2578 let session_handle = self.get_current_session(cust, ct)?;
2579 let mut session = session_handle.try_lock().map_err(|_| {
2580 admin_error!("Session already locked, unable to proceed.");
2581 OperationError::InvalidState
2582 })?;
2583 trace!(?session);
2584
2585 if !(matches!(session.passkeys_state, CredentialState::Modifiable)
2586 || matches!(session.passkeys_state, CredentialState::DeleteOnly))
2587 {
2588 error!("Session does not have permission to modify passkeys");
2589 return Err(OperationError::AccessDenied);
2590 };
2591
2592 session.dirty = true;
2594 session.passkeys.remove(&uuid);
2595
2596 Ok(session.deref().into())
2597 }
2598
2599 pub fn credential_attested_passkey_init(
2600 &self,
2601 cust: &CredentialUpdateSessionToken,
2602 ct: Duration,
2603 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2604 let session_handle = self.get_current_session(cust, ct)?;
2605 let mut session = session_handle.try_lock().map_err(|_| {
2606 error!("Session already locked, unable to proceed.");
2607 OperationError::InvalidState
2608 })?;
2609 trace!(?session);
2610
2611 if !matches!(session.attested_passkeys_state, CredentialState::Modifiable) {
2612 error!("Session does not have permission to modify attested passkeys");
2613 return Err(OperationError::AccessDenied);
2614 };
2615
2616 if !matches!(session.mfaregstate, MfaRegState::None) {
2617 debug!("Cancelling abandoned mfareg");
2618 }
2619
2620 let att_ca_list = session
2621 .resolved_account_policy
2622 .webauthn_attestation_ca_list()
2623 .cloned()
2624 .ok_or_else(|| {
2625 error!(
2626 "No attestation CA list is available, can not proceed with attested passkeys."
2627 );
2628 OperationError::AccessDenied
2629 })?;
2630
2631 let (ccr, pk_reg) = self
2632 .webauthn
2633 .start_attested_passkey_registration(
2634 session.account.uuid,
2635 session.account.spn(),
2636 &session.account.displayname,
2637 session.account.existing_credential_id_list(),
2638 att_ca_list,
2639 None,
2640 )
2641 .map_err(|e| {
2642 error!(eclass=?e, emsg=%e, "Unable to start passkey registration");
2643 OperationError::Webauthn
2644 })?;
2645
2646 session.mfaregstate = MfaRegState::AttestedPasskey(Box::new(ccr), pk_reg);
2647 Ok(session.deref().into())
2649 }
2650
2651 pub fn credential_attested_passkey_finish(
2652 &self,
2653 cust: &CredentialUpdateSessionToken,
2654 ct: Duration,
2655 label: String,
2656 reg: &RegisterPublicKeyCredential,
2657 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2658 let session_handle = self.get_current_session(cust, ct)?;
2659 let mut session = session_handle.try_lock().map_err(|_| {
2660 admin_error!("Session already locked, unable to proceed.");
2661 OperationError::InvalidState
2662 })?;
2663 trace!(?session);
2664
2665 if !matches!(session.attested_passkeys_state, CredentialState::Modifiable) {
2666 error!("Session does not have permission to modify attested passkeys");
2667 return Err(OperationError::AccessDenied);
2668 };
2669
2670 match &session.mfaregstate {
2671 MfaRegState::AttestedPasskey(_ccr, pk_reg) => {
2672 let result = self
2673 .webauthn
2674 .finish_attested_passkey_registration(reg, pk_reg)
2675 .map_err(|e| {
2676 error!(eclass=?e, emsg=%e, "Unable to complete attested passkey registration");
2677
2678 match e {
2679 WebauthnError::AttestationChainNotTrusted(_)
2680 | WebauthnError::AttestationNotVerifiable => {
2681 OperationError::CU0001WebauthnAttestationNotTrusted
2682 },
2683 WebauthnError::UserNotVerified => {
2684 OperationError::CU0003WebauthnUserNotVerified
2685 },
2686 _ => OperationError::CU0002WebauthnRegistrationError,
2687 }
2688 });
2689
2690 session.mfaregstate = MfaRegState::None;
2692
2693 let passkey = result?;
2694 trace!(?passkey);
2695
2696 session.dirty = true;
2697
2698 let pk_id = Uuid::new_v4();
2699 session.attested_passkeys.insert(pk_id, (label, passkey));
2700
2701 trace!(?session.attested_passkeys);
2702
2703 Ok(session.deref().into())
2704 }
2705 _ => Err(OperationError::InvalidRequestState),
2706 }
2707 }
2708
2709 pub fn credential_attested_passkey_remove(
2710 &self,
2711 cust: &CredentialUpdateSessionToken,
2712 ct: Duration,
2713 uuid: Uuid,
2714 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2715 let session_handle = self.get_current_session(cust, ct)?;
2716 let mut session = session_handle.try_lock().map_err(|_| {
2717 admin_error!("Session already locked, unable to proceed.");
2718 OperationError::InvalidState
2719 })?;
2720 trace!(?session);
2721
2722 if !(matches!(session.attested_passkeys_state, CredentialState::Modifiable)
2723 || matches!(session.attested_passkeys_state, CredentialState::DeleteOnly))
2724 {
2725 error!("Session does not have permission to modify attested passkeys");
2726 return Err(OperationError::AccessDenied);
2727 };
2728
2729 session.dirty = true;
2731 session.attested_passkeys.remove(&uuid);
2732
2733 Ok(session.deref().into())
2734 }
2735
2736 #[instrument(level = "trace", skip(cust, self))]
2737 pub fn credential_unix_set_password(
2738 &self,
2739 cust: &CredentialUpdateSessionToken,
2740 ct: Duration,
2741 pw: &str,
2742 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2743 let session_handle = self.get_current_session(cust, ct)?;
2744 let mut session = session_handle.try_lock().map_err(|_| {
2745 admin_error!("Session already locked, unable to proceed.");
2746 OperationError::InvalidState
2747 })?;
2748 trace!(?session);
2749
2750 if !matches!(session.unixcred_state, CredentialState::Modifiable) {
2751 error!("Session does not have permission to modify unix credential");
2752 return Err(OperationError::AccessDenied);
2753 };
2754
2755 let timestamp = OffsetDateTime::UNIX_EPOCH + ct;
2756
2757 self.check_password_quality(
2758 pw,
2759 &session.resolved_account_policy,
2760 session.account.related_inputs().as_slice(),
2761 session.account.radius_secret.as_deref(),
2762 )
2763 .map_err(|e| match e {
2764 PasswordQuality::TooShort(sz) => {
2765 OperationError::PasswordQuality(vec![PasswordFeedback::TooShort(sz)])
2766 }
2767 PasswordQuality::TooLong(sz) => {
2768 OperationError::PasswordQuality(vec![PasswordFeedback::TooLong(sz)])
2769 }
2770 PasswordQuality::BadListed => {
2771 OperationError::PasswordQuality(vec![PasswordFeedback::BadListed])
2772 }
2773 PasswordQuality::DontReusePasswords => {
2774 OperationError::PasswordQuality(vec![PasswordFeedback::DontReusePasswords])
2775 }
2776 PasswordQuality::Feedback(feedback) => OperationError::PasswordQuality(feedback),
2777 })?;
2778
2779 let ncred = match &session.unixcred {
2780 Some(unixcred) => {
2781 unixcred.set_password(self.crypto_policy, pw, timestamp)?
2783 }
2784 None => Credential::new_password_only(self.crypto_policy, pw, timestamp)?,
2785 };
2786
2787 session.dirty = true;
2788 session.unixcred = Some(ncred);
2789 Ok(session.deref().into())
2790 }
2791
2792 pub fn credential_unix_delete(
2793 &self,
2794 cust: &CredentialUpdateSessionToken,
2795 ct: Duration,
2796 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2797 let session_handle = self.get_current_session(cust, ct)?;
2798 let mut session = session_handle.try_lock().map_err(|_| {
2799 admin_error!("Session already locked, unable to proceed.");
2800 OperationError::InvalidState
2801 })?;
2802 trace!(?session);
2803
2804 if !(matches!(session.unixcred_state, CredentialState::Modifiable)
2805 || matches!(session.unixcred_state, CredentialState::DeleteOnly))
2806 {
2807 error!("Session does not have permission to modify unix credential");
2808 return Err(OperationError::AccessDenied);
2809 };
2810
2811 session.dirty = true;
2812 session.unixcred = None;
2813 Ok(session.deref().into())
2814 }
2815
2816 #[instrument(level = "trace", skip(cust, self))]
2817 pub fn credential_sshkey_add(
2818 &self,
2819 cust: &CredentialUpdateSessionToken,
2820 ct: Duration,
2821 label: String,
2822 sshpubkey: SshPublicKey,
2823 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2824 let session_handle = self.get_current_session(cust, ct)?;
2825 let mut session = session_handle.try_lock().map_err(|_| {
2826 admin_error!("Session already locked, unable to proceed.");
2827 OperationError::InvalidState
2828 })?;
2829 trace!(?session);
2830
2831 if !matches!(session.unixcred_state, CredentialState::Modifiable) {
2832 error!("Session does not have permission to modify unix credential");
2833 return Err(OperationError::AccessDenied);
2834 };
2835
2836 if !LABEL_RE.is_match(&label) {
2838 error!("SSH Public Key label invalid");
2839 return Err(OperationError::InvalidLabel);
2840 }
2841
2842 if session.sshkeys.contains_key(&label) {
2843 error!("SSH Public Key label duplicate");
2844 return Err(OperationError::DuplicateLabel);
2845 }
2846
2847 if session.sshkeys.values().any(|sk| *sk == sshpubkey) {
2848 error!("SSH Public Key duplicate");
2849 return Err(OperationError::DuplicateKey);
2850 }
2851
2852 session.dirty = true;
2853 session.sshkeys.insert(label, sshpubkey);
2854
2855 Ok(session.deref().into())
2856 }
2857
2858 pub fn credential_sshkey_remove(
2859 &self,
2860 cust: &CredentialUpdateSessionToken,
2861 ct: Duration,
2862 label: &str,
2863 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2864 let session_handle = self.get_current_session(cust, ct)?;
2865 let mut session = session_handle.try_lock().map_err(|_| {
2866 admin_error!("Session already locked, unable to proceed.");
2867 OperationError::InvalidState
2868 })?;
2869 trace!(?session);
2870
2871 if !(matches!(session.sshkeys_state, CredentialState::Modifiable)
2872 || matches!(session.sshkeys_state, CredentialState::DeleteOnly))
2873 {
2874 error!("Session does not have permission to modify sshkeys");
2875 return Err(OperationError::AccessDenied);
2876 };
2877
2878 session.dirty = true;
2879 session.sshkeys.remove(label).ok_or_else(|| {
2880 error!("No such key for label");
2881 OperationError::NoMatchingEntries
2882 })?;
2883
2884 Ok(session.deref().into())
2887 }
2888
2889 pub fn credential_update_cancel_mfareg(
2890 &self,
2891 cust: &CredentialUpdateSessionToken,
2892 ct: Duration,
2893 ) -> Result<CredentialUpdateSessionStatus, OperationError> {
2894 let session_handle = self.get_current_session(cust, ct)?;
2895 let mut session = session_handle.try_lock().map_err(|_| {
2896 admin_error!("Session already locked, unable to proceed.");
2897 OperationError::InvalidState
2898 })?;
2899 trace!(?session);
2900 session.mfaregstate = MfaRegState::None;
2901 Ok(session.deref().into())
2902 }
2903
2904 }
2906
2907#[cfg(test)]
2908mod tests {
2909 use super::{
2910 CredentialState, CredentialUpdateAccountRecovery, CredentialUpdateSessionStatus,
2911 CredentialUpdateSessionStatusWarnings, CredentialUpdateSessionToken,
2912 InitCredentialUpdateEvent, InitCredentialUpdateIntentEvent,
2913 InitCredentialUpdateIntentSendEvent, MfaRegStateStatus, MAXIMUM_CRED_UPDATE_TTL,
2914 MAXIMUM_INTENT_TTL, MINIMUM_INTENT_TTL,
2915 };
2916 use crate::{
2917 credential::totp::Totp,
2918 event::CreateEvent,
2919 idm::{
2920 audit::AuditEvent,
2921 authentication::AuthState,
2922 delayed::DelayedAction,
2923 event::{AuthEvent, AuthResult, RegenerateRadiusSecretEvent, UnixUserAuthEvent},
2924 server::{IdmServer, IdmServerCredUpdateTransaction, IdmServerDelayed},
2925 },
2926 prelude::*,
2927 utils::{password_from_random_len, readable_password_from_random},
2928 value::CredentialType,
2929 valueset::ValueSetEmailAddress,
2930 };
2931 use compact_jwt::JwsCompact;
2932 use kanidm_lib_crypto::{PW_MAX_LENGTH_NIST, PW_SFA_MIN_LENGTH_NIST};
2933 use kanidm_proto::{
2934 internal::{CUExtPortal, CredentialDetailType, PasswordFeedback},
2935 v1::{AuthAllowed, AuthIssueSession, AuthMech, OutboundMessage, UnixUserToken},
2936 };
2937 use sshkey_attest::proto::PublicKey as SshPublicKey;
2938 use std::time::Duration;
2939 use time::OffsetDateTime;
2940 use uuid::uuid;
2941 use webauthn_authenticator_rs::{
2942 softpasskey::SoftPasskey,
2943 softtoken::{self, SoftToken},
2944 WebauthnAuthenticator,
2945 };
2946 use webauthn_rs::prelude::AttestationCaListBuilder;
2947
2948 const TEST_CURRENT_TIME: u64 = 6000;
2949 const TESTPERSON_UUID: Uuid = uuid!("cf231fea-1a8f-4410-a520-fd9b1a379c86");
2950 const TESTPERSON_NAME: &str = "testperson";
2951
2952 const SSHKEY_VALID_1: &str = "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBENubZikrb8hu+HeVRdZ0pp/VAk2qv4JDbuJhvD0yNdWDL2e3cBbERiDeNPkWx58Q4rVnxkbV1fa8E2waRtT91wAAAAEc3NoOg== testuser@fidokey";
2953 const SSHKEY_VALID_2: &str = "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBIbkSsdGCRoW6v0nO/3vNYPhG20YhWU0wQPY7x52EOb4dmYhC4IJfzVDpEPg313BxWRKQglb5RQ1PPkou7JFyCUAAAAEc3NoOg== testuser@fidokey";
2954 const SSHKEY_INVALID: &str = "sk-ecrsa-sha9000-nistp@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBIbkSsdGCRoW6v0nO/3vNYPhG20YhWU0wQPY7x52EOb4dmYhC4IJfzVDpEPg313BxWRKQglb5RQ1PPkou7JFyCUAAAAEc3NoOg== badkey@rejectme";
2955
2956 #[idm_test]
2957 async fn credential_update_session_init(
2958 idms: &IdmServer,
2959 _idms_delayed: &mut IdmServerDelayed,
2960 ) {
2961 let ct = Duration::from_secs(TEST_CURRENT_TIME);
2962 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2963
2964 let testaccount_uuid = Uuid::new_v4();
2965
2966 let e1 = entry_init!(
2967 (Attribute::Class, EntryClass::Object.to_value()),
2968 (Attribute::Class, EntryClass::Account.to_value()),
2969 (Attribute::Class, EntryClass::ServiceAccount.to_value()),
2970 (Attribute::Name, Value::new_iname("user_account_only")),
2971 (Attribute::Uuid, Value::Uuid(testaccount_uuid)),
2972 (Attribute::Description, Value::new_utf8s("testaccount")),
2973 (Attribute::DisplayName, Value::new_utf8s("testaccount"))
2974 );
2975
2976 let e2 = entry_init!(
2977 (Attribute::Class, EntryClass::Object.to_value()),
2978 (Attribute::Class, EntryClass::Account.to_value()),
2979 (Attribute::Class, EntryClass::PosixAccount.to_value()),
2980 (Attribute::Class, EntryClass::Person.to_value()),
2981 (Attribute::Name, Value::new_iname(TESTPERSON_NAME)),
2982 (Attribute::Uuid, Value::Uuid(TESTPERSON_UUID)),
2983 (Attribute::Description, Value::new_utf8s(TESTPERSON_NAME)),
2984 (Attribute::DisplayName, Value::new_utf8s(TESTPERSON_NAME))
2985 );
2986
2987 let ce = CreateEvent::new_internal(vec![e1, e2]);
2988 let cr = idms_prox_write.qs_write.create(&ce);
2989 assert!(cr.is_ok());
2990
2991 let testaccount = idms_prox_write
2992 .qs_write
2993 .internal_search_uuid(testaccount_uuid)
2994 .expect("failed");
2995
2996 let testperson = idms_prox_write
2997 .qs_write
2998 .internal_search_uuid(TESTPERSON_UUID)
2999 .expect("failed");
3000
3001 let idm_admin = idms_prox_write
3002 .qs_write
3003 .internal_search_uuid(UUID_IDM_ADMIN)
3004 .expect("failed");
3005
3006 let cur = idms_prox_write.init_credential_update(
3010 &InitCredentialUpdateEvent::new_impersonate_entry(testaccount),
3011 ct,
3012 );
3013
3014 assert!(matches!(cur, Err(OperationError::NotAuthorised)));
3015
3016 let cur = idms_prox_write.init_credential_update(
3019 &InitCredentialUpdateEvent::new_impersonate_entry(testperson),
3020 ct,
3021 );
3022
3023 assert!(cur.is_ok());
3024
3025 let cur = idms_prox_write.init_credential_update_intent(
3030 &InitCredentialUpdateIntentEvent::new_impersonate_entry(
3031 idm_admin.clone(),
3032 TESTPERSON_UUID,
3033 MINIMUM_INTENT_TTL,
3034 ),
3035 ct,
3036 );
3037
3038 assert!(cur.is_ok());
3039 let intent_tok = cur.expect("Failed to create intent token!");
3040
3041 let cur = idms_prox_write
3044 .exchange_intent_credential_update(intent_tok.clone().into(), ct + MINIMUM_INTENT_TTL);
3045
3046 assert!(matches!(cur, Err(OperationError::SessionExpired)));
3047
3048 let cur = idms_prox_write
3049 .exchange_intent_credential_update(intent_tok.clone().into(), ct + MAXIMUM_INTENT_TTL);
3050
3051 assert!(matches!(cur, Err(OperationError::SessionExpired)));
3052
3053 let (cust_a, _c_status) = idms_prox_write
3055 .exchange_intent_credential_update(intent_tok.clone().into(), ct)
3056 .unwrap();
3057
3058 let (cust_b, _c_status) = idms_prox_write
3061 .exchange_intent_credential_update(intent_tok.into(), ct + Duration::from_secs(1))
3062 .unwrap();
3063
3064 let cur = idms_prox_write.commit_credential_update(&cust_a, ct);
3065
3066 trace!(?cur);
3068 assert!(cur.is_err());
3069
3070 let _ = idms_prox_write.commit_credential_update(&cust_b, ct);
3072
3073 debug!("Start intent token revoke");
3074
3075 let intent_tok = idms_prox_write
3077 .init_credential_update_intent(
3078 &InitCredentialUpdateIntentEvent::new_impersonate_entry(
3079 idm_admin,
3080 TESTPERSON_UUID,
3081 MINIMUM_INTENT_TTL,
3082 ),
3083 ct,
3084 )
3085 .expect("Failed to create intent token!");
3086
3087 idms_prox_write
3088 .revoke_credential_update_intent(intent_tok.clone().into(), ct)
3089 .expect("Failed to revoke intent");
3090
3091 let cur = idms_prox_write.exchange_intent_credential_update(
3093 intent_tok.clone().into(),
3094 ct + Duration::from_secs(1),
3095 );
3096 debug!(?cur);
3097 assert!(matches!(cur, Err(OperationError::SessionExpired)));
3098
3099 idms_prox_write.commit().expect("Failed to commit txn");
3100 }
3101
3102 async fn setup_test_session(
3103 idms: &IdmServer,
3104 ct: Duration,
3105 ) -> (CredentialUpdateSessionToken, CredentialUpdateSessionStatus) {
3106 setup_test_session_inner(idms, ct, true).await
3107 }
3108
3109 async fn setup_test_session_no_posix(
3110 idms: &IdmServer,
3111 ct: Duration,
3112 ) -> (CredentialUpdateSessionToken, CredentialUpdateSessionStatus) {
3113 setup_test_session_inner(idms, ct, false).await
3114 }
3115
3116 async fn setup_test_session_inner(
3117 idms: &IdmServer,
3118 ct: Duration,
3119 posix: bool,
3120 ) -> (CredentialUpdateSessionToken, CredentialUpdateSessionStatus) {
3121 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3122
3123 let modlist = ModifyList::new_purge(Attribute::CredentialTypeMinimum);
3125 idms_prox_write
3126 .qs_write
3127 .internal_modify_uuid(UUID_IDM_ALL_PERSONS, &modlist)
3128 .expect("Unable to change default session exp");
3129
3130 let mut builder = entry_init!(
3131 (Attribute::Class, EntryClass::Object.to_value()),
3132 (Attribute::Class, EntryClass::Account.to_value()),
3133 (Attribute::Class, EntryClass::Person.to_value()),
3134 (Attribute::Name, Value::new_iname(TESTPERSON_NAME)),
3135 (Attribute::Uuid, Value::Uuid(TESTPERSON_UUID)),
3136 (Attribute::Description, Value::new_utf8s(TESTPERSON_NAME)),
3137 (Attribute::DisplayName, Value::new_utf8s(TESTPERSON_NAME))
3138 );
3139
3140 if posix {
3141 builder.add_ava(Attribute::Class, EntryClass::PosixAccount.to_value());
3142 }
3143
3144 let ce = CreateEvent::new_internal(vec![builder]);
3145 let cr = idms_prox_write.qs_write.create(&ce);
3146 assert!(cr.is_ok());
3147
3148 let testperson = idms_prox_write
3149 .qs_write
3150 .internal_search_uuid(TESTPERSON_UUID)
3151 .expect("failed");
3152
3153 if posix {
3154 let rrse = RegenerateRadiusSecretEvent::new_internal(TESTPERSON_UUID);
3156
3157 let _ = idms_prox_write
3158 .regenerate_radius_secret(&rrse)
3159 .expect("Failed to reset radius credential 1");
3160 }
3161
3162 let cur = idms_prox_write.init_credential_update(
3163 &InitCredentialUpdateEvent::new_impersonate_entry(testperson),
3164 ct,
3165 );
3166
3167 idms_prox_write.commit().expect("Failed to commit txn");
3168
3169 cur.expect("Failed to start update")
3170 }
3171
3172 async fn renew_test_session(
3173 idms: &IdmServer,
3174 ct: Duration,
3175 ) -> (CredentialUpdateSessionToken, CredentialUpdateSessionStatus) {
3176 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3177
3178 let testperson = idms_prox_write
3179 .qs_write
3180 .internal_search_uuid(TESTPERSON_UUID)
3181 .expect("failed");
3182
3183 let cur = idms_prox_write.init_credential_update(
3184 &InitCredentialUpdateEvent::new_impersonate_entry(testperson),
3185 ct,
3186 );
3187
3188 trace!(renew_test_session_result = ?cur);
3189
3190 idms_prox_write.commit().expect("Failed to commit txn");
3191
3192 cur.expect("Failed to start update")
3193 }
3194
3195 async fn commit_session(idms: &IdmServer, ct: Duration, cust: CredentialUpdateSessionToken) {
3196 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3197
3198 idms_prox_write
3199 .commit_credential_update(&cust, ct)
3200 .expect("Failed to commit credential update.");
3201
3202 idms_prox_write.commit().expect("Failed to commit txn");
3203 }
3204
3205 async fn check_testperson_password(
3206 idms: &IdmServer,
3207 idms_delayed: &mut IdmServerDelayed,
3208 pw: &str,
3209 ct: Duration,
3210 ) -> Option<JwsCompact> {
3211 let mut idms_auth = idms.auth().await.unwrap();
3212
3213 let auth_init = AuthEvent::named_init(TESTPERSON_NAME);
3214
3215 let r1 = idms_auth
3216 .auth(&auth_init, ct, Source::Internal.into())
3217 .await;
3218 let ar = r1.unwrap();
3219 let AuthResult { sessionid, state } = ar;
3220
3221 if !matches!(state, AuthState::Choose(_)) {
3222 debug!("Can't proceed - {:?}", state);
3223 return None;
3224 };
3225
3226 let auth_begin = AuthEvent::begin_mech(sessionid, AuthMech::Password);
3227
3228 let r2 = idms_auth
3229 .auth(&auth_begin, ct, Source::Internal.into())
3230 .await;
3231 let ar = r2.unwrap();
3232 let AuthResult { sessionid, state } = ar;
3233
3234 assert!(matches!(state, AuthState::Continue(_)));
3235
3236 let pw_step = AuthEvent::cred_step_password(sessionid, pw);
3237
3238 let r2 = idms_auth.auth(&pw_step, ct, Source::Internal.into()).await;
3240 debug!("r2 ==> {:?}", r2);
3241 idms_auth.commit().expect("Must not fail");
3242
3243 match r2 {
3244 Ok(AuthResult {
3245 sessionid: _,
3246 state: AuthState::Success(token, AuthIssueSession::Token),
3247 }) => {
3248 let da = idms_delayed.try_recv().expect("invalid");
3250 assert!(matches!(da, DelayedAction::AuthSessionRecord(_)));
3251
3252 Some(*token)
3253 }
3254 _ => None,
3255 }
3256 }
3257
3258 async fn check_testperson_unix_password(
3259 idms: &IdmServer,
3260 pw: &str,
3262 ct: Duration,
3263 ) -> Option<UnixUserToken> {
3264 let mut idms_auth = idms.auth().await.unwrap();
3265
3266 let auth_event = UnixUserAuthEvent::new_internal(TESTPERSON_UUID, pw);
3267
3268 idms_auth
3269 .auth_unix(&auth_event, ct)
3270 .await
3271 .expect("Unable to perform unix authentication")
3272 }
3273
3274 async fn check_testperson_password_totp(
3275 idms: &IdmServer,
3276 idms_delayed: &mut IdmServerDelayed,
3277 pw: &str,
3278 token: &Totp,
3279 ct: Duration,
3280 ) -> Option<JwsCompact> {
3281 let mut idms_auth = idms.auth().await.unwrap();
3282
3283 let auth_init = AuthEvent::named_init(TESTPERSON_NAME);
3284
3285 let r1 = idms_auth
3286 .auth(&auth_init, ct, Source::Internal.into())
3287 .await;
3288 let ar = r1.unwrap();
3289 let AuthResult { sessionid, state } = ar;
3290
3291 if !matches!(state, AuthState::Choose(_)) {
3292 debug!("Can't proceed - {:?}", state);
3293 return None;
3294 };
3295
3296 let auth_begin = AuthEvent::begin_mech(sessionid, AuthMech::PasswordTotp);
3297
3298 let r2 = idms_auth
3299 .auth(&auth_begin, ct, Source::Internal.into())
3300 .await;
3301 let ar = r2.unwrap();
3302 let AuthResult { sessionid, state } = ar;
3303
3304 assert!(matches!(state, AuthState::Continue(_)));
3305
3306 let totp = token
3307 .do_totp_duration_from_epoch(&ct)
3308 .expect("Failed to perform totp step");
3309
3310 let totp_step = AuthEvent::cred_step_totp(sessionid, totp);
3311 let r2 = idms_auth
3312 .auth(&totp_step, ct, Source::Internal.into())
3313 .await;
3314 let ar = r2.unwrap();
3315 let AuthResult { sessionid, state } = ar;
3316
3317 assert!(matches!(state, AuthState::Continue(_)));
3318
3319 let pw_step = AuthEvent::cred_step_password(sessionid, pw);
3320
3321 let r3 = idms_auth.auth(&pw_step, ct, Source::Internal.into()).await;
3323 debug!("r3 ==> {:?}", r3);
3324 idms_auth.commit().expect("Must not fail");
3325
3326 match r3 {
3327 Ok(AuthResult {
3328 sessionid: _,
3329 state: AuthState::Success(token, AuthIssueSession::Token),
3330 }) => {
3331 let da = idms_delayed.try_recv().expect("invalid");
3333 assert!(matches!(da, DelayedAction::AuthSessionRecord(_)));
3334 Some(*token)
3335 }
3336 _ => None,
3337 }
3338 }
3339
3340 async fn check_testperson_password_backup_code(
3341 idms: &IdmServer,
3342 idms_delayed: &mut IdmServerDelayed,
3343 pw: &str,
3344 code: &str,
3345 ct: Duration,
3346 ) -> Option<JwsCompact> {
3347 let mut idms_auth = idms.auth().await.unwrap();
3348
3349 let auth_init = AuthEvent::named_init(TESTPERSON_NAME);
3350
3351 let r1 = idms_auth
3352 .auth(&auth_init, ct, Source::Internal.into())
3353 .await;
3354 let ar = r1.unwrap();
3355 let AuthResult { sessionid, state } = ar;
3356
3357 if !matches!(state, AuthState::Choose(_)) {
3358 debug!("Can't proceed - {:?}", state);
3359 return None;
3360 };
3361
3362 let auth_begin = AuthEvent::begin_mech(sessionid, AuthMech::PasswordBackupCode);
3363
3364 let r2 = idms_auth
3365 .auth(&auth_begin, ct, Source::Internal.into())
3366 .await;
3367 let ar = r2.unwrap();
3368 let AuthResult { sessionid, state } = ar;
3369
3370 assert!(matches!(state, AuthState::Continue(_)));
3371
3372 let code_step = AuthEvent::cred_step_backup_code(sessionid, code);
3373 let r2 = idms_auth
3374 .auth(&code_step, ct, Source::Internal.into())
3375 .await;
3376 let ar = r2.unwrap();
3377 let AuthResult { sessionid, state } = ar;
3378
3379 assert!(matches!(state, AuthState::Continue(_)));
3380
3381 let pw_step = AuthEvent::cred_step_password(sessionid, pw);
3382
3383 let r3 = idms_auth.auth(&pw_step, ct, Source::Internal.into()).await;
3385 debug!("r3 ==> {:?}", r3);
3386 idms_auth.commit().expect("Must not fail");
3387
3388 match r3 {
3389 Ok(AuthResult {
3390 sessionid: _,
3391 state: AuthState::Success(token, AuthIssueSession::Token),
3392 }) => {
3393 let da = idms_delayed.try_recv().expect("invalid");
3395 assert!(matches!(da, DelayedAction::BackupCodeRemoval(_)));
3396 let r = idms.delayed_action(ct, da).await;
3397 assert!(r.is_ok());
3398
3399 let da = idms_delayed.try_recv().expect("invalid");
3401 assert!(matches!(da, DelayedAction::AuthSessionRecord(_)));
3402 Some(*token)
3403 }
3404 _ => None,
3405 }
3406 }
3407
3408 async fn check_testperson_passkey<T: WebauthnAuthenticator>(
3409 idms: &IdmServer,
3410 idms_delayed: &mut IdmServerDelayed,
3411 wa: &mut T,
3412 origin: Url,
3413 ct: Duration,
3414 ) -> Option<JwsCompact> {
3415 let mut idms_auth = idms.auth().await.unwrap();
3416
3417 let auth_init = AuthEvent::named_init(TESTPERSON_NAME);
3418
3419 let r1 = idms_auth
3420 .auth(&auth_init, ct, Source::Internal.into())
3421 .await;
3422 let ar = r1.unwrap();
3423 let AuthResult { sessionid, state } = ar;
3424
3425 if !matches!(state, AuthState::Choose(_)) {
3426 debug!("Can't proceed - {:?}", state);
3427 return None;
3428 };
3429
3430 let auth_begin = AuthEvent::begin_mech(sessionid, AuthMech::Passkey);
3431
3432 let ar = idms_auth
3433 .auth(&auth_begin, ct, Source::Internal.into())
3434 .await
3435 .inspect_err(|err| error!(?err))
3436 .ok()?;
3437 let AuthResult { sessionid, state } = ar;
3438
3439 trace!(?state);
3440
3441 let rcr = match state {
3442 AuthState::Continue(mut allowed) => match allowed.pop() {
3443 Some(AuthAllowed::Passkey(rcr)) => rcr,
3444 _ => unreachable!(),
3445 },
3446 _ => unreachable!(),
3447 };
3448
3449 trace!(?rcr);
3450
3451 let resp = wa
3452 .do_authentication(origin, rcr)
3453 .inspect_err(|err| error!(?err))
3454 .ok()?;
3455
3456 let passkey_step = AuthEvent::cred_step_passkey(sessionid, resp);
3457
3458 let r3 = idms_auth
3459 .auth(&passkey_step, ct, Source::Internal.into())
3460 .await;
3461 debug!("r3 ==> {:?}", r3);
3462 idms_auth.commit().expect("Must not fail");
3463
3464 match r3 {
3465 Ok(AuthResult {
3466 sessionid: _,
3467 state: AuthState::Success(token, AuthIssueSession::Token),
3468 }) => {
3469 let da = idms_delayed.try_recv().expect("invalid");
3471 assert!(matches!(da, DelayedAction::WebauthnCounterIncrement(_)));
3472 let r = idms.delayed_action(ct, da).await;
3473 assert!(r.is_ok());
3474
3475 let da = idms_delayed.try_recv().expect("invalid");
3477 assert!(matches!(da, DelayedAction::AuthSessionRecord(_)));
3478
3479 Some(*token)
3480 }
3481 _ => None,
3482 }
3483 }
3484
3485 #[idm_test]
3486 async fn credential_update_session_cleanup(
3487 idms: &IdmServer,
3488 _idms_delayed: &mut IdmServerDelayed,
3489 ) {
3490 let ct = Duration::from_secs(TEST_CURRENT_TIME);
3491 let (cust, _) = setup_test_session(idms, ct).await;
3492
3493 let cutxn = idms.cred_update_transaction().await.unwrap();
3494 let c_status = cutxn.credential_update_status(&cust, ct);
3496 assert!(c_status.is_ok());
3497 drop(cutxn);
3498
3499 let (_cust, _) =
3501 renew_test_session(idms, ct + MAXIMUM_CRED_UPDATE_TTL + Duration::from_secs(1)).await;
3502
3503 let cutxn = idms.cred_update_transaction().await.unwrap();
3504
3505 let c_status = cutxn
3508 .credential_update_status(&cust, ct)
3509 .expect_err("Session is still valid!");
3510 assert!(matches!(c_status, OperationError::InvalidState));
3511 }
3512
3513 #[idm_test]
3514 async fn credential_update_intent_send(idms: &IdmServer, _idms_delayed: &mut IdmServerDelayed) {
3515 let ct = Duration::from_secs(TEST_CURRENT_TIME);
3516
3517 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3518
3519 let email_address = format!("{}@example.com", TESTPERSON_NAME);
3520
3521 let test_entry = EntryInitNew::from_iter([
3522 (
3523 Attribute::Class,
3524 ValueSetIutf8N::from_iter([
3525 EntryClass::Object.into(),
3526 EntryClass::Account.into(),
3527 EntryClass::PosixAccount.into(),
3528 EntryClass::Person.into(),
3529 ])
3530 .unwrap() as ValueSet,
3531 ),
3532 (
3533 Attribute::Name,
3534 ValueSetIname::new(TESTPERSON_NAME) as ValueSet,
3535 ),
3536 (
3537 Attribute::Uuid,
3538 ValueSetUuid::new(TESTPERSON_UUID) as ValueSet,
3539 ),
3540 (
3541 Attribute::Description,
3542 ValueSetUtf8::new(TESTPERSON_NAME.into()) as ValueSet,
3543 ),
3544 (
3545 Attribute::DisplayName,
3546 ValueSetUtf8::new(TESTPERSON_NAME.into()) as ValueSet,
3547 ),
3548 ]);
3549
3550 let ce = CreateEvent::new_internal(vec![test_entry]);
3551 let cr = idms_prox_write.qs_write.create(&ce);
3552 assert!(cr.is_ok());
3553
3554 let idm_admin_identity = idms_prox_write
3555 .qs_write
3556 .impersonate_uuid_as_readwrite_identity(UUID_IDM_ADMIN)
3557 .expect("Failed to retrieve identity");
3558
3559 let event = InitCredentialUpdateIntentSendEvent {
3561 ident: idm_admin_identity.clone(),
3562 target: TESTPERSON_UUID,
3563 max_ttl: None,
3564 email: None,
3565 };
3566
3567 let err = idms_prox_write
3568 .init_credential_update_intent_send(event, ct)
3569 .expect_err("Should not succeed!");
3570 assert_eq!(err, OperationError::CU0008AccountMissingEmail);
3571
3572 idms_prox_write
3574 .qs_write
3575 .internal_modify_uuid(
3576 TESTPERSON_UUID,
3577 &ModifyList::new_set(
3578 Attribute::Mail,
3579 ValueSetEmailAddress::new(email_address.clone()) as ValueSet,
3580 ),
3581 )
3582 .expect("Failed to update test person account");
3583
3584 let event = InitCredentialUpdateIntentSendEvent {
3587 ident: idm_admin_identity.clone(),
3588 target: TESTPERSON_UUID,
3589 max_ttl: None,
3590 email: Some("email-that-is-not-present@example.com".into()),
3591 };
3592
3593 let err = idms_prox_write
3594 .init_credential_update_intent_send(event, ct)
3595 .expect_err("Should not succeed!");
3596 assert_eq!(err, OperationError::CU0007AccountEmailNotFound);
3597
3598 let event = InitCredentialUpdateIntentSendEvent {
3602 ident: idm_admin_identity.clone(),
3603 target: TESTPERSON_UUID,
3604 max_ttl: None,
3605 email: Some(email_address.clone()),
3606 };
3607
3608 idms_prox_write
3609 .init_credential_update_intent_send(event, ct)
3610 .expect("Should succeed!");
3611
3612 let filter = filter!(f_and(vec![
3614 f_eq(Attribute::Class, EntryClass::OutboundMessage.into()),
3615 f_eq(
3616 Attribute::MailDestination,
3617 PartialValue::EmailAddress(email_address)
3618 )
3619 ]));
3620
3621 let mut entries = idms_prox_write
3622 .qs_write
3623 .impersonate_search(filter.clone(), filter, &idm_admin_identity)
3624 .expect("Unable to search message queue");
3625
3626 assert_eq!(entries.len(), 1);
3627 let message_entry = entries.pop().unwrap();
3628
3629 let message = message_entry
3630 .get_ava_set(Attribute::MessageTemplate)
3631 .and_then(|vs| vs.as_message())
3632 .unwrap();
3633
3634 match message {
3635 OutboundMessage::CredentialResetV1 { display_name, .. } => {
3636 assert_eq!(display_name, TESTPERSON_NAME);
3637 }
3638 _ => panic!("Wrong message type!"),
3639 }
3640 }
3642
3643 #[idm_test]
3644 async fn account_recovery_basic(idms: &IdmServer, _idms_delayed: &mut IdmServerDelayed) {
3645 let ct = Duration::from_secs(TEST_CURRENT_TIME);
3646
3647 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3648
3649 let idm_admin_identity = idms_prox_write
3650 .qs_write
3651 .impersonate_uuid_as_readwrite_identity(UUID_IDM_ADMIN)
3652 .expect("Failed to retrieve identity");
3653
3654 let email_address = format!("{}@example.com", TESTPERSON_NAME);
3655
3656 let test_entry = EntryInitNew::from_iter([
3657 (
3658 Attribute::Class,
3659 ValueSetIutf8N::from_iter([
3660 EntryClass::Object.into(),
3661 EntryClass::Account.into(),
3662 EntryClass::Person.into(),
3663 ])
3664 .unwrap() as ValueSet,
3665 ),
3666 (
3667 Attribute::Name,
3668 ValueSetIname::new(TESTPERSON_NAME) as ValueSet,
3669 ),
3670 (
3671 Attribute::Uuid,
3672 ValueSetUuid::new(TESTPERSON_UUID) as ValueSet,
3673 ),
3674 (
3675 Attribute::DisplayName,
3676 ValueSetUtf8::new(TESTPERSON_NAME.into()) as ValueSet,
3677 ),
3678 (
3679 Attribute::Mail,
3680 ValueSetEmailAddress::new(email_address.clone()) as ValueSet,
3681 ),
3682 ]);
3683
3684 let ce =
3685 CreateEvent::new_impersonate_identity(idm_admin_identity.clone(), vec![test_entry]);
3686 let cr = idms_prox_write.qs_write.create(&ce);
3687 assert!(cr.is_ok());
3688
3689 let event = CredentialUpdateAccountRecovery {
3691 email: "invalid@example.com".into(),
3692 max_ttl: None,
3693 };
3694
3695 let result = idms_prox_write
3696 .credential_update_account_recovery(event, ct)
3697 .expect_err("Must not succeed!");
3698
3699 assert_eq!(result, OperationError::CU0010AccountRecoveryDisabled);
3700
3701 idms_prox_write
3703 .qs_write
3704 .internal_modify_uuid(
3705 UUID_DOMAIN_INFO,
3706 &ModifyList::new_set(
3707 Attribute::DomainAllowAccountRecovery,
3708 ValueSetBool::new(true),
3709 ),
3710 )
3711 .expect("Unable to activate credential reset feature.");
3712
3713 idms_prox_write
3714 .qs_write
3715 .reload()
3716 .expect("Unable to reload domain info.");
3717
3718 let event = CredentialUpdateAccountRecovery {
3720 email: "invalid@example.com".into(),
3721 max_ttl: None,
3722 };
3723
3724 let result = idms_prox_write
3725 .credential_update_account_recovery(event, ct)
3726 .expect_err("Must not succeed!");
3727
3728 assert_eq!(result, OperationError::CU0009AccountEmailNotFound);
3729
3730 let event = CredentialUpdateAccountRecovery {
3732 email: email_address.clone(),
3733 max_ttl: None,
3734 };
3735
3736 idms_prox_write
3737 .credential_update_account_recovery(event, ct)
3738 .expect("Must succeed!");
3739
3740 let filter = filter!(f_and(vec![
3742 f_eq(Attribute::Class, EntryClass::OutboundMessage.into()),
3743 f_eq(
3744 Attribute::MailDestination,
3745 PartialValue::EmailAddress(email_address)
3746 )
3747 ]));
3748
3749 let mut entries = idms_prox_write
3750 .qs_write
3751 .impersonate_search(filter.clone(), filter, &idm_admin_identity)
3752 .expect("Unable to search message queue");
3753
3754 assert_eq!(entries.len(), 1);
3755 let message_entry = entries.pop().unwrap();
3756
3757 let message = message_entry
3758 .get_ava_set(Attribute::MessageTemplate)
3759 .and_then(|vs| vs.as_message())
3760 .unwrap();
3761
3762 match message {
3763 OutboundMessage::CredentialResetV1 { display_name, .. } => {
3764 assert_eq!(display_name, TESTPERSON_NAME);
3765 }
3766 _ => panic!("Wrong message type!"),
3767 }
3768 }
3770
3771 #[idm_test]
3772 async fn credential_update_onboarding_create_new_pw(
3773 idms: &IdmServer,
3774 idms_delayed: &mut IdmServerDelayed,
3775 ) {
3776 let test_pw = readable_password_from_random();
3777 let ct = Duration::from_secs(TEST_CURRENT_TIME);
3778
3779 let (cust, _) = setup_test_session(idms, ct).await;
3780
3781 let cutxn = idms.cred_update_transaction().await.unwrap();
3782
3783 let c_status = cutxn
3787 .credential_update_status(&cust, ct)
3788 .expect("Failed to get the current session status.");
3789
3790 trace!(?c_status);
3791 assert!(c_status.primary.is_none());
3792
3793 let c_status = cutxn
3796 .credential_primary_set_password(&cust, ct, &test_pw)
3797 .expect("Failed to update the primary cred password");
3798
3799 assert!(c_status.can_commit);
3800 assert!(c_status.dirty);
3801
3802 drop(cutxn);
3803 commit_session(idms, ct, cust).await;
3804
3805 assert!(check_testperson_password(idms, idms_delayed, &test_pw, ct)
3807 .await
3808 .is_some());
3809
3810 let (cust, _) = renew_test_session(idms, ct).await;
3812 let cutxn = idms.cred_update_transaction().await.unwrap();
3813
3814 let c_status = cutxn
3815 .credential_update_status(&cust, ct)
3816 .expect("Failed to get the current session status.");
3817 trace!(?c_status);
3818 assert!(c_status.primary.is_some());
3819
3820 let c_status = cutxn
3821 .credential_primary_delete(&cust, ct)
3822 .expect("Failed to delete the primary cred");
3823 trace!(?c_status);
3824 assert!(c_status.primary.is_none());
3825 assert!(c_status
3826 .warnings
3827 .contains(&CredentialUpdateSessionStatusWarnings::NoValidCredentials));
3828 assert!(!c_status.can_commit);
3830 assert!(c_status.dirty);
3831
3832 drop(cutxn);
3833 }
3834
3835 #[idm_test]
3836 async fn credential_update_password_quality_checks(
3837 idms: &IdmServer,
3838 _idms_delayed: &mut IdmServerDelayed,
3839 ) {
3840 let ct = Duration::from_secs(TEST_CURRENT_TIME);
3841 let (cust, _) = setup_test_session(idms, ct).await;
3842
3843 let mut r_txn = idms.proxy_read().await.unwrap();
3846
3847 let radius_secret = r_txn
3848 .qs_read
3849 .internal_search_uuid(TESTPERSON_UUID)
3850 .expect("No such entry")
3851 .get_ava_single_secret(Attribute::RadiusSecret)
3852 .expect("No radius secret found")
3853 .to_string();
3854
3855 drop(r_txn);
3856
3857 let cutxn = idms.cred_update_transaction().await.unwrap();
3858
3859 let c_status = cutxn
3863 .credential_update_status(&cust, ct)
3864 .expect("Failed to get the current session status.");
3865
3866 trace!(?c_status);
3867
3868 assert!(c_status.primary.is_none());
3869
3870 let err = cutxn
3874 .credential_primary_set_password(&cust, ct, "password")
3875 .unwrap_err();
3876 trace!(?err);
3877 assert!(
3878 matches!(err, OperationError::PasswordQuality(details) if details == vec!(PasswordFeedback::TooShort(PW_SFA_MIN_LENGTH_NIST),))
3879 );
3880
3881 let random_pw = password_from_random_len(PW_MAX_LENGTH_NIST + 1);
3882 let err = cutxn
3883 .credential_primary_set_password(&cust, ct, &random_pw)
3884 .unwrap_err();
3885 trace!(?err);
3886 assert!(
3887 matches!(err, OperationError::PasswordQuality(details) if details == vec!(PasswordFeedback::TooLong(PW_MAX_LENGTH_NIST),))
3888 );
3889
3890 let err = cutxn
3891 .credential_primary_set_password(&cust, ct, "password 12345678")
3892 .unwrap_err();
3893 trace!(?err);
3894 assert!(
3895 matches!(err, OperationError::PasswordQuality(details) if details
3896 == vec!(
3897 PasswordFeedback::UseAFewWordsAvoidCommonPhrases,
3898 PasswordFeedback::AddAnotherWordOrTwo,
3899 PasswordFeedback::NoNeedForSymbolsDigitsOrUppercaseLetters
3900 ))
3901 );
3902
3903 let err = cutxn
3904 .credential_primary_set_password(&cust, ct, &radius_secret)
3905 .unwrap_err();
3906 trace!(?err);
3907 assert!(
3908 matches!(err, OperationError::PasswordQuality(details) if details == vec!(PasswordFeedback::DontReusePasswords,))
3909 );
3910
3911 let err = cutxn
3912 .credential_primary_set_password(&cust, ct, "testperson 2023")
3913 .unwrap_err();
3914 trace!(?err);
3915 assert!(
3916 matches!(err, OperationError::PasswordQuality(details) if details == vec!(
3917 PasswordFeedback::NamesAndSurnamesByThemselvesAreEasyToGuess,
3918 PasswordFeedback::AvoidDatesAndYearsThatAreAssociatedWithYou,
3919 ))
3920 );
3921
3922 let err = cutxn
3923 .credential_primary_set_password(
3924 &cust,
3925 ct,
3926 "demo_badlist_shohfie3aeci2oobur0aru9uushah6EiPi2woh4hohngoighaiR",
3927 )
3928 .unwrap_err();
3929 trace!(?err);
3930 assert!(
3931 matches!(err, OperationError::PasswordQuality(details) if details == vec!(PasswordFeedback::BadListed))
3932 );
3933
3934 assert!(c_status
3936 .warnings
3937 .contains(&CredentialUpdateSessionStatusWarnings::NoValidCredentials));
3938 assert!(!c_status.can_commit);
3939 assert!(!c_status.dirty);
3940
3941 drop(cutxn);
3942 }
3943
3944 #[idm_test]
3945 async fn credential_update_password_min_length_account_policy(
3946 idms: &IdmServer,
3947 _idms_delayed: &mut IdmServerDelayed,
3948 ) {
3949 let ct = Duration::from_secs(TEST_CURRENT_TIME);
3950
3951 let test_pw_min_length = PW_SFA_MIN_LENGTH_NIST * 2;
3953
3954 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3955
3956 let modlist = ModifyList::new_purge_and_set(
3957 Attribute::AuthPasswordMinimumLength,
3958 Value::Uint32(test_pw_min_length),
3959 );
3960 idms_prox_write
3961 .qs_write
3962 .internal_modify_uuid(UUID_IDM_ALL_ACCOUNTS, &modlist)
3963 .expect("Unable to change default session exp");
3964
3965 assert!(idms_prox_write.commit().is_ok());
3966 let (cust, _) = setup_test_session(idms, ct).await;
3969
3970 let cutxn = idms.cred_update_transaction().await.unwrap();
3971
3972 let c_status = cutxn
3976 .credential_update_status(&cust, ct)
3977 .expect("Failed to get the current session status.");
3978
3979 trace!(?c_status);
3980
3981 assert!(c_status.primary.is_none());
3982
3983 let pw = password_from_random_len(8);
3986 let err = cutxn
3987 .credential_primary_set_password(&cust, ct, &pw)
3988 .unwrap_err();
3989 trace!(?err);
3990 assert!(
3991 matches!(err, OperationError::PasswordQuality(details) if details == vec!(PasswordFeedback::TooShort(test_pw_min_length),))
3992 );
3993
3994 let pw = password_from_random_len(test_pw_min_length - 1);
3996 let err = cutxn
3997 .credential_primary_set_password(&cust, ct, &pw)
3998 .unwrap_err();
3999 trace!(?err);
4000 assert!(matches!(err,OperationError::PasswordQuality(details)
4001 if details == vec!(PasswordFeedback::TooShort(test_pw_min_length),)));
4002
4003 let pw = password_from_random_len(test_pw_min_length);
4005 let c_status = cutxn
4006 .credential_primary_set_password(&cust, ct, &pw)
4007 .expect("Failed to update the primary cred password");
4008
4009 assert!(c_status.can_commit);
4010 assert!(c_status.dirty);
4011
4012 drop(cutxn);
4013 commit_session(idms, ct, cust).await;
4014 }
4015
4016 #[idm_test]
4022 async fn credential_update_onboarding_create_new_mfa_totp_basic(
4023 idms: &IdmServer,
4024 idms_delayed: &mut IdmServerDelayed,
4025 ) {
4026 let test_pw = readable_password_from_random();
4027 let ct = Duration::from_secs(TEST_CURRENT_TIME);
4028
4029 let (cust, _) = setup_test_session(idms, ct).await;
4030 let cutxn = idms.cred_update_transaction().await.unwrap();
4031
4032 let c_status = cutxn
4034 .credential_primary_set_password(&cust, ct, &test_pw)
4035 .expect("Failed to update the primary cred password");
4036
4037 assert!(c_status.can_commit);
4039 assert!(c_status.dirty);
4040
4041 let c_status = cutxn
4043 .credential_primary_init_totp(&cust, ct)
4044 .expect("Failed to update the primary cred password");
4045
4046 let totp_token: Totp = match c_status.mfaregstate {
4048 MfaRegStateStatus::TotpCheck(secret) => Some(secret.try_into().unwrap()),
4049
4050 _ => None,
4051 }
4052 .expect("Unable to retrieve totp token, invalid state.");
4053
4054 trace!(?totp_token);
4055 let chal = totp_token
4056 .do_totp_duration_from_epoch(&ct)
4057 .expect("Failed to perform totp step");
4058
4059 let c_status = cutxn
4061 .credential_primary_check_totp(&cust, ct, chal + 1, "totp")
4062 .expect("Failed to update the primary cred totp");
4063
4064 assert!(
4065 matches!(c_status.mfaregstate, MfaRegStateStatus::TotpTryAgain),
4066 "{:?}",
4067 c_status.mfaregstate
4068 );
4069
4070 let c_status = cutxn
4072 .credential_primary_check_totp(&cust, ct, chal, "")
4073 .expect("Failed to update the primary cred totp");
4074
4075 assert!(
4076 matches!(
4077 c_status.mfaregstate,
4078 MfaRegStateStatus::TotpNameTryAgain(ref val) if val.is_empty()
4079 ),
4080 "{:?}",
4081 c_status.mfaregstate
4082 );
4083
4084 let c_status = cutxn
4086 .credential_primary_check_totp(&cust, ct, chal, " ")
4087 .expect("Failed to update the primary cred totp");
4088
4089 assert!(
4090 matches!(
4091 c_status.mfaregstate,
4092 MfaRegStateStatus::TotpNameTryAgain(ref val) if val == " "
4093 ),
4094 "{:?}",
4095 c_status.mfaregstate
4096 );
4097
4098 let c_status = cutxn
4099 .credential_primary_check_totp(&cust, ct, chal, "totp")
4100 .expect("Failed to update the primary cred totp");
4101
4102 assert!(matches!(c_status.mfaregstate, MfaRegStateStatus::None));
4103 assert!(match c_status.primary.as_ref().map(|c| &c.type_) {
4104 Some(CredentialDetailType::PasswordMfa(totp, _, 0)) => !totp.is_empty(),
4105 _ => false,
4106 });
4107
4108 {
4109 let c_status = cutxn
4110 .credential_primary_init_totp(&cust, ct)
4111 .expect("Failed to update the primary cred password");
4112
4113 let totp_token: Totp = match c_status.mfaregstate {
4115 MfaRegStateStatus::TotpCheck(secret) => Some(secret.try_into().unwrap()),
4116 _ => None,
4117 }
4118 .expect("Unable to retrieve totp token, invalid state.");
4119
4120 trace!(?totp_token);
4121 let chal = totp_token
4122 .do_totp_duration_from_epoch(&ct)
4123 .expect("Failed to perform totp step");
4124
4125 let c_status = cutxn
4127 .credential_primary_check_totp(&cust, ct, chal, "totp")
4128 .expect("Failed to update the primary cred totp");
4129
4130 assert!(
4131 matches!(
4132 c_status.mfaregstate,
4133 MfaRegStateStatus::TotpNameTryAgain(ref val) if val == "totp"
4134 ),
4135 "{:?}",
4136 c_status.mfaregstate
4137 );
4138
4139 assert!(cutxn.credential_update_cancel_mfareg(&cust, ct).is_ok())
4140 }
4141
4142 drop(cutxn);
4145 commit_session(idms, ct, cust).await;
4146
4147 assert!(
4149 check_testperson_password_totp(idms, idms_delayed, &test_pw, &totp_token, ct)
4150 .await
4151 .is_some()
4152 );
4153 let (cust, _) = renew_test_session(idms, ct).await;
4157 let cutxn = idms.cred_update_transaction().await.unwrap();
4158
4159 let c_status = cutxn
4160 .credential_primary_remove_totp(&cust, ct, "totp")
4161 .expect("Failed to update the primary cred password");
4162
4163 assert!(matches!(c_status.mfaregstate, MfaRegStateStatus::None));
4164 assert!(matches!(
4165 c_status.primary.as_ref().map(|c| &c.type_),
4166 Some(CredentialDetailType::Password)
4167 ));
4168
4169 drop(cutxn);
4170 commit_session(idms, ct, cust).await;
4171
4172 assert!(check_testperson_password(idms, idms_delayed, &test_pw, ct)
4174 .await
4175 .is_some());
4176 }
4177
4178 #[idm_test]
4180 async fn credential_update_onboarding_create_new_mfa_totp_sha1(
4181 idms: &IdmServer,
4182 idms_delayed: &mut IdmServerDelayed,
4183 ) {
4184 let test_pw = readable_password_from_random();
4185 let ct = Duration::from_secs(TEST_CURRENT_TIME);
4186
4187 let (cust, _) = setup_test_session(idms, ct).await;
4188 let cutxn = idms.cred_update_transaction().await.unwrap();
4189
4190 let c_status = cutxn
4192 .credential_primary_set_password(&cust, ct, &test_pw)
4193 .expect("Failed to update the primary cred password");
4194
4195 assert!(c_status.can_commit);
4197 assert!(c_status.dirty);
4198
4199 let c_status = cutxn
4201 .credential_primary_init_totp(&cust, ct)
4202 .expect("Failed to update the primary cred password");
4203
4204 let totp_token: Totp = match c_status.mfaregstate {
4206 MfaRegStateStatus::TotpCheck(secret) => Some(secret.try_into().unwrap()),
4207
4208 _ => None,
4209 }
4210 .expect("Unable to retrieve totp token, invalid state.");
4211
4212 let totp_token = totp_token.downgrade_to_legacy();
4213
4214 trace!(?totp_token);
4215 let chal = totp_token
4216 .do_totp_duration_from_epoch(&ct)
4217 .expect("Failed to perform totp step");
4218
4219 let c_status = cutxn
4221 .credential_primary_check_totp(&cust, ct, chal, "totp")
4222 .expect("Failed to update the primary cred password");
4223
4224 assert!(matches!(
4225 c_status.mfaregstate,
4226 MfaRegStateStatus::TotpInvalidSha1
4227 ));
4228
4229 let c_status = cutxn
4231 .credential_primary_accept_sha1_totp(&cust, ct)
4232 .expect("Failed to update the primary cred password");
4233
4234 assert!(matches!(c_status.mfaregstate, MfaRegStateStatus::None));
4235 assert!(match c_status.primary.as_ref().map(|c| &c.type_) {
4236 Some(CredentialDetailType::PasswordMfa(totp, _, 0)) => !totp.is_empty(),
4237 _ => false,
4238 });
4239
4240 drop(cutxn);
4243 commit_session(idms, ct, cust).await;
4244
4245 assert!(
4247 check_testperson_password_totp(idms, idms_delayed, &test_pw, &totp_token, ct)
4248 .await
4249 .is_some()
4250 );
4251 }
4253
4254 #[idm_test]
4255 async fn credential_update_onboarding_create_new_mfa_totp_backup_codes(
4256 idms: &IdmServer,
4257 idms_delayed: &mut IdmServerDelayed,
4258 ) {
4259 let test_pw = readable_password_from_random();
4260 let ct = Duration::from_secs(TEST_CURRENT_TIME);
4261
4262 let (cust, _) = setup_test_session(idms, ct).await;
4263 let cutxn = idms.cred_update_transaction().await.unwrap();
4264
4265 let _c_status = cutxn
4267 .credential_primary_set_password(&cust, ct, &test_pw)
4268 .expect("Failed to update the primary cred password");
4269
4270 assert!(matches!(
4272 cutxn.credential_primary_init_backup_codes(&cust, ct),
4273 Err(OperationError::InvalidState)
4274 ));
4275
4276 let c_status = cutxn
4277 .credential_primary_init_totp(&cust, ct)
4278 .expect("Failed to update the primary cred password");
4279
4280 let totp_token: Totp = match c_status.mfaregstate {
4281 MfaRegStateStatus::TotpCheck(secret) => Some(secret.try_into().unwrap()),
4282 _ => None,
4283 }
4284 .expect("Unable to retrieve totp token, invalid state.");
4285
4286 trace!(?totp_token);
4287 let chal = totp_token
4288 .do_totp_duration_from_epoch(&ct)
4289 .expect("Failed to perform totp step");
4290
4291 let c_status = cutxn
4292 .credential_primary_check_totp(&cust, ct, chal, "totp")
4293 .expect("Failed to update the primary cred totp");
4294
4295 assert!(matches!(c_status.mfaregstate, MfaRegStateStatus::None));
4296 assert!(match c_status.primary.as_ref().map(|c| &c.type_) {
4297 Some(CredentialDetailType::PasswordMfa(totp, _, 0)) => !totp.is_empty(),
4298 _ => false,
4299 });
4300
4301 let c_status = cutxn
4304 .credential_primary_init_backup_codes(&cust, ct)
4305 .expect("Failed to update the primary cred password");
4306
4307 let codes = match c_status.mfaregstate {
4308 MfaRegStateStatus::BackupCodes(codes) => Some(codes),
4309 _ => None,
4310 }
4311 .expect("Unable to retrieve backupcodes, invalid state.");
4312
4313 debug!("{:?}", c_status.primary.as_ref().map(|c| &c.type_));
4315 assert!(match c_status.primary.as_ref().map(|c| &c.type_) {
4316 Some(CredentialDetailType::PasswordMfa(totp, _, 8)) => !totp.is_empty(),
4317 _ => false,
4318 });
4319
4320 drop(cutxn);
4322 commit_session(idms, ct, cust).await;
4323
4324 let backup_code = codes.iter().next().expect("No codes available");
4325
4326 assert!(check_testperson_password_backup_code(
4328 idms,
4329 idms_delayed,
4330 &test_pw,
4331 backup_code,
4332 ct
4333 )
4334 .await
4335 .is_some());
4336
4337 let (cust, _) = renew_test_session(idms, ct).await;
4339 let cutxn = idms.cred_update_transaction().await.unwrap();
4340
4341 let c_status = cutxn
4343 .credential_update_status(&cust, ct)
4344 .expect("Failed to get the current session status.");
4345
4346 assert!(match c_status.primary.as_ref().map(|c| &c.type_) {
4347 Some(CredentialDetailType::PasswordMfa(totp, _, 7)) => !totp.is_empty(),
4348 _ => false,
4349 });
4350
4351 let c_status = cutxn
4353 .credential_primary_remove_backup_codes(&cust, ct)
4354 .expect("Failed to update the primary cred password");
4355
4356 assert!(matches!(c_status.mfaregstate, MfaRegStateStatus::None));
4357 assert!(match c_status.primary.as_ref().map(|c| &c.type_) {
4358 Some(CredentialDetailType::PasswordMfa(totp, _, 0)) => !totp.is_empty(),
4359 _ => false,
4360 });
4361
4362 let c_status = cutxn
4364 .credential_primary_init_backup_codes(&cust, ct)
4365 .expect("Failed to update the primary cred password");
4366
4367 assert!(matches!(
4368 c_status.mfaregstate,
4369 MfaRegStateStatus::BackupCodes(_)
4370 ));
4371 assert!(match c_status.primary.as_ref().map(|c| &c.type_) {
4372 Some(CredentialDetailType::PasswordMfa(totp, _, 8)) => !totp.is_empty(),
4373 _ => false,
4374 });
4375
4376 let c_status = cutxn
4378 .credential_primary_remove_totp(&cust, ct, "totp")
4379 .expect("Failed to update the primary cred password");
4380
4381 assert!(matches!(c_status.mfaregstate, MfaRegStateStatus::None));
4382 assert!(matches!(
4383 c_status.primary.as_ref().map(|c| &c.type_),
4384 Some(CredentialDetailType::Password)
4385 ));
4386
4387 drop(cutxn);
4388 commit_session(idms, ct, cust).await;
4389 }
4390
4391 #[idm_test]
4392 async fn credential_update_onboarding_cancel_inprogress_totp(
4393 idms: &IdmServer,
4394 idms_delayed: &mut IdmServerDelayed,
4395 ) {
4396 let test_pw = readable_password_from_random();
4397 let ct = Duration::from_secs(TEST_CURRENT_TIME);
4398
4399 let (cust, _) = setup_test_session(idms, ct).await;
4400 let cutxn = idms.cred_update_transaction().await.unwrap();
4401
4402 let c_status = cutxn
4404 .credential_primary_set_password(&cust, ct, &test_pw)
4405 .expect("Failed to update the primary cred password");
4406
4407 assert!(c_status.can_commit);
4409 assert!(c_status.dirty);
4410
4411 let c_status = cutxn
4413 .credential_primary_init_totp(&cust, ct)
4414 .expect("Failed to update the primary cred totp");
4415
4416 assert!(c_status.can_commit);
4418 assert!(c_status.dirty);
4419 assert!(matches!(
4420 c_status.mfaregstate,
4421 MfaRegStateStatus::TotpCheck(_)
4422 ));
4423
4424 let c_status = cutxn
4425 .credential_update_cancel_mfareg(&cust, ct)
4426 .expect("Failed to cancel in-flight totp change");
4427
4428 assert!(matches!(c_status.mfaregstate, MfaRegStateStatus::None));
4429 assert!(c_status.can_commit);
4430 assert!(c_status.dirty);
4431
4432 drop(cutxn);
4433 commit_session(idms, ct, cust).await;
4434
4435 assert!(check_testperson_password(idms, idms_delayed, &test_pw, ct)
4437 .await
4438 .is_some());
4439 }
4440
4441 async fn create_new_passkey(
4448 ct: Duration,
4449 origin: &Url,
4450 cutxn: &IdmServerCredUpdateTransaction<'_>,
4451 cust: &CredentialUpdateSessionToken,
4452 wa: &mut SoftPasskey,
4453 ) -> CredentialUpdateSessionStatus {
4454 let c_status = cutxn
4456 .credential_passkey_init(cust, ct)
4457 .expect("Failed to initiate passkey registration");
4458
4459 assert!(c_status.passkeys.is_empty());
4460
4461 let passkey_chal = match c_status.mfaregstate {
4462 MfaRegStateStatus::Passkey(c) => Some(c),
4463 _ => None,
4464 }
4465 .expect("Unable to access passkey challenge, invalid state");
4466
4467 let passkey_resp = wa
4468 .do_registration(origin.clone(), passkey_chal)
4469 .expect("Failed to create soft passkey");
4470
4471 let label = "softtoken".to_string();
4473 let c_status = cutxn
4474 .credential_passkey_finish(cust, ct, label, &passkey_resp)
4475 .expect("Failed to initiate passkey registration");
4476
4477 assert!(matches!(c_status.mfaregstate, MfaRegStateStatus::None));
4478 assert!(c_status.primary.as_ref().is_none());
4479
4480 trace!(?c_status);
4482 assert_eq!(c_status.passkeys.len(), 1);
4483
4484 c_status
4485 }
4486
4487 #[idm_test]
4488 async fn credential_update_onboarding_create_new_passkey(
4489 idms: &IdmServer,
4490 idms_delayed: &mut IdmServerDelayed,
4491 ) {
4492 let ct = Duration::from_secs(TEST_CURRENT_TIME);
4493 let test_pw = readable_password_from_random();
4494
4495 let (cust, _) = setup_test_session(idms, ct).await;
4496 let cutxn = idms.cred_update_transaction().await.unwrap();
4497 let origin = cutxn.get_origin().clone();
4498
4499 let mut wa = SoftPasskey::new(true);
4501
4502 let c_status = create_new_passkey(ct, &origin, &cutxn, &cust, &mut wa).await;
4503
4504 let pk_uuid = c_status.passkeys.first().map(|pkd| pkd.uuid).unwrap();
4506
4507 drop(cutxn);
4509 commit_session(idms, ct, cust).await;
4510
4511 assert!(
4513 check_testperson_passkey(idms, idms_delayed, &mut wa, origin.clone(), ct)
4514 .await
4515 .is_some()
4516 );
4517
4518 let (cust, _) = renew_test_session(idms, ct).await;
4520 let cutxn = idms.cred_update_transaction().await.unwrap();
4521
4522 trace!(?c_status);
4523 assert!(c_status.primary.is_none());
4524 assert_eq!(c_status.passkeys.len(), 1);
4525
4526 let c_status = cutxn
4527 .credential_passkey_remove(&cust, ct, pk_uuid)
4528 .expect("Failed to delete the passkey");
4529
4530 trace!(?c_status);
4531 assert!(c_status.primary.is_none());
4532 assert!(c_status.passkeys.is_empty());
4533
4534 assert!(c_status
4535 .warnings
4536 .contains(&CredentialUpdateSessionStatusWarnings::NoValidCredentials));
4537 assert!(!c_status.can_commit);
4538 assert!(c_status.dirty);
4539
4540 let c_status = cutxn
4542 .credential_primary_set_password(&cust, ct, &test_pw)
4543 .expect("Failed to update the primary cred password");
4544
4545 assert!(c_status.can_commit);
4547 assert!(c_status.dirty);
4548 assert!(!c_status
4549 .warnings
4550 .contains(&CredentialUpdateSessionStatusWarnings::NoValidCredentials));
4551
4552 drop(cutxn);
4553 commit_session(idms, ct, cust).await;
4554
4555 assert!(
4557 check_testperson_passkey(idms, idms_delayed, &mut wa, origin, ct)
4558 .await
4559 .is_none()
4560 );
4561 }
4562
4563 #[idm_test]
4564 async fn credential_update_access_denied(
4565 idms: &IdmServer,
4566 _idms_delayed: &mut IdmServerDelayed,
4567 ) {
4568 let ct = Duration::from_secs(TEST_CURRENT_TIME);
4572
4573 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4574
4575 let sync_uuid = Uuid::new_v4();
4576
4577 let e1 = entry_init!(
4578 (Attribute::Class, EntryClass::Object.to_value()),
4579 (Attribute::Class, EntryClass::SyncAccount.to_value()),
4580 (Attribute::Name, Value::new_iname("test_scim_sync")),
4581 (Attribute::Uuid, Value::Uuid(sync_uuid)),
4582 (
4583 Attribute::Description,
4584 Value::new_utf8s("A test sync agreement")
4585 )
4586 );
4587
4588 let e2 = entry_init!(
4589 (Attribute::Class, EntryClass::Object.to_value()),
4590 (Attribute::Class, EntryClass::SyncObject.to_value()),
4591 (Attribute::Class, EntryClass::Account.to_value()),
4592 (Attribute::Class, EntryClass::PosixAccount.to_value()),
4593 (Attribute::Class, EntryClass::Person.to_value()),
4594 (Attribute::SyncParentUuid, Value::Refer(sync_uuid)),
4595 (Attribute::Name, Value::new_iname(TESTPERSON_NAME)),
4596 (Attribute::Uuid, Value::Uuid(TESTPERSON_UUID)),
4597 (Attribute::Description, Value::new_utf8s(TESTPERSON_NAME)),
4598 (Attribute::DisplayName, Value::new_utf8s(TESTPERSON_NAME))
4599 );
4600
4601 let ce = CreateEvent::new_internal(vec![e1, e2]);
4602 let cr = idms_prox_write.qs_write.create(&ce);
4603 assert!(cr.is_ok());
4604
4605 let testperson = idms_prox_write
4606 .qs_write
4607 .internal_search_uuid(TESTPERSON_UUID)
4608 .expect("failed");
4609
4610 let cur = idms_prox_write.init_credential_update(
4611 &InitCredentialUpdateEvent::new_impersonate_entry(testperson),
4612 ct,
4613 );
4614
4615 idms_prox_write.commit().expect("Failed to commit txn");
4616
4617 let (cust, custatus) = cur.expect("Failed to start update");
4618
4619 trace!(?custatus);
4620
4621 let CredentialUpdateSessionStatus {
4624 spn: _,
4625 displayname: _,
4626 ext_cred_portal,
4627 mfaregstate: _,
4628 can_commit: _,
4629 dirty: _,
4630 warnings: _,
4631 primary: _,
4632 primary_state,
4633 passkeys: _,
4634 passkeys_state,
4635 attested_passkeys: _,
4636 attested_passkeys_state,
4637 attested_passkeys_allowed_devices: _,
4638 unixcred_state,
4639 unixcred: _,
4640 sshkeys: _,
4641 sshkeys_state,
4642 } = custatus;
4643
4644 assert!(matches!(ext_cred_portal, CUExtPortal::Hidden));
4645 assert!(matches!(primary_state, CredentialState::AccessDeny));
4646 assert!(matches!(passkeys_state, CredentialState::AccessDeny));
4647 assert!(matches!(
4648 attested_passkeys_state,
4649 CredentialState::AccessDeny
4650 ));
4651 assert!(matches!(unixcred_state, CredentialState::AccessDeny));
4652 assert!(matches!(sshkeys_state, CredentialState::AccessDeny));
4653
4654 let cutxn = idms.cred_update_transaction().await.unwrap();
4655
4656 let err = cutxn
4662 .credential_primary_set_password(&cust, ct, "password")
4663 .unwrap_err();
4664 assert!(matches!(err, OperationError::AccessDenied));
4665
4666 let err = cutxn
4667 .credential_unix_set_password(&cust, ct, "password")
4668 .unwrap_err();
4669 assert!(matches!(err, OperationError::AccessDenied));
4670
4671 let sshkey = SshPublicKey::from_string(SSHKEY_VALID_1).expect("Invalid SSHKEY_VALID_1");
4672
4673 let err = cutxn
4674 .credential_sshkey_add(&cust, ct, "label".to_string(), sshkey)
4675 .unwrap_err();
4676 assert!(matches!(err, OperationError::AccessDenied));
4677
4678 let err = cutxn.credential_primary_init_totp(&cust, ct).unwrap_err();
4680 assert!(matches!(err, OperationError::AccessDenied));
4681
4682 let err = cutxn
4684 .credential_primary_check_totp(&cust, ct, 0, "totp")
4685 .unwrap_err();
4686 assert!(matches!(err, OperationError::AccessDenied));
4687
4688 let err = cutxn
4690 .credential_primary_accept_sha1_totp(&cust, ct)
4691 .unwrap_err();
4692 assert!(matches!(err, OperationError::AccessDenied));
4693
4694 let err = cutxn
4696 .credential_primary_remove_totp(&cust, ct, "totp")
4697 .unwrap_err();
4698 assert!(matches!(err, OperationError::AccessDenied));
4699
4700 let err = cutxn
4702 .credential_primary_init_backup_codes(&cust, ct)
4703 .unwrap_err();
4704 assert!(matches!(err, OperationError::AccessDenied));
4705
4706 let err = cutxn
4708 .credential_primary_remove_backup_codes(&cust, ct)
4709 .unwrap_err();
4710 assert!(matches!(err, OperationError::AccessDenied));
4711
4712 let err = cutxn.credential_primary_delete(&cust, ct).unwrap_err();
4714 assert!(matches!(err, OperationError::AccessDenied));
4715
4716 let err = cutxn.credential_passkey_init(&cust, ct).unwrap_err();
4718 assert!(matches!(err, OperationError::AccessDenied));
4719
4720 let err = cutxn
4725 .credential_passkey_remove(&cust, ct, Uuid::new_v4())
4726 .unwrap_err();
4727 assert!(matches!(err, OperationError::AccessDenied));
4728
4729 let c_status = cutxn
4730 .credential_update_status(&cust, ct)
4731 .expect("Failed to get the current session status.");
4732 trace!(?c_status);
4733 assert!(c_status.primary.is_none());
4734 assert!(c_status.passkeys.is_empty());
4735
4736 assert!(!c_status.can_commit);
4738 assert!(!c_status.dirty);
4740 assert!(c_status
4741 .warnings
4742 .contains(&CredentialUpdateSessionStatusWarnings::NoValidCredentials));
4743 }
4744
4745 #[idm_test]
4747 async fn credential_update_account_policy_mfa_required(
4748 idms: &IdmServer,
4749 _idms_delayed: &mut IdmServerDelayed,
4750 ) {
4751 let test_pw = readable_password_from_random();
4752 let ct = Duration::from_secs(TEST_CURRENT_TIME);
4753
4754 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4755
4756 let modlist = ModifyList::new_purge_and_set(
4757 Attribute::CredentialTypeMinimum,
4758 CredentialType::Mfa.into(),
4759 );
4760 idms_prox_write
4761 .qs_write
4762 .internal_modify_uuid(UUID_IDM_ALL_ACCOUNTS, &modlist)
4763 .expect("Unable to change default session exp");
4764
4765 assert!(idms_prox_write.commit().is_ok());
4766 let (cust, _) = setup_test_session(idms, ct).await;
4769
4770 let cutxn = idms.cred_update_transaction().await.unwrap();
4771
4772 let c_status = cutxn
4776 .credential_update_status(&cust, ct)
4777 .expect("Failed to get the current session status.");
4778
4779 trace!(?c_status);
4780
4781 assert!(c_status.primary.is_none());
4782
4783 let c_status = cutxn
4786 .credential_primary_set_password(&cust, ct, &test_pw)
4787 .expect("Failed to update the primary cred password");
4788
4789 assert!(!c_status.can_commit);
4790 assert!(c_status.dirty);
4791 assert!(c_status
4792 .warnings
4793 .contains(&CredentialUpdateSessionStatusWarnings::MfaRequired));
4794 let c_status = cutxn
4797 .credential_primary_init_totp(&cust, ct)
4798 .expect("Failed to update the primary cred password");
4799
4800 let totp_token: Totp = match c_status.mfaregstate {
4802 MfaRegStateStatus::TotpCheck(secret) => Some(secret.try_into().unwrap()),
4803
4804 _ => None,
4805 }
4806 .expect("Unable to retrieve totp token, invalid state.");
4807
4808 trace!(?totp_token);
4809 let chal = totp_token
4810 .do_totp_duration_from_epoch(&ct)
4811 .expect("Failed to perform totp step");
4812
4813 let c_status = cutxn
4814 .credential_primary_check_totp(&cust, ct, chal, "totp")
4815 .expect("Failed to update the primary cred totp");
4816
4817 assert!(matches!(c_status.mfaregstate, MfaRegStateStatus::None));
4818 assert!(match c_status.primary.as_ref().map(|c| &c.type_) {
4819 Some(CredentialDetailType::PasswordMfa(totp, _, 0)) => !totp.is_empty(),
4820 _ => false,
4821 });
4822
4823 assert!(c_status.can_commit);
4825 assert!(c_status.dirty);
4826 assert!(c_status.warnings.is_empty());
4827
4828 drop(cutxn);
4829 commit_session(idms, ct, cust).await;
4830
4831 let (cust, _) = renew_test_session(idms, ct).await;
4833 let cutxn = idms.cred_update_transaction().await.unwrap();
4834
4835 let c_status = cutxn
4836 .credential_primary_remove_totp(&cust, ct, "totp")
4837 .expect("Failed to update the primary cred totp");
4838
4839 assert!(matches!(c_status.mfaregstate, MfaRegStateStatus::None));
4840 assert!(matches!(
4841 c_status.primary.as_ref().map(|c| &c.type_),
4842 Some(CredentialDetailType::Password)
4843 ));
4844
4845 assert!(!c_status.can_commit);
4847 assert!(c_status.dirty);
4848 assert!(c_status
4849 .warnings
4850 .contains(&CredentialUpdateSessionStatusWarnings::MfaRequired));
4851
4852 let c_status = cutxn
4854 .credential_primary_delete(&cust, ct)
4855 .expect("Failed to delete the primary credential");
4856 assert!(c_status.primary.is_none());
4857
4858 let origin = cutxn.get_origin().clone();
4859 let mut wa = SoftPasskey::new(true);
4860
4861 let c_status = create_new_passkey(ct, &origin, &cutxn, &cust, &mut wa).await;
4862
4863 assert!(c_status.can_commit);
4864 assert!(c_status.dirty);
4865 assert!(c_status.warnings.is_empty());
4866 assert_eq!(c_status.passkeys.len(), 1);
4867
4868 drop(cutxn);
4869 commit_session(idms, ct, cust).await;
4870 }
4871
4872 #[idm_test]
4873 async fn credential_update_account_policy_passkey_required(
4874 idms: &IdmServer,
4875 _idms_delayed: &mut IdmServerDelayed,
4876 ) {
4877 let test_pw = readable_password_from_random();
4878 let ct = Duration::from_secs(TEST_CURRENT_TIME);
4879
4880 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4881
4882 let modlist = ModifyList::new_purge_and_set(
4883 Attribute::CredentialTypeMinimum,
4884 CredentialType::Passkey.into(),
4885 );
4886 idms_prox_write
4887 .qs_write
4888 .internal_modify_uuid(UUID_IDM_ALL_ACCOUNTS, &modlist)
4889 .expect("Unable to change default session exp");
4890
4891 assert!(idms_prox_write.commit().is_ok());
4892 let (cust, _) = setup_test_session(idms, ct).await;
4895
4896 let cutxn = idms.cred_update_transaction().await.unwrap();
4897
4898 let c_status = cutxn
4902 .credential_update_status(&cust, ct)
4903 .expect("Failed to get the current session status.");
4904
4905 trace!(?c_status);
4906 assert!(c_status.primary.is_none());
4907 assert!(matches!(
4908 c_status.primary_state,
4909 CredentialState::PolicyDeny
4910 ));
4911
4912 let err = cutxn
4913 .credential_primary_set_password(&cust, ct, &test_pw)
4914 .unwrap_err();
4915 assert!(matches!(err, OperationError::AccessDenied));
4916
4917 let origin = cutxn.get_origin().clone();
4918 let mut wa = SoftPasskey::new(true);
4919
4920 let c_status = create_new_passkey(ct, &origin, &cutxn, &cust, &mut wa).await;
4921
4922 assert!(c_status.can_commit);
4923 assert!(c_status.dirty);
4924 assert!(c_status.warnings.is_empty());
4925 assert_eq!(c_status.passkeys.len(), 1);
4926
4927 drop(cutxn);
4928 commit_session(idms, ct, cust).await;
4929 }
4930
4931 #[idm_test]
4934 async fn credential_update_account_policy_attested_passkey_required(
4935 idms: &IdmServer,
4936 idms_delayed: &mut IdmServerDelayed,
4937 ) {
4938 let ct = Duration::from_secs(TEST_CURRENT_TIME);
4939
4940 let (soft_token_valid_a, ca_root_a) = SoftToken::new(true).unwrap();
4942 let mut wa_token_valid = soft_token_valid_a;
4943
4944 let (soft_token_valid_b, ca_root_b) = SoftToken::new(true).unwrap();
4946 let mut wa_token_valid_b = soft_token_valid_b;
4947
4948 let mut att_ca_builder = AttestationCaListBuilder::new();
4950 att_ca_builder
4951 .insert_device_x509(
4952 ca_root_a,
4953 softtoken::AAGUID,
4954 "softtoken_a".to_string(),
4955 Default::default(),
4956 )
4957 .unwrap();
4958 att_ca_builder
4959 .insert_device_x509(
4960 ca_root_b,
4961 softtoken::AAGUID,
4962 "softtoken_b".to_string(),
4963 Default::default(),
4964 )
4965 .unwrap();
4966 let att_ca_list = att_ca_builder.build();
4967
4968 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4969
4970 let modlist = ModifyList::new_purge_and_set(
4971 Attribute::WebauthnAttestationCaList,
4972 Value::WebauthnAttestationCaList(att_ca_list),
4973 );
4974 idms_prox_write
4975 .qs_write
4976 .internal_modify_uuid(UUID_IDM_ALL_ACCOUNTS, &modlist)
4977 .expect("Unable to change webauthn attestation policy");
4978
4979 assert!(idms_prox_write.commit().is_ok());
4980
4981 let (soft_token_invalid, _) = SoftToken::new(true).unwrap();
4983 let mut wa_token_invalid = soft_token_invalid;
4984
4985 let mut wa_passkey_invalid = SoftPasskey::new(true);
4986
4987 let (cust, _) = setup_test_session(idms, ct).await;
4990 let cutxn = idms.cred_update_transaction().await.unwrap();
4991 let origin = cutxn.get_origin().clone();
4992
4993 let c_status = cutxn
4995 .credential_update_status(&cust, ct)
4996 .expect("Failed to get the current session status.");
4997
4998 trace!(?c_status);
4999 assert!(c_status.attested_passkeys.is_empty());
5000 assert!(c_status
5001 .attested_passkeys_allowed_devices
5002 .contains(&"softtoken_a".to_string()));
5003 assert!(c_status
5004 .attested_passkeys_allowed_devices
5005 .contains(&"softtoken_b".to_string()));
5006
5007 let err = cutxn.credential_passkey_init(&cust, ct).unwrap_err();
5010 assert!(matches!(err, OperationError::AccessDenied));
5011
5012 let c_status = cutxn
5015 .credential_attested_passkey_init(&cust, ct)
5016 .expect("Failed to initiate attested passkey registration");
5017
5018 let passkey_chal = match c_status.mfaregstate {
5019 MfaRegStateStatus::AttestedPasskey(c) => Some(c),
5020 _ => None,
5021 }
5022 .expect("Unable to access passkey challenge, invalid state");
5023
5024 let passkey_resp = wa_passkey_invalid
5025 .do_registration(origin.clone(), passkey_chal)
5026 .expect("Failed to create soft passkey");
5027
5028 let label = "softtoken".to_string();
5030 let err = cutxn
5031 .credential_attested_passkey_finish(&cust, ct, label, &passkey_resp)
5032 .unwrap_err();
5033
5034 assert!(matches!(
5035 err,
5036 OperationError::CU0001WebauthnAttestationNotTrusted
5037 ));
5038
5039 let c_status = cutxn
5042 .credential_attested_passkey_init(&cust, ct)
5043 .expect("Failed to initiate attested passkey registration");
5044
5045 let passkey_chal = match c_status.mfaregstate {
5046 MfaRegStateStatus::AttestedPasskey(c) => Some(c),
5047 _ => None,
5048 }
5049 .expect("Unable to access passkey challenge, invalid state");
5050
5051 let passkey_resp = wa_token_invalid
5052 .do_registration(origin.clone(), passkey_chal)
5053 .expect("Failed to create soft passkey");
5054
5055 let label = "softtoken".to_string();
5057 let err = cutxn
5058 .credential_attested_passkey_finish(&cust, ct, label, &passkey_resp)
5059 .unwrap_err();
5060
5061 assert!(matches!(
5062 err,
5063 OperationError::CU0001WebauthnAttestationNotTrusted
5064 ));
5065
5066 let c_status = cutxn
5069 .credential_attested_passkey_init(&cust, ct)
5070 .expect("Failed to initiate attested passkey registration");
5071
5072 let passkey_chal = match c_status.mfaregstate {
5073 MfaRegStateStatus::AttestedPasskey(c) => Some(c),
5074 _ => None,
5075 }
5076 .expect("Unable to access passkey challenge, invalid state");
5077
5078 let passkey_resp = wa_token_valid
5079 .do_registration(origin.clone(), passkey_chal)
5080 .expect("Failed to create soft passkey");
5081
5082 let label = "softtoken".to_string();
5084 let c_status = cutxn
5085 .credential_attested_passkey_finish(&cust, ct, label, &passkey_resp)
5086 .expect("Failed to initiate passkey registration");
5087
5088 assert!(matches!(c_status.mfaregstate, MfaRegStateStatus::None));
5089 trace!(?c_status);
5090 assert_eq!(c_status.attested_passkeys.len(), 1);
5091
5092 let pk_uuid = c_status
5093 .attested_passkeys
5094 .first()
5095 .map(|pkd| pkd.uuid)
5096 .unwrap();
5097
5098 drop(cutxn);
5099 commit_session(idms, ct, cust).await;
5100
5101 assert!(check_testperson_passkey(
5103 idms,
5104 idms_delayed,
5105 &mut wa_token_valid,
5106 origin.clone(),
5107 ct
5108 )
5109 .await
5110 .is_some());
5111
5112 let (cust, _) = renew_test_session(idms, ct).await;
5114 let cutxn = idms.cred_update_transaction().await.unwrap();
5115
5116 trace!(?c_status);
5117 assert!(c_status.primary.is_none());
5118 assert!(c_status.passkeys.is_empty());
5119 assert_eq!(c_status.attested_passkeys.len(), 1);
5120
5121 let c_status = cutxn
5122 .credential_attested_passkey_remove(&cust, ct, pk_uuid)
5123 .expect("Failed to delete the attested passkey");
5124
5125 trace!(?c_status);
5126 assert!(c_status.primary.is_none());
5127 assert!(c_status.passkeys.is_empty());
5128 assert!(c_status.attested_passkeys.is_empty());
5129
5130 assert!(!c_status.can_commit);
5132 assert!(c_status.dirty);
5133 assert!(c_status
5134 .warnings
5135 .contains(&CredentialUpdateSessionStatusWarnings::NoValidCredentials));
5136
5137 let c_status = cutxn
5139 .credential_attested_passkey_init(&cust, ct)
5140 .expect("Failed to initiate attested passkey registration");
5141
5142 let passkey_chal = match c_status.mfaregstate {
5143 MfaRegStateStatus::AttestedPasskey(c) => Some(c),
5144 _ => None,
5145 }
5146 .expect("Unable to access passkey challenge, invalid state");
5147
5148 let passkey_resp = wa_token_valid_b
5150 .do_registration(origin.clone(), passkey_chal)
5151 .expect("Failed to create soft passkey");
5152
5153 let label = "softtoken".to_string();
5155 let c_status = cutxn
5156 .credential_attested_passkey_finish(&cust, ct, label, &passkey_resp)
5157 .expect("Failed to initiate passkey registration");
5158
5159 assert!(matches!(c_status.mfaregstate, MfaRegStateStatus::None));
5160 trace!(?c_status);
5161 assert_eq!(c_status.attested_passkeys.len(), 1);
5162
5163 drop(cutxn);
5164 commit_session(idms, ct, cust).await;
5165
5166 assert!(
5169 check_testperson_passkey(idms, idms_delayed, &mut wa_token_valid, origin, ct)
5170 .await
5171 .is_none()
5172 );
5173 }
5174
5175 #[idm_test(audit = 1)]
5176 async fn credential_update_account_policy_attested_passkey_changed(
5177 idms: &IdmServer,
5178 idms_delayed: &mut IdmServerDelayed,
5179 idms_audit: &mut IdmServerAudit,
5180 ) {
5181 let ct = Duration::from_secs(TEST_CURRENT_TIME);
5182
5183 let (soft_token_1, ca_root_1) = SoftToken::new(true).unwrap();
5185 let mut wa_token_1 = soft_token_1;
5186
5187 let (soft_token_2, ca_root_2) = SoftToken::new(true).unwrap();
5188 let mut wa_token_2 = soft_token_2;
5189
5190 let mut att_ca_builder = AttestationCaListBuilder::new();
5192 att_ca_builder
5193 .insert_device_x509(
5194 ca_root_1.clone(),
5195 softtoken::AAGUID,
5196 "softtoken_1".to_string(),
5197 Default::default(),
5198 )
5199 .unwrap();
5200 let att_ca_list = att_ca_builder.build();
5201
5202 trace!(?att_ca_list);
5203
5204 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5205
5206 let modlist = ModifyList::new_purge_and_set(
5207 Attribute::WebauthnAttestationCaList,
5208 Value::WebauthnAttestationCaList(att_ca_list),
5209 );
5210 idms_prox_write
5211 .qs_write
5212 .internal_modify_uuid(UUID_IDM_ALL_ACCOUNTS, &modlist)
5213 .expect("Unable to change webauthn attestation policy");
5214
5215 assert!(idms_prox_write.commit().is_ok());
5216
5217 let mut att_ca_builder = AttestationCaListBuilder::new();
5219 att_ca_builder
5220 .insert_device_x509(
5221 ca_root_2,
5222 softtoken::AAGUID,
5223 "softtoken_2".to_string(),
5224 Default::default(),
5225 )
5226 .unwrap();
5227 let att_ca_list_post = att_ca_builder.build();
5228
5229 let (cust, _) = setup_test_session(idms, ct).await;
5231 let cutxn = idms.cred_update_transaction().await.unwrap();
5232 let origin = cutxn.get_origin().clone();
5233
5234 let c_status = cutxn
5236 .credential_attested_passkey_init(&cust, ct)
5237 .expect("Failed to initiate attested passkey registration");
5238
5239 let passkey_chal = match c_status.mfaregstate {
5240 MfaRegStateStatus::AttestedPasskey(c) => Some(c),
5241 _ => None,
5242 }
5243 .expect("Unable to access passkey challenge, invalid state");
5244
5245 let passkey_resp = wa_token_1
5246 .do_registration(origin.clone(), passkey_chal)
5247 .expect("Failed to create soft passkey");
5248
5249 let label = "softtoken".to_string();
5251 let c_status = cutxn
5252 .credential_attested_passkey_finish(&cust, ct, label, &passkey_resp)
5253 .expect("Failed to initiate passkey registration");
5254
5255 assert!(matches!(c_status.mfaregstate, MfaRegStateStatus::None));
5256 trace!(?c_status);
5257 assert_eq!(c_status.attested_passkeys.len(), 1);
5258
5259 drop(cutxn);
5262 commit_session(idms, ct, cust).await;
5263
5264 assert!(
5266 check_testperson_passkey(idms, idms_delayed, &mut wa_token_1, origin.clone(), ct)
5267 .await
5268 .is_some()
5269 );
5270
5271 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5273
5274 let modlist = ModifyList::new_purge_and_set(
5275 Attribute::WebauthnAttestationCaList,
5276 Value::WebauthnAttestationCaList(att_ca_list_post),
5277 );
5278 idms_prox_write
5279 .qs_write
5280 .internal_modify_uuid(UUID_IDM_ALL_ACCOUNTS, &modlist)
5281 .expect("Unable to change webauthn attestation policy");
5282
5283 assert!(idms_prox_write.commit().is_ok());
5284
5285 assert!(
5287 check_testperson_passkey(idms, idms_delayed, &mut wa_token_1, origin.clone(), ct)
5288 .await
5289 .is_none()
5290 );
5291
5292 match idms_audit.audit_rx().try_recv() {
5295 Ok(AuditEvent::AuthenticationDenied { .. }) => {}
5296 _ => panic!("Oh no"),
5297 }
5298
5299 let (cust, _) = renew_test_session(idms, ct).await;
5301 let cutxn = idms.cred_update_transaction().await.unwrap();
5302
5303 let c_status = cutxn
5305 .credential_update_status(&cust, ct)
5306 .expect("Failed to get the current session status.");
5307
5308 trace!(?c_status);
5309 assert!(c_status.attested_passkeys.is_empty());
5310
5311 assert!(!c_status.can_commit);
5313 assert!(!c_status.dirty);
5315 assert!(c_status
5316 .warnings
5317 .contains(&CredentialUpdateSessionStatusWarnings::NoValidCredentials));
5318
5319 let c_status = cutxn
5322 .credential_attested_passkey_init(&cust, ct)
5323 .expect("Failed to initiate attested passkey registration");
5324
5325 let passkey_chal = match c_status.mfaregstate {
5326 MfaRegStateStatus::AttestedPasskey(c) => Some(c),
5327 _ => None,
5328 }
5329 .expect("Unable to access passkey challenge, invalid state");
5330
5331 let passkey_resp = wa_token_2
5332 .do_registration(origin.clone(), passkey_chal)
5333 .expect("Failed to create soft passkey");
5334
5335 let label = "softtoken".to_string();
5337 let c_status = cutxn
5338 .credential_attested_passkey_finish(&cust, ct, label, &passkey_resp)
5339 .expect("Failed to initiate passkey registration");
5340
5341 assert!(matches!(c_status.mfaregstate, MfaRegStateStatus::None));
5342 trace!(?c_status);
5343 assert_eq!(c_status.attested_passkeys.len(), 1);
5344
5345 drop(cutxn);
5346 commit_session(idms, ct, cust).await;
5347
5348 assert!(
5350 check_testperson_passkey(idms, idms_delayed, &mut wa_token_1, origin.clone(), ct)
5351 .await
5352 .is_none()
5353 );
5354
5355 assert!(
5357 check_testperson_passkey(idms, idms_delayed, &mut wa_token_2, origin.clone(), ct)
5358 .await
5359 .is_some()
5360 );
5361 }
5362
5363 #[idm_test]
5365 async fn credential_update_account_policy_attested_passkey_downgrade(
5366 idms: &IdmServer,
5367 idms_delayed: &mut IdmServerDelayed,
5368 ) {
5369 let ct = Duration::from_secs(TEST_CURRENT_TIME);
5370
5371 let (soft_token_1, ca_root_1) = SoftToken::new(true).unwrap();
5373 let mut wa_token_1 = soft_token_1;
5374
5375 let mut att_ca_builder = AttestationCaListBuilder::new();
5376 att_ca_builder
5377 .insert_device_x509(
5378 ca_root_1.clone(),
5379 softtoken::AAGUID,
5380 "softtoken_1".to_string(),
5381 Default::default(),
5382 )
5383 .unwrap();
5384 let att_ca_list = att_ca_builder.build();
5385
5386 trace!(?att_ca_list);
5387
5388 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5389
5390 let modlist = ModifyList::new_purge_and_set(
5391 Attribute::WebauthnAttestationCaList,
5392 Value::WebauthnAttestationCaList(att_ca_list),
5393 );
5394 idms_prox_write
5395 .qs_write
5396 .internal_modify_uuid(UUID_IDM_ALL_ACCOUNTS, &modlist)
5397 .expect("Unable to change webauthn attestation policy");
5398
5399 assert!(idms_prox_write.commit().is_ok());
5400
5401 let (cust, _) = setup_test_session(idms, ct).await;
5403 let cutxn = idms.cred_update_transaction().await.unwrap();
5404 let origin = cutxn.get_origin().clone();
5405
5406 let c_status = cutxn
5408 .credential_attested_passkey_init(&cust, ct)
5409 .expect("Failed to initiate attested passkey registration");
5410
5411 let passkey_chal = match c_status.mfaregstate {
5412 MfaRegStateStatus::AttestedPasskey(c) => Some(c),
5413 _ => None,
5414 }
5415 .expect("Unable to access passkey challenge, invalid state");
5416
5417 let passkey_resp = wa_token_1
5418 .do_registration(origin.clone(), passkey_chal)
5419 .expect("Failed to create soft passkey");
5420
5421 let label = "softtoken".to_string();
5423 let c_status = cutxn
5424 .credential_attested_passkey_finish(&cust, ct, label, &passkey_resp)
5425 .expect("Failed to initiate passkey registration");
5426
5427 assert!(matches!(c_status.mfaregstate, MfaRegStateStatus::None));
5428 trace!(?c_status);
5429 assert_eq!(c_status.attested_passkeys.len(), 1);
5430
5431 drop(cutxn);
5434 commit_session(idms, ct, cust).await;
5435
5436 assert!(
5438 check_testperson_passkey(idms, idms_delayed, &mut wa_token_1, origin.clone(), ct)
5439 .await
5440 .is_some()
5441 );
5442
5443 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5445
5446 let modlist = ModifyList::new_purge(Attribute::WebauthnAttestationCaList);
5447 idms_prox_write
5448 .qs_write
5449 .internal_modify_uuid(UUID_IDM_ALL_ACCOUNTS, &modlist)
5450 .expect("Unable to change webauthn attestation policy");
5451
5452 assert!(idms_prox_write.commit().is_ok());
5453
5454 assert!(
5456 check_testperson_passkey(idms, idms_delayed, &mut wa_token_1, origin.clone(), ct)
5457 .await
5458 .is_some()
5459 );
5460
5461 let (cust, _) = renew_test_session(idms, ct).await;
5463 let cutxn = idms.cred_update_transaction().await.unwrap();
5464
5465 let c_status = cutxn
5466 .credential_update_status(&cust, ct)
5467 .expect("Failed to get the current session status.");
5468
5469 trace!(?c_status);
5470 assert_eq!(c_status.attested_passkeys.len(), 1);
5471 assert!(matches!(
5472 c_status.attested_passkeys_state,
5473 CredentialState::DeleteOnly
5474 ));
5475 assert!(!c_status.dirty);
5476
5477 drop(cutxn);
5478 commit_session(idms, ct, cust).await;
5479 }
5480
5481 #[idm_test]
5482 async fn credential_update_unix_password(
5483 idms: &IdmServer,
5484 _idms_delayed: &mut IdmServerDelayed,
5485 ) {
5486 let test_pw = readable_password_from_random();
5487 let ct = Duration::from_secs(TEST_CURRENT_TIME);
5488
5489 let (cust, _) = setup_test_session(idms, ct).await;
5490
5491 let cutxn = idms.cred_update_transaction().await.unwrap();
5492
5493 let c_status = cutxn
5497 .credential_update_status(&cust, ct)
5498 .expect("Failed to get the current session status.");
5499
5500 trace!(?c_status);
5501 assert!(c_status.unixcred.is_none());
5502
5503 assert!(c_status
5505 .warnings
5506 .contains(&CredentialUpdateSessionStatusWarnings::NoValidCredentials));
5507 assert!(!c_status.can_commit);
5508 assert!(!c_status.dirty);
5509 let c_status = cutxn
5511 .credential_primary_set_password(&cust, ct, &test_pw)
5512 .expect("Failed to update the primary cred password");
5513 assert!(c_status.can_commit);
5514 assert!(c_status.dirty);
5515 assert!(!c_status
5516 .warnings
5517 .contains(&CredentialUpdateSessionStatusWarnings::NoValidCredentials));
5518
5519 let c_status = cutxn
5522 .credential_unix_set_password(&cust, ct, &test_pw)
5523 .expect("Failed to update the unix cred password");
5524
5525 assert!(c_status.can_commit);
5526 assert!(c_status.dirty);
5527
5528 drop(cutxn);
5529 commit_session(idms, ct, cust).await;
5530
5531 assert!(check_testperson_unix_password(idms, &test_pw, ct)
5533 .await
5534 .is_some());
5535
5536 let (cust, _) = renew_test_session(idms, ct).await;
5538 let cutxn = idms.cred_update_transaction().await.unwrap();
5539
5540 let c_status = cutxn
5541 .credential_update_status(&cust, ct)
5542 .expect("Failed to get the current session status.");
5543 trace!(?c_status);
5544 assert!(c_status.unixcred.is_some());
5545
5546 let c_status = cutxn
5547 .credential_unix_delete(&cust, ct)
5548 .expect("Failed to delete the unix cred");
5549 trace!(?c_status);
5550 assert!(c_status.unixcred.is_none());
5551
5552 drop(cutxn);
5553 commit_session(idms, ct, cust).await;
5554
5555 assert!(check_testperson_unix_password(idms, &test_pw, ct)
5557 .await
5558 .is_none());
5559 }
5560
5561 #[idm_test]
5562 async fn credential_update_sshkeys(idms: &IdmServer, _idms_delayed: &mut IdmServerDelayed) {
5563 let test_pw = readable_password_from_random();
5564 let sshkey_valid_1 =
5565 SshPublicKey::from_string(SSHKEY_VALID_1).expect("Invalid SSHKEY_VALID_1");
5566 let sshkey_valid_2 =
5567 SshPublicKey::from_string(SSHKEY_VALID_2).expect("Invalid SSHKEY_VALID_2");
5568
5569 assert!(SshPublicKey::from_string(SSHKEY_INVALID).is_err());
5570
5571 let ct = Duration::from_secs(TEST_CURRENT_TIME);
5572 let (cust, _) = setup_test_session(idms, ct).await;
5573 let cutxn = idms.cred_update_transaction().await.unwrap();
5574
5575 let c_status = cutxn
5576 .credential_update_status(&cust, ct)
5577 .expect("Failed to get the current session status.");
5578
5579 assert!(c_status
5581 .warnings
5582 .contains(&CredentialUpdateSessionStatusWarnings::NoValidCredentials));
5583 assert!(!c_status.can_commit);
5584 assert!(!c_status.dirty);
5585 let c_status = cutxn
5587 .credential_primary_set_password(&cust, ct, &test_pw)
5588 .expect("Failed to update the primary cred password");
5589
5590 trace!(?c_status);
5593
5594 assert!(c_status.sshkeys.is_empty());
5595
5596 let result = cutxn.credential_sshkey_add(&cust, ct, "".to_string(), sshkey_valid_1.clone());
5598 assert!(matches!(result, Err(OperationError::InvalidLabel)));
5599
5600 let result =
5602 cutxn.credential_sshkey_add(&cust, ct, "🚛".to_string(), sshkey_valid_1.clone());
5603 assert!(matches!(result, Err(OperationError::InvalidLabel)));
5604
5605 let result = cutxn.credential_sshkey_remove(&cust, ct, "key1");
5607 assert!(matches!(result, Err(OperationError::NoMatchingEntries)));
5608
5609 let c_status = cutxn
5611 .credential_sshkey_add(&cust, ct, "key1".to_string(), sshkey_valid_1.clone())
5612 .expect("Failed to add sshkey_valid_1");
5613
5614 trace!(?c_status);
5615 assert_eq!(c_status.sshkeys.len(), 1);
5616 assert!(c_status.sshkeys.contains_key("key1"));
5617
5618 let c_status = cutxn
5620 .credential_sshkey_add(&cust, ct, "key2".to_string(), sshkey_valid_2.clone())
5621 .expect("Failed to add sshkey_valid_2");
5622
5623 trace!(?c_status);
5624 assert_eq!(c_status.sshkeys.len(), 2);
5625 assert!(c_status.sshkeys.contains_key("key1"));
5626 assert!(c_status.sshkeys.contains_key("key2"));
5627
5628 let c_status = cutxn
5630 .credential_sshkey_remove(&cust, ct, "key2")
5631 .expect("Failed to remove sshkey_valid_2");
5632
5633 trace!(?c_status);
5634 assert_eq!(c_status.sshkeys.len(), 1);
5635 assert!(c_status.sshkeys.contains_key("key1"));
5636
5637 let result =
5639 cutxn.credential_sshkey_add(&cust, ct, "key1".to_string(), sshkey_valid_2.clone());
5640 assert!(matches!(result, Err(OperationError::DuplicateLabel)));
5641
5642 let result =
5644 cutxn.credential_sshkey_add(&cust, ct, "key2".to_string(), sshkey_valid_1.clone());
5645 assert!(matches!(result, Err(OperationError::DuplicateKey)));
5646
5647 drop(cutxn);
5648 commit_session(idms, ct, cust).await;
5649 }
5650
5651 #[idm_test]
5653 async fn credential_update_at_least_one_credential(
5654 idms: &IdmServer,
5655 _idms_delayed: &mut IdmServerDelayed,
5656 ) {
5657 let test_pw = readable_password_from_random();
5658 let ct = Duration::from_secs(TEST_CURRENT_TIME);
5659
5660 let (cust, _) = setup_test_session(idms, ct).await;
5661
5662 let cutxn = idms.cred_update_transaction().await.unwrap();
5663
5664 let c_status = cutxn
5668 .credential_update_status(&cust, ct)
5669 .expect("Failed to get the current session status.");
5670
5671 trace!(?c_status);
5672
5673 assert!(c_status.primary.is_none());
5674 assert!(c_status
5676 .warnings
5677 .contains(&CredentialUpdateSessionStatusWarnings::NoValidCredentials));
5678 assert!(!c_status.can_commit);
5679 assert!(!c_status.dirty);
5680
5681 let c_status = cutxn
5683 .credential_primary_set_password(&cust, ct, &test_pw)
5684 .expect("Failed to update the primary cred password");
5685
5686 assert!(c_status.can_commit);
5688 assert!(c_status.dirty);
5689 assert!(!c_status
5690 .warnings
5691 .contains(&CredentialUpdateSessionStatusWarnings::NoValidCredentials));
5692
5693 let c_status = cutxn
5695 .credential_primary_delete(&cust, ct)
5696 .expect("Failed to remove the primary credential");
5697
5698 assert!(c_status
5700 .warnings
5701 .contains(&CredentialUpdateSessionStatusWarnings::NoValidCredentials));
5702 assert!(!c_status.can_commit);
5703 assert!(c_status.dirty);
5704 }
5705
5706 async fn get_testperson_password_changed_time(idms: &IdmServer) -> Option<OffsetDateTime> {
5707 let mut txn = idms.proxy_read().await.unwrap();
5708 let entry = txn
5709 .qs_read
5710 .internal_search_uuid(TESTPERSON_UUID)
5711 .expect("Failed to read testperson entry");
5712 entry.get_ava_single_datetime(Attribute::PasswordChangedTime)
5713 }
5714
5715 #[idm_test]
5716 async fn credential_update_password_changed_time_password_set(
5717 idms: &IdmServer,
5718 _idms_delayed: &mut IdmServerDelayed,
5719 ) {
5720 let testpw = readable_password_from_random();
5721 let ct = Duration::from_secs(TEST_CURRENT_TIME);
5722
5723 let (cust, _) = setup_test_session(idms, ct).await;
5724
5725 assert!(get_testperson_password_changed_time(idms).await.is_none());
5727
5728 let cutxn = idms.cred_update_transaction().await.unwrap();
5730 let c_status = cutxn
5731 .credential_primary_set_password(&cust, ct, &testpw)
5732 .expect("Failed to update the primary cred password");
5733 assert!(c_status.can_commit);
5734 assert!(c_status.dirty);
5735 drop(cutxn);
5736 commit_session(idms, ct, cust).await;
5737
5738 let pwd_changed = get_testperson_password_changed_time(idms)
5739 .await
5740 .expect("PasswordChangedTime should be set after setting primary password");
5741 assert_eq!(pwd_changed, OffsetDateTime::UNIX_EPOCH);
5742
5743 let (cust, _) = renew_test_session(idms, ct).await;
5745 let cutxn = idms.cred_update_transaction().await.unwrap();
5746 let c_status = cutxn
5747 .credential_unix_set_password(&cust, ct, &testpw)
5748 .expect("Failed to set unix password");
5749 assert!(c_status.can_commit);
5750 assert!(c_status.dirty);
5751 drop(cutxn);
5752 commit_session(idms, ct, cust).await;
5753
5754 let pwd_changed = get_testperson_password_changed_time(idms)
5755 .await
5756 .expect("PasswordChangedTime should be set after setting both passwords");
5757 assert_eq!(pwd_changed, OffsetDateTime::UNIX_EPOCH + ct);
5759
5760 let ct = Duration::from_secs(TEST_CURRENT_TIME + 1000);
5761
5762 let (cust, _) = renew_test_session(idms, ct).await;
5764 let cutxn = idms.cred_update_transaction().await.unwrap();
5765 let _ = cutxn
5766 .credential_unix_set_password(&cust, ct, "R290Y2hhIGFnYWlu")
5767 .expect("Failed to set unix password on second update");
5768 drop(cutxn);
5769 commit_session(idms, ct, cust).await;
5770
5771 let pwd_changed_2 = get_testperson_password_changed_time(idms)
5772 .await
5773 .expect("PasswordChangedTime should be updated on second update");
5774 assert_eq!(pwd_changed_2, OffsetDateTime::UNIX_EPOCH + ct);
5775 assert!(pwd_changed_2 > pwd_changed);
5776 }
5777
5778 #[idm_test]
5779 async fn credential_update_password_changed_time_unix_deleted(
5780 idms: &IdmServer,
5781 _idms_delayed: &mut IdmServerDelayed,
5782 ) {
5783 let testpw = readable_password_from_random();
5784 let ct = Duration::from_secs(TEST_CURRENT_TIME);
5785
5786 let (cust, _) = setup_test_session(idms, ct).await;
5788 let cutxn = idms.cred_update_transaction().await.unwrap();
5789 let _ = cutxn
5790 .credential_primary_set_password(&cust, ct, &testpw)
5791 .expect("Failed to set primary password");
5792 let _ = cutxn
5793 .credential_unix_set_password(&cust, ct, &testpw)
5794 .expect("Failed to set unix password");
5795 drop(cutxn);
5796 commit_session(idms, ct, cust).await;
5797
5798 let pwd_changed_1 = get_testperson_password_changed_time(idms)
5799 .await
5800 .expect("PasswordChangedTime should be set");
5801 assert_eq!(pwd_changed_1, OffsetDateTime::UNIX_EPOCH + ct);
5802
5803 let ct = Duration::from_secs(TEST_CURRENT_TIME + 1000);
5804
5805 let (cust, _) = renew_test_session(idms, ct).await;
5807 let cutxn = idms.cred_update_transaction().await.unwrap();
5808 let c_status = cutxn
5809 .credential_unix_delete(&cust, ct)
5810 .expect("Failed to delete unix credential");
5811 assert!(c_status.unixcred.is_none());
5812 assert!(c_status.can_commit);
5813 assert!(c_status.dirty);
5814 drop(cutxn);
5815 commit_session(idms, ct, cust).await;
5816
5817 let pwd_changed_2 = get_testperson_password_changed_time(idms)
5819 .await
5820 .expect("PasswordChangedTime should still be set after deleting unix password");
5821 assert_eq!(pwd_changed_2, OffsetDateTime::UNIX_EPOCH);
5822 }
5823
5824 #[idm_test]
5825 async fn credential_update_password_changed_time_non_posix(
5826 idms: &IdmServer,
5827 _idms_delayed: &mut IdmServerDelayed,
5828 ) {
5829 let testpw = readable_password_from_random();
5830 let ct = Duration::from_secs(TEST_CURRENT_TIME);
5831
5832 let (cust, _) = setup_test_session_no_posix(idms, ct).await;
5833
5834 assert!(get_testperson_password_changed_time(idms).await.is_none());
5836
5837 let cutxn = idms.cred_update_transaction().await.unwrap();
5839 let c_status = cutxn
5840 .credential_primary_set_password(&cust, ct, &testpw)
5841 .expect("Failed to set primary password");
5842 assert!(c_status.can_commit);
5843 assert!(c_status.dirty);
5844 drop(cutxn);
5845 commit_session(idms, ct, cust).await;
5846
5847 let pwd_changed = get_testperson_password_changed_time(idms)
5848 .await
5849 .expect("PasswordChangedTime should be set for non-posix person");
5850 assert_eq!(pwd_changed, OffsetDateTime::UNIX_EPOCH);
5851
5852 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5854 idms_prox_write
5855 .qs_write
5856 .internal_modify_uuid(
5857 UUID_IDM_ALL_ACCOUNTS,
5858 &ModifyList::new_purge_and_set(
5859 Attribute::AllowPrimaryCredFallback,
5860 Value::new_bool(true),
5861 ),
5862 )
5863 .expect("Unable to set allow_primary_cred_fallback");
5864 idms_prox_write.commit().expect("Failed to commit txn");
5865
5866 let (cust, _) = renew_test_session(idms, ct).await;
5868 let cutxn = idms.cred_update_transaction().await.unwrap();
5869 let _ = cutxn
5870 .credential_primary_set_password(&cust, ct, &testpw)
5871 .expect("Failed to set primary password");
5872 drop(cutxn);
5873 commit_session(idms, ct, cust).await;
5874 let pwd_changed = get_testperson_password_changed_time(idms)
5875 .await
5876 .expect("PasswordChangedTime should be set with fallback enabled");
5877 assert_eq!(pwd_changed, OffsetDateTime::UNIX_EPOCH + ct);
5878 }
5879
5880 #[idm_test]
5881 async fn credential_update_password_changed_time_passkey_only(
5882 idms: &IdmServer,
5883 _idms_delayed: &mut IdmServerDelayed,
5884 ) {
5885 let ct = Duration::from_secs(TEST_CURRENT_TIME);
5886 let (cust, _) = setup_test_session_no_posix(idms, ct).await;
5887
5888 assert!(get_testperson_password_changed_time(idms).await.is_none());
5890
5891 let cutxn = idms.cred_update_transaction().await.unwrap();
5893 let origin = cutxn.get_origin().clone();
5894 let mut wa = SoftPasskey::new(true);
5895
5896 let c_status = create_new_passkey(ct, &origin, &cutxn, &cust, &mut wa).await;
5897 assert!(c_status.can_commit);
5898 assert!(c_status.dirty);
5899 assert_eq!(c_status.passkeys.len(), 1);
5900 drop(cutxn);
5901 commit_session(idms, ct, cust).await;
5902
5903 let pwd_changed = get_testperson_password_changed_time(idms)
5905 .await
5906 .expect("PasswordChangedTime should be set even for passkey-only");
5907 assert_eq!(pwd_changed, time::OffsetDateTime::UNIX_EPOCH);
5908 }
5909
5910 #[idm_test]
5911 async fn credential_update_password_changed_time_no_change_commit(
5912 idms: &IdmServer,
5913 _idms_delayed: &mut IdmServerDelayed,
5914 ) {
5915 let testpw = readable_password_from_random();
5916 let ct = Duration::from_secs(TEST_CURRENT_TIME);
5917 let (cust, _) = setup_test_session(idms, ct).await;
5918
5919 let cutxn = idms.cred_update_transaction().await.unwrap();
5920 let _ = cutxn
5921 .credential_primary_set_password(&cust, ct, &testpw)
5922 .expect("Failed to set primary password");
5923 let _ = cutxn
5924 .credential_unix_set_password(&cust, ct, &testpw)
5925 .expect("Failed to set unix password");
5926 drop(cutxn);
5927 commit_session(idms, ct, cust).await;
5928
5929 let pwd_changed_1 = get_testperson_password_changed_time(idms)
5930 .await
5931 .expect("PasswordChangedTime should be set after first update");
5932
5933 let ct2 = Duration::from_secs(TEST_CURRENT_TIME + 2000);
5934
5935 let (cust, c_status) = renew_test_session(idms, ct2).await;
5937 assert!(c_status.primary.is_some());
5938 assert!(c_status.can_commit);
5939 assert!(!c_status.dirty);
5940 commit_session(idms, ct2, cust).await;
5941
5942 let pwd_changed_2 = get_testperson_password_changed_time(idms)
5943 .await
5944 .expect("PasswordChangedTime should still be present after no-change commit");
5945
5946 assert_eq!(pwd_changed_2, OffsetDateTime::UNIX_EPOCH + ct);
5947 assert_eq!(pwd_changed_2, pwd_changed_1);
5948 }
5949
5950 #[idm_test]
5951 async fn credential_update_unix_password_deleted_falls_back(
5952 idms: &IdmServer,
5953 _idms_delayed: &mut IdmServerDelayed,
5954 ) {
5955 let testpw = readable_password_from_random();
5956 let ct = Duration::from_secs(TEST_CURRENT_TIME);
5957 let ct2 = Duration::from_secs(TEST_CURRENT_TIME + 50);
5958
5959 let (cust, _) = setup_test_session(idms, ct).await;
5960
5961 let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5963 idms_prox_write
5964 .qs_write
5965 .internal_modify_uuid(
5966 UUID_IDM_ALL_ACCOUNTS,
5967 &ModifyList::new_purge_and_set(
5968 Attribute::AllowPrimaryCredFallback,
5969 Value::new_bool(true),
5970 ),
5971 )
5972 .expect("Unable to set allow_primary_cred_fallback");
5973 idms_prox_write.commit().expect("Failed to commit txn");
5974
5975 assert!(get_testperson_password_changed_time(idms).await.is_none());
5977
5978 let cutxn = idms.cred_update_transaction().await.unwrap();
5979 let _ = cutxn
5980 .credential_primary_set_password(&cust, ct, &testpw)
5981 .expect("Failed to set primary password");
5982
5983 let _ = cutxn
5984 .credential_unix_set_password(&cust, ct2, &testpw)
5985 .expect("Failed to set unix password");
5986
5987 let c_status = cutxn
5988 .credential_primary_init_totp(&cust, ct)
5989 .expect("Failed to init totp");
5990
5991 let totp_token: Totp = match c_status.mfaregstate {
5992 MfaRegStateStatus::TotpCheck(secret) => Some(secret.try_into().unwrap()),
5993 _ => None,
5994 }
5995 .expect("Unable to retrieve totp token");
5996
5997 let chal = totp_token
5998 .do_totp_duration_from_epoch(&ct)
5999 .expect("Failed to perform totp step");
6000
6001 let c_status = cutxn
6002 .credential_primary_check_totp(&cust, ct, chal, "totp")
6003 .expect("Failed to check totp");
6004
6005 assert!(matches!(c_status.mfaregstate, MfaRegStateStatus::None));
6006 assert!(c_status.can_commit);
6007 assert!(c_status.dirty);
6008
6009 drop(cutxn);
6010 commit_session(idms, ct, cust).await;
6011
6012 let pwd_changed = get_testperson_password_changed_time(idms)
6013 .await
6014 .expect("PasswordChangedTime should be set for password+TOTP");
6015 assert_eq!(pwd_changed, OffsetDateTime::UNIX_EPOCH + ct2);
6017
6018 let (cust, _) = renew_test_session(idms, ct2).await;
6020 let cutxn = idms.cred_update_transaction().await.unwrap();
6021
6022 let _ = cutxn
6023 .credential_unix_delete(&cust, ct2)
6024 .expect("Failed to delete unix credential");
6025
6026 assert!(c_status.can_commit);
6027 assert!(c_status.dirty);
6028 drop(cutxn);
6029 commit_session(idms, ct2, cust).await;
6030
6031 let pwd_changed_2 = get_testperson_password_changed_time(idms)
6032 .await
6033 .expect("PasswordChangedTime should be set after switching to passkey");
6034 assert_eq!(pwd_changed_2, OffsetDateTime::UNIX_EPOCH + ct);
6035 }
6036}