Skip to main content

kanidmd_lib/idm/
account.rs

1use super::{
2    accountpolicy::ResolvedAccountPolicy,
3    group::{load_account_policy, load_all_groups_from_account, Group, Unix},
4};
5use crate::{
6    constants::UUID_ANONYMOUS,
7    credential::{apppwd::ApplicationPassword, softlock::CredSoftLockPolicy, Credential},
8    entry::{Entry, EntryCommitted, EntryReduced, EntrySealed},
9    event::SearchEvent,
10    idm::{
11        application::Application,
12        ldap::{LdapBoundToken, LdapSession},
13        server::{IdmServerProxyReadTransaction, IdmServerProxyWriteTransaction},
14    },
15    modify::{ModifyInvalid, ModifyList},
16    prelude::*,
17    schema::SchemaTransaction,
18    value::{IntentTokenState, PartialValue, SessionState, Value},
19};
20use kanidm_lib_crypto::CryptoPolicy;
21use kanidm_proto::{
22    internal::{CredentialStatus, UatPurpose, UiHint, UserAuthToken},
23    v1::{UatStatus, UatStatusState, UnixGroupToken, UnixUserToken},
24};
25use sshkey_attest::proto::PublicKey as SshPublicKey;
26use std::{
27    collections::{BTreeMap, BTreeSet},
28    time::Duration,
29};
30use time::OffsetDateTime;
31use uuid::Uuid;
32use webauthn_rs::prelude::{
33    AttestedPasskey as AttestedPasskeyV4, AuthenticationResult, CredentialID, Passkey as PasskeyV4,
34};
35
36#[derive(Debug, Clone)]
37pub struct UnixExtensions {
38    ucred: Option<Credential>,
39    shell: Option<String>,
40    gidnumber: u32,
41    groups: Vec<Group<Unix>>,
42}
43
44impl UnixExtensions {
45    pub(crate) fn ucred(&self) -> Option<&Credential> {
46        self.ucred.as_ref()
47    }
48}
49
50#[derive(Default, Debug, Clone)]
51pub struct OAuth2AccountCredential {
52    pub(crate) provider: Uuid,
53    pub(crate) cred_id: Uuid,
54    pub(crate) user_id: String,
55    pub(crate) user_sub: String,
56}
57
58#[derive(Default, Debug, Clone)]
59pub struct Account {
60    // To make this self-referential, we'll need to likely make Entry Pin<Arc<_>>
61    // so that we can make the references work.
62    spn: String,
63    name: Option<String>,
64    pub displayname: String,
65    pub uuid: Uuid,
66    pub sync_parent_uuid: Option<Uuid>,
67    pub groups: Vec<Group<()>>,
68    pub primary: Option<Credential>,
69    pub passkeys: BTreeMap<Uuid, (String, PasskeyV4)>,
70    pub attested_passkeys: BTreeMap<Uuid, (String, AttestedPasskeyV4)>,
71    pub valid_from: Option<OffsetDateTime>,
72    pub expire: Option<OffsetDateTime>,
73    softlock_expire: Option<OffsetDateTime>,
74    pub radius_secret: Option<String>,
75    pub ui_hints: BTreeSet<UiHint>,
76    pub mail_primary: Option<String>,
77    pub mail: Vec<String>,
78    pub credential_update_intent_tokens: BTreeMap<String, IntentTokenState>,
79    pub(crate) unix_extn: Option<UnixExtensions>,
80    pub(crate) sshkeys: BTreeMap<String, SshPublicKey>,
81    pub apps_pwds: BTreeMap<Uuid, Vec<ApplicationPassword>>,
82    pub(crate) oauth2_client_provider: Option<OAuth2AccountCredential>,
83    pub updated_at: Option<Cid>,
84}
85
86#[cfg(test)]
87impl From<crate::migration_data::BuiltinAccount> for crate::idm::account::Account {
88    fn from(value: crate::migration_data::BuiltinAccount) -> Self {
89        Self {
90            name: Some(value.name.to_string()),
91            uuid: value.uuid,
92            displayname: value.displayname.to_string(),
93            spn: format!("{}@example.com", value.name),
94            mail_primary: None,
95            mail: Vec::with_capacity(0),
96            ..Default::default()
97        }
98    }
99}
100
101macro_rules! try_from_entry {
102    ($value:expr, $groups:expr, $unix_groups:expr) => {{
103        // Check the classes
104        if !$value.attribute_equality(Attribute::Class, &EntryClass::Account.to_partialvalue()) {
105            return Err(OperationError::MissingClass(ENTRYCLASS_ACCOUNT.into()));
106        }
107
108        // Now extract our needed attributes
109        let name = $value
110            .get_ava_single_iname(Attribute::Name)
111            .map(|s| s.to_string());
112
113        let displayname = $value
114            .get_ava_single_utf8(Attribute::DisplayName)
115            .map(|s| s.to_string())
116            .ok_or(OperationError::MissingAttribute(Attribute::DisplayName))?;
117
118        let sync_parent_uuid = $value.get_ava_single_refer(Attribute::SyncParentUuid);
119
120        let primary = $value
121            .get_ava_single_credential(Attribute::PrimaryCredential)
122            .cloned();
123
124        let passkeys = $value
125            .get_ava_passkeys(Attribute::PassKeys)
126            .cloned()
127            .unwrap_or_default();
128
129        let attested_passkeys = $value
130            .get_ava_attestedpasskeys(Attribute::AttestedPasskeys)
131            .cloned()
132            .unwrap_or_default();
133
134        let spn = $value
135            .get_ava_single_proto_string(Attribute::Spn)
136            .ok_or(OperationError::MissingAttribute(Attribute::Spn))?;
137
138        let mail_primary = $value
139            .get_ava_mail_primary(Attribute::Mail)
140            .map(str::to_string);
141
142        let mail = $value
143            .get_ava_iter_mail(Attribute::Mail)
144            .map(|i| i.map(str::to_string).collect())
145            .unwrap_or_default();
146
147        let valid_from = $value.get_ava_single_datetime(Attribute::AccountValidFrom);
148
149        let expire = $value.get_ava_single_datetime(Attribute::AccountExpire);
150
151        let softlock_expire = $value.get_ava_single_datetime(Attribute::AccountSoftlockExpire);
152
153        let radius_secret = $value
154            .get_ava_single_secret(Attribute::RadiusSecret)
155            .map(str::to_string);
156
157        // Resolved by the caller
158        let groups = $groups;
159
160        let uuid = $value.get_uuid().clone();
161
162        let credential_update_intent_tokens = $value
163            .get_ava_as_intenttokens(Attribute::CredentialUpdateIntentToken)
164            .cloned()
165            .unwrap_or_default();
166
167        // Provide hints from groups.
168        let mut ui_hints: BTreeSet<_> = groups
169            .iter()
170            .map(|group: &Group<()>| group.ui_hints().iter())
171            .flatten()
172            .copied()
173            .collect();
174
175        // For now disable cred updates on sync accounts too.
176        if $value.attribute_equality(Attribute::Class, &EntryClass::Person.to_partialvalue()) {
177            ui_hints.insert(UiHint::CredentialUpdate);
178        }
179
180        if $value.attribute_equality(Attribute::Class, &EntryClass::SyncObject.to_partialvalue()) {
181            ui_hints.insert(UiHint::SynchronisedAccount);
182        }
183
184        let sshkeys = $value
185            .get_ava_set(Attribute::SshPublicKey)
186            .and_then(|vs| vs.as_sshkey_map())
187            .cloned()
188            .unwrap_or_default();
189
190        let unix_extn = if $value.attribute_equality(
191            Attribute::Class,
192            &EntryClass::PosixAccount.to_partialvalue(),
193        ) {
194            ui_hints.insert(UiHint::PosixAccount);
195
196            let ucred = $value
197                .get_ava_single_credential(Attribute::UnixPassword)
198                .cloned();
199
200            let shell = $value
201                .get_ava_single_iutf8(Attribute::LoginShell)
202                .map(|s| s.to_string());
203
204            let gidnumber = $value
205                .get_ava_single_uint32(Attribute::GidNumber)
206                .ok_or_else(|| OperationError::MissingAttribute(Attribute::GidNumber))?;
207
208            let groups = $unix_groups;
209
210            Some(UnixExtensions {
211                ucred,
212                shell,
213                gidnumber,
214                groups,
215            })
216        } else {
217            None
218        };
219
220        let apps_pwds = $value
221            .get_ava_application_password(Attribute::ApplicationPassword)
222            .cloned()
223            .unwrap_or_default();
224
225        let maybe_account_provider = $value.get_ava_single_refer(Attribute::OAuth2AccountProvider);
226
227        let maybe_account_unique_user_id =
228            $value.get_ava_single_utf8(Attribute::OAuth2AccountUniqueUserId);
229
230        let maybe_account_unique_user_sub =
231            $value.get_ava_single_utf8(Attribute::OAuth2AccountUniqueUserSub);
232
233        let maybe_account_credential_id =
234            $value.get_ava_single_uuid(Attribute::OAuth2AccountCredentialUuid);
235
236        let oauth2_client_provider = match (
237            maybe_account_provider,
238            maybe_account_unique_user_id,
239            maybe_account_unique_user_sub,
240            maybe_account_credential_id,
241        ) {
242            (Some(provider), Some(user_id), Some(user_sub), Some(cred_id)) => {
243                Some(OAuth2AccountCredential {
244                    provider,
245                    cred_id,
246                    user_id: user_id.to_string(),
247                    user_sub: user_sub.to_string(),
248                })
249            }
250            _ => None,
251        };
252
253        let updated_at: Option<Cid> = $value
254            .get_ava_set(Attribute::LastModifiedCid)
255            .cloned()
256            .and_then(|u| u.to_cid_single());
257
258        Ok(Account {
259            uuid,
260            name,
261            sync_parent_uuid,
262            displayname,
263            groups,
264            primary,
265            passkeys,
266            attested_passkeys,
267            valid_from,
268            expire,
269            softlock_expire,
270            radius_secret,
271            spn,
272            ui_hints,
273            mail_primary,
274            mail,
275            credential_update_intent_tokens,
276            unix_extn,
277            sshkeys,
278            apps_pwds,
279            oauth2_client_provider,
280            updated_at,
281        })
282    }};
283}
284
285impl Account {
286    pub(crate) fn unix_extn(&self) -> Option<&UnixExtensions> {
287        self.unix_extn.as_ref()
288    }
289
290    pub(crate) fn primary(&self) -> Option<&Credential> {
291        self.primary.as_ref()
292    }
293
294    pub(crate) fn sshkeys(&self) -> &BTreeMap<String, SshPublicKey> {
295        &self.sshkeys
296    }
297
298    pub(crate) fn uuid(&self) -> Uuid {
299        self.uuid
300    }
301
302    pub(crate) fn spn(&self) -> &str {
303        self.spn.as_str()
304    }
305
306    pub(crate) fn name(&self) -> &str {
307        self.name.as_deref().unwrap_or(self.spn.as_str())
308    }
309
310    pub(crate) fn display_name(&self) -> &str {
311        &self.displayname
312    }
313
314    pub(crate) fn mail_primary(&self) -> Option<&str> {
315        self.mail_primary.as_deref()
316    }
317
318    pub(crate) fn mail(&self) -> &[String] {
319        self.mail.as_slice()
320    }
321
322    pub(crate) fn softlock_expire(&self) -> Option<OffsetDateTime> {
323        self.softlock_expire
324    }
325
326    #[instrument(level = "trace", skip_all)]
327    pub(crate) fn try_from_entry_ro(
328        value: &Entry<EntrySealed, EntryCommitted>,
329        qs: &mut QueryServerReadTransaction,
330    ) -> Result<Self, OperationError> {
331        let (groups, unix_groups) = load_all_groups_from_account(value, qs)?;
332
333        try_from_entry!(value, groups, unix_groups)
334    }
335
336    #[instrument(level = "trace", skip_all)]
337    pub(crate) fn try_from_entry_with_policy<'a, TXN>(
338        value: &Entry<EntrySealed, EntryCommitted>,
339        qs: &mut TXN,
340    ) -> Result<(Self, ResolvedAccountPolicy), OperationError>
341    where
342        TXN: QueryServerTransaction<'a>,
343    {
344        let (groups, unix_groups) = load_all_groups_from_account(value, qs)?;
345        let rap = load_account_policy(value, qs)?;
346
347        try_from_entry!(value, groups, unix_groups).map(|acct| (acct, rap))
348    }
349
350    #[instrument(level = "trace", skip_all)]
351    pub(crate) fn try_from_entry_rw(
352        value: &Entry<EntrySealed, EntryCommitted>,
353        qs: &mut QueryServerWriteTransaction,
354    ) -> Result<Self, OperationError> {
355        let (groups, unix_groups) = load_all_groups_from_account(value, qs)?;
356
357        try_from_entry!(value, groups, unix_groups)
358    }
359
360    #[instrument(level = "trace", skip_all)]
361    pub(crate) fn try_from_entry_reduced(
362        value: &Entry<EntryReduced, EntryCommitted>,
363        qs: &mut QueryServerReadTransaction,
364    ) -> Result<Self, OperationError> {
365        let (groups, unix_groups) = load_all_groups_from_account(value, qs)?;
366        try_from_entry!(value, groups, unix_groups)
367    }
368
369    /// Given the session_id and other metadata, create a user authentication token
370    /// that represents a users session. Since this metadata can vary from session
371    /// to session, this userauthtoken may contain some data (claims) that may yield
372    /// different privileges to the bearer.
373    pub(crate) fn to_userauthtoken(
374        &self,
375        session_id: Uuid,
376        scope: SessionScope,
377        ct: Duration,
378        account_policy: &ResolvedAccountPolicy,
379    ) -> Option<UserAuthToken> {
380        // We have to remove the nanoseconds because when we transmit this / serialise it we drop
381        // the nanoseconds, but if we haven't done a serialise on the server our db cache has the
382        // ns value which breaks some checks.
383        let ct = ct - Duration::from_nanos(ct.subsec_nanos() as u64);
384        let issued_at = OffsetDateTime::UNIX_EPOCH + ct;
385
386        let limit_search_max_results = account_policy.limit_search_max_results();
387        let limit_search_max_filter_test = account_policy.limit_search_max_filter_test();
388
389        // Note that currently the auth_session time comes from policy, but the already-privileged
390        // session bound is hardcoded. This mostly affects admin/idm_admin breakglass accounts.
391        let expiry = OffsetDateTime::UNIX_EPOCH
392            + ct
393            + Duration::from_secs(account_policy.authsession_expiry() as u64);
394        let limited_expiry = OffsetDateTime::UNIX_EPOCH
395            + ct
396            + Duration::from_secs(DEFAULT_AUTH_SESSION_LIMITED_EXPIRY as u64);
397
398        let (purpose, expiry) = match scope {
399            // Issue an invalid/expired session.
400            SessionScope::Synchronise => {
401                warn!(
402                    "Should be impossible to issue sync sessions with a uat. Refusing to proceed."
403                );
404                return None;
405            }
406            SessionScope::ReadOnly => (UatPurpose::ReadOnly, expiry),
407            SessionScope::ReadWrite => {
408                // These sessions are always rw, and so have limited life.
409                // Ensure that we take the lower of the two bounds.
410                let capped = std::cmp::min(expiry, limited_expiry);
411
412                (
413                    UatPurpose::ReadWrite {
414                        expiry: Some(capped),
415                    },
416                    capped,
417                )
418            }
419            SessionScope::PrivilegeCapable => (UatPurpose::ReadWrite { expiry: None }, expiry),
420        };
421
422        Some(UserAuthToken {
423            session_id,
424            expiry: Some(expiry),
425            issued_at,
426            purpose,
427            uuid: self.uuid,
428            displayname: self.displayname.clone(),
429            spn: self.spn.clone(),
430            mail_primary: self.mail_primary.clone(),
431            ui_hints: self.ui_hints.clone(),
432            // application: None,
433            // groups: self.groups.iter().map(|g| g.to_proto()).collect(),
434            limit_search_max_results,
435            limit_search_max_filter_test,
436        })
437    }
438
439    /// Given the session_id and other metadata, reissue a user authentication token
440    /// that has elevated privileges. In the future we may adapt this to change what
441    /// scopes are granted per-reauth.
442    pub(crate) fn to_reissue_userauthtoken(
443        &self,
444        session_id: Uuid,
445        session_expiry: Option<OffsetDateTime>,
446        scope: SessionScope,
447        read_write: bool,
448        ct: Duration,
449        account_policy: &ResolvedAccountPolicy,
450    ) -> Option<UserAuthToken> {
451        let issued_at = OffsetDateTime::UNIX_EPOCH + ct;
452
453        let limit_search_max_results = account_policy.limit_search_max_results();
454        let limit_search_max_filter_test = account_policy.limit_search_max_filter_test();
455
456        let (purpose, expiry) = match scope {
457            SessionScope::Synchronise | SessionScope::ReadOnly | SessionScope::ReadWrite => {
458                warn!(
459                    "Impossible state, should not be re-issuing for session scope {:?}",
460                    scope
461                );
462                return None;
463            }
464            SessionScope::PrivilegeCapable if read_write => {
465                // Return a ReadWrite session with an inner expiry for the privileges
466                let expiry = Some(
467                    OffsetDateTime::UNIX_EPOCH
468                        + ct
469                        + Duration::from_secs(account_policy.privilege_expiry().into()),
470                );
471                // session_expiry needs to come from the actual original session. If we don't do this we have
472                // to re-update the expiry in the DB. We don't want a re-auth to extend a time
473                // bound session.
474                (UatPurpose::ReadWrite { expiry }, session_expiry)
475            }
476            SessionScope::PrivilegeCapable => {
477                // The user is not requesting privileges, just proof of presence. Reissue as priv capable.
478                (UatPurpose::ReadWrite { expiry: None }, session_expiry)
479            }
480        };
481
482        Some(UserAuthToken {
483            session_id,
484            expiry,
485            issued_at,
486            purpose,
487            uuid: self.uuid,
488            displayname: self.displayname.clone(),
489            spn: self.spn.clone(),
490            mail_primary: self.mail_primary.clone(),
491            ui_hints: self.ui_hints.clone(),
492            // application: None,
493            // groups: self.groups.iter().map(|g| g.to_proto()).collect(),
494            limit_search_max_results,
495            limit_search_max_filter_test,
496        })
497    }
498
499    /// Given the currently bound client certificate, yield a user auth token that
500    /// represents the current session for the account.
501    pub(crate) fn client_cert_info_to_userauthtoken(
502        &self,
503        certificate_id: Uuid,
504        session_is_rw: bool,
505        ct: Duration,
506        account_policy: &ResolvedAccountPolicy,
507    ) -> Option<UserAuthToken> {
508        let issued_at = OffsetDateTime::UNIX_EPOCH + ct;
509
510        let limit_search_max_results = account_policy.limit_search_max_results();
511        let limit_search_max_filter_test = account_policy.limit_search_max_filter_test();
512
513        let purpose = if session_is_rw {
514            UatPurpose::ReadWrite { expiry: None }
515        } else {
516            UatPurpose::ReadOnly
517        };
518
519        Some(UserAuthToken {
520            session_id: certificate_id,
521            expiry: None,
522            issued_at,
523            purpose,
524            uuid: self.uuid,
525            displayname: self.displayname.clone(),
526            spn: self.spn.clone(),
527            mail_primary: self.mail_primary.clone(),
528            ui_hints: self.ui_hints.clone(),
529            // application: None,
530            // groups: self.groups.iter().map(|g| g.to_proto()).collect(),
531            limit_search_max_results,
532            limit_search_max_filter_test,
533        })
534    }
535
536    /// Determine if an entry is within it's validity period using it's `valid_from` and
537    /// `expire` attributes. `true` indicates the account is within the valid period.
538    pub fn check_within_valid_time(
539        ct: Duration,
540        valid_from: Option<&OffsetDateTime>,
541        expire: Option<&OffsetDateTime>,
542    ) -> bool {
543        let cot = OffsetDateTime::UNIX_EPOCH + ct;
544        trace!("Checking within valid time: {:?} {:?}", valid_from, expire);
545
546        let vmin = if let Some(vft) = valid_from {
547            // If current time greater than start time window
548            vft <= &cot
549        } else {
550            // We have no time, not expired.
551            true
552        };
553        let vmax = if let Some(ext) = expire {
554            // If exp greater than ct then expired.
555            &cot <= ext
556        } else {
557            // If not present, we are not expired
558            true
559        };
560        // Mix the results
561        vmin && vmax
562    }
563
564    /// Determine if this account is within it's validity period. `true` indicates the
565    /// account is within the valid period.
566    pub fn is_within_valid_time(&self, ct: Duration) -> bool {
567        Self::check_within_valid_time(ct, self.valid_from.as_ref(), self.expire.as_ref())
568    }
569
570    /// Get related inputs, such as account name, email, etc. This is used for password
571    /// quality checking.
572    pub fn related_inputs(&self) -> Vec<&str> {
573        let mut inputs = Vec::with_capacity(4 + self.mail.len());
574        self.mail.iter().for_each(|m| {
575            inputs.push(m.as_str());
576        });
577        inputs.push(self.spn.as_str());
578        if let Some(name) = self.name.as_ref() {
579            inputs.push(name)
580        }
581        inputs.push(self.displayname.as_str());
582        if let Some(s) = self.radius_secret.as_deref() {
583            inputs.push(s);
584        }
585        inputs
586    }
587
588    pub fn primary_cred_uuid_and_policy(&self) -> Option<(Uuid, CredSoftLockPolicy)> {
589        self.primary
590            .as_ref()
591            .map(|cred| (cred.uuid, cred.softlock_policy()))
592            .or_else(|| {
593                if self.is_anonymous() {
594                    Some((UUID_ANONYMOUS, CredSoftLockPolicy::Unrestricted))
595                } else {
596                    None
597                }
598            })
599    }
600
601    pub fn is_anonymous(&self) -> bool {
602        self.uuid == UUID_ANONYMOUS
603    }
604
605    #[cfg(test)]
606    pub(crate) fn gen_password_mod(
607        &self,
608        cleartext: &str,
609        crypto_policy: &CryptoPolicy,
610        ct: OffsetDateTime,
611    ) -> Result<ModifyList<ModifyInvalid>, OperationError> {
612        match &self.primary {
613            // Change the cred
614            Some(primary) => {
615                let ncred = primary.set_password(crypto_policy, cleartext, ct)?;
616                let vcred = Value::new_credential("primary", ncred);
617                Ok(ModifyList::new_purge_and_set(
618                    Attribute::PrimaryCredential,
619                    vcred,
620                ))
621            }
622            // Make a new credential instead
623            None => {
624                let ncred = Credential::new_password_only(
625                    crypto_policy,
626                    cleartext,
627                    OffsetDateTime::UNIX_EPOCH,
628                )?;
629                let vcred = Value::new_credential("primary", ncred);
630                Ok(ModifyList::new_purge_and_set(
631                    Attribute::PrimaryCredential,
632                    vcred,
633                ))
634            }
635        }
636    }
637
638    pub(crate) fn gen_password_upgrade_mod(
639        &self,
640        cleartext: &str,
641        crypto_policy: &CryptoPolicy,
642    ) -> Result<Option<ModifyList<ModifyInvalid>>, OperationError> {
643        match &self.primary {
644            // Change the cred
645            Some(primary) => {
646                if let Some(ncred) = primary.upgrade_password(crypto_policy, cleartext)? {
647                    let vcred = Value::new_credential("primary", ncred);
648                    Ok(Some(ModifyList::new_purge_and_set(
649                        Attribute::PrimaryCredential,
650                        vcred,
651                    )))
652                } else {
653                    // No action, not the same pw
654                    Ok(None)
655                }
656            }
657            // Nothing to do.
658            None => Ok(None),
659        }
660    }
661
662    pub(crate) fn gen_webauthn_counter_mod(
663        &mut self,
664        auth_result: &AuthenticationResult,
665    ) -> Result<Option<ModifyList<ModifyInvalid>>, OperationError> {
666        let mut ml = Vec::with_capacity(2);
667        // Where is the credential we need to update?
668        let opt_ncred = match self.primary.as_ref() {
669            Some(primary) => primary.update_webauthn_properties(auth_result)?,
670            None => None,
671        };
672
673        if let Some(ncred) = opt_ncred {
674            let vcred = Value::new_credential("primary", ncred);
675            ml.push(Modify::Purged(Attribute::PrimaryCredential));
676            ml.push(Modify::Present(Attribute::PrimaryCredential, vcred));
677        }
678
679        // Is it a passkey?
680        self.passkeys.iter_mut().for_each(|(u, (t, k))| {
681            if let Some(true) = k.update_credential(auth_result) {
682                ml.push(Modify::Removed(
683                    Attribute::PassKeys,
684                    PartialValue::Passkey(*u),
685                ));
686
687                ml.push(Modify::Present(
688                    Attribute::PassKeys,
689                    Value::Passkey(*u, t.clone(), k.clone()),
690                ));
691            }
692        });
693
694        // Is it an attested passkey?
695        self.attested_passkeys.iter_mut().for_each(|(u, (t, k))| {
696            if let Some(true) = k.update_credential(auth_result) {
697                ml.push(Modify::Removed(
698                    Attribute::AttestedPasskeys,
699                    PartialValue::AttestedPasskey(*u),
700                ));
701
702                ml.push(Modify::Present(
703                    Attribute::AttestedPasskeys,
704                    Value::AttestedPasskey(*u, t.clone(), k.clone()),
705                ));
706            }
707        });
708
709        if ml.is_empty() {
710            Ok(None)
711        } else {
712            Ok(Some(ModifyList::new_list(ml)))
713        }
714    }
715
716    pub(crate) fn invalidate_backup_code_mod(
717        self,
718        code_to_remove: &str,
719    ) -> Result<ModifyList<ModifyInvalid>, OperationError> {
720        match self.primary {
721            // Change the cred
722            Some(primary) => {
723                let r_ncred = primary.invalidate_backup_code(code_to_remove);
724                match r_ncred {
725                    Ok(ncred) => {
726                        let vcred = Value::new_credential("primary", ncred);
727                        Ok(ModifyList::new_purge_and_set(
728                            Attribute::PrimaryCredential,
729                            vcred,
730                        ))
731                    }
732                    Err(e) => Err(e),
733                }
734            }
735            None => {
736                // No credential exists, we can't supplementy it.
737                Err(OperationError::InvalidState)
738            }
739        }
740    }
741
742    pub(crate) fn regenerate_radius_secret_mod(
743        &self,
744        cleartext: &str,
745    ) -> Result<ModifyList<ModifyInvalid>, OperationError> {
746        let vcred = Value::new_secret_str(cleartext);
747        Ok(ModifyList::new_purge_and_set(
748            Attribute::RadiusSecret,
749            vcred,
750        ))
751    }
752
753    pub(crate) fn to_credentialstatus(&self) -> Result<CredentialStatus, OperationError> {
754        // In the future this will need to handle multiple credentials, not just single.
755
756        self.primary
757            .as_ref()
758            .map(|cred| CredentialStatus {
759                creds: vec![cred.into()],
760            })
761            .ok_or(OperationError::NoMatchingAttributes)
762    }
763
764    pub(crate) fn existing_credential_id_list(&self) -> Option<Vec<CredentialID>> {
765        // TODO!!!
766        // Used in registrations only for disallowing existing credentials.
767        None
768    }
769
770    pub(crate) fn check_user_auth_token_valid(
771        ct: Duration,
772        uat: &UserAuthToken,
773        entry: &Entry<EntrySealed, EntryCommitted>,
774    ) -> bool {
775        // Remember, token expiry is checked by validate_and_parse_token_to_token.
776        // If we wanted we could check other properties of the uat here?
777        // Alternatively, we could always store LESS in the uat because of this?
778
779        let within_valid_window = Account::check_within_valid_time(
780            ct,
781            entry
782                .get_ava_single_datetime(Attribute::AccountValidFrom)
783                .as_ref(),
784            entry
785                .get_ava_single_datetime(Attribute::AccountExpire)
786                .as_ref(),
787        );
788
789        if !within_valid_window {
790            security_info!("Account has expired or is not yet valid, not allowing to proceed");
791            return false;
792        }
793
794        // Anonymous does NOT record it's sessions, so we simply check the expiry time
795        // of the token. This is already done for us as noted above.
796        trace!("{}", &uat);
797
798        if uat.uuid == UUID_ANONYMOUS {
799            security_debug!("Anonymous sessions do not have session records, session is valid.");
800            true
801        } else {
802            // Get the sessions.
803            let session_present = entry
804                .get_ava_as_session_map(Attribute::UserAuthTokenSession)
805                .and_then(|session_map| session_map.get(&uat.session_id));
806
807            // Important - we don't have to check the expiry time against ct here since it was
808            // already checked in token_to_token. Here we just need to check it's consistent
809            // to our internal session knowledge.
810            if let Some(session) = session_present {
811                match (&session.state, &uat.expiry) {
812                    (SessionState::ExpiresAt(s_exp), Some(u_exp)) if s_exp == u_exp => {
813                        security_info!("A valid limited session value exists for this token");
814                        true
815                    }
816                    (SessionState::NeverExpires, None) => {
817                        security_info!("A valid unbound session value exists for this token");
818                        true
819                    }
820                    (SessionState::RevokedAt(_), _) => {
821                        // William, if you have added a new type of credential, and end up here, you
822                        // need to look at session consistency plugin.
823                        security_info!("Session has been revoked");
824                        false
825                    }
826                    _ => {
827                        security_info!("Session and uat expiry are not consistent, rejecting.");
828                        debug!(ses_st = ?session.state, uat_exp = ?uat.expiry);
829                        false
830                    }
831                }
832            } else {
833                let grace = uat.issued_at + AUTH_TOKEN_GRACE_WINDOW;
834                let current = time::OffsetDateTime::UNIX_EPOCH + ct;
835                trace!(%grace, %current);
836                if current >= grace {
837                    security_info!(
838                        "The token grace window has passed, and no session exists. Assuming invalid."
839                    );
840                    false
841                } else {
842                    security_info!("The token grace window is in effect. Assuming valid.");
843                    true
844                }
845            }
846        }
847    }
848
849    pub(crate) fn verify_application_password(
850        &self,
851        application: &Application,
852        cleartext: &str,
853    ) -> Result<Option<LdapBoundToken>, OperationError> {
854        if let Some(v) = self.apps_pwds.get(&application.uuid) {
855            for ap in v.iter() {
856                let password_verified = ap.password.verify(cleartext).map_err(|e| {
857                    error!(crypto_err = ?e);
858                    OperationError::CryptographyError
859                })?;
860
861                if password_verified {
862                    let session_id = uuid::Uuid::new_v4();
863                    security_info!(
864                        "Starting session {} for {} {}",
865                        session_id,
866                        self.spn,
867                        self.uuid
868                    );
869
870                    return Ok(Some(LdapBoundToken {
871                        spn: self.spn.clone(),
872                        session_id,
873                        effective_session: LdapSession::ApplicationPasswordBind(
874                            application.uuid,
875                            self.uuid,
876                        ),
877                    }));
878                }
879            }
880        }
881        Ok(None)
882    }
883
884    pub(crate) fn to_unixusertoken(&self, ct: Duration) -> Result<UnixUserToken, OperationError> {
885        let (gidnumber, shell, sshkeys, groups) = match &self.unix_extn {
886            Some(ue) => {
887                let sshkeys: Vec<_> = self.sshkeys.values().cloned().collect();
888                (ue.gidnumber, ue.shell.clone(), sshkeys, ue.groups.clone())
889            }
890            None => {
891                return Err(OperationError::MissingClass(
892                    ENTRYCLASS_POSIX_ACCOUNT.into(),
893                ));
894            }
895        };
896
897        let groups: Vec<UnixGroupToken> = groups.iter().map(|g| g.to_unixgrouptoken()).collect();
898
899        Ok(UnixUserToken {
900            name: self.name().into(),
901            spn: self.spn.clone(),
902            displayname: self.displayname.clone(),
903            gidnumber,
904            uuid: self.uuid,
905            shell: shell.clone(),
906            groups,
907            sshkeys,
908            valid: self.is_within_valid_time(ct),
909        })
910    }
911
912    pub(crate) fn oauth2_client_provider(&self) -> Option<&OAuth2AccountCredential> {
913        self.oauth2_client_provider.as_ref()
914    }
915
916    #[cfg(test)]
917    pub(crate) fn setup_oauth2_client_provider(
918        &mut self,
919        client_provider: &crate::idm::oauth2_client::OAuth2ClientProvider,
920    ) {
921        self.oauth2_client_provider = Some(OAuth2AccountCredential {
922            provider: client_provider.uuid,
923            cred_id: Uuid::new_v4(),
924            user_id: self.spn.clone(),
925            user_sub: self.uuid.to_string(),
926        });
927    }
928}
929
930// Need to also add a "to UserAuthToken" ...
931
932// Need tests for conversion and the cred validations
933
934pub struct DestroySessionTokenEvent {
935    // Who initiated this?
936    pub ident: Identity,
937    // Who is it targeting?
938    pub target: Uuid,
939    // Which token id.
940    pub token_id: Uuid,
941}
942
943impl DestroySessionTokenEvent {
944    #[cfg(test)]
945    pub fn new_internal(target: Uuid, token_id: Uuid) -> Self {
946        DestroySessionTokenEvent {
947            ident: Identity::from_internal(),
948            target,
949            token_id,
950        }
951    }
952}
953
954impl IdmServerProxyWriteTransaction<'_> {
955    pub fn account_destroy_session_token(
956        &mut self,
957        dte: &DestroySessionTokenEvent,
958    ) -> Result<(), OperationError> {
959        // Delete the attribute with uuid.
960        let modlist = ModifyList::new_list(vec![Modify::Removed(
961            Attribute::UserAuthTokenSession,
962            PartialValue::Refer(dte.token_id),
963        )]);
964
965        self.qs_write
966            .impersonate_modify(
967                // Filter as executed
968                &filter!(f_and!([
969                    f_eq(Attribute::Uuid, PartialValue::Uuid(dte.target)),
970                    f_eq(
971                        Attribute::UserAuthTokenSession,
972                        PartialValue::Refer(dte.token_id)
973                    )
974                ])),
975                // Filter as intended (acp)
976                &filter_all!(f_and!([
977                    f_eq(Attribute::Uuid, PartialValue::Uuid(dte.target)),
978                    f_eq(
979                        Attribute::UserAuthTokenSession,
980                        PartialValue::Refer(dte.token_id)
981                    )
982                ])),
983                &modlist,
984                // Provide the event to impersonate. Notice how we project this with readwrite
985                // capability? This is because without this we'd force re-auths to end
986                // a session and we don't want that! you should always be able to logout!
987                &dte.ident.project_with_scope(AccessScope::ReadWrite),
988            )
989            .map_err(|e| {
990                admin_error!("Failed to destroy user auth token {:?}", e);
991                e
992            })
993    }
994
995    pub fn service_account_into_person(
996        &mut self,
997        ident: &Identity,
998        target_uuid: Uuid,
999    ) -> Result<(), OperationError> {
1000        let schema_ref = self.qs_write.get_schema();
1001
1002        // Get the entry.
1003        let account_entry = self
1004            .qs_write
1005            .internal_search_uuid(target_uuid)
1006            .map_err(|e| {
1007                admin_error!("Failed to start service account into person -> {:?}", e);
1008                e
1009            })?;
1010
1011        // Copy the current classes
1012        let prev_classes: BTreeSet<_> = account_entry
1013            .get_ava_as_iutf8_iter(Attribute::Class)
1014            .ok_or_else(|| {
1015                error!(
1016                    "Invalid entry, {} attribute is not present or not iutf8",
1017                    Attribute::Class
1018                );
1019                OperationError::MissingAttribute(Attribute::Class)
1020            })?
1021            .collect();
1022
1023        // Remove the service account class.
1024        // Add the person class.
1025        let mut new_iutf8es = prev_classes.clone();
1026        new_iutf8es.remove(EntryClass::ServiceAccount.into());
1027        new_iutf8es.insert(EntryClass::Person.into());
1028
1029        // diff the schema attrs, and remove the ones that are service_account only.
1030        let (_added, removed) = schema_ref
1031            .query_attrs_difference(&prev_classes, &new_iutf8es)
1032            .map_err(|se| {
1033                admin_error!("While querying the schema, it reported that requested classes may not be present indicating a possible corruption");
1034                OperationError::SchemaViolation(
1035                    se
1036                )
1037            })?;
1038
1039        // Now construct the modlist which:
1040        // removes service_account
1041        let mut modlist = ModifyList::new_remove(
1042            Attribute::Class,
1043            EntryClass::ServiceAccount.to_partialvalue(),
1044        );
1045        // add person
1046        modlist.push_mod(Modify::Present(
1047            Attribute::Class,
1048            EntryClass::Person.to_value(),
1049        ));
1050        // purge the other attrs that are SA only.
1051        removed
1052            .into_iter()
1053            .for_each(|attr| modlist.push_mod(Modify::Purged(attr.into())));
1054        // purge existing sessions
1055
1056        // Modify
1057        self.qs_write
1058            .impersonate_modify(
1059                // Filter as executed
1060                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(target_uuid))),
1061                // Filter as intended (acp)
1062                &filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(target_uuid))),
1063                &modlist,
1064                // Provide the entry to impersonate
1065                ident,
1066            )
1067            .map_err(|e| {
1068                admin_error!("Failed to migrate service account to person - {:?}", e);
1069                e
1070            })
1071    }
1072}
1073
1074pub struct ListUserAuthTokenEvent {
1075    // Who initiated this?
1076    pub ident: Identity,
1077    // Who is it targeting?
1078    pub target: Uuid,
1079}
1080
1081impl IdmServerProxyReadTransaction<'_> {
1082    pub fn account_list_user_auth_tokens(
1083        &mut self,
1084        lte: &ListUserAuthTokenEvent,
1085    ) -> Result<Vec<UatStatus>, OperationError> {
1086        // Make an event from the request
1087        let srch = match SearchEvent::from_target_uuid_request(
1088            lte.ident.clone(),
1089            lte.target,
1090            &self.qs_read,
1091        ) {
1092            Ok(s) => s,
1093            Err(e) => {
1094                admin_error!("Failed to begin account list user auth tokens: {:?}", e);
1095                return Err(e);
1096            }
1097        };
1098
1099        match self.qs_read.search_ext(&srch) {
1100            Ok(mut entries) => {
1101                entries
1102                    .pop()
1103                    // get the first entry
1104                    .and_then(|e| {
1105                        let account_id = e.get_uuid();
1106                        // From the entry, turn it into the value
1107                        e.get_ava_as_session_map(Attribute::UserAuthTokenSession)
1108                            .map(|smap| {
1109                                smap.iter()
1110                                    .map(|(u, s)| {
1111                                        let state = match s.state {
1112                                            SessionState::ExpiresAt(odt) => {
1113                                                UatStatusState::ExpiresAt(odt)
1114                                            }
1115                                            SessionState::NeverExpires => {
1116                                                UatStatusState::NeverExpires
1117                                            }
1118                                            SessionState::RevokedAt(_) => UatStatusState::Revoked,
1119                                        };
1120
1121                                        s.scope
1122                                            .try_into()
1123                                            .map(|purpose| UatStatus {
1124                                                account_id,
1125                                                session_id: *u,
1126                                                state,
1127                                                issued_at: s.issued_at,
1128                                                purpose,
1129                                            })
1130                                            .inspect_err(|_e| {
1131                                                admin_error!("Invalid user auth token {}", u);
1132                                            })
1133                                    })
1134                                    .collect::<Result<Vec<_>, _>>()
1135                            })
1136                    })
1137                    .unwrap_or_else(|| {
1138                        // No matching entry? Return none.
1139                        Ok(Vec::with_capacity(0))
1140                    })
1141            }
1142            Err(e) => Err(e),
1143        }
1144    }
1145}
1146
1147#[cfg(test)]
1148mod tests {
1149    use crate::{idm::accountpolicy::ResolvedAccountPolicy, prelude::*};
1150    use kanidm_proto::internal::UiHint;
1151
1152    #[idm_test]
1153    async fn test_idm_account_ui_hints(idms: &IdmServer, _idms_delayed: &mut IdmServerDelayed) {
1154        let ct = duration_from_epoch_now();
1155        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
1156
1157        let target_uuid = Uuid::new_v4();
1158
1159        // Create a user. So far no ui hints.
1160        // Create a service account
1161        let e = entry_init!(
1162            (Attribute::Class, EntryClass::Object.to_value()),
1163            (Attribute::Class, EntryClass::Account.to_value()),
1164            (Attribute::Class, EntryClass::Person.to_value()),
1165            (Attribute::Name, Value::new_iname("testaccount")),
1166            (Attribute::Uuid, Value::Uuid(target_uuid)),
1167            (Attribute::Description, Value::new_utf8s("testaccount")),
1168            (Attribute::DisplayName, Value::new_utf8s("Test Account"))
1169        );
1170
1171        let ce = CreateEvent::new_internal(vec![e]);
1172        assert!(idms_prox_write.qs_write.create(&ce).is_ok());
1173
1174        let account = idms_prox_write
1175            .target_to_account(target_uuid)
1176            .expect("account must exist");
1177        let session_id = uuid::Uuid::new_v4();
1178        let uat = account
1179            .to_userauthtoken(
1180                session_id,
1181                SessionScope::ReadWrite,
1182                ct,
1183                &ResolvedAccountPolicy::test_policy(),
1184            )
1185            .expect("Unable to create uat");
1186
1187        // Check the ui hints are as expected.
1188        assert_eq!(uat.ui_hints.len(), 1);
1189        assert!(uat.ui_hints.contains(&UiHint::CredentialUpdate));
1190
1191        // Modify the user to be a posix account, ensure they get the hint.
1192        let me_posix = ModifyEvent::new_internal_invalid(
1193            filter!(f_eq(
1194                Attribute::Name,
1195                PartialValue::new_iname("testaccount")
1196            )),
1197            ModifyList::new_list(vec![
1198                Modify::Present(Attribute::Class, EntryClass::PosixAccount.into()),
1199                Modify::Present(Attribute::GidNumber, Value::new_uint32(2001)),
1200            ]),
1201        );
1202        assert!(idms_prox_write.qs_write.modify(&me_posix).is_ok());
1203
1204        // Check the ui hints are as expected.
1205        let account = idms_prox_write
1206            .target_to_account(target_uuid)
1207            .expect("account must exist");
1208        let session_id = uuid::Uuid::new_v4();
1209        let uat = account
1210            .to_userauthtoken(
1211                session_id,
1212                SessionScope::ReadWrite,
1213                ct,
1214                &ResolvedAccountPolicy::test_policy(),
1215            )
1216            .expect("Unable to create uat");
1217
1218        assert_eq!(uat.ui_hints.len(), 2);
1219        assert!(uat.ui_hints.contains(&UiHint::PosixAccount));
1220        assert!(uat.ui_hints.contains(&UiHint::CredentialUpdate));
1221
1222        // Add a group with a ui hint, and then check they get the hint.
1223        let e = entry_init!(
1224            (Attribute::Class, EntryClass::Object.to_value()),
1225            (Attribute::Class, EntryClass::Group.to_value()),
1226            (Attribute::Name, Value::new_iname("test_uihint_group")),
1227            (Attribute::Member, Value::ReferN(target_uuid)),
1228            (
1229                Attribute::GrantUiHint,
1230                Value::UiHint(UiHint::ExperimentalFeatures)
1231            )
1232        );
1233
1234        let ce = CreateEvent::new_internal(vec![e]);
1235        assert!(idms_prox_write.qs_write.create(&ce).is_ok());
1236
1237        // Check the ui hints are as expected.
1238        let account = idms_prox_write
1239            .target_to_account(target_uuid)
1240            .expect("account must exist");
1241        let session_id = uuid::Uuid::new_v4();
1242        let uat = account
1243            .to_userauthtoken(
1244                session_id,
1245                SessionScope::ReadWrite,
1246                ct,
1247                &ResolvedAccountPolicy::test_policy(),
1248            )
1249            .expect("Unable to create uat");
1250
1251        assert_eq!(uat.ui_hints.len(), 3);
1252        assert!(uat.ui_hints.contains(&UiHint::PosixAccount));
1253        assert!(uat.ui_hints.contains(&UiHint::ExperimentalFeatures));
1254        assert!(uat.ui_hints.contains(&UiHint::CredentialUpdate));
1255
1256        assert!(idms_prox_write.commit().is_ok());
1257    }
1258}