Skip to main content

kanidmd_lib/idm/
server.rs

1use super::ldap::{LdapBoundToken, LdapSession};
2use crate::{
3    credential::{softlock::CredSoftLock, Credential},
4    idm::{
5        account::Account,
6        application::{
7            LdapApplications, LdapApplicationsReadTransaction, LdapApplicationsWriteTransaction,
8        },
9        audit::AuditEvent,
10        authentication::{AuthState, PreValidatedTokenStatus},
11        authsession::{AuthSession, AuthSessionData},
12        credupdatesession::CredentialUpdateSessionMutex,
13        delayed::{
14            AuthSessionRecord, BackupCodeRemoval, DelayedAction, PasswordUpgrade,
15            UnixPasswordUpgrade, WebauthnCounterIncrement,
16        },
17        event::{
18            AuthEvent, AuthEventStep, AuthResult, CredentialStatusEvent, LdapAuthEvent,
19            LdapTokenAuthEvent, RadiusAuthTokenEvent, RegenerateRadiusSecretEvent,
20            UnixGroupTokenEvent, UnixPasswordChangeEvent, UnixUserAuthEvent, UnixUserTokenEvent,
21        },
22        group::{Group, Unix},
23        oauth2::{
24            Oauth2ResourceServers, Oauth2ResourceServersReadTransaction,
25            Oauth2ResourceServersWriteTransaction,
26        },
27        oauth2_client::OAuth2ClientProvider,
28        radius::RadiusAccount,
29        scim::SyncAccount,
30        serviceaccount::ServiceAccount,
31    },
32    prelude::*,
33    server::{keys::KeyProvidersTransaction, DomainInfo},
34    utils::{password_from_random, readable_password_from_random, uuid_from_duration, Sid},
35    value::{Session, SessionState},
36};
37use compact_jwt::{Jwk, JwsCompact};
38use concread::{
39    bptree::{BptreeMap, BptreeMapReadTxn, BptreeMapWriteTxn},
40    cowcell::CowCellReadTxn,
41    hashmap::{HashMap, HashMapReadTxn, HashMapWriteTxn},
42};
43use kanidm_lib_crypto::{CryptoPolicy, PW_MAX_LENGTH_NIST, PW_SFA_MIN_LENGTH_NIST};
44use kanidm_proto::{
45    internal::{
46        ApiToken, CredentialStatus, PasswordFeedback, RadiusAuthToken, ScimSyncToken, UatPurpose,
47        UserAuthToken,
48    },
49    v1::{UnixGroupToken, UnixUserToken},
50};
51use rand::prelude::*;
52use std::{convert::TryFrom, sync::Arc, time::Duration};
53use time::OffsetDateTime;
54use tokio::sync::{
55    mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender},
56    Mutex, Semaphore,
57};
58use tracing::trace;
59use url::Url;
60use webauthn_rs::prelude::{Webauthn, WebauthnBuilder};
61use zxcvbn::{zxcvbn, Score};
62
63#[cfg(test)]
64use crate::idm::event::PasswordChangeEvent;
65
66pub(crate) type AuthSessionMutex = Arc<Mutex<AuthSession>>;
67pub(crate) type CredSoftLockMutex = Arc<Mutex<CredSoftLock>>;
68
69pub type DomainInfoRead = CowCellReadTxn<DomainInfo>;
70
71pub struct IdmServer {
72    // There is a good reason to keep this single thread - it
73    // means that limits to sessions can be easily applied and checked to
74    // various accounts, and we have a good idea of how to structure the
75    // in memory caches related to locking.
76    session_ticket: Semaphore,
77    sessions: BptreeMap<Uuid, AuthSessionMutex>,
78    softlocks: HashMap<Uuid, CredSoftLockMutex>,
79    /// A set of in progress credential registrations
80    cred_update_sessions: BptreeMap<Uuid, CredentialUpdateSessionMutex>,
81    /// Reference to the query server.
82    qs: QueryServer,
83    /// The configured crypto policy for the IDM server. Later this could be transactional and loaded from the db similar to access. But today it's just to allow dynamic pbkdf2rounds
84    crypto_policy: CryptoPolicy,
85    async_tx: UnboundedSender<DelayedAction>,
86    audit_tx: UnboundedSender<AuditEvent>,
87    /// [Webauthn] verifier/config
88    webauthn: Webauthn,
89    oauth2rs: Arc<Oauth2ResourceServers>,
90    applications: Arc<LdapApplications>,
91
92    /// OAuth2ClientProviders
93    origin: Url,
94    oauth2_client_providers: HashMap<Uuid, OAuth2ClientProvider>,
95}
96
97/// Contains methods that require writes, but in the context of writing to the idm in memory structures (maybe the query server too). This is things like authentication.
98pub struct IdmServerAuthTransaction<'a> {
99    pub(crate) session_ticket: &'a Semaphore,
100    pub(crate) sessions: &'a BptreeMap<Uuid, AuthSessionMutex>,
101    pub(crate) softlocks: &'a HashMap<Uuid, CredSoftLockMutex>,
102    pub(crate) oauth2_client_providers: HashMapReadTxn<'a, Uuid, OAuth2ClientProvider>,
103
104    pub qs_read: QueryServerReadTransaction<'a>,
105    /// Thread/Server ID
106    pub(crate) sid: Sid,
107    // For flagging eventual actions.
108    pub(crate) async_tx: UnboundedSender<DelayedAction>,
109    pub(crate) audit_tx: UnboundedSender<AuditEvent>,
110    pub(crate) webauthn: &'a Webauthn,
111    pub(crate) applications: LdapApplicationsReadTransaction,
112}
113
114pub struct IdmServerCredUpdateTransaction<'a> {
115    pub(crate) qs_read: QueryServerReadTransaction<'a>,
116    // sid: Sid,
117    pub(crate) webauthn: &'a Webauthn,
118    pub(crate) cred_update_sessions: BptreeMapReadTxn<'a, Uuid, CredentialUpdateSessionMutex>,
119    pub(crate) crypto_policy: &'a CryptoPolicy,
120}
121
122/// This contains read-only methods, like getting users, groups and other structured content.
123pub struct IdmServerProxyReadTransaction<'a> {
124    pub qs_read: QueryServerReadTransaction<'a>,
125    pub(crate) oauth2rs: Oauth2ResourceServersReadTransaction,
126}
127
128pub struct IdmServerProxyWriteTransaction<'a> {
129    // This does NOT take any read to the memory content, allowing safe
130    // qs operations to occur through this interface.
131    pub qs_write: QueryServerWriteTransaction<'a>,
132    /// Associate to an event origin ID, which has a TS and a UUID instead
133    pub(crate) cred_update_sessions: BptreeMapWriteTxn<'a, Uuid, CredentialUpdateSessionMutex>,
134    pub(crate) sid: Sid,
135    crypto_policy: &'a CryptoPolicy,
136    webauthn: &'a Webauthn,
137    pub(crate) oauth2rs: Oauth2ResourceServersWriteTransaction<'a>,
138    pub(crate) applications: LdapApplicationsWriteTransaction<'a>,
139
140    pub(crate) origin: &'a Url,
141    pub(crate) oauth2_client_providers: HashMapWriteTxn<'a, Uuid, OAuth2ClientProvider>,
142}
143
144pub struct IdmServerDelayed {
145    pub(crate) async_rx: UnboundedReceiver<DelayedAction>,
146}
147
148pub struct IdmServerAudit {
149    pub(crate) audit_rx: UnboundedReceiver<AuditEvent>,
150}
151
152impl IdmServer {
153    pub async fn new(
154        qs: QueryServer,
155        origin: &Url,
156        is_integration_test: bool,
157        current_time: Duration,
158    ) -> Result<(IdmServer, IdmServerDelayed, IdmServerAudit), OperationError> {
159        let crypto_policy = if cfg!(test) || is_integration_test {
160            CryptoPolicy::danger_test_minimum()
161        } else {
162            CryptoPolicy::minimum()
163        };
164
165        let (async_tx, async_rx) = unbounded_channel();
166        let (audit_tx, audit_rx) = unbounded_channel();
167
168        // Get the domain name, as the relying party id.
169        let (rp_id, rp_name, application_set) = {
170            let mut qs_read = qs.read().await?;
171            (
172                qs_read.get_domain_name().to_string(),
173                qs_read.get_domain_display_name().to_string(),
174                // Add a read/reload of all oauth2 configurations.
175                qs_read.get_applications_set()?,
176            )
177        };
178
179        // Check that it gels with our origin.
180        let valid = origin
181            .domain()
182            .map(|effective_domain| {
183                // We need to prepend the '.' here to ensure that myexample.com != example.com,
184                // rather than just ends with.
185                effective_domain.ends_with(&format!(".{rp_id}")) || effective_domain == rp_id
186            })
187            .unwrap_or(false);
188
189        if !valid {
190            admin_error!(
191                "Effective domain (ed) is not a descendent of server domain name (rp_id)."
192            );
193            admin_error!(
194                "You must change origin or domain name to be consistent. ed: {:?} - rp_id: {:?}",
195                origin,
196                rp_id
197            );
198            admin_error!("To change the origin or domain name see: https://kanidm.github.io/kanidm/master/server_configuration.html");
199            return Err(OperationError::InvalidState);
200        };
201
202        let webauthn = WebauthnBuilder::new(&rp_id, origin)
203            .and_then(|builder| builder.allow_subdomains(true).rp_name(&rp_name).build())
204            .map_err(|e| {
205                admin_error!("Invalid Webauthn Configuration - {:?}", e);
206                OperationError::InvalidState
207            })?;
208
209        let oauth2rs = Oauth2ResourceServers::new(origin.to_owned()).map_err(|err| {
210            error!(?err, "Failed to load oauth2 resource servers");
211            err
212        })?;
213
214        let applications = LdapApplications::try_from(application_set).map_err(|e| {
215            admin_error!("Failed to load ldap applications - {:?}", e);
216            e
217        })?;
218
219        let idm_server = IdmServer {
220            session_ticket: Semaphore::new(1),
221            sessions: BptreeMap::new(),
222            softlocks: HashMap::new(),
223            cred_update_sessions: BptreeMap::new(),
224            qs,
225            crypto_policy,
226            async_tx,
227            audit_tx,
228            webauthn,
229            oauth2rs: Arc::new(oauth2rs),
230            applications: Arc::new(applications),
231            origin: origin.clone(),
232            oauth2_client_providers: HashMap::new(),
233        };
234        let idm_server_delayed = IdmServerDelayed { async_rx };
235        let idm_server_audit = IdmServerAudit { audit_rx };
236
237        let mut idm_write_txn = idm_server.proxy_write(current_time).await?;
238
239        idm_write_txn.reload_applications()?;
240        idm_write_txn.reload_oauth2()?;
241        idm_write_txn.reload_oauth2_client_providers()?;
242
243        idm_write_txn.commit()?;
244
245        Ok((idm_server, idm_server_delayed, idm_server_audit))
246    }
247
248    /// Start an auth txn
249    pub async fn auth(&self) -> Result<IdmServerAuthTransaction<'_>, OperationError> {
250        let qs_read = self.qs.read().await?;
251
252        let mut sid = [0; 4];
253        let mut rng = rand::rng();
254        rng.fill(&mut sid);
255
256        Ok(IdmServerAuthTransaction {
257            session_ticket: &self.session_ticket,
258            sessions: &self.sessions,
259            softlocks: &self.softlocks,
260            qs_read,
261            sid,
262            async_tx: self.async_tx.clone(),
263            audit_tx: self.audit_tx.clone(),
264            webauthn: &self.webauthn,
265            applications: self.applications.read(),
266            oauth2_client_providers: self.oauth2_client_providers.read(),
267        })
268    }
269
270    /// Begin a fast (low cost) read of the servers domain info. It is important to note
271    /// this does not conflict with any other type of transaction type and may safely
272    /// beheld over other transaction boundaries.
273    #[instrument(level = "debug", skip_all)]
274    pub fn domain_read(&self) -> DomainInfoRead {
275        self.qs.d_info.read()
276    }
277
278    /// Read from the database, in a transaction.
279    #[instrument(level = "debug", skip_all)]
280    pub async fn proxy_read(&self) -> Result<IdmServerProxyReadTransaction<'_>, OperationError> {
281        let qs_read = self.qs.read().await?;
282        Ok(IdmServerProxyReadTransaction {
283            qs_read,
284            oauth2rs: self.oauth2rs.read(),
285            // async_tx: self.async_tx.clone(),
286        })
287    }
288
289    #[instrument(level = "debug", skip_all)]
290    pub async fn proxy_write(
291        &self,
292        ts: Duration,
293    ) -> Result<IdmServerProxyWriteTransaction<'_>, OperationError> {
294        let qs_write = self.qs.write(ts).await?;
295
296        let mut sid = [0; 4];
297        let mut rng = rand::rng();
298        rng.fill(&mut sid);
299
300        Ok(IdmServerProxyWriteTransaction {
301            cred_update_sessions: self.cred_update_sessions.write(),
302            qs_write,
303            sid,
304            crypto_policy: &self.crypto_policy,
305            webauthn: &self.webauthn,
306            oauth2rs: self.oauth2rs.write(),
307            applications: self.applications.write(),
308            origin: &self.origin,
309            oauth2_client_providers: self.oauth2_client_providers.write(),
310        })
311    }
312
313    pub async fn cred_update_transaction(
314        &self,
315    ) -> Result<IdmServerCredUpdateTransaction<'_>, OperationError> {
316        let qs_read = self.qs.read().await?;
317        Ok(IdmServerCredUpdateTransaction {
318            qs_read,
319            // sid: Sid,
320            webauthn: &self.webauthn,
321            cred_update_sessions: self.cred_update_sessions.read(),
322            crypto_policy: &self.crypto_policy,
323        })
324    }
325
326    #[cfg(test)]
327    pub(crate) async fn delayed_action(
328        &self,
329        ct: Duration,
330        da: DelayedAction,
331    ) -> Result<bool, OperationError> {
332        let mut pw = self.proxy_write(ct).await?;
333        pw.process_delayedaction(&da, ct)
334            .and_then(|_| pw.commit())
335            .map(|()| true)
336    }
337}
338
339impl IdmServerAudit {
340    #[cfg(test)]
341    pub(crate) fn check_is_empty_or_panic(&mut self) {
342        use tokio::sync::mpsc::error::TryRecvError;
343
344        match self.audit_rx.try_recv() {
345            Err(TryRecvError::Empty) => {}
346            Err(TryRecvError::Disconnected) => {
347                panic!("Task queue disconnected");
348            }
349            Ok(m) => {
350                trace!(?m);
351                panic!("Task queue not empty");
352            }
353        }
354    }
355
356    pub fn audit_rx(&mut self) -> &mut UnboundedReceiver<AuditEvent> {
357        &mut self.audit_rx
358    }
359}
360
361impl IdmServerDelayed {
362    #[cfg(test)]
363    pub(crate) fn check_is_empty_or_panic(&mut self) {
364        use tokio::sync::mpsc::error::TryRecvError;
365
366        match self.async_rx.try_recv() {
367            Err(TryRecvError::Empty) => {}
368            Err(TryRecvError::Disconnected) => {
369                panic!("Task queue disconnected");
370            }
371            #[allow(clippy::panic)]
372            Ok(m) => {
373                trace!(?m);
374                panic!("Task queue not empty");
375            }
376        }
377    }
378
379    #[cfg(test)]
380    pub(crate) fn try_recv(&mut self) -> Result<DelayedAction, OperationError> {
381        use core::task::{Context, Poll};
382
383        let waker = futures::task::noop_waker();
384        let mut cx = Context::from_waker(&waker);
385        match self.async_rx.poll_recv(&mut cx) {
386            Poll::Pending => Err(OperationError::InvalidState),
387            Poll::Ready(None) => Err(OperationError::QueueDisconnected),
388            Poll::Ready(Some(m)) => Ok(m),
389        }
390    }
391
392    pub async fn recv_many(&mut self, buffer: &mut Vec<DelayedAction>) -> usize {
393        debug_assert!(buffer.is_empty());
394        let limit = buffer.capacity();
395        self.async_rx.recv_many(buffer, limit).await
396    }
397}
398
399pub enum Token {
400    UserAuthToken(UserAuthToken),
401    ApiToken(ApiToken, Arc<EntrySealedCommitted>),
402}
403
404pub trait IdmServerTransaction<'a> {
405    type QsTransactionType: QueryServerTransaction<'a>;
406
407    fn get_qs_txn(&mut self) -> &mut Self::QsTransactionType;
408
409    /// This is the preferred method to transform and securely verify a token into
410    /// an identity that can be used for operations and access enforcement. This
411    /// function *is* aware of the various classes of tokens that may exist, and can
412    /// appropriately check them.
413    ///
414    /// The primary method of verification selection is the use of the KID parameter
415    /// that we internally sign with. We can use this to select the appropriate token type
416    /// and validation method.
417    #[instrument(level = "debug", skip_all)]
418    fn validate_client_auth_info_to_ident(
419        &mut self,
420        client_auth_info: ClientAuthInfo,
421        ct: Duration,
422    ) -> Result<Identity, OperationError> {
423        let ClientAuthInfo {
424            source,
425            client_cert,
426            bearer_token,
427            basic_authz: _,
428            pre_validated_token,
429        } = client_auth_info;
430
431        // If there is a pre-validated UAT, use that. This pre-validation is an "optimisation"
432        // for the web-ui where operations will make a number of api calls, and we don't
433        // want to do redundant work.
434        match pre_validated_token {
435            PreValidatedTokenStatus::Valid(uat) => {
436                return self.process_uat_to_identity(&uat, ct, source)
437            }
438            PreValidatedTokenStatus::SessionExpired => return Err(OperationError::SessionExpired),
439            PreValidatedTokenStatus::NotAuthenticated | PreValidatedTokenStatus::None => {
440                // Fall through and verify the credential details.
441                //
442                // TODO: Currently pre-validation only applies to UAT, not certificate
443                // or api token flows. These will incorrectly set the pre-validation
444                // to NotAuthenticated. It's a larger refactor to correct that.
445            }
446        }
447
448        match (client_cert, bearer_token) {
449            (Some(client_cert_info), _) => {
450                self.client_certificate_to_identity(&client_cert_info, ct, source)
451            }
452            (None, Some(token)) => {
453                match self.validate_and_parse_token_to_identity_token(&token, ct)? {
454                    Token::UserAuthToken(uat) => self.process_uat_to_identity(&uat, ct, source),
455                    Token::ApiToken(apit, entry) => {
456                        self.process_apit_to_identity(&apit, source, entry, ct)
457                    }
458                }
459            }
460            (None, None) => {
461                debug!("No client certificate or bearer tokens were supplied");
462                Err(OperationError::NotAuthenticated)
463            }
464        }
465    }
466
467    /// This function will pre-validate the credentials provided and update the
468    /// ClientAuthInfo structure so that future operations using the same auth
469    /// info will not need to perform all the same checks (time, cryptography, etc).
470    /// However, subsequent callers will still need to load the entry into the
471    /// identity.
472    #[instrument(level = "debug", skip_all)]
473    fn pre_validate_client_auth_info(
474        &mut self,
475        client_auth_info: &mut ClientAuthInfo,
476        ct: Duration,
477    ) -> Result<(), OperationError> {
478        let (result, status) = match self.validate_client_auth_info_to_uat(client_auth_info, ct) {
479            Ok(uat) => (Ok(()), PreValidatedTokenStatus::Valid(Box::new(uat))),
480            Err(OperationError::NotAuthenticated) => {
481                (Ok(()), PreValidatedTokenStatus::NotAuthenticated)
482            }
483            Err(OperationError::SessionExpired) => {
484                (Ok(()), PreValidatedTokenStatus::SessionExpired)
485            }
486            Err(err) => (Err(err), PreValidatedTokenStatus::None),
487        };
488
489        client_auth_info.set_pre_validated_uat(status);
490
491        // The result to bubble up.
492        result
493    }
494
495    /// This function is not used in authentication flows - it is a reflector of the
496    /// current session state to allow a user-auth-token to be presented to the
497    /// user via the whoami call.
498    #[instrument(level = "debug", skip_all)]
499    fn validate_client_auth_info_to_uat(
500        &mut self,
501        client_auth_info: &ClientAuthInfo,
502        ct: Duration,
503    ) -> Result<UserAuthToken, OperationError> {
504        // Future - if there is a pre-validated UAT, use that.
505
506        match (
507            client_auth_info.client_cert.as_ref(),
508            client_auth_info.bearer_token.as_ref(),
509        ) {
510            (Some(client_cert_info), _) => {
511                self.client_certificate_to_user_auth_token(client_cert_info, ct)
512            }
513            (None, Some(token)) => {
514                match self.validate_and_parse_token_to_identity_token(token, ct)? {
515                    Token::UserAuthToken(uat) => Ok(uat),
516                    Token::ApiToken(_apit, _entry) => {
517                        debug!("Unable to process non user auth token");
518                        Err(OperationError::NotAuthenticated)
519                    }
520                }
521            }
522            (None, None) => {
523                debug!("No client certificate or bearer tokens were supplied");
524                Err(OperationError::NotAuthenticated)
525            }
526        }
527    }
528
529    fn validate_and_parse_token_to_identity_token(
530        &mut self,
531        jwsu: &JwsCompact,
532        ct: Duration,
533    ) -> Result<Token, OperationError> {
534        // Our key objects now handle this logic and determine the correct key
535        // from the input type.
536        let jws_inner = self
537            .get_qs_txn()
538            .get_domain_key_object_handle()?
539            .jws_verify(jwsu)
540            .map_err(|err| {
541                security_info!(?err, "Unable to verify token");
542                OperationError::NotAuthenticated
543            })?;
544
545        // Is it a UAT?
546        if let Ok(uat) = jws_inner.from_json::<UserAuthToken>() {
547            if let Some(exp) = uat.expiry {
548                let ct_odt = time::OffsetDateTime::UNIX_EPOCH + ct;
549                if exp < ct_odt {
550                    security_info!(?ct_odt, ?exp, "Session expired");
551                    return Err(OperationError::SessionExpired);
552                } else {
553                    trace!(?ct_odt, ?exp, "Session not yet expired");
554                    return Ok(Token::UserAuthToken(uat));
555                }
556            } else {
557                debug!("Session has no expiry");
558                return Ok(Token::UserAuthToken(uat));
559            }
560        };
561
562        // Handle legacy formatted API tokens.
563        // Is it an API Token?
564        if let Ok(apit) = jws_inner.from_json::<ApiToken>() {
565            if let Some(expiry) = apit.expiry {
566                if time::OffsetDateTime::UNIX_EPOCH + ct >= expiry {
567                    security_info!("Session expired");
568                    return Err(OperationError::SessionExpired);
569                }
570            }
571
572            let entry = self
573                .get_qs_txn()
574                .internal_search_uuid(apit.account_id)
575                .map_err(|err| {
576                    security_info!(?err, "Account associated with api token no longer exists.");
577                    OperationError::NotAuthenticated
578                })?;
579
580            return Ok(Token::ApiToken(apit, entry));
581        };
582
583        // Is it just directly encoded session UUID?
584        if let Ok(session_id) = Uuid::from_slice(jws_inner.payload()) {
585            // Now we have to look up the session.
586
587            let filter = filter!(f_eq(
588                Attribute::ApiTokenSession,
589                PartialValue::Refer(session_id)
590            ));
591
592            let mut entry = self.get_qs_txn().internal_search(filter).map_err(|err| {
593                security_info!(
594                    ?err,
595                    "Account or session associated with session token no longer exists."
596                );
597                OperationError::NotAuthenticated
598            })?;
599
600            let entry = entry.pop().ok_or_else(|| {
601                security_info!("Search result failed to return a valid entry.");
602                OperationError::NotAuthenticated
603            })?;
604
605            let api_token_map = entry.get_ava_as_apitoken_map(Attribute::ApiTokenSession)
606            .ok_or_else(|| {
607                security_info!(entry_id = %entry.get_display_id(), "Account does not contain any valid api token sessions.");
608                OperationError::NotAuthenticated
609            })?;
610
611            let api_token_internal = api_token_map.get(&session_id)
612            .ok_or_else(|| {
613                security_info!(entry_id = %entry.get_display_id(), "Account does not contain a valid api token for the session.");
614                OperationError::NotAuthenticated
615            })?;
616
617            let purpose = api_token_internal.scope.try_into().map_err(|_| {
618                security_info!(entry_id = %entry.get_display_id(), "Account scope is not valid.");
619                OperationError::NotAuthenticated
620            })?;
621
622            let apit = kanidm_proto::internal::ApiToken {
623                account_id: entry.get_uuid(),
624                token_id: session_id,
625                label: api_token_internal.label.clone(),
626                expiry: api_token_internal.expiry,
627                issued_at: api_token_internal.issued_at,
628                purpose,
629            };
630
631            if let Some(expiry) = apit.expiry {
632                if time::OffsetDateTime::UNIX_EPOCH + ct >= expiry {
633                    security_info!(entry_id = %entry.get_display_id(), "Session expired");
634                    return Err(OperationError::SessionExpired);
635                }
636            }
637
638            return Ok(Token::ApiToken(apit, entry));
639        }
640
641        security_info!("Unable to verify token, invalid inner JSON");
642        Err(OperationError::NotAuthenticated)
643    }
644
645    fn check_oauth2_account_uuid_valid(
646        &mut self,
647        uuid: Uuid,
648        session_id: Uuid,
649        parent_session_id: Option<Uuid>,
650        iat: i64,
651        ct: Duration,
652    ) -> Result<Option<Arc<Entry<EntrySealed, EntryCommitted>>>, OperationError> {
653        let entry = self.get_qs_txn().internal_search_uuid(uuid).map_err(|e| {
654            admin_error!(?e, "check_oauth2_account_uuid_valid failed");
655            e
656        })?;
657
658        let within_valid_window = Account::check_within_valid_time(
659            ct,
660            entry
661                .get_ava_single_datetime(Attribute::AccountValidFrom)
662                .as_ref(),
663            entry
664                .get_ava_single_datetime(Attribute::AccountExpire)
665                .as_ref(),
666        );
667
668        if !within_valid_window {
669            security_info!("Account has expired or is not yet valid, not allowing to proceed");
670            return Ok(None);
671        }
672
673        // We are past the grace window. Enforce session presence.
674        // We enforce both sessions are present in case of inconsistency
675        // that may occur with replication.
676
677        let grace_valid = ct < (Duration::from_secs(iat as u64) + AUTH_TOKEN_GRACE_WINDOW);
678
679        let oauth2_session = entry
680            .get_ava_as_oauth2session_map(Attribute::OAuth2Session)
681            .and_then(|sessions| sessions.get(&session_id));
682
683        if let Some(oauth2_session) = oauth2_session {
684            // We have the oauth2 session, lets check it.
685            let oauth2_session_valid = !matches!(oauth2_session.state, SessionState::RevokedAt(_));
686
687            if !oauth2_session_valid {
688                security_info!("The oauth2 session associated to this token is revoked.");
689                return Ok(None);
690            }
691
692            // Do we have a parent session? If yes, we need to enforce it's presence.
693            if let Some(parent_session_id) = parent_session_id {
694                let uat_session = entry
695                    .get_ava_as_session_map(Attribute::UserAuthTokenSession)
696                    .and_then(|sessions| sessions.get(&parent_session_id));
697
698                if let Some(uat_session) = uat_session {
699                    let parent_session_valid =
700                        !matches!(uat_session.state, SessionState::RevokedAt(_));
701                    if parent_session_valid {
702                        security_info!(
703                            "A valid parent and oauth2 session value exists for this token"
704                        );
705                    } else {
706                        security_info!(
707                            "The parent oauth2 session associated to this token is revoked."
708                        );
709                        return Ok(None);
710                    }
711                } else {
712                    let api_session = entry
713                        .get_ava_as_apitoken_map(Attribute::ApiTokenSession)
714                        .and_then(|sessions| sessions.get(&parent_session_id));
715                    if api_session.is_some() {
716                        security_info!("A valid api token session value exists for this token");
717                    } else if grace_valid {
718                        security_info!(
719                            "The token grace window is in effect. Assuming parent session valid."
720                        );
721                    } else {
722                        security_info!("The token grace window has passed and no entry parent sessions exist. Assuming invalid.");
723                        return Ok(None);
724                    }
725                }
726            }
727            // If we don't have a parent session id, we are good to proceed.
728        } else if grace_valid {
729            security_info!("The token grace window is in effect. Assuming valid.");
730        } else {
731            security_info!(
732                "The token grace window has passed and no entry sessions exist. Assuming invalid."
733            );
734            return Ok(None);
735        }
736
737        Ok(Some(entry))
738    }
739
740    /// For any event/operation to proceed, we need to attach an identity to the
741    /// event for security and access processing. When that event is externally
742    /// triggered via one of our various api layers, we process some type of
743    /// account token into this identity. In the current server this is the
744    /// UserAuthToken. For a UserAuthToken to be provided it MUST have been
745    /// cryptographically verified meaning it is now a *trusted* source of
746    /// data that we previously issued.
747    ///
748    /// This is the function that is responsible for converting that UAT into
749    /// something we can pin access controls and other limits and references to.
750    /// This is why it is the location where validity windows are checked and other
751    /// relevant session information is injected.
752    #[instrument(level = "debug", skip_all)]
753    fn process_uat_to_identity(
754        &mut self,
755        uat: &UserAuthToken,
756        ct: Duration,
757        source: Source,
758    ) -> Result<Identity, OperationError> {
759        // From a UAT, get the current identity and associated information.
760        let entry = self
761            .get_qs_txn()
762            .internal_search_uuid(uat.uuid)
763            .map_err(|err| {
764                error!(?err, "from_ro_uat failed");
765                // If the account was deleted, or has not yet been replicated to this instance,
766                // we need to inform the user that the session they are using isn't valid. So
767                // we pass up SessionExpired here.
768                match err {
769                    OperationError::NoMatchingEntries => OperationError::SessionExpired,
770                    err => err,
771                }
772            })?;
773
774        let valid = Account::check_user_auth_token_valid(ct, uat, &entry);
775
776        if !valid {
777            return Err(OperationError::SessionExpired);
778        }
779
780        // ✅  Session is valid! Start to setup for it to be used.
781
782        let scope = match uat.purpose {
783            UatPurpose::ReadOnly => AccessScope::ReadOnly,
784            UatPurpose::ReadWrite { expiry: None } => AccessScope::ReadOnly,
785            UatPurpose::ReadWrite {
786                expiry: Some(expiry),
787            } => {
788                let cot = time::OffsetDateTime::UNIX_EPOCH + ct;
789                if cot < expiry {
790                    AccessScope::ReadWrite
791                } else {
792                    AccessScope::ReadOnly
793                }
794            }
795        };
796
797        let mut limits = Limits::default();
798        // Apply the limits from the uat
799        if let Some(lim) = uat.limit_search_max_results.and_then(|v| v.try_into().ok()) {
800            limits.search_max_results = lim;
801        }
802        if let Some(lim) = uat
803            .limit_search_max_filter_test
804            .and_then(|v| v.try_into().ok())
805        {
806            limits.search_max_filter_test = lim;
807        }
808
809        // #64: Now apply claims from the uat into the Entry
810        // to allow filtering.
811        /*
812        entry.insert_claim(match &uat.auth_type {
813            AuthType::Anonymous => "authtype_anonymous",
814            AuthType::UnixPassword => "authtype_unixpassword",
815            AuthType::Password => "authtype_password",
816            AuthType::GeneratedPassword => "authtype_generatedpassword",
817            AuthType::Webauthn => "authtype_webauthn",
818            AuthType::PasswordMfa => "authtype_passwordmfa",
819        });
820
821        trace!(claims = ?entry.get_ava_set("claim"), "Applied claims");
822        */
823
824        Ok(Identity::new(
825            IdentType::User(IdentUser { entry }),
826            source,
827            uat.session_id,
828            scope,
829            limits,
830            // This strictly is the "last_verified_at" time but due to the current
831            // design of uat, issued_at is the same as last verification.
832            Some(uat.issued_at),
833        ))
834    }
835
836    #[instrument(level = "debug", skip_all)]
837    fn process_apit_to_identity(
838        &mut self,
839        apit: &ApiToken,
840        source: Source,
841        entry: Arc<EntrySealedCommitted>,
842        ct: Duration,
843    ) -> Result<Identity, OperationError> {
844        let valid = ServiceAccount::check_api_token_valid(ct, apit, &entry);
845
846        if !valid {
847            // Check_api token logs this.
848            return Err(OperationError::SessionExpired);
849        }
850
851        let scope = (&apit.purpose).into();
852        // While we did just verify the token, that's different to an interactive
853        // proof of presence like a human would provide.
854        let last_verified_at = None;
855
856        let limits = Limits::api_token();
857
858        Ok(Identity::new(
859            IdentType::User(IdentUser { entry }),
860            source,
861            apit.token_id,
862            scope,
863            limits,
864            last_verified_at,
865        ))
866    }
867
868    fn client_cert_info_entry(
869        &mut self,
870        client_cert_info: &ClientCertInfo,
871    ) -> Result<Arc<EntrySealedCommitted>, OperationError> {
872        let pks256 = hex::encode(client_cert_info.public_key_s256);
873        // Using the certificate hash, find our matching cert.
874        let mut maybe_cert_entries = self.get_qs_txn().internal_search(filter!(f_eq(
875            Attribute::Certificate,
876            PartialValue::HexString(pks256.clone())
877        )))?;
878
879        let maybe_cert_entry = maybe_cert_entries.pop();
880
881        if let Some(cert_entry) = maybe_cert_entry {
882            if maybe_cert_entries.is_empty() {
883                Ok(cert_entry)
884            } else {
885                debug!(?pks256, "Multiple certificates matched, unable to proceed.");
886                Err(OperationError::NotAuthenticated)
887            }
888        } else {
889            debug!(?pks256, "No certificates were able to be mapped.");
890            Err(OperationError::NotAuthenticated)
891        }
892    }
893
894    /// Given a certificate, validate it and discover the associated entry that
895    /// the certificate relates to. Currently, this relies on mapping the public
896    /// key sha256 to a stored client certificate, which then links to the owner.
897    ///
898    /// In the future we *could* consider alternate mapping strategies such as
899    /// subjectAltName or subject DN, but these have subtle security risks and
900    /// configuration challenges, so binary mapping is the simplest - and safest -
901    /// option today.
902    #[instrument(level = "debug", skip_all)]
903    fn client_certificate_to_identity(
904        &mut self,
905        client_cert_info: &ClientCertInfo,
906        ct: Duration,
907        source: Source,
908    ) -> Result<Identity, OperationError> {
909        let cert_entry = self.client_cert_info_entry(client_cert_info)?;
910
911        // This is who the certificate belongs to.
912        let refers_uuid = cert_entry
913            .get_ava_single_refer(Attribute::Refers)
914            .ok_or_else(|| {
915                warn!("Invalid certificate entry, missing refers");
916                OperationError::InvalidState
917            })?;
918
919        // Now get the related entry.
920        let entry = self.get_qs_txn().internal_search_uuid(refers_uuid)?;
921
922        let (account, account_policy) =
923            Account::try_from_entry_with_policy(entry.as_ref(), self.get_qs_txn())?;
924
925        // Is the account in it's valid window?
926        if !account.is_within_valid_time(ct) {
927            // Nope, expired
928            return Err(OperationError::SessionExpired);
929        };
930
931        // scope is related to the cert. For now, default to RO.
932        let scope = AccessScope::ReadOnly;
933
934        let mut limits = Limits::default();
935        // Apply the limits from the account policy
936        if let Some(lim) = account_policy
937            .limit_search_max_results()
938            .and_then(|v| v.try_into().ok())
939        {
940            limits.search_max_results = lim;
941        }
942        if let Some(lim) = account_policy
943            .limit_search_max_filter_test()
944            .and_then(|v| v.try_into().ok())
945        {
946            limits.search_max_filter_test = lim;
947        }
948
949        let certificate_uuid = cert_entry.get_uuid();
950        // The certificate is still valid, so we mark the session as always
951        // valid/issued at now. Because of how mTLS works, this means the
952        // certificate MUST have been JUST verified for the ongoing connection.
953        let odt_ct = OffsetDateTime::UNIX_EPOCH + ct;
954        let last_verified_at = Some(odt_ct);
955
956        Ok(Identity::new(
957            IdentType::User(IdentUser { entry }),
958            source,
959            // session_id is the certificate uuid.
960            certificate_uuid,
961            scope,
962            limits,
963            last_verified_at,
964        ))
965    }
966
967    #[instrument(level = "debug", skip_all)]
968    fn client_certificate_to_user_auth_token(
969        &mut self,
970        client_cert_info: &ClientCertInfo,
971        ct: Duration,
972    ) -> Result<UserAuthToken, OperationError> {
973        let cert_entry = self.client_cert_info_entry(client_cert_info)?;
974
975        // This is who the certificate belongs to.
976        let refers_uuid = cert_entry
977            .get_ava_single_refer(Attribute::Refers)
978            .ok_or_else(|| {
979                warn!("Invalid certificate entry, missing refers");
980                OperationError::InvalidState
981            })?;
982
983        // Now get the related entry.
984        let entry = self.get_qs_txn().internal_search_uuid(refers_uuid)?;
985
986        let (account, account_policy) =
987            Account::try_from_entry_with_policy(entry.as_ref(), self.get_qs_txn())?;
988
989        // Is the account in it's valid window?
990        if !account.is_within_valid_time(ct) {
991            // Nope, expired
992            return Err(OperationError::SessionExpired);
993        };
994
995        let certificate_uuid = cert_entry.get_uuid();
996        let session_is_rw = false;
997
998        account
999            .client_cert_info_to_userauthtoken(certificate_uuid, session_is_rw, ct, &account_policy)
1000            .ok_or(OperationError::InvalidState)
1001    }
1002
1003    fn process_ldap_uuid_to_identity(
1004        &mut self,
1005        uuid: &Uuid,
1006        ct: Duration,
1007        source: Source,
1008    ) -> Result<Identity, OperationError> {
1009        let entry = self
1010            .get_qs_txn()
1011            .internal_search_uuid(*uuid)
1012            .map_err(|err| {
1013                error!(?err, ?uuid, "Failed to search user by uuid");
1014                err
1015            })?;
1016
1017        let (account, account_policy) =
1018            Account::try_from_entry_with_policy(entry.as_ref(), self.get_qs_txn())?;
1019
1020        if !account.is_within_valid_time(ct) {
1021            info!("Account is expired or not yet valid.");
1022            return Err(OperationError::SessionExpired);
1023        }
1024
1025        // Good to go
1026        let anon_entry = if *uuid == UUID_ANONYMOUS {
1027            // We already have it.
1028            entry
1029        } else {
1030            // Pull the anon entry for mapping the identity.
1031            self.get_qs_txn()
1032                .internal_search_uuid(UUID_ANONYMOUS)
1033                .map_err(|err| {
1034                    error!(
1035                        ?err,
1036                        "Unable to search anonymous user for privilege bounding."
1037                    );
1038                    err
1039                })?
1040        };
1041
1042        let mut limits = Limits::default();
1043        let session_id = Uuid::new_v4();
1044
1045        // Update limits from account policy
1046        if let Some(max_results) = account_policy.limit_search_max_results() {
1047            limits.search_max_results = max_results as usize;
1048        }
1049        if let Some(max_filter) = account_policy.limit_search_max_filter_test() {
1050            limits.search_max_filter_test = max_filter as usize;
1051        }
1052
1053        // Ldap sessions don't provide strong proof of presence.
1054        let last_verified_at = None;
1055
1056        // Users via LDAP are always only granted anonymous rights unless
1057        // they auth with an api-token
1058        Ok(Identity::new(
1059            IdentType::User(IdentUser { entry: anon_entry }),
1060            source,
1061            session_id,
1062            AccessScope::ReadOnly,
1063            limits,
1064            last_verified_at,
1065        ))
1066    }
1067
1068    #[instrument(level = "debug", skip_all)]
1069    fn validate_ldap_session(
1070        &mut self,
1071        session: &LdapSession,
1072        source: Source,
1073        ct: Duration,
1074    ) -> Result<Identity, OperationError> {
1075        match session {
1076            LdapSession::UnixBind(uuid) | LdapSession::ApplicationPasswordBind(_, uuid) => {
1077                self.process_ldap_uuid_to_identity(uuid, ct, source)
1078            }
1079            LdapSession::UserAuthToken(uat) => self.process_uat_to_identity(uat, ct, source),
1080            LdapSession::ApiToken(apit) => {
1081                let entry = self
1082                    .get_qs_txn()
1083                    .internal_search_uuid(apit.account_id)
1084                    .map_err(|e| {
1085                        admin_error!("Failed to validate ldap session -> {:?}", e);
1086                        e
1087                    })?;
1088
1089                self.process_apit_to_identity(apit, source, entry, ct)
1090            }
1091        }
1092    }
1093
1094    #[instrument(level = "info", skip_all)]
1095    fn validate_sync_client_auth_info_to_ident(
1096        &mut self,
1097        client_auth_info: ClientAuthInfo,
1098        ct: Duration,
1099    ) -> Result<Identity, OperationError> {
1100        // FUTURE: Could allow mTLS here instead?
1101
1102        let jwsu = client_auth_info.bearer_token.ok_or_else(|| {
1103            security_info!("No token provided");
1104            OperationError::NotAuthenticated
1105        })?;
1106
1107        let jws_inner = self
1108            .get_qs_txn()
1109            .get_domain_key_object_handle()?
1110            .jws_verify(&jwsu)
1111            .map_err(|err| {
1112                security_info!(?err, "Unable to verify token");
1113                OperationError::NotAuthenticated
1114            })?;
1115
1116        let sync_token = jws_inner.from_json::<ScimSyncToken>().map_err(|err| {
1117            error!(?err, "Unable to deserialise JWS");
1118            OperationError::SerdeJsonError
1119        })?;
1120
1121        let entry = self
1122            .get_qs_txn()
1123            .internal_search(filter!(f_eq(
1124                Attribute::SyncTokenSession,
1125                PartialValue::Refer(sync_token.token_id)
1126            )))
1127            .and_then(|mut vs| match vs.pop() {
1128                Some(entry) if vs.is_empty() => Ok(entry),
1129                _ => {
1130                    admin_error!(
1131                        token_id = ?sync_token.token_id,
1132                        "entries was empty, or matched multiple results for token id"
1133                    );
1134                    Err(OperationError::NotAuthenticated)
1135                }
1136            })?;
1137
1138        let valid = SyncAccount::check_sync_token_valid(ct, &sync_token, &entry);
1139
1140        if !valid {
1141            security_info!("Unable to proceed with invalid sync token");
1142            return Err(OperationError::NotAuthenticated);
1143        }
1144
1145        // If scope is not Synchronise, then fail.
1146        let scope = (&sync_token.purpose).into();
1147        let last_verified_at = None;
1148
1149        let limits = Limits::unlimited();
1150        Ok(Identity::new(
1151            IdentType::Synch(entry.get_uuid()),
1152            client_auth_info.source,
1153            sync_token.token_id,
1154            scope,
1155            limits,
1156            last_verified_at,
1157        ))
1158    }
1159}
1160
1161impl<'a> IdmServerTransaction<'a> for IdmServerAuthTransaction<'a> {
1162    type QsTransactionType = QueryServerReadTransaction<'a>;
1163
1164    fn get_qs_txn(&mut self) -> &mut Self::QsTransactionType {
1165        &mut self.qs_read
1166    }
1167}
1168
1169impl IdmServerAuthTransaction<'_> {
1170    #[cfg(test)]
1171    pub fn is_sessionid_present(&self, sessionid: Uuid) -> bool {
1172        let session_read = self.sessions.read();
1173        session_read.contains_key(&sessionid)
1174    }
1175
1176    pub fn get_origin(&self) -> &Url {
1177        #[allow(clippy::unwrap_used)]
1178        self.webauthn.get_allowed_origins().first().unwrap()
1179    }
1180
1181    #[instrument(level = "trace", skip(self))]
1182    pub async fn expire_auth_sessions(&mut self, ct: Duration) {
1183        // ct is current time - sub the timeout. and then split.
1184        let expire = ct - Duration::from_secs(AUTH_SESSION_TIMEOUT);
1185        let split_at = uuid_from_duration(expire, self.sid);
1186        // Removes older sessions in place.
1187        let _session_ticket = self.session_ticket.acquire().await;
1188        let mut session_write = self.sessions.write();
1189        session_write.split_off_lt(&split_at);
1190        // expired will now be dropped, and can't be used by future sessions.
1191        session_write.commit();
1192    }
1193
1194    pub async fn auth(
1195        &mut self,
1196        ae: &AuthEvent,
1197        ct: Duration,
1198        client_auth_info: ClientAuthInfo,
1199    ) -> Result<AuthResult, OperationError> {
1200        // Match on the auth event, to see what we need to do.
1201        match &ae.step {
1202            AuthEventStep::Init(init) => {
1203                // lperf_segment!("idm::server::auth<Init>", || {
1204                // Allocate a session id, based on current time.
1205                let sessionid = uuid_from_duration(ct, self.sid);
1206
1207                // Begin the auth procedure!
1208                // Start a read
1209                //
1210                // Actually we may not need this - at the time we issue the auth-init
1211                // we could generate the uat, the nonce and cache hashes in memory,
1212                // then this can just be fully without a txn.
1213                //
1214                // We do need a txn so that we can process/search and claims
1215                // or related based on the quality of the provided auth steps
1216                //
1217                // We *DO NOT* need a write though, because I think that lock outs
1218                // and rate limits are *per server* and *in memory* only.
1219                //
1220                // Check anything needed? Get the current auth-session-id from request
1221                // because it associates to the nonce's etc which were all cached.
1222                let euuid = self.qs_read.name_to_uuid(init.username.as_str())?;
1223
1224                // Get the first / single entry we expect here ....
1225                let entry = self.qs_read.internal_search_uuid(euuid)?;
1226
1227                info!(
1228                    username = %init.username,
1229                    issue = ?init.issue,
1230                    privileged = ?init.privileged,
1231                    uuid = %euuid,
1232                    "Initiating Authentication Session",
1233                );
1234
1235                // Now, convert the Entry to an account - this gives us some stronger
1236                // typing and functionality so we can assess what auth types can
1237                // continue, and helps to keep non-needed entry specific data
1238                // out of the session tree.
1239                let (account, account_policy) =
1240                    Account::try_from_entry_with_policy(entry.as_ref(), &mut self.qs_read)?;
1241
1242                trace!(?account.primary);
1243
1244                // Intent to take both trees to write.
1245                let _session_ticket = self.session_ticket.acquire().await;
1246
1247                // We don't actually check the softlock here. We just initialise
1248                // it under the write lock we currently have, so that we can validate
1249                // it once we understand what auth mech we will be using.
1250                //
1251                // NOTE: Very careful use of await here to avoid an issue with write.
1252                let _maybe_slock_ref =
1253                    account
1254                        .primary_cred_uuid_and_policy()
1255                        .map(|(cred_uuid, policy)| {
1256                            // Acquire the softlock map
1257                            //
1258                            // We have no issue calling this with .write here, since we
1259                            // already hold the session_ticket above.
1260                            let mut softlock_write = self.softlocks.write();
1261                            let slock_ref: CredSoftLockMutex =
1262                                if let Some(slock_ref) = softlock_write.get(&cred_uuid) {
1263                                    slock_ref.clone()
1264                                } else {
1265                                    // Create if not exist, and the cred type supports softlocking.
1266                                    let slock = Arc::new(Mutex::new(CredSoftLock::new(policy)));
1267                                    softlock_write.insert(cred_uuid, slock.clone());
1268                                    slock
1269                                };
1270                            softlock_write.commit();
1271                            slock_ref
1272                        });
1273
1274                // Does the account have any auth trusts?
1275                let oauth2_client_provider =
1276                    account.oauth2_client_provider().and_then(|trust_provider| {
1277                        debug!(?trust_provider);
1278                        // Now get the provider, if it'still linked and exists.
1279                        self.oauth2_client_providers.get(&trust_provider.provider)
1280                    });
1281
1282                debug!(?oauth2_client_provider);
1283
1284                let asd: AuthSessionData = AuthSessionData {
1285                    account,
1286                    account_policy,
1287                    issue: init.issue,
1288                    webauthn: self.webauthn,
1289                    ct,
1290                    client_auth_info,
1291                    oauth2_client_provider,
1292                };
1293
1294                let domain_keys = self.qs_read.get_domain_key_object_handle()?;
1295
1296                let (auth_session, state) = AuthSession::new(asd, init.privileged, domain_keys);
1297
1298                match auth_session {
1299                    Some(auth_session) => {
1300                        let mut session_write = self.sessions.write();
1301                        if session_write.contains_key(&sessionid) {
1302                            // If we have a session of the same id, return an error (despite how
1303                            // unlikely this is ...
1304                            Err(OperationError::InvalidSessionState)
1305                        } else {
1306                            session_write.insert(sessionid, Arc::new(Mutex::new(auth_session)));
1307                            // Debugging: ensure we really inserted ...
1308                            debug_assert!(session_write.get(&sessionid).is_some());
1309                            Ok(())
1310                        }?;
1311                        session_write.commit();
1312                    }
1313                    None => {
1314                        security_info!("Authentication Session Unable to begin");
1315                    }
1316                };
1317
1318                Ok(AuthResult { sessionid, state })
1319            } // AuthEventStep::Init
1320            AuthEventStep::Begin(mech) => {
1321                let session_read = self.sessions.read();
1322                // Do we have a session?
1323                let auth_session_ref = session_read
1324                    // Why is the session missing?
1325                    .get(&mech.sessionid)
1326                    .cloned()
1327                    .ok_or_else(|| {
1328                        admin_error!("Invalid Session State (no present session uuid)");
1329                        OperationError::InvalidSessionState
1330                    })?;
1331
1332                let mut auth_session = auth_session_ref.lock().await;
1333
1334                // Indicate to the session which auth mech we now want to proceed with.
1335                let auth_result = auth_session.start_session(&mech.mech);
1336
1337                let is_valid = match auth_session.get_credential_uuid()? {
1338                    Some(cred_uuid) => {
1339                        // From the auth_session, determine if the current account
1340                        // credential that we are using has become softlocked or not.
1341                        let softlock_read = self.softlocks.read();
1342                        if let Some(slock_ref) = softlock_read.get(&cred_uuid) {
1343                            let mut slock = slock_ref.lock().await;
1344
1345                            let softlock_expire_odt = auth_session.account().softlock_expire();
1346
1347                            let softlock_expire = softlock_expire_odt
1348                                .map(|odt| odt.unix_timestamp() as u64)
1349                                .map(Duration::from_secs);
1350
1351                            // Apply the current time, which clears the softlock if needed.
1352                            slock.apply_time_step(ct, softlock_expire);
1353                            // Now check the results
1354                            slock.is_valid()
1355                        } else {
1356                            trace!("slock not found");
1357                            false
1358                        }
1359                    }
1360                    None => true,
1361                };
1362
1363                if is_valid {
1364                    auth_result
1365                } else {
1366                    // Fail the session
1367                    trace!("lock step begin");
1368                    auth_session.end_session("Account is temporarily locked")
1369                }
1370                .map(|aus| AuthResult {
1371                    sessionid: mech.sessionid,
1372                    state: aus,
1373                })
1374            } // End AuthEventStep::Mech
1375            AuthEventStep::Cred(creds) => {
1376                // lperf_segment!("idm::server::auth<Creds>", || {
1377                // let _session_ticket = self.session_ticket.acquire().await;
1378
1379                let session_read = self.sessions.read();
1380                // Do we have a session?
1381                let auth_session_ref = session_read
1382                    // Why is the session missing?
1383                    .get(&creds.sessionid)
1384                    .cloned()
1385                    .ok_or_else(|| {
1386                        admin_error!("Invalid Session State (no present session uuid)");
1387                        OperationError::InvalidSessionState
1388                    })?;
1389
1390                let mut auth_session = auth_session_ref.lock().await;
1391
1392                let maybe_slock_ref = match auth_session.get_credential_uuid()? {
1393                    Some(cred_uuid) => {
1394                        let softlock_read = self.softlocks.read();
1395                        softlock_read.get(&cred_uuid).cloned()
1396                    }
1397                    None => None,
1398                };
1399
1400                // From the auth_session, determine if the current account
1401                // credential that we are using has become softlocked or not.
1402                let mut maybe_slock = if let Some(s) = maybe_slock_ref.as_ref() {
1403                    Some(s.lock().await)
1404                } else {
1405                    None
1406                };
1407
1408                let is_valid = if let Some(ref mut slock) = maybe_slock {
1409                    // Apply the current time.
1410                    slock.apply_time_step(ct, None);
1411                    // Now check the results
1412                    slock.is_valid()
1413                } else {
1414                    // No slock is present for this cred_uuid
1415                    true
1416                };
1417
1418                if is_valid {
1419                    // Process the credentials here as required.
1420                    // Basically throw them at the auth_session and see what
1421                    // falls out.
1422                    auth_session
1423                        .validate_creds(
1424                            &creds.cred,
1425                            ct,
1426                            &self.async_tx,
1427                            &self.audit_tx,
1428                            self.webauthn,
1429                            self.qs_read.pw_badlist(),
1430                        )
1431                        .inspect(|aus| {
1432                            // Inspect the result:
1433                            // if it was a failure, we need to inc the softlock.
1434                            if let AuthState::Denied(_) = aus {
1435                                // Update it.
1436                                if let Some(ref mut slock) = maybe_slock {
1437                                    slock.record_failure(ct);
1438                                }
1439                            };
1440                        })
1441                } else {
1442                    // Fail the session
1443                    trace!("lock step cred");
1444                    auth_session.end_session("Account is temporarily locked")
1445                }
1446                .map(|aus| AuthResult {
1447                    sessionid: creds.sessionid,
1448                    state: aus,
1449                })
1450            } // End AuthEventStep::Cred
1451        }
1452    }
1453
1454    async fn auth_with_unix_pass(
1455        &mut self,
1456        id: Uuid,
1457        cleartext: &str,
1458        ct: Duration,
1459    ) -> Result<Option<Account>, OperationError> {
1460        let entry = match self.qs_read.internal_search_uuid(id) {
1461            Ok(entry) => entry,
1462            Err(e) => {
1463                admin_error!("Failed to start auth unix -> {:?}", e);
1464                return Err(e);
1465            }
1466        };
1467
1468        let (account, acp) =
1469            Account::try_from_entry_with_policy(entry.as_ref(), &mut self.qs_read)?;
1470
1471        if !account.is_within_valid_time(ct) {
1472            security_info!("Account is expired or not yet valid.");
1473            return Ok(None);
1474        }
1475
1476        let softlock_expire_odt = account.softlock_expire();
1477
1478        let softlock_expire = softlock_expire_odt
1479            .map(|odt| odt.unix_timestamp() as u64)
1480            .map(Duration::from_secs);
1481
1482        let cred = if acp.allow_primary_cred_fallback() == Some(true) {
1483            account
1484                .unix_extn()
1485                .and_then(|extn| extn.ucred())
1486                .or_else(|| account.primary())
1487        } else {
1488            account.unix_extn().and_then(|extn| extn.ucred())
1489        };
1490
1491        let (cred, cred_id, cred_slock_policy) = match cred {
1492            None => {
1493                if acp.allow_primary_cred_fallback() == Some(true) {
1494                    security_info!("Account does not have a POSIX or primary password configured.");
1495                } else {
1496                    security_info!("Account does not have a POSIX password configured.");
1497                }
1498                return Ok(None);
1499            }
1500            Some(cred) => (cred, cred.uuid, cred.softlock_policy()),
1501        };
1502
1503        // The credential should only ever be a password
1504        let Ok(password) = cred.password_ref() else {
1505            error!("User's UNIX or primary credential is not a password, can't authenticate!");
1506            return Err(OperationError::InvalidState);
1507        };
1508
1509        let slock_ref = {
1510            let softlock_read = self.softlocks.read();
1511            if let Some(slock_ref) = softlock_read.get(&cred_id) {
1512                slock_ref.clone()
1513            } else {
1514                let _session_ticket = self.session_ticket.acquire().await;
1515                let mut softlock_write = self.softlocks.write();
1516                let slock = Arc::new(Mutex::new(CredSoftLock::new(cred_slock_policy)));
1517                softlock_write.insert(cred_id, slock.clone());
1518                softlock_write.commit();
1519                slock
1520            }
1521        };
1522
1523        let mut slock = slock_ref.lock().await;
1524
1525        slock.apply_time_step(ct, softlock_expire);
1526
1527        if !slock.is_valid() {
1528            security_info!("Account is softlocked.");
1529            return Ok(None);
1530        }
1531
1532        // Check the provided password against the stored hash
1533        let valid = password.verify(cleartext).map_err(|e| {
1534            error!(crypto_err = ?e);
1535            OperationError::CryptographyError
1536        })?;
1537
1538        if !valid {
1539            // Update it.
1540            slock.record_failure(ct);
1541
1542            return Ok(None);
1543        }
1544
1545        security_info!("Successfully authenticated with unix (or primary) password");
1546        if password.requires_upgrade() {
1547            self.async_tx
1548                .send(DelayedAction::UnixPwUpgrade(UnixPasswordUpgrade {
1549                    target_uuid: id,
1550                    existing_password: cleartext.to_string(),
1551                }))
1552                .map_err(|_| {
1553                    admin_error!("failed to queue delayed action - unix password upgrade");
1554                    OperationError::InvalidState
1555                })?;
1556        }
1557
1558        Ok(Some(account))
1559    }
1560
1561    pub async fn auth_unix(
1562        &mut self,
1563        uae: &UnixUserAuthEvent,
1564        ct: Duration,
1565    ) -> Result<Option<UnixUserToken>, OperationError> {
1566        Ok(self
1567            .auth_with_unix_pass(uae.target, &uae.cleartext, ct)
1568            .await?
1569            .and_then(|acc| acc.to_unixusertoken(ct).ok()))
1570    }
1571
1572    pub async fn auth_ldap(
1573        &mut self,
1574        lae: &LdapAuthEvent,
1575        ct: Duration,
1576    ) -> Result<Option<LdapBoundToken>, OperationError> {
1577        if lae.target == UUID_ANONYMOUS {
1578            let account_entry = self.qs_read.internal_search_uuid(lae.target).map_err(|e| {
1579                admin_error!("Failed to start auth ldap -> {:?}", e);
1580                e
1581            })?;
1582
1583            let account = Account::try_from_entry_ro(account_entry.as_ref(), &mut self.qs_read)?;
1584
1585            // Check if the anon account has been locked.
1586            if !account.is_within_valid_time(ct) {
1587                security_info!("Account is not within valid time period");
1588                return Ok(None);
1589            }
1590
1591            let session_id = Uuid::new_v4();
1592            security_info!(
1593                "Starting session {} for {} {}",
1594                session_id,
1595                account.spn(),
1596                account.uuid()
1597            );
1598
1599            // Account must be anon, so we can gen the uat.
1600            Ok(Some(LdapBoundToken {
1601                session_id,
1602                spn: account.spn().into(),
1603                effective_session: LdapSession::UnixBind(UUID_ANONYMOUS),
1604            }))
1605        } else {
1606            if !self.qs_read.d_info.d_ldap_allow_unix_pw_bind {
1607                security_info!("Bind not allowed through Unix passwords.");
1608                return Ok(None);
1609            }
1610
1611            let auth = self
1612                .auth_with_unix_pass(lae.target, &lae.cleartext, ct)
1613                .await?;
1614
1615            match auth {
1616                Some(account) => {
1617                    let session_id = Uuid::new_v4();
1618                    security_info!(
1619                        "Starting session {} for {} {}",
1620                        session_id,
1621                        account.spn(),
1622                        account.uuid
1623                    );
1624
1625                    Ok(Some(LdapBoundToken {
1626                        spn: account.spn().into(),
1627                        session_id,
1628                        effective_session: LdapSession::UnixBind(account.uuid),
1629                    }))
1630                }
1631                None => Ok(None),
1632            }
1633        }
1634    }
1635
1636    pub async fn token_auth_ldap(
1637        &mut self,
1638        lae: &LdapTokenAuthEvent,
1639        ct: Duration,
1640    ) -> Result<Option<LdapBoundToken>, OperationError> {
1641        match self.validate_and_parse_token_to_identity_token(&lae.token, ct)? {
1642            Token::UserAuthToken(uat) => {
1643                let spn = uat.spn.clone();
1644                Ok(Some(LdapBoundToken {
1645                    session_id: uat.session_id,
1646                    spn,
1647                    effective_session: LdapSession::UserAuthToken(uat),
1648                }))
1649            }
1650            Token::ApiToken(apit, entry) => {
1651                let spn = entry
1652                    .get_ava_single_proto_string(Attribute::Spn)
1653                    .ok_or_else(|| OperationError::MissingAttribute(Attribute::Spn))?;
1654
1655                Ok(Some(LdapBoundToken {
1656                    session_id: apit.token_id,
1657                    spn,
1658                    effective_session: LdapSession::ApiToken(apit),
1659                }))
1660            }
1661        }
1662    }
1663
1664    pub fn commit(self) -> Result<(), OperationError> {
1665        Ok(())
1666    }
1667}
1668
1669impl<'a> IdmServerTransaction<'a> for IdmServerProxyReadTransaction<'a> {
1670    type QsTransactionType = QueryServerReadTransaction<'a>;
1671
1672    fn get_qs_txn(&mut self) -> &mut Self::QsTransactionType {
1673        &mut self.qs_read
1674    }
1675}
1676
1677fn gen_password_mod(
1678    cleartext: &str,
1679    crypto_policy: &CryptoPolicy,
1680    timestamp: OffsetDateTime,
1681) -> Result<ModifyList<ModifyInvalid>, OperationError> {
1682    let new_cred = Credential::new_password_only(crypto_policy, cleartext, timestamp)?;
1683    let cred_value = Value::new_credential("unix", new_cred);
1684    Ok(ModifyList::new_purge_and_set(
1685        Attribute::UnixPassword,
1686        cred_value,
1687    ))
1688}
1689
1690fn gen_password_upgrade_mod(
1691    unix_cred: &Credential,
1692    cleartext: &str,
1693    crypto_policy: &CryptoPolicy,
1694) -> Result<Option<ModifyList<ModifyInvalid>>, OperationError> {
1695    if let Some(new_cred) = unix_cred.upgrade_password(crypto_policy, cleartext)? {
1696        let cred_value = Value::new_credential("primary", new_cred);
1697        Ok(Some(ModifyList::new_purge_and_set(
1698            Attribute::UnixPassword,
1699            cred_value,
1700        )))
1701    } else {
1702        // No action, not the same pw
1703        Ok(None)
1704    }
1705}
1706
1707impl IdmServerProxyReadTransaction<'_> {
1708    pub fn jws_public_jwk(&mut self, key_id: &str) -> Result<Jwk, OperationError> {
1709        self.qs_read
1710            .get_key_providers()
1711            .get_key_object_handle(UUID_DOMAIN_INFO)
1712            // If there is no domain info, error.
1713            .ok_or(OperationError::NoMatchingEntries)
1714            .and_then(|key_object| key_object.jws_public_jwk(key_id))
1715            .and_then(|maybe_key: Option<Jwk>| maybe_key.ok_or(OperationError::NoMatchingEntries))
1716    }
1717
1718    pub fn get_radiusauthtoken(
1719        &mut self,
1720        rate: &RadiusAuthTokenEvent,
1721        ct: Duration,
1722    ) -> Result<RadiusAuthToken, OperationError> {
1723        let account = self
1724            .qs_read
1725            .impersonate_search_ext_uuid(rate.target, &rate.ident)
1726            .and_then(|account_entry| {
1727                RadiusAccount::try_from_entry_reduced(&account_entry, &mut self.qs_read)
1728            })
1729            .map_err(|e| {
1730                admin_error!("Failed to start radius auth token {:?}", e);
1731                e
1732            })?;
1733
1734        account.to_radiusauthtoken(ct)
1735    }
1736
1737    pub fn get_unixusertoken(
1738        &mut self,
1739        uute: &UnixUserTokenEvent,
1740        ct: Duration,
1741    ) -> Result<UnixUserToken, OperationError> {
1742        let account = self
1743            .qs_read
1744            .impersonate_search_uuid(uute.target, &uute.ident)
1745            .and_then(|account_entry| Account::try_from_entry_ro(&account_entry, &mut self.qs_read))
1746            .map_err(|e| {
1747                admin_error!("Failed to start unix user token -> {:?}", e);
1748                e
1749            })?;
1750
1751        account.to_unixusertoken(ct)
1752    }
1753
1754    pub fn get_unixgrouptoken(
1755        &mut self,
1756        uute: &UnixGroupTokenEvent,
1757    ) -> Result<UnixGroupToken, OperationError> {
1758        let group = self
1759            .qs_read
1760            .impersonate_search_ext_uuid(uute.target, &uute.ident)
1761            .and_then(|e| Group::<Unix>::try_from_entry(&e))
1762            .map_err(|e| {
1763                admin_error!("Failed to start unix group token {:?}", e);
1764                e
1765            })?;
1766        Ok(group.to_unixgrouptoken())
1767    }
1768
1769    pub fn get_credentialstatus(
1770        &mut self,
1771        cse: &CredentialStatusEvent,
1772    ) -> Result<CredentialStatus, OperationError> {
1773        let account = self
1774            .qs_read
1775            .impersonate_search_ext_uuid(cse.target, &cse.ident)
1776            .and_then(|account_entry| {
1777                Account::try_from_entry_reduced(&account_entry, &mut self.qs_read)
1778            })
1779            .map_err(|e| {
1780                admin_error!("Failed to search account {:?}", e);
1781                e
1782            })?;
1783
1784        account.to_credentialstatus()
1785    }
1786}
1787
1788impl<'a> IdmServerTransaction<'a> for IdmServerProxyWriteTransaction<'a> {
1789    type QsTransactionType = QueryServerWriteTransaction<'a>;
1790
1791    fn get_qs_txn(&mut self) -> &mut Self::QsTransactionType {
1792        &mut self.qs_write
1793    }
1794}
1795
1796impl IdmServerProxyWriteTransaction<'_> {
1797    pub(crate) fn crypto_policy(&self) -> &CryptoPolicy {
1798        self.crypto_policy
1799    }
1800
1801    pub fn get_origin(&self) -> &Url {
1802        #[allow(clippy::unwrap_used)]
1803        self.webauthn.get_allowed_origins().first().unwrap()
1804    }
1805
1806    fn check_password_quality(
1807        &mut self,
1808        cleartext: &str,
1809        related_inputs: &[&str],
1810    ) -> Result<(), OperationError> {
1811        // password strength and badlisting is always global, rather than per-pw-policy.
1812        // pw-policy as check on the account is about requirements for mfa for example.
1813        if cleartext.len() < PW_SFA_MIN_LENGTH_NIST as usize {
1814            return Err(OperationError::PasswordQuality(vec![
1815                PasswordFeedback::TooShort(PW_SFA_MIN_LENGTH_NIST),
1816            ]));
1817        } else if cleartext.len() > PW_MAX_LENGTH_NIST as usize {
1818            return Err(OperationError::PasswordQuality(vec![
1819                PasswordFeedback::TooLong(PW_MAX_LENGTH_NIST),
1820            ]));
1821        };
1822
1823        // does the password pass zxcvbn?
1824
1825        let entropy = zxcvbn(cleartext, related_inputs);
1826
1827        // Unix PW's are a single factor, so we enforce good pws
1828        if entropy.score() < Score::Four {
1829            // The password is too week as per:
1830            // https://docs.rs/zxcvbn/2.0.0/zxcvbn/struct.Entropy.html
1831            let feedback: zxcvbn::feedback::Feedback =
1832                entropy.feedback().cloned().ok_or_else(|| {
1833                    security_info!("zxcvbn returned no feedback when score < 3");
1834                    // Return some generic feedback when the password is this bad.
1835                    OperationError::PasswordQuality(vec![
1836                        PasswordFeedback::UseAFewWordsAvoidCommonPhrases,
1837                        PasswordFeedback::AddAnotherWordOrTwo,
1838                        PasswordFeedback::NoNeedForSymbolsDigitsOrUppercaseLetters,
1839                    ])
1840                })?;
1841
1842            security_info!(?feedback, "pw quality feedback");
1843
1844            return Err(OperationError::PasswordQuality(vec![
1845                PasswordFeedback::BadListed,
1846            ]));
1847        }
1848
1849        // check a password badlist to eliminate more content
1850        // we check the password as "lower case" to help eliminate possibilities
1851        // also, when pw_badlist_cache is read from DB, it is read as Value (iutf8 lowercase)
1852        if self
1853            .qs_write
1854            .pw_badlist()
1855            .contains(&cleartext.to_lowercase())
1856        {
1857            security_info!("Password found in badlist, rejecting");
1858            Err(OperationError::PasswordQuality(vec![
1859                PasswordFeedback::BadListed,
1860            ]))
1861        } else {
1862            Ok(())
1863        }
1864    }
1865
1866    pub(crate) fn target_to_account(&mut self, target: Uuid) -> Result<Account, OperationError> {
1867        // Get the account
1868        let account = self
1869            .qs_write
1870            .internal_search_uuid(target)
1871            .and_then(|account_entry| {
1872                Account::try_from_entry_rw(&account_entry, &mut self.qs_write)
1873            })
1874            .map_err(|e| {
1875                admin_error!("Failed to search account {:?}", e);
1876                e
1877            })?;
1878        // Ask if tis all good - this step checks pwpolicy and such
1879
1880        // Deny the change if the account is anonymous!
1881        if account.is_anonymous() {
1882            admin_warn!("Unable to convert anonymous to account during write txn");
1883            Err(OperationError::SystemProtectedObject)
1884        } else {
1885            Ok(account)
1886        }
1887    }
1888
1889    #[cfg(test)]
1890    pub(crate) fn set_account_password(
1891        &mut self,
1892        pce: &PasswordChangeEvent,
1893        ct: OffsetDateTime,
1894    ) -> Result<(), OperationError> {
1895        let account = self.target_to_account(pce.target)?;
1896
1897        // Get the modifications we *want* to perform.
1898        let modlist = account
1899            .gen_password_mod(pce.cleartext.as_str(), self.crypto_policy, ct)
1900            .map_err(|e| {
1901                admin_error!("Failed to generate password mod {:?}", e);
1902                e
1903            })?;
1904        trace!(?modlist, "processing change");
1905
1906        // Check with the QS if we would be ALLOWED to do this change.
1907
1908        let me = self
1909            .qs_write
1910            .impersonate_modify_gen_event(
1911                // Filter as executed
1912                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(pce.target))),
1913                // Filter as intended (acp)
1914                &filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(pce.target))),
1915                &modlist,
1916                &pce.ident,
1917            )
1918            .map_err(|e| {
1919                request_error!(error = ?e);
1920                e
1921            })?;
1922
1923        let mp = self
1924            .qs_write
1925            .modify_pre_apply(&me)
1926            .and_then(|opt_mp| opt_mp.ok_or(OperationError::NoMatchingEntries))
1927            .map_err(|e| {
1928                request_error!(error = ?e);
1929                e
1930            })?;
1931
1932        // If we got here, then pre-apply succeeded, and that means access control
1933        // passed. Now we can do the extra checks.
1934
1935        // And actually really apply it now.
1936        self.qs_write.modify_apply(mp).map_err(|e| {
1937            request_error!(error = ?e);
1938            e
1939        })?;
1940
1941        Ok(())
1942    }
1943
1944    pub fn set_unix_account_password(
1945        &mut self,
1946        pce: &UnixPasswordChangeEvent,
1947    ) -> Result<(), OperationError> {
1948        // Get the account
1949        let account = self
1950            .qs_write
1951            .internal_search_uuid(pce.target)
1952            .and_then(|account_entry| {
1953                // Assert the account is unix and valid.
1954                Account::try_from_entry_rw(&account_entry, &mut self.qs_write)
1955            })
1956            .map_err(|e| {
1957                admin_error!("Failed to start set unix account password {:?}", e);
1958                e
1959            })?;
1960
1961        // Account is not a unix account
1962        if account.unix_extn().is_none() {
1963            return Err(OperationError::MissingClass(
1964                ENTRYCLASS_POSIX_ACCOUNT.into(),
1965            ));
1966        }
1967
1968        // Deny the change if the account is anonymous!
1969        if account.is_anonymous() {
1970            trace!("Unable to use anonymous to change UNIX account password");
1971            return Err(OperationError::SystemProtectedObject);
1972        }
1973
1974        let timestamp = self.qs_write.get_curtime_odt();
1975
1976        let modlist = gen_password_mod(pce.cleartext.as_str(), self.crypto_policy, timestamp)
1977            .map_err(|e| {
1978                admin_error!(?e, "Unable to generate password change modlist");
1979                e
1980            })?;
1981        trace!(?modlist, "processing change");
1982
1983        // Check with the QS if we would be ALLOWED to do this change.
1984
1985        let me = self
1986            .qs_write
1987            .impersonate_modify_gen_event(
1988                // Filter as executed
1989                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(pce.target))),
1990                // Filter as intended (acp)
1991                &filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(pce.target))),
1992                &modlist,
1993                &pce.ident,
1994            )
1995            .map_err(|e| {
1996                request_error!(error = ?e);
1997                e
1998            })?;
1999
2000        let mp = self
2001            .qs_write
2002            .modify_pre_apply(&me)
2003            .and_then(|opt_mp| opt_mp.ok_or(OperationError::NoMatchingEntries))
2004            .map_err(|e| {
2005                request_error!(error = ?e);
2006                e
2007            })?;
2008
2009        // If we got here, then pre-apply succeeded, and that means access control
2010        // passed. Now we can do the extra checks.
2011
2012        self.check_password_quality(pce.cleartext.as_str(), account.related_inputs().as_slice())
2013            .map_err(|e| {
2014                admin_error!(?e, "Failed to checked password quality");
2015                e
2016            })?;
2017
2018        // And actually really apply it now.
2019        self.qs_write.modify_apply(mp).map_err(|e| {
2020            request_error!(error = ?e);
2021            e
2022        })?;
2023
2024        Ok(())
2025    }
2026
2027    #[instrument(level = "debug", skip_all)]
2028    pub fn recover_account(
2029        &mut self,
2030        name: &str,
2031        cleartext: Option<&str>,
2032    ) -> Result<String, OperationError> {
2033        // name to uuid
2034        let target = self.qs_write.name_to_uuid(name).inspect_err(|err| {
2035            error!(?err, "name to uuid failed");
2036        })?;
2037
2038        let cleartext = cleartext
2039            .map(|s| s.to_string())
2040            .unwrap_or_else(password_from_random);
2041
2042        let timestamp = self.qs_write.get_curtime_odt();
2043        let ncred =
2044            Credential::new_generatedpassword_only(self.crypto_policy, &cleartext, timestamp)
2045                .inspect_err(|err| {
2046                    error!(?err, "unable to generate password modification");
2047                })?;
2048        let vcred = Value::new_credential("primary", ncred);
2049        let v_valid_from = Value::new_datetime_epoch(self.qs_write.get_curtime());
2050
2051        let modlist = ModifyList::new_list(vec![
2052            // Ensure the account is valid from *now*, and that the expiry is unset.
2053            m_purge(Attribute::AccountExpire),
2054            m_purge(Attribute::AccountValidFrom),
2055            Modify::Present(Attribute::AccountValidFrom, v_valid_from),
2056            // We need to remove other credentials too.
2057            m_purge(Attribute::PassKeys),
2058            m_purge(Attribute::PrimaryCredential),
2059            Modify::Present(Attribute::PrimaryCredential, vcred),
2060        ]);
2061
2062        trace!(?modlist, "processing change");
2063
2064        self.qs_write
2065            .internal_modify(
2066                // Filter as executed
2067                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(target))),
2068                &modlist,
2069            )
2070            .inspect_err(|err| {
2071                error!(?err);
2072            })?;
2073
2074        Ok(cleartext)
2075    }
2076
2077    #[instrument(level = "debug", skip(self))]
2078    pub fn disable_account(&mut self, name: &str) -> Result<(), OperationError> {
2079        // name to uuid
2080        let target = self.qs_write.name_to_uuid(name).inspect_err(|err| {
2081            error!(?err, "name to uuid failed");
2082        })?;
2083
2084        let v_expire = Value::new_datetime_epoch(self.qs_write.get_curtime());
2085
2086        let modlist = ModifyList::new_list(vec![
2087            // Ensure that the account has no validity, and the expiry is now.
2088            m_purge(Attribute::AccountValidFrom),
2089            m_purge(Attribute::AccountExpire),
2090            Modify::Present(Attribute::AccountExpire, v_expire),
2091        ]);
2092
2093        trace!(?modlist, "processing change");
2094
2095        self.qs_write
2096            .internal_modify(
2097                // Filter as executed
2098                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(target))),
2099                &modlist,
2100            )
2101            .inspect_err(|err| {
2102                error!(?err);
2103            })?;
2104
2105        Ok(())
2106    }
2107
2108    #[instrument(level = "debug", skip_all)]
2109    pub fn regenerate_radius_secret(
2110        &mut self,
2111        rrse: &RegenerateRadiusSecretEvent,
2112    ) -> Result<String, OperationError> {
2113        let account = self.target_to_account(rrse.target)?;
2114
2115        // Difference to the password above, this is intended to be read/copied
2116        // by a human wiath a keyboard in some cases.
2117        let cleartext = readable_password_from_random();
2118
2119        // Create a modlist from the change.
2120        let modlist = account
2121            .regenerate_radius_secret_mod(cleartext.as_str())
2122            .map_err(|e| {
2123                admin_error!("Unable to generate radius secret mod {:?}", e);
2124                e
2125            })?;
2126        trace!(?modlist, "processing change");
2127
2128        // Apply it.
2129        self.qs_write
2130            .impersonate_modify(
2131                // Filter as executed
2132                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(rrse.target))),
2133                // Filter as intended (acp)
2134                &filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(rrse.target))),
2135                &modlist,
2136                // Provide the event to impersonate
2137                &rrse.ident,
2138            )
2139            .map_err(|e| {
2140                request_error!(error = ?e);
2141                e
2142            })
2143            .map(|_| cleartext)
2144    }
2145
2146    // -- delayed action processing --
2147    #[instrument(level = "debug", skip_all)]
2148    fn process_pwupgrade(&mut self, pwu: &PasswordUpgrade) -> Result<(), OperationError> {
2149        // get the account
2150        let account = self.target_to_account(pwu.target_uuid)?;
2151
2152        info!(session_id = %pwu.target_uuid, "Processing password hash upgrade");
2153
2154        let maybe_modlist = account
2155            .gen_password_upgrade_mod(pwu.existing_password.as_str(), self.crypto_policy)
2156            .map_err(|e| {
2157                admin_error!("Unable to generate password mod {:?}", e);
2158                e
2159            })?;
2160
2161        if let Some(modlist) = maybe_modlist {
2162            self.qs_write.internal_modify(
2163                &filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(pwu.target_uuid))),
2164                &modlist,
2165            )
2166        } else {
2167            // No action needed, it's probably been changed/updated already.
2168            Ok(())
2169        }
2170    }
2171
2172    #[instrument(level = "debug", skip_all)]
2173    fn process_unixpwupgrade(&mut self, pwu: &UnixPasswordUpgrade) -> Result<(), OperationError> {
2174        info!(session_id = %pwu.target_uuid, "Processing unix password hash upgrade");
2175
2176        let account = self
2177            .qs_write
2178            .internal_search_uuid(pwu.target_uuid)
2179            .and_then(|account_entry| {
2180                Account::try_from_entry_rw(&account_entry, &mut self.qs_write)
2181            })
2182            .map_err(|e| {
2183                admin_error!("Failed to start unix pw upgrade -> {:?}", e);
2184                e
2185            })?;
2186
2187        let cred = match account.unix_extn() {
2188            Some(ue) => ue.ucred(),
2189            None => {
2190                return Err(OperationError::MissingClass(
2191                    ENTRYCLASS_POSIX_ACCOUNT.into(),
2192                ));
2193            }
2194        };
2195
2196        // No credential no problem
2197        let Some(cred) = cred else {
2198            return Ok(());
2199        };
2200
2201        let maybe_modlist =
2202            gen_password_upgrade_mod(cred, pwu.existing_password.as_str(), self.crypto_policy)?;
2203
2204        match maybe_modlist {
2205            Some(modlist) => self.qs_write.internal_modify(
2206                &filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(pwu.target_uuid))),
2207                &modlist,
2208            ),
2209            None => Ok(()),
2210        }
2211    }
2212
2213    #[instrument(level = "debug", skip_all)]
2214    pub(crate) fn process_webauthncounterinc(
2215        &mut self,
2216        wci: &WebauthnCounterIncrement,
2217    ) -> Result<(), OperationError> {
2218        info!(session_id = %wci.target_uuid, "Processing webauthn counter increment");
2219
2220        let mut account = self.target_to_account(wci.target_uuid)?;
2221
2222        // Generate an optional mod and then attempt to apply it.
2223        let opt_modlist = account
2224            .gen_webauthn_counter_mod(&wci.auth_result)
2225            .map_err(|e| {
2226                admin_error!("Unable to generate webauthn counter mod {:?}", e);
2227                e
2228            })?;
2229
2230        if let Some(modlist) = opt_modlist {
2231            self.qs_write.internal_modify(
2232                &filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(wci.target_uuid))),
2233                &modlist,
2234            )
2235        } else {
2236            // No mod needed.
2237            trace!("No modification required");
2238            Ok(())
2239        }
2240    }
2241
2242    #[instrument(level = "debug", skip_all)]
2243    pub(crate) fn process_backupcoderemoval(
2244        &mut self,
2245        bcr: &BackupCodeRemoval,
2246    ) -> Result<(), OperationError> {
2247        info!(session_id = %bcr.target_uuid, "Processing backup code removal");
2248
2249        let account = self.target_to_account(bcr.target_uuid)?;
2250        // Generate an optional mod and then attempt to apply it.
2251        let modlist = account
2252            .invalidate_backup_code_mod(&bcr.code_to_remove)
2253            .map_err(|e| {
2254                admin_error!("Unable to generate backup code mod {:?}", e);
2255                e
2256            })?;
2257
2258        self.qs_write.internal_modify(
2259            &filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(bcr.target_uuid))),
2260            &modlist,
2261        )
2262    }
2263
2264    #[instrument(level = "debug", skip_all)]
2265    pub(crate) fn process_authsessionrecord(
2266        &mut self,
2267        asr: &AuthSessionRecord,
2268    ) -> Result<(), OperationError> {
2269        // We have to get the entry so we can work out if we need to expire any of it's sessions.
2270        let state = match asr.expiry {
2271            Some(e) => SessionState::ExpiresAt(e),
2272            None => SessionState::NeverExpires,
2273        };
2274
2275        let session = Value::Session(
2276            asr.session_id,
2277            Session {
2278                label: asr.label.clone(),
2279                state,
2280                // Need the other inner bits?
2281                // for the gracewindow.
2282                issued_at: asr.issued_at,
2283                // Who actually created this?
2284                issued_by: asr.issued_by.clone(),
2285                // Which credential was used?
2286                cred_id: asr.cred_id,
2287                // What is the access scope of this session? This is
2288                // for auditing purposes.
2289                scope: asr.scope,
2290                type_: asr.type_,
2291                ext_metadata: Default::default(),
2292            },
2293        );
2294
2295        info!(session_id = %asr.session_id, "Persisting auth session");
2296
2297        // modify the account to put the session onto it.
2298        let modlist = ModifyList::new_append(Attribute::UserAuthTokenSession, session);
2299
2300        self.qs_write
2301            .internal_modify(
2302                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(asr.target_uuid))),
2303                &modlist,
2304            )
2305            .map_err(|e| {
2306                admin_error!("Failed to persist user auth token {:?}", e);
2307                e
2308            })
2309        // Done!
2310    }
2311
2312    #[instrument(level = "debug", skip_all)]
2313    pub fn process_delayedaction(
2314        &mut self,
2315        da: &DelayedAction,
2316        _ct: Duration,
2317    ) -> Result<(), OperationError> {
2318        match da {
2319            DelayedAction::PwUpgrade(pwu) => self.process_pwupgrade(pwu),
2320            DelayedAction::UnixPwUpgrade(upwu) => self.process_unixpwupgrade(upwu),
2321            DelayedAction::WebauthnCounterIncrement(wci) => self.process_webauthncounterinc(wci),
2322            DelayedAction::BackupCodeRemoval(bcr) => self.process_backupcoderemoval(bcr),
2323            DelayedAction::AuthSessionRecord(asr) => self.process_authsessionrecord(asr),
2324        }
2325    }
2326
2327    fn reload_applications(&mut self) -> Result<(), OperationError> {
2328        self.qs_write
2329            .get_applications_set()
2330            .and_then(|application_set| self.applications.reload(application_set))
2331    }
2332
2333    fn reload_oauth2(&mut self) -> Result<(), OperationError> {
2334        let domain_level = self.qs_write.get_domain_version();
2335        self.qs_write.get_oauth2rs_set().and_then(|oauth2rs_set| {
2336            let key_providers = self.qs_write.get_key_providers();
2337            self.oauth2rs
2338                .reload(oauth2rs_set, key_providers, domain_level)
2339        })?;
2340        // Clear the flag to indicate we completed the reload.
2341        self.qs_write.clear_changed_oauth2();
2342        Ok(())
2343    }
2344
2345    #[instrument(level = "debug", skip_all)]
2346    pub fn commit(mut self) -> Result<(), OperationError> {
2347        // The problem we have here is that we need the qs_write layer to reload *first*
2348        // so that things like schema and key objects are ready.
2349        self.qs_write.reload()?;
2350
2351        // Now that's done, let's proceed.
2352        if self.qs_write.get_changed_app() {
2353            self.reload_applications()?;
2354        }
2355
2356        if self.qs_write.get_changed_oauth2() {
2357            self.reload_oauth2()?;
2358        }
2359
2360        if self.qs_write.get_changed_oauth2_client() {
2361            self.reload_oauth2_client_providers()?;
2362        }
2363
2364        // Commit everything.
2365        self.applications.commit();
2366        self.oauth2rs.commit();
2367        self.cred_update_sessions.commit();
2368        self.oauth2_client_providers.commit();
2369
2370        trace!("cred_update_session.commit");
2371        self.qs_write.commit()
2372    }
2373}
2374
2375// Need tests of the sessions and the auth ...
2376
2377#[cfg(test)]
2378mod tests {
2379    use std::{convert::TryFrom, time::Duration};
2380
2381    use crate::{
2382        credential::{Credential, Password},
2383        idm::{
2384            account::DestroySessionTokenEvent,
2385            accountpolicy::ResolvedAccountPolicy,
2386            audit::AuditEvent,
2387            authentication::AuthState,
2388            delayed::{AuthSessionRecord, DelayedAction},
2389            event::{
2390                AuthEvent, AuthResult, LdapAuthEvent, PasswordChangeEvent, RadiusAuthTokenEvent,
2391                RegenerateRadiusSecretEvent, UnixGroupTokenEvent, UnixPasswordChangeEvent,
2392                UnixUserAuthEvent, UnixUserTokenEvent,
2393            },
2394            server::{IdmServer, IdmServerTransaction, Token},
2395        },
2396        modify::{Modify, ModifyList},
2397        prelude::*,
2398        server::keys::KeyProvidersTransaction,
2399        value::{AuthType, SessionState},
2400    };
2401    use compact_jwt::{traits::JwsVerifiable, JwsCompact, JwsEs256Verifier, JwsVerifier};
2402    use kanidm_lib_crypto::CryptoPolicy;
2403    use kanidm_proto::v1::{AuthAllowed, AuthIssueSession, AuthMech};
2404    use time::OffsetDateTime;
2405    use uuid::Uuid;
2406
2407    const TEST_PASSWORD: &str = "ntaoeuntnaoeuhraohuercahu😍";
2408    const TEST_PASSWORD_INC: &str = "ntaoentu nkrcgaeunhibwmwmqj;k wqjbkx ";
2409    const TEST_CURRENT_TIME: u64 = 6000;
2410
2411    #[idm_test]
2412    async fn test_idm_anonymous_auth(idms: &IdmServer, _idms_delayed: &IdmServerDelayed) {
2413        // Start and test anonymous auth.
2414        let mut idms_auth = idms.auth().await.unwrap();
2415        // Send the initial auth event for initialising the session
2416        let anon_init = AuthEvent::anonymous_init();
2417        // Expect success
2418        let r1 = idms_auth
2419            .auth(
2420                &anon_init,
2421                Duration::from_secs(TEST_CURRENT_TIME),
2422                Source::Internal.into(),
2423            )
2424            .await;
2425        /* Some weird lifetime things happen here ... */
2426
2427        let sid = match r1 {
2428            Ok(ar) => {
2429                let AuthResult { sessionid, state } = ar;
2430                match state {
2431                    AuthState::Choose(mut conts) => {
2432                        // Should only be one auth mech
2433                        assert_eq!(conts.len(), 1);
2434                        // And it should be anonymous
2435                        let m = conts.pop().expect("Should not fail");
2436                        assert_eq!(m, AuthMech::Anonymous);
2437                    }
2438                    _ => {
2439                        error!("A critical error has occurred! We have a non-continue result!");
2440                        panic!();
2441                    }
2442                };
2443                // Now pass back the sessionid, we are good to continue.
2444                sessionid
2445            }
2446            Err(e) => {
2447                // Should not occur!
2448                error!("A critical error has occurred! {:?}", e);
2449                panic!();
2450            }
2451        };
2452
2453        debug!("sessionid is ==> {:?}", sid);
2454
2455        idms_auth.commit().expect("Must not fail");
2456
2457        let mut idms_auth = idms.auth().await.unwrap();
2458        let anon_begin = AuthEvent::begin_mech(sid, AuthMech::Anonymous);
2459
2460        let r2 = idms_auth
2461            .auth(
2462                &anon_begin,
2463                Duration::from_secs(TEST_CURRENT_TIME),
2464                Source::Internal.into(),
2465            )
2466            .await;
2467        debug!("r2 ==> {:?}", r2);
2468
2469        match r2 {
2470            Ok(ar) => {
2471                let AuthResult {
2472                    sessionid: _,
2473                    state,
2474                } = ar;
2475
2476                match state {
2477                    AuthState::Continue(allowed) => {
2478                        // Check the uat.
2479                        assert_eq!(allowed.len(), 1);
2480                        assert_eq!(allowed.first(), Some(&AuthAllowed::Anonymous));
2481                    }
2482                    _ => {
2483                        error!("A critical error has occurred! We have a non-continue result!");
2484                        panic!();
2485                    }
2486                }
2487            }
2488            Err(e) => {
2489                error!("A critical error has occurred! {:?}", e);
2490                // Should not occur!
2491                panic!();
2492            }
2493        };
2494
2495        idms_auth.commit().expect("Must not fail");
2496
2497        let mut idms_auth = idms.auth().await.unwrap();
2498        // Now send the anonymous request, given the session id.
2499        let anon_step = AuthEvent::cred_step_anonymous(sid);
2500
2501        // Expect success
2502        let r2 = idms_auth
2503            .auth(
2504                &anon_step,
2505                Duration::from_secs(TEST_CURRENT_TIME),
2506                Source::Internal.into(),
2507            )
2508            .await;
2509        debug!("r2 ==> {:?}", r2);
2510
2511        match r2 {
2512            Ok(ar) => {
2513                let AuthResult {
2514                    sessionid: _,
2515                    state,
2516                } = ar;
2517
2518                match state {
2519                    AuthState::Success(_uat, AuthIssueSession::Token) => {
2520                        // Check the uat.
2521                    }
2522                    _ => {
2523                        error!("A critical error has occurred! We have a non-success result!");
2524                        panic!();
2525                    }
2526                }
2527            }
2528            Err(e) => {
2529                error!("A critical error has occurred! {:?}", e);
2530                // Should not occur!
2531                panic!();
2532            }
2533        };
2534
2535        idms_auth.commit().expect("Must not fail");
2536    }
2537
2538    // Test sending anonymous but with no session init.
2539    #[idm_test]
2540    async fn test_idm_anonymous_auth_invalid_states(
2541        idms: &IdmServer,
2542        _idms_delayed: &IdmServerDelayed,
2543    ) {
2544        {
2545            let mut idms_auth = idms.auth().await.unwrap();
2546            let sid = Uuid::new_v4();
2547            let anon_step = AuthEvent::cred_step_anonymous(sid);
2548
2549            // Expect failure
2550            let r2 = idms_auth
2551                .auth(
2552                    &anon_step,
2553                    Duration::from_secs(TEST_CURRENT_TIME),
2554                    Source::Internal.into(),
2555                )
2556                .await;
2557            debug!("r2 ==> {:?}", r2);
2558
2559            match r2 {
2560                Ok(_) => {
2561                    error!("Auth state machine not correctly enforced!");
2562                    panic!();
2563                }
2564                Err(e) => match e {
2565                    OperationError::InvalidSessionState => {}
2566                    _ => panic!(),
2567                },
2568            };
2569        }
2570    }
2571
2572    async fn init_testperson_w_password(
2573        idms: &IdmServer,
2574        pw: &str,
2575    ) -> Result<Uuid, OperationError> {
2576        let p = CryptoPolicy::minimum();
2577        let cred = Credential::new_password_only(&p, pw, OffsetDateTime::UNIX_EPOCH)?;
2578        let cred_id = cred.uuid;
2579        let v_cred = Value::new_credential("primary", cred);
2580        let mut idms_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
2581
2582        idms_write
2583            .qs_write
2584            .internal_create(vec![E_TESTPERSON_1.clone()])
2585            .expect("Failed to create test person");
2586
2587        // now modify and provide a primary credential.
2588        let me_inv_m = ModifyEvent::new_internal_invalid(
2589            filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(UUID_TESTPERSON_1))),
2590            ModifyList::new_list(vec![Modify::Present(Attribute::PrimaryCredential, v_cred)]),
2591        );
2592        // go!
2593        assert!(idms_write.qs_write.modify(&me_inv_m).is_ok());
2594
2595        idms_write.commit().map(|()| cred_id)
2596    }
2597
2598    async fn init_authsession_sid(idms: &IdmServer, ct: Duration, name: &str) -> Uuid {
2599        let mut idms_auth = idms.auth().await.unwrap();
2600        let admin_init = AuthEvent::named_init(name);
2601
2602        let r1 = idms_auth
2603            .auth(&admin_init, ct, Source::Internal.into())
2604            .await;
2605        let ar = r1.unwrap();
2606        let AuthResult { sessionid, state } = ar;
2607
2608        assert!(matches!(state, AuthState::Choose(_)));
2609
2610        // Now push that we want the Password Mech.
2611        let admin_begin = AuthEvent::begin_mech(sessionid, AuthMech::Password);
2612
2613        let r2 = idms_auth
2614            .auth(&admin_begin, ct, Source::Internal.into())
2615            .await;
2616        let ar = r2.unwrap();
2617        let AuthResult { sessionid, state } = ar;
2618
2619        match state {
2620            AuthState::Continue(_) => {}
2621            s => {
2622                error!(?s, "Sessions was not initialised");
2623                panic!();
2624            }
2625        };
2626
2627        idms_auth.commit().expect("Must not fail");
2628
2629        sessionid
2630    }
2631
2632    async fn check_testperson_password(idms: &IdmServer, pw: &str, ct: Duration) -> JwsCompact {
2633        let sid = init_authsession_sid(idms, ct, "testperson1").await;
2634
2635        let mut idms_auth = idms.auth().await.unwrap();
2636        let anon_step = AuthEvent::cred_step_password(sid, pw);
2637
2638        // Expect success
2639        let r2 = idms_auth
2640            .auth(&anon_step, ct, Source::Internal.into())
2641            .await;
2642        debug!("r2 ==> {:?}", r2);
2643
2644        let token = match r2 {
2645            Ok(ar) => {
2646                let AuthResult {
2647                    sessionid: _,
2648                    state,
2649                } = ar;
2650
2651                match state {
2652                    AuthState::Success(token, AuthIssueSession::Token) => {
2653                        // Check the uat.
2654                        token
2655                    }
2656                    _ => {
2657                        error!("A critical error has occurred! We have a non-success result!");
2658                        panic!();
2659                    }
2660                }
2661            }
2662            Err(e) => {
2663                error!("A critical error has occurred! {:?}", e);
2664                // Should not occur!
2665                panic!();
2666            }
2667        };
2668
2669        idms_auth.commit().expect("Must not fail");
2670
2671        *token
2672    }
2673
2674    #[idm_test]
2675    async fn test_idm_simple_password_auth(idms: &IdmServer, idms_delayed: &mut IdmServerDelayed) {
2676        let ct = duration_from_epoch_now();
2677        init_testperson_w_password(idms, TEST_PASSWORD)
2678            .await
2679            .expect("Failed to setup admin account");
2680        check_testperson_password(idms, TEST_PASSWORD, ct).await;
2681
2682        // Clear our the session record
2683        let da = idms_delayed.try_recv().expect("invalid");
2684        assert!(matches!(da, DelayedAction::AuthSessionRecord(_)));
2685        idms_delayed.check_is_empty_or_panic();
2686    }
2687
2688    #[idm_test]
2689    async fn test_idm_simple_password_spn_auth(
2690        idms: &IdmServer,
2691        idms_delayed: &mut IdmServerDelayed,
2692    ) {
2693        init_testperson_w_password(idms, TEST_PASSWORD)
2694            .await
2695            .expect("Failed to setup admin account");
2696
2697        let sid = init_authsession_sid(
2698            idms,
2699            Duration::from_secs(TEST_CURRENT_TIME),
2700            "testperson1@example.com",
2701        )
2702        .await;
2703
2704        let mut idms_auth = idms.auth().await.unwrap();
2705        let anon_step = AuthEvent::cred_step_password(sid, TEST_PASSWORD);
2706
2707        // Expect success
2708        let r2 = idms_auth
2709            .auth(
2710                &anon_step,
2711                Duration::from_secs(TEST_CURRENT_TIME),
2712                Source::Internal.into(),
2713            )
2714            .await;
2715        debug!("r2 ==> {:?}", r2);
2716
2717        match r2 {
2718            Ok(ar) => {
2719                let AuthResult {
2720                    sessionid: _,
2721                    state,
2722                } = ar;
2723                match state {
2724                    AuthState::Success(_uat, AuthIssueSession::Token) => {
2725                        // Check the uat.
2726                    }
2727                    _ => {
2728                        error!("A critical error has occurred! We have a non-success result!");
2729                        panic!();
2730                    }
2731                }
2732            }
2733            Err(e) => {
2734                error!("A critical error has occurred! {:?}", e);
2735                // Should not occur!
2736                panic!();
2737            }
2738        };
2739
2740        // Clear our the session record
2741        let da = idms_delayed.try_recv().expect("invalid");
2742        assert!(matches!(da, DelayedAction::AuthSessionRecord(_)));
2743        idms_delayed.check_is_empty_or_panic();
2744
2745        idms_auth.commit().expect("Must not fail");
2746    }
2747
2748    #[idm_test(audit = 1)]
2749    async fn test_idm_simple_password_invalid(
2750        idms: &IdmServer,
2751        _idms_delayed: &IdmServerDelayed,
2752        idms_audit: &mut IdmServerAudit,
2753    ) {
2754        init_testperson_w_password(idms, TEST_PASSWORD)
2755            .await
2756            .expect("Failed to setup admin account");
2757        let sid =
2758            init_authsession_sid(idms, Duration::from_secs(TEST_CURRENT_TIME), "testperson1").await;
2759        let mut idms_auth = idms.auth().await.unwrap();
2760        let anon_step = AuthEvent::cred_step_password(sid, TEST_PASSWORD_INC);
2761
2762        // Expect success
2763        let r2 = idms_auth
2764            .auth(
2765                &anon_step,
2766                Duration::from_secs(TEST_CURRENT_TIME),
2767                Source::Internal.into(),
2768            )
2769            .await;
2770        debug!("r2 ==> {:?}", r2);
2771
2772        match r2 {
2773            Ok(ar) => {
2774                let AuthResult {
2775                    sessionid: _,
2776                    state,
2777                } = ar;
2778                match state {
2779                    AuthState::Denied(_reason) => {
2780                        // Check the uat.
2781                    }
2782                    _ => {
2783                        error!("A critical error has occurred! We have a non-denied result!");
2784                        panic!();
2785                    }
2786                }
2787            }
2788            Err(e) => {
2789                error!("A critical error has occurred! {:?}", e);
2790                // Should not occur!
2791                panic!();
2792            }
2793        };
2794
2795        // There should be a queued audit event
2796        match idms_audit.audit_rx().try_recv() {
2797            Ok(AuditEvent::AuthenticationDenied { .. }) => {}
2798            _ => panic!("Oh no"),
2799        }
2800
2801        idms_auth.commit().expect("Must not fail");
2802    }
2803
2804    #[idm_test]
2805    async fn test_idm_simple_password_reset(idms: &IdmServer, _idms_delayed: &IdmServerDelayed) {
2806        let pce = PasswordChangeEvent::new_internal(UUID_ADMIN, TEST_PASSWORD);
2807
2808        let ct = duration_from_epoch_now();
2809
2810        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2811        assert!(idms_prox_write
2812            .set_account_password(&pce, OffsetDateTime::UNIX_EPOCH + ct)
2813            .is_ok());
2814        assert!(idms_prox_write
2815            .set_account_password(&pce, OffsetDateTime::UNIX_EPOCH + ct)
2816            .is_ok());
2817        assert!(idms_prox_write.commit().is_ok());
2818    }
2819
2820    #[idm_test]
2821    async fn test_idm_anonymous_set_password_denied(
2822        idms: &IdmServer,
2823        _idms_delayed: &IdmServerDelayed,
2824    ) {
2825        let pce = PasswordChangeEvent::new_internal(UUID_ANONYMOUS, TEST_PASSWORD);
2826
2827        let ct = duration_from_epoch_now();
2828
2829        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2830        assert!(idms_prox_write
2831            .set_account_password(&pce, OffsetDateTime::UNIX_EPOCH + ct)
2832            .is_err());
2833        assert!(idms_prox_write.commit().is_ok());
2834    }
2835
2836    #[idm_test]
2837    async fn test_idm_regenerate_radius_secret(idms: &IdmServer, _idms_delayed: &IdmServerDelayed) {
2838        let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
2839
2840        idms_prox_write
2841            .qs_write
2842            .internal_create(vec![E_TESTPERSON_1.clone()])
2843            .expect("unable to create test person");
2844
2845        let rrse = RegenerateRadiusSecretEvent::new_internal(UUID_TESTPERSON_1);
2846
2847        // Generates a new credential when none exists
2848        let r1 = idms_prox_write
2849            .regenerate_radius_secret(&rrse)
2850            .expect("Failed to reset radius credential 1");
2851        // Regenerates and overwrites the radius credential
2852        let r2 = idms_prox_write
2853            .regenerate_radius_secret(&rrse)
2854            .expect("Failed to reset radius credential 2");
2855        assert!(r1 != r2);
2856    }
2857
2858    #[idm_test]
2859    async fn test_idm_radiusauthtoken(idms: &IdmServer, _idms_delayed: &IdmServerDelayed) {
2860        let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
2861
2862        idms_prox_write
2863            .qs_write
2864            .internal_create(vec![E_TESTPERSON_1.clone()])
2865            .expect("unable to create test person");
2866
2867        let rrse = RegenerateRadiusSecretEvent::new_internal(UUID_TESTPERSON_1);
2868        let r1 = idms_prox_write
2869            .regenerate_radius_secret(&rrse)
2870            .expect("Failed to reset radius credential 1");
2871        idms_prox_write.commit().expect("failed to commit");
2872
2873        let mut idms_prox_read = idms.proxy_read().await.unwrap();
2874        let person_entry = idms_prox_read
2875            .qs_read
2876            .internal_search_uuid(UUID_TESTPERSON_1)
2877            .expect("Can't access admin entry.");
2878
2879        let rate = RadiusAuthTokenEvent::new_impersonate(person_entry, UUID_TESTPERSON_1);
2880        let tok_r = idms_prox_read
2881            .get_radiusauthtoken(&rate, duration_from_epoch_now())
2882            .expect("Failed to generate radius auth token");
2883
2884        // view the token?
2885        assert_eq!(r1, tok_r.secret);
2886    }
2887
2888    #[idm_test]
2889    async fn test_idm_unixusertoken(idms: &IdmServer, _idms_delayed: &IdmServerDelayed) {
2890        let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
2891        // Modify admin to have posixaccount
2892        let me_posix = ModifyEvent::new_internal_invalid(
2893            filter!(f_eq(Attribute::Name, PartialValue::new_iname("admin"))),
2894            ModifyList::new_list(vec![
2895                Modify::Present(Attribute::Class, EntryClass::PosixAccount.into()),
2896                Modify::Present(Attribute::GidNumber, Value::new_uint32(2001)),
2897            ]),
2898        );
2899        assert!(idms_prox_write.qs_write.modify(&me_posix).is_ok());
2900        // Add a posix group that has the admin as a member.
2901        let e: Entry<EntryInit, EntryNew> = entry_init!(
2902            (Attribute::Class, EntryClass::Object.to_value()),
2903            (Attribute::Class, EntryClass::Group.to_value()),
2904            (Attribute::Class, EntryClass::PosixGroup.to_value()),
2905            (Attribute::Name, Value::new_iname("testgroup")),
2906            (
2907                Attribute::Uuid,
2908                Value::Uuid(uuid::uuid!("01609135-a1c4-43d5-966b-a28227644445"))
2909            ),
2910            (Attribute::Description, Value::new_utf8s("testgroup")),
2911            (
2912                Attribute::Member,
2913                Value::ReferN(uuid::uuid!("00000000-0000-0000-0000-000000000000"))
2914            )
2915        );
2916
2917        let ce = CreateEvent::new_internal(vec![e]);
2918
2919        assert!(idms_prox_write.qs_write.create(&ce).is_ok());
2920
2921        idms_prox_write.commit().expect("failed to commit");
2922
2923        let mut idms_prox_read = idms.proxy_read().await.unwrap();
2924
2925        // Get the account that will be doing the actual reads.
2926        let idm_admin_entry = idms_prox_read
2927            .qs_read
2928            .internal_search_uuid(UUID_IDM_ADMIN)
2929            .expect("Can't access admin entry.");
2930
2931        let ugte = UnixGroupTokenEvent::new_impersonate(
2932            idm_admin_entry.clone(),
2933            uuid!("01609135-a1c4-43d5-966b-a28227644445"),
2934        );
2935        let tok_g = idms_prox_read
2936            .get_unixgrouptoken(&ugte)
2937            .expect("Failed to generate unix group token");
2938
2939        assert_eq!(tok_g.name, "testgroup");
2940        assert_eq!(tok_g.spn, "testgroup@example.com");
2941
2942        let uute = UnixUserTokenEvent::new_internal(UUID_ADMIN);
2943        let tok_r = idms_prox_read
2944            .get_unixusertoken(&uute, duration_from_epoch_now())
2945            .expect("Failed to generate unix user token");
2946
2947        assert_eq!(tok_r.name, "admin");
2948        assert_eq!(tok_r.spn, "admin@example.com");
2949        assert_eq!(tok_r.groups.len(), 2);
2950        assert_eq!(tok_r.groups[0].name, "admin");
2951        assert_eq!(tok_r.groups[1].name, "testgroup");
2952        assert!(tok_r.valid);
2953
2954        // Show we can get the admin as a unix group token too
2955        let ugte = UnixGroupTokenEvent::new_impersonate(
2956            idm_admin_entry,
2957            uuid!("00000000-0000-0000-0000-000000000000"),
2958        );
2959        let tok_g = idms_prox_read
2960            .get_unixgrouptoken(&ugte)
2961            .expect("Failed to generate unix group token");
2962
2963        assert_eq!(tok_g.name, "admin");
2964        assert_eq!(tok_g.spn, "admin@example.com");
2965    }
2966
2967    #[idm_test]
2968    async fn test_idm_simple_unix_password_reset(
2969        idms: &IdmServer,
2970        _idms_delayed: &IdmServerDelayed,
2971    ) {
2972        let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
2973        // make the admin a valid posix account
2974        let me_posix = ModifyEvent::new_internal_invalid(
2975            filter!(f_eq(Attribute::Name, PartialValue::new_iname("admin"))),
2976            ModifyList::new_list(vec![
2977                Modify::Present(Attribute::Class, EntryClass::PosixAccount.into()),
2978                Modify::Present(Attribute::GidNumber, Value::new_uint32(2001)),
2979            ]),
2980        );
2981        assert!(idms_prox_write.qs_write.modify(&me_posix).is_ok());
2982
2983        let pce = UnixPasswordChangeEvent::new_internal(UUID_ADMIN, TEST_PASSWORD);
2984
2985        assert!(idms_prox_write.set_unix_account_password(&pce).is_ok());
2986        assert!(idms_prox_write.commit().is_ok());
2987
2988        let mut idms_auth = idms.auth().await.unwrap();
2989        // Check auth verification of the password
2990
2991        let uuae_good = UnixUserAuthEvent::new_internal(UUID_ADMIN, TEST_PASSWORD);
2992        let a1 = idms_auth
2993            .auth_unix(&uuae_good, Duration::from_secs(TEST_CURRENT_TIME))
2994            .await;
2995        match a1 {
2996            Ok(Some(_tok)) => {}
2997            _ => panic!("Oh no"),
2998        };
2999        // Check bad password
3000        let uuae_bad = UnixUserAuthEvent::new_internal(UUID_ADMIN, TEST_PASSWORD_INC);
3001        let a2 = idms_auth
3002            .auth_unix(&uuae_bad, Duration::from_secs(TEST_CURRENT_TIME))
3003            .await;
3004        match a2 {
3005            Ok(None) => {}
3006            _ => panic!("Oh no"),
3007        };
3008        assert!(idms_auth.commit().is_ok());
3009
3010        // Check deleting the password
3011        let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
3012        let me_purge_up = ModifyEvent::new_internal_invalid(
3013            filter!(f_eq(Attribute::Name, PartialValue::new_iname("admin"))),
3014            ModifyList::new_list(vec![Modify::Purged(Attribute::UnixPassword)]),
3015        );
3016        assert!(idms_prox_write.qs_write.modify(&me_purge_up).is_ok());
3017        assert!(idms_prox_write.commit().is_ok());
3018
3019        // And auth should now fail due to the lack of PW material (note that
3020        // softlocking WON'T kick in because the cred_uuid is gone!)
3021        let mut idms_auth = idms.auth().await.unwrap();
3022        let a3 = idms_auth
3023            .auth_unix(&uuae_good, Duration::from_secs(TEST_CURRENT_TIME))
3024            .await;
3025        match a3 {
3026            Ok(None) => {}
3027            _ => panic!("Oh no"),
3028        };
3029        assert!(idms_auth.commit().is_ok());
3030    }
3031
3032    #[idm_test]
3033    async fn test_idm_simple_password_upgrade(
3034        idms: &IdmServer,
3035        idms_delayed: &mut IdmServerDelayed,
3036    ) {
3037        let ct = duration_from_epoch_now();
3038        // Assert the delayed action queue is empty
3039        idms_delayed.check_is_empty_or_panic();
3040        // Setup the admin w_ an imported password.
3041        {
3042            let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3043            // now modify and provide a primary credential.
3044
3045            idms_prox_write
3046                .qs_write
3047                .internal_create(vec![E_TESTPERSON_1.clone()])
3048                .expect("Failed to create test person");
3049
3050            let me_inv_m =
3051                ModifyEvent::new_internal_invalid(
3052                        filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(UUID_TESTPERSON_1))),
3053                        ModifyList::new_list(vec![Modify::Present(
3054                            Attribute::PasswordImport,
3055                            Value::from("{SSHA512}JwrSUHkI7FTAfHRVR6KoFlSN0E3dmaQWARjZ+/UsShYlENOqDtFVU77HJLLrY2MuSp0jve52+pwtdVl2QUAHukQ0XUf5LDtM")
3056                        )]),
3057                    );
3058            // go!
3059            assert!(idms_prox_write.qs_write.modify(&me_inv_m).is_ok());
3060            assert!(idms_prox_write.commit().is_ok());
3061        }
3062        // Still empty
3063        idms_delayed.check_is_empty_or_panic();
3064
3065        let mut idms_prox_read = idms.proxy_read().await.unwrap();
3066        let person_entry = idms_prox_read
3067            .qs_read
3068            .internal_search_uuid(UUID_TESTPERSON_1)
3069            .expect("Can't access admin entry.");
3070        let cred_before = person_entry
3071            .get_ava_single_credential(Attribute::PrimaryCredential)
3072            .expect("No credential present")
3073            .clone();
3074        drop(idms_prox_read);
3075
3076        // Do an auth, this will trigger the action to send.
3077        check_testperson_password(idms, "password", ct).await;
3078
3079        // ⚠️  We have to be careful here. Between these two actions, it's possible
3080        // that on the pw upgrade that the credential uuid changes. This immediately
3081        // causes the session to be invalidated.
3082
3083        // We need to check the credential id does not change between these steps to
3084        // prevent this!
3085
3086        // process it.
3087        let da = idms_delayed.try_recv().expect("invalid");
3088        // The first task is the pw upgrade
3089        assert!(matches!(da, DelayedAction::PwUpgrade(_)));
3090        let r = idms.delayed_action(duration_from_epoch_now(), da).await;
3091        // The second is the auth session record
3092        let da = idms_delayed.try_recv().expect("invalid");
3093        assert!(matches!(da, DelayedAction::AuthSessionRecord(_)));
3094        assert_eq!(Ok(true), r);
3095
3096        let mut idms_prox_read = idms.proxy_read().await.unwrap();
3097        let person_entry = idms_prox_read
3098            .qs_read
3099            .internal_search_uuid(UUID_TESTPERSON_1)
3100            .expect("Can't access admin entry.");
3101        let cred_after = person_entry
3102            .get_ava_single_credential(Attribute::PrimaryCredential)
3103            .expect("No credential present")
3104            .clone();
3105        drop(idms_prox_read);
3106
3107        assert_eq!(cred_before.uuid, cred_after.uuid);
3108
3109        // Check the admin pw still matches
3110        check_testperson_password(idms, "password", ct).await;
3111        // Clear the next auth session record
3112        let da = idms_delayed.try_recv().expect("invalid");
3113        assert!(matches!(da, DelayedAction::AuthSessionRecord(_)));
3114
3115        // No delayed action was queued.
3116        idms_delayed.check_is_empty_or_panic();
3117    }
3118
3119    #[idm_test]
3120    async fn test_idm_unix_password_upgrade(idms: &IdmServer, idms_delayed: &mut IdmServerDelayed) {
3121        // Assert the delayed action queue is empty
3122        idms_delayed.check_is_empty_or_panic();
3123        // Setup the admin with an imported unix pw.
3124        let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
3125
3126        let im_pw = "{SSHA512}JwrSUHkI7FTAfHRVR6KoFlSN0E3dmaQWARjZ+/UsShYlENOqDtFVU77HJLLrY2MuSp0jve52+pwtdVl2QUAHukQ0XUf5LDtM";
3127        let pw = Password::try_from(im_pw).expect("failed to parse");
3128        let cred = Credential::new_from_password(pw, OffsetDateTime::UNIX_EPOCH);
3129        let v_cred = Value::new_credential("unix", cred);
3130
3131        let me_posix = ModifyEvent::new_internal_invalid(
3132            filter!(f_eq(Attribute::Name, PartialValue::new_iname("admin"))),
3133            ModifyList::new_list(vec![
3134                Modify::Present(Attribute::Class, EntryClass::PosixAccount.into()),
3135                Modify::Present(Attribute::GidNumber, Value::new_uint32(2001)),
3136                Modify::Present(Attribute::UnixPassword, v_cred),
3137            ]),
3138        );
3139        assert!(idms_prox_write.qs_write.modify(&me_posix).is_ok());
3140        assert!(idms_prox_write.commit().is_ok());
3141        idms_delayed.check_is_empty_or_panic();
3142        // Get the auth ready.
3143        let uuae = UnixUserAuthEvent::new_internal(UUID_ADMIN, "password");
3144        let mut idms_auth = idms.auth().await.unwrap();
3145        let a1 = idms_auth
3146            .auth_unix(&uuae, Duration::from_secs(TEST_CURRENT_TIME))
3147            .await;
3148        match a1 {
3149            Ok(Some(_tok)) => {}
3150            _ => panic!("Oh no"),
3151        };
3152        idms_auth.commit().expect("Must not fail");
3153        // The upgrade was queued
3154        // Process it.
3155        let da = idms_delayed.try_recv().expect("invalid");
3156        let _r = idms.delayed_action(duration_from_epoch_now(), da).await;
3157        // Go again
3158        let mut idms_auth = idms.auth().await.unwrap();
3159        let a2 = idms_auth
3160            .auth_unix(&uuae, Duration::from_secs(TEST_CURRENT_TIME))
3161            .await;
3162        match a2 {
3163            Ok(Some(_tok)) => {}
3164            _ => panic!("Oh no"),
3165        };
3166        idms_auth.commit().expect("Must not fail");
3167        // No delayed action was queued.
3168        idms_delayed.check_is_empty_or_panic();
3169    }
3170
3171    // For testing the timeouts
3172    // We need times on this scale
3173    //    not yet valid <-> valid from time <-> current_time <-> expire time <-> expired
3174    const TEST_NOT_YET_VALID_TIME: u64 = TEST_CURRENT_TIME - 240;
3175    const TEST_VALID_FROM_TIME: u64 = TEST_CURRENT_TIME - 120;
3176    const TEST_EXPIRE_TIME: u64 = TEST_CURRENT_TIME + 120;
3177    const TEST_AFTER_EXPIRY: u64 = TEST_CURRENT_TIME + 240;
3178
3179    async fn set_testperson_valid_time(idms: &IdmServer) {
3180        let mut idms_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
3181
3182        let v_valid_from = Value::new_datetime_epoch(Duration::from_secs(TEST_VALID_FROM_TIME));
3183        let v_expire = Value::new_datetime_epoch(Duration::from_secs(TEST_EXPIRE_TIME));
3184
3185        // now modify and provide a primary credential.
3186        let me_inv_m = ModifyEvent::new_internal_invalid(
3187            filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(UUID_TESTPERSON_1))),
3188            ModifyList::new_list(vec![
3189                Modify::Present(Attribute::AccountExpire, v_expire),
3190                Modify::Present(Attribute::AccountValidFrom, v_valid_from),
3191            ]),
3192        );
3193        // go!
3194        assert!(idms_write.qs_write.modify(&me_inv_m).is_ok());
3195
3196        idms_write.commit().expect("Must not fail");
3197    }
3198
3199    #[idm_test]
3200    async fn test_idm_account_valid_from_expire(
3201        idms: &IdmServer,
3202        _idms_delayed: &mut IdmServerDelayed,
3203    ) {
3204        // Any account that is not yet valrid / expired can't auth.
3205
3206        init_testperson_w_password(idms, TEST_PASSWORD)
3207            .await
3208            .expect("Failed to setup admin account");
3209        // Set the valid bounds high/low
3210        // TEST_VALID_FROM_TIME/TEST_EXPIRE_TIME
3211        set_testperson_valid_time(idms).await;
3212
3213        let time_low = Duration::from_secs(TEST_NOT_YET_VALID_TIME);
3214        let time_high = Duration::from_secs(TEST_AFTER_EXPIRY);
3215
3216        let mut idms_auth = idms.auth().await.unwrap();
3217        let admin_init = AuthEvent::named_init("admin");
3218        let r1 = idms_auth
3219            .auth(&admin_init, time_low, Source::Internal.into())
3220            .await;
3221
3222        let ar = r1.unwrap();
3223        let AuthResult {
3224            sessionid: _,
3225            state,
3226        } = ar;
3227
3228        match state {
3229            AuthState::Denied(_) => {}
3230            _ => {
3231                panic!();
3232            }
3233        };
3234
3235        idms_auth.commit().expect("Must not fail");
3236
3237        // And here!
3238        let mut idms_auth = idms.auth().await.unwrap();
3239        let admin_init = AuthEvent::named_init("admin");
3240        let r1 = idms_auth
3241            .auth(&admin_init, time_high, Source::Internal.into())
3242            .await;
3243
3244        let ar = r1.unwrap();
3245        let AuthResult {
3246            sessionid: _,
3247            state,
3248        } = ar;
3249
3250        match state {
3251            AuthState::Denied(_) => {}
3252            _ => {
3253                panic!();
3254            }
3255        };
3256
3257        idms_auth.commit().expect("Must not fail");
3258    }
3259
3260    #[idm_test]
3261    async fn test_idm_unix_valid_from_expire(
3262        idms: &IdmServer,
3263        _idms_delayed: &mut IdmServerDelayed,
3264    ) {
3265        // Any account that is expired can't unix auth.
3266        init_testperson_w_password(idms, TEST_PASSWORD)
3267            .await
3268            .expect("Failed to setup admin account");
3269        set_testperson_valid_time(idms).await;
3270
3271        let time_low = Duration::from_secs(TEST_NOT_YET_VALID_TIME);
3272        let time_high = Duration::from_secs(TEST_AFTER_EXPIRY);
3273
3274        // make the admin a valid posix account
3275        let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
3276        let me_posix = ModifyEvent::new_internal_invalid(
3277            filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(UUID_TESTPERSON_1))),
3278            ModifyList::new_list(vec![
3279                Modify::Present(Attribute::Class, EntryClass::PosixAccount.into()),
3280                Modify::Present(Attribute::GidNumber, Value::new_uint32(2001)),
3281            ]),
3282        );
3283        assert!(idms_prox_write.qs_write.modify(&me_posix).is_ok());
3284
3285        let pce = UnixPasswordChangeEvent::new_internal(UUID_TESTPERSON_1, TEST_PASSWORD);
3286
3287        assert!(idms_prox_write.set_unix_account_password(&pce).is_ok());
3288        assert!(idms_prox_write.commit().is_ok());
3289
3290        // Now check auth when the time is too high or too low.
3291        let mut idms_auth = idms.auth().await.unwrap();
3292        let uuae_good = UnixUserAuthEvent::new_internal(UUID_TESTPERSON_1, TEST_PASSWORD);
3293
3294        let a1 = idms_auth.auth_unix(&uuae_good, time_low).await;
3295        // Should this actually send an error with the details? Or just silently act as
3296        // badpw?
3297        match a1 {
3298            Ok(None) => {}
3299            _ => panic!("Oh no"),
3300        };
3301
3302        let a2 = idms_auth.auth_unix(&uuae_good, time_high).await;
3303        match a2 {
3304            Ok(None) => {}
3305            _ => panic!("Oh no"),
3306        };
3307
3308        idms_auth.commit().expect("Must not fail");
3309        // Also check the generated unix tokens are invalid.
3310        let mut idms_prox_read = idms.proxy_read().await.unwrap();
3311        let uute = UnixUserTokenEvent::new_internal(UUID_TESTPERSON_1);
3312
3313        let tok_r = idms_prox_read
3314            .get_unixusertoken(&uute, time_low)
3315            .expect("Failed to generate unix user token");
3316
3317        assert_eq!(tok_r.name, "testperson1");
3318        assert!(!tok_r.valid);
3319
3320        let tok_r = idms_prox_read
3321            .get_unixusertoken(&uute, time_high)
3322            .expect("Failed to generate unix user token");
3323
3324        assert_eq!(tok_r.name, "testperson1");
3325        assert!(!tok_r.valid);
3326    }
3327
3328    #[idm_test]
3329    async fn test_idm_radius_valid_from_expire(
3330        idms: &IdmServer,
3331        _idms_delayed: &mut IdmServerDelayed,
3332    ) {
3333        // Any account not valid/expiry should not return
3334        // a radius packet.
3335        init_testperson_w_password(idms, TEST_PASSWORD)
3336            .await
3337            .expect("Failed to setup admin account");
3338        set_testperson_valid_time(idms).await;
3339
3340        let time_low = Duration::from_secs(TEST_NOT_YET_VALID_TIME);
3341        let time_high = Duration::from_secs(TEST_AFTER_EXPIRY);
3342
3343        let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
3344        let rrse = RegenerateRadiusSecretEvent::new_internal(UUID_TESTPERSON_1);
3345        let _r1 = idms_prox_write
3346            .regenerate_radius_secret(&rrse)
3347            .expect("Failed to reset radius credential 1");
3348        idms_prox_write.commit().expect("failed to commit");
3349
3350        let mut idms_prox_read = idms.proxy_read().await.unwrap();
3351        let admin_entry = idms_prox_read
3352            .qs_read
3353            .internal_search_uuid(UUID_ADMIN)
3354            .expect("Can't access admin entry.");
3355
3356        let rate = RadiusAuthTokenEvent::new_impersonate(admin_entry, UUID_ADMIN);
3357        let tok_r = idms_prox_read.get_radiusauthtoken(&rate, time_low);
3358
3359        if tok_r.is_err() {
3360            // Ok?
3361        } else {
3362            debug_assert!(false);
3363        }
3364
3365        let tok_r = idms_prox_read.get_radiusauthtoken(&rate, time_high);
3366
3367        if tok_r.is_err() {
3368            // Ok?
3369        } else {
3370            debug_assert!(false);
3371        }
3372    }
3373
3374    #[idm_test(audit = 1)]
3375    async fn test_idm_account_softlocking(
3376        idms: &IdmServer,
3377        idms_delayed: &mut IdmServerDelayed,
3378        idms_audit: &mut IdmServerAudit,
3379    ) {
3380        init_testperson_w_password(idms, TEST_PASSWORD)
3381            .await
3382            .expect("Failed to setup admin account");
3383
3384        // Auth invalid, no softlock present.
3385        let sid =
3386            init_authsession_sid(idms, Duration::from_secs(TEST_CURRENT_TIME), "testperson1").await;
3387        let mut idms_auth = idms.auth().await.unwrap();
3388        let anon_step = AuthEvent::cred_step_password(sid, TEST_PASSWORD_INC);
3389
3390        let r2 = idms_auth
3391            .auth(
3392                &anon_step,
3393                Duration::from_secs(TEST_CURRENT_TIME),
3394                Source::Internal.into(),
3395            )
3396            .await;
3397        debug!("r2 ==> {:?}", r2);
3398
3399        match r2 {
3400            Ok(ar) => {
3401                let AuthResult {
3402                    sessionid: _,
3403                    state,
3404                } = ar;
3405                match state {
3406                    AuthState::Denied(reason) => {
3407                        assert!(reason != "Account is temporarily locked");
3408                    }
3409                    _ => {
3410                        error!("A critical error has occurred! We have a non-denied result!");
3411                        panic!();
3412                    }
3413                }
3414            }
3415            Err(e) => {
3416                error!("A critical error has occurred! {:?}", e);
3417                panic!();
3418            }
3419        };
3420
3421        // There should be a queued audit event
3422        match idms_audit.audit_rx().try_recv() {
3423            Ok(AuditEvent::AuthenticationDenied { .. }) => {}
3424            _ => panic!("Oh no"),
3425        }
3426
3427        idms_auth.commit().expect("Must not fail");
3428
3429        // Auth init, softlock present, count == 1, same time (so before unlock_at)
3430        // aka Auth valid immediate, (ct < exp), autofail
3431        // aka Auth invalid immediate, (ct < exp), autofail
3432        let mut idms_auth = idms.auth().await.unwrap();
3433        let admin_init = AuthEvent::named_init("testperson1");
3434
3435        let r1 = idms_auth
3436            .auth(
3437                &admin_init,
3438                Duration::from_secs(TEST_CURRENT_TIME),
3439                Source::Internal.into(),
3440            )
3441            .await;
3442        let ar = r1.unwrap();
3443        let AuthResult { sessionid, state } = ar;
3444        assert!(matches!(state, AuthState::Choose(_)));
3445
3446        // Soft locks only apply once a mechanism is chosen
3447        let admin_begin = AuthEvent::begin_mech(sessionid, AuthMech::Password);
3448
3449        let r2 = idms_auth
3450            .auth(
3451                &admin_begin,
3452                Duration::from_secs(TEST_CURRENT_TIME),
3453                Source::Internal.into(),
3454            )
3455            .await;
3456        let ar = r2.unwrap();
3457        let AuthResult {
3458            sessionid: _,
3459            state,
3460        } = ar;
3461
3462        match state {
3463            AuthState::Denied(reason) => {
3464                assert_eq!(reason, "Account is temporarily locked");
3465            }
3466            _ => {
3467                error!("Sessions was not denied (softlock)");
3468                panic!();
3469            }
3470        };
3471
3472        idms_auth.commit().expect("Must not fail");
3473
3474        // Auth invalid once softlock pass (count == 2, exp_at grows)
3475        // Tested in the softlock state machine.
3476
3477        // Auth valid once softlock pass, valid. Count remains.
3478        let sid = init_authsession_sid(
3479            idms,
3480            Duration::from_secs(TEST_CURRENT_TIME + 2),
3481            "testperson1",
3482        )
3483        .await;
3484
3485        let mut idms_auth = idms.auth().await.unwrap();
3486        let anon_step = AuthEvent::cred_step_password(sid, TEST_PASSWORD);
3487
3488        // Expect success
3489        let r2 = idms_auth
3490            .auth(
3491                &anon_step,
3492                Duration::from_secs(TEST_CURRENT_TIME + 2),
3493                Source::Internal.into(),
3494            )
3495            .await;
3496        debug!("r2 ==> {:?}", r2);
3497
3498        match r2 {
3499            Ok(ar) => {
3500                let AuthResult {
3501                    sessionid: _,
3502                    state,
3503                } = ar;
3504                match state {
3505                    AuthState::Success(_uat, AuthIssueSession::Token) => {
3506                        // Check the uat.
3507                    }
3508                    _ => {
3509                        error!("A critical error has occurred! We have a non-success result!");
3510                        panic!();
3511                    }
3512                }
3513            }
3514            Err(e) => {
3515                error!("A critical error has occurred! {:?}", e);
3516                // Should not occur!
3517                panic!();
3518            }
3519        };
3520
3521        idms_auth.commit().expect("Must not fail");
3522
3523        // Clear the auth session record
3524        let da = idms_delayed.try_recv().expect("invalid");
3525        assert!(matches!(da, DelayedAction::AuthSessionRecord(_)));
3526        idms_delayed.check_is_empty_or_panic();
3527
3528        // Auth valid after reset at, count == 0.
3529        // Tested in the softlock state machine.
3530
3531        // Auth invalid, softlock present, count == 1
3532        // Auth invalid after reset at, count == 0 and then to count == 1
3533        // Tested in the softlock state machine.
3534    }
3535
3536    #[idm_test(audit = 1)]
3537    async fn test_idm_account_softlocking_interleaved(
3538        idms: &IdmServer,
3539        _idms_delayed: &mut IdmServerDelayed,
3540        idms_audit: &mut IdmServerAudit,
3541    ) {
3542        init_testperson_w_password(idms, TEST_PASSWORD)
3543            .await
3544            .expect("Failed to setup admin account");
3545
3546        // Start an *early* auth session.
3547        let sid_early =
3548            init_authsession_sid(idms, Duration::from_secs(TEST_CURRENT_TIME), "testperson1").await;
3549
3550        // Start a second auth session
3551        let sid_later =
3552            init_authsession_sid(idms, Duration::from_secs(TEST_CURRENT_TIME), "testperson1").await;
3553        // Get the detail wrong in sid_later.
3554        let mut idms_auth = idms.auth().await.unwrap();
3555        let anon_step = AuthEvent::cred_step_password(sid_later, TEST_PASSWORD_INC);
3556
3557        let r2 = idms_auth
3558            .auth(
3559                &anon_step,
3560                Duration::from_secs(TEST_CURRENT_TIME),
3561                Source::Internal.into(),
3562            )
3563            .await;
3564        debug!("r2 ==> {:?}", r2);
3565
3566        match r2 {
3567            Ok(ar) => {
3568                let AuthResult {
3569                    sessionid: _,
3570                    state,
3571                } = ar;
3572                match state {
3573                    AuthState::Denied(reason) => {
3574                        assert!(reason != "Account is temporarily locked");
3575                    }
3576                    _ => {
3577                        error!("A critical error has occurred! We have a non-denied result!");
3578                        panic!();
3579                    }
3580                }
3581            }
3582            Err(e) => {
3583                error!("A critical error has occurred! {:?}", e);
3584                panic!();
3585            }
3586        };
3587
3588        match idms_audit.audit_rx().try_recv() {
3589            Ok(AuditEvent::AuthenticationDenied { .. }) => {}
3590            _ => panic!("Oh no"),
3591        }
3592
3593        idms_auth.commit().expect("Must not fail");
3594
3595        // Now check that sid_early is denied due to softlock.
3596        let mut idms_auth = idms.auth().await.unwrap();
3597        let anon_step = AuthEvent::cred_step_password(sid_early, TEST_PASSWORD);
3598
3599        // Expect success
3600        let r2 = idms_auth
3601            .auth(
3602                &anon_step,
3603                Duration::from_secs(TEST_CURRENT_TIME),
3604                Source::Internal.into(),
3605            )
3606            .await;
3607        debug!("r2 ==> {:?}", r2);
3608        match r2 {
3609            Ok(ar) => {
3610                let AuthResult {
3611                    sessionid: _,
3612                    state,
3613                } = ar;
3614                match state {
3615                    AuthState::Denied(reason) => {
3616                        assert_eq!(reason, "Account is temporarily locked");
3617                    }
3618                    _ => {
3619                        error!("A critical error has occurred! We have a non-denied result!");
3620                        panic!();
3621                    }
3622                }
3623            }
3624            Err(e) => {
3625                error!("A critical error has occurred! {:?}", e);
3626                panic!();
3627            }
3628        };
3629        idms_auth.commit().expect("Must not fail");
3630    }
3631
3632    #[idm_test]
3633    async fn test_idm_account_unix_softlocking(
3634        idms: &IdmServer,
3635        _idms_delayed: &mut IdmServerDelayed,
3636    ) {
3637        init_testperson_w_password(idms, TEST_PASSWORD)
3638            .await
3639            .expect("Failed to setup admin account");
3640        // make the admin a valid posix account
3641        let mut idms_prox_write = idms.proxy_write(duration_from_epoch_now()).await.unwrap();
3642        let me_posix = ModifyEvent::new_internal_invalid(
3643            filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(UUID_TESTPERSON_1))),
3644            ModifyList::new_list(vec![
3645                Modify::Present(Attribute::Class, EntryClass::PosixAccount.into()),
3646                Modify::Present(Attribute::GidNumber, Value::new_uint32(2001)),
3647            ]),
3648        );
3649        assert!(idms_prox_write.qs_write.modify(&me_posix).is_ok());
3650
3651        let pce = UnixPasswordChangeEvent::new_internal(UUID_TESTPERSON_1, TEST_PASSWORD);
3652        assert!(idms_prox_write.set_unix_account_password(&pce).is_ok());
3653        assert!(idms_prox_write.commit().is_ok());
3654
3655        let mut idms_auth = idms.auth().await.unwrap();
3656        let uuae_good = UnixUserAuthEvent::new_internal(UUID_TESTPERSON_1, TEST_PASSWORD);
3657        let uuae_bad = UnixUserAuthEvent::new_internal(UUID_TESTPERSON_1, TEST_PASSWORD_INC);
3658
3659        let a2 = idms_auth
3660            .auth_unix(&uuae_bad, Duration::from_secs(TEST_CURRENT_TIME))
3661            .await;
3662        match a2 {
3663            Ok(None) => {}
3664            _ => panic!("Oh no"),
3665        };
3666
3667        // Now if we immediately auth again, should fail at same time due to SL
3668        let a1 = idms_auth
3669            .auth_unix(&uuae_good, Duration::from_secs(TEST_CURRENT_TIME))
3670            .await;
3671        match a1 {
3672            Ok(None) => {}
3673            _ => panic!("Oh no"),
3674        };
3675
3676        // And then later, works because of SL lifting.
3677        let a1 = idms_auth
3678            .auth_unix(&uuae_good, Duration::from_secs(TEST_CURRENT_TIME + 2))
3679            .await;
3680        match a1 {
3681            Ok(Some(_tok)) => {}
3682            _ => panic!("Oh no"),
3683        };
3684
3685        assert!(idms_auth.commit().is_ok());
3686    }
3687
3688    #[idm_test]
3689    async fn test_idm_jwt_uat_expiry(idms: &IdmServer, idms_delayed: &mut IdmServerDelayed) {
3690        let ct = Duration::from_secs(TEST_CURRENT_TIME);
3691        let expiry = ct + Duration::from_secs((DEFAULT_AUTH_SESSION_EXPIRY + 1).into());
3692        // Do an authenticate
3693        init_testperson_w_password(idms, TEST_PASSWORD)
3694            .await
3695            .expect("Failed to setup admin account");
3696        let token = check_testperson_password(idms, TEST_PASSWORD, ct).await;
3697
3698        // Clear out the queued session record
3699        let da = idms_delayed.try_recv().expect("invalid");
3700        assert!(matches!(da, DelayedAction::AuthSessionRecord(_)));
3701        // Persist it.
3702        let r = idms.delayed_action(ct, da).await;
3703        assert_eq!(Ok(true), r);
3704        idms_delayed.check_is_empty_or_panic();
3705
3706        let mut idms_prox_read = idms.proxy_read().await.unwrap();
3707
3708        // Check it's valid - This is within the time window so will pass.
3709        idms_prox_read
3710            .validate_client_auth_info_to_ident(token.clone().into(), ct)
3711            .expect("Failed to validate");
3712
3713        // In X time it should be INVALID
3714        match idms_prox_read.validate_client_auth_info_to_ident(token.into(), expiry) {
3715            Err(OperationError::SessionExpired) => {}
3716            _ => panic!("Oh no"),
3717        }
3718    }
3719
3720    #[idm_test]
3721    async fn test_idm_expired_auth_session_cleanup(
3722        idms: &IdmServer,
3723        _idms_delayed: &mut IdmServerDelayed,
3724    ) {
3725        let ct = Duration::from_secs(TEST_CURRENT_TIME);
3726        let expiry_a = ct + Duration::from_secs((DEFAULT_AUTH_SESSION_EXPIRY + 1).into());
3727        let expiry_b = ct + Duration::from_secs(((DEFAULT_AUTH_SESSION_EXPIRY + 1) * 2).into());
3728
3729        let session_a = Uuid::new_v4();
3730        let session_b = Uuid::new_v4();
3731
3732        // We need to put the credential on the admin.
3733        let cred_id = init_testperson_w_password(idms, TEST_PASSWORD)
3734            .await
3735            .expect("Failed to setup admin account");
3736
3737        // Assert no sessions present
3738        let mut idms_prox_read = idms.proxy_read().await.unwrap();
3739        let admin = idms_prox_read
3740            .qs_read
3741            .internal_search_uuid(UUID_TESTPERSON_1)
3742            .expect("failed");
3743        let sessions = admin.get_ava_as_session_map(Attribute::UserAuthTokenSession);
3744        assert!(sessions.is_none());
3745        drop(idms_prox_read);
3746
3747        let da = DelayedAction::AuthSessionRecord(AuthSessionRecord {
3748            target_uuid: UUID_TESTPERSON_1,
3749            session_id: session_a,
3750            cred_id,
3751            label: "Test Session A".to_string(),
3752            expiry: Some(OffsetDateTime::UNIX_EPOCH + expiry_a),
3753            issued_at: OffsetDateTime::UNIX_EPOCH + ct,
3754            issued_by: IdentityId::User(UUID_ADMIN),
3755            scope: SessionScope::ReadOnly,
3756            type_: AuthType::Passkey,
3757            ext_metadata: Default::default(),
3758        });
3759        // Persist it.
3760        let r = idms.delayed_action(ct, da).await;
3761        assert_eq!(Ok(true), r);
3762
3763        // Check it was written, and check
3764        let mut idms_prox_read = idms.proxy_read().await.unwrap();
3765        let admin = idms_prox_read
3766            .qs_read
3767            .internal_search_uuid(UUID_TESTPERSON_1)
3768            .expect("failed");
3769        let sessions = admin
3770            .get_ava_as_session_map(Attribute::UserAuthTokenSession)
3771            .expect("Sessions must be present!");
3772        assert_eq!(sessions.len(), 1);
3773        let session_data_a = sessions.get(&session_a).expect("Session A is missing!");
3774        assert!(matches!(session_data_a.state, SessionState::ExpiresAt(_)));
3775
3776        drop(idms_prox_read);
3777
3778        // When we re-auth, this is what triggers the session revoke via the delayed action.
3779
3780        let da = DelayedAction::AuthSessionRecord(AuthSessionRecord {
3781            target_uuid: UUID_TESTPERSON_1,
3782            session_id: session_b,
3783            cred_id,
3784            label: "Test Session B".to_string(),
3785            expiry: Some(OffsetDateTime::UNIX_EPOCH + expiry_b),
3786            issued_at: OffsetDateTime::UNIX_EPOCH + ct,
3787            issued_by: IdentityId::User(UUID_ADMIN),
3788            scope: SessionScope::ReadOnly,
3789            type_: AuthType::Passkey,
3790            ext_metadata: Default::default(),
3791        });
3792        // Persist it.
3793        let r = idms.delayed_action(expiry_a, da).await;
3794        assert_eq!(Ok(true), r);
3795
3796        let mut idms_prox_read = idms.proxy_read().await.unwrap();
3797        let admin = idms_prox_read
3798            .qs_read
3799            .internal_search_uuid(UUID_TESTPERSON_1)
3800            .expect("failed");
3801        let sessions = admin
3802            .get_ava_as_session_map(Attribute::UserAuthTokenSession)
3803            .expect("Sessions must be present!");
3804        trace!(?sessions);
3805        assert_eq!(sessions.len(), 2);
3806
3807        let session_data_a = sessions.get(&session_a).expect("Session A is missing!");
3808        assert!(matches!(session_data_a.state, SessionState::RevokedAt(_)));
3809
3810        let session_data_b = sessions.get(&session_b).expect("Session B is missing!");
3811        assert!(matches!(session_data_b.state, SessionState::ExpiresAt(_)));
3812        // Now show that sessions trim!
3813    }
3814
3815    #[idm_test]
3816    async fn test_idm_account_session_validation(
3817        idms: &IdmServer,
3818        idms_delayed: &mut IdmServerDelayed,
3819    ) {
3820        use kanidm_proto::internal::UserAuthToken;
3821
3822        let ct = duration_from_epoch_now();
3823
3824        let post_grace = ct + AUTH_TOKEN_GRACE_WINDOW + Duration::from_secs(1);
3825        let expiry = ct + Duration::from_secs(DEFAULT_AUTH_SESSION_EXPIRY as u64 + 1);
3826
3827        // Assert that our grace time is less than expiry, so we know the failure is due to
3828        // this.
3829        assert!(post_grace < expiry);
3830
3831        // Do an authenticate
3832        init_testperson_w_password(idms, TEST_PASSWORD)
3833            .await
3834            .expect("Failed to setup admin account");
3835        let uat_unverified = check_testperson_password(idms, TEST_PASSWORD, ct).await;
3836
3837        // Process the session info.
3838        let da = idms_delayed.try_recv().expect("invalid");
3839        assert!(matches!(da, DelayedAction::AuthSessionRecord(_)));
3840        let r = idms.delayed_action(ct, da).await;
3841        assert_eq!(Ok(true), r);
3842
3843        let mut idms_prox_read = idms.proxy_read().await.unwrap();
3844
3845        let token_kid = uat_unverified.kid().expect("no key id present");
3846
3847        let uat_jwk = idms_prox_read
3848            .qs_read
3849            .get_key_providers()
3850            .get_key_object(UUID_DOMAIN_INFO)
3851            .and_then(|object| {
3852                object
3853                    .jws_public_jwk(token_kid)
3854                    .expect("Unable to access uat jwk")
3855            })
3856            .expect("No jwk by this kid");
3857
3858        let jws_validator = JwsEs256Verifier::try_from(&uat_jwk).unwrap();
3859
3860        let uat_inner: UserAuthToken = jws_validator
3861            .verify(&uat_unverified)
3862            .unwrap()
3863            .from_json()
3864            .unwrap();
3865
3866        // Check it's valid.
3867        idms_prox_read
3868            .validate_client_auth_info_to_ident(uat_unverified.clone().into(), ct)
3869            .expect("Failed to validate");
3870
3871        // If the auth session record wasn't processed, this will fail.
3872        idms_prox_read
3873            .validate_client_auth_info_to_ident(uat_unverified.clone().into(), post_grace)
3874            .expect("Failed to validate");
3875
3876        drop(idms_prox_read);
3877
3878        // Mark the session as invalid now.
3879        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3880        let dte = DestroySessionTokenEvent::new_internal(uat_inner.uuid, uat_inner.session_id);
3881        assert!(idms_prox_write.account_destroy_session_token(&dte).is_ok());
3882        assert!(idms_prox_write.commit().is_ok());
3883
3884        // Now check again with the session destroyed.
3885        let mut idms_prox_read = idms.proxy_read().await.unwrap();
3886
3887        // Now, within gracewindow, it's NOT valid because the session entry exists and is in
3888        // the revoked state!
3889        match idms_prox_read
3890            .validate_client_auth_info_to_ident(uat_unverified.clone().into(), post_grace)
3891        {
3892            Err(OperationError::SessionExpired) => {}
3893            _ => panic!("Oh no"),
3894        }
3895        drop(idms_prox_read);
3896
3897        // Force trim the session out so that we can check the grate handling.
3898        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3899        let filt = filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(uat_inner.uuid)));
3900        let mut work_set = idms_prox_write
3901            .qs_write
3902            .internal_search_writeable(&filt)
3903            .expect("Failed to perform internal search writeable");
3904        for (_, entry) in work_set.iter_mut() {
3905            let _ = entry.force_trim_ava(Attribute::UserAuthTokenSession);
3906        }
3907        assert!(idms_prox_write
3908            .qs_write
3909            .internal_apply_writable(work_set)
3910            .is_ok());
3911
3912        assert!(idms_prox_write.commit().is_ok());
3913
3914        let mut idms_prox_read = idms.proxy_read().await.unwrap();
3915        idms_prox_read
3916            .validate_client_auth_info_to_ident(uat_unverified.clone().into(), ct)
3917            .expect("Failed to validate");
3918
3919        // post grace, it's not valid.
3920        match idms_prox_read
3921            .validate_client_auth_info_to_ident(uat_unverified.clone().into(), post_grace)
3922        {
3923            Err(OperationError::SessionExpired) => {}
3924            _ => panic!("Oh no"),
3925        }
3926    }
3927
3928    #[idm_test]
3929    async fn test_idm_account_session_expiry(
3930        idms: &IdmServer,
3931        _idms_delayed: &mut IdmServerDelayed,
3932    ) {
3933        let ct = Duration::from_secs(TEST_CURRENT_TIME);
3934
3935        //we first set the expiry to a custom value
3936        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3937
3938        let new_authsession_expiry = 1000;
3939
3940        let modlist = ModifyList::new_purge_and_set(
3941            Attribute::AuthSessionExpiry,
3942            Value::Uint32(new_authsession_expiry),
3943        );
3944        idms_prox_write
3945            .qs_write
3946            .internal_modify_uuid(UUID_IDM_ALL_ACCOUNTS, &modlist)
3947            .expect("Unable to change default session exp");
3948
3949        assert!(idms_prox_write.commit().is_ok());
3950
3951        // Start anonymous auth.
3952        let mut idms_auth = idms.auth().await.unwrap();
3953        // Send the initial auth event for initialising the session
3954        let anon_init = AuthEvent::anonymous_init();
3955        // Expect success
3956        let r1 = idms_auth
3957            .auth(&anon_init, ct, Source::Internal.into())
3958            .await;
3959        /* Some weird lifetime things happen here ... */
3960
3961        let sid = match r1 {
3962            Ok(ar) => {
3963                let AuthResult { sessionid, state } = ar;
3964                match state {
3965                    AuthState::Choose(mut conts) => {
3966                        // Should only be one auth mech
3967                        assert_eq!(conts.len(), 1);
3968                        // And it should be anonymous
3969                        let m = conts.pop().expect("Should not fail");
3970                        assert_eq!(m, AuthMech::Anonymous);
3971                    }
3972                    _ => {
3973                        error!("A critical error has occurred! We have a non-continue result!");
3974                        panic!();
3975                    }
3976                };
3977                // Now pass back the sessionid, we are good to continue.
3978                sessionid
3979            }
3980            Err(e) => {
3981                // Should not occur!
3982                error!("A critical error has occurred! {:?}", e);
3983                panic!();
3984            }
3985        };
3986
3987        idms_auth.commit().expect("Must not fail");
3988
3989        let mut idms_auth = idms.auth().await.unwrap();
3990        let anon_begin = AuthEvent::begin_mech(sid, AuthMech::Anonymous);
3991
3992        let r2 = idms_auth
3993            .auth(&anon_begin, ct, Source::Internal.into())
3994            .await;
3995
3996        match r2 {
3997            Ok(ar) => {
3998                let AuthResult {
3999                    sessionid: _,
4000                    state,
4001                } = ar;
4002
4003                match state {
4004                    AuthState::Continue(allowed) => {
4005                        // Check the uat.
4006                        assert_eq!(allowed.len(), 1);
4007                        assert_eq!(allowed.first(), Some(&AuthAllowed::Anonymous));
4008                    }
4009                    _ => {
4010                        error!("A critical error has occurred! We have a non-continue result!");
4011                        panic!();
4012                    }
4013                }
4014            }
4015            Err(e) => {
4016                error!("A critical error has occurred! {:?}", e);
4017                // Should not occur!
4018                panic!();
4019            }
4020        };
4021
4022        idms_auth.commit().expect("Must not fail");
4023
4024        let mut idms_auth = idms.auth().await.unwrap();
4025        // Now send the anonymous request, given the session id.
4026        let anon_step = AuthEvent::cred_step_anonymous(sid);
4027
4028        // Expect success
4029        let r2 = idms_auth
4030            .auth(&anon_step, ct, Source::Internal.into())
4031            .await;
4032
4033        let token = match r2 {
4034            Ok(ar) => {
4035                let AuthResult {
4036                    sessionid: _,
4037                    state,
4038                } = ar;
4039
4040                match state {
4041                    AuthState::Success(uat, AuthIssueSession::Token) => uat,
4042                    _ => {
4043                        error!("A critical error has occurred! We have a non-success result!");
4044                        panic!();
4045                    }
4046                }
4047            }
4048            Err(e) => {
4049                error!("A critical error has occurred! {:?}", e);
4050                // Should not occur!
4051                panic!("A critical error has occurred! {e:?}");
4052            }
4053        };
4054
4055        idms_auth.commit().expect("Must not fail");
4056
4057        // Token_str to uat
4058        // we have to do it this way because anonymous doesn't have an ideantity for which we cam get the expiry value
4059        let Token::UserAuthToken(uat) = idms
4060            .proxy_read()
4061            .await
4062            .unwrap()
4063            .validate_and_parse_token_to_identity_token(&token, ct)
4064            .expect("Must not fail")
4065        else {
4066            panic!("Unexpected auth token type for anonymous auth");
4067        };
4068
4069        debug!(?uat);
4070
4071        assert!(
4072            matches!(uat.expiry, Some(exp) if exp == OffsetDateTime::UNIX_EPOCH + ct + Duration::from_secs(new_authsession_expiry as u64))
4073        );
4074    }
4075
4076    #[idm_test]
4077    async fn test_idm_uat_claim_insertion(idms: &IdmServer, _idms_delayed: &mut IdmServerDelayed) {
4078        let ct = Duration::from_secs(TEST_CURRENT_TIME);
4079        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4080
4081        // get an account.
4082        let account = idms_prox_write
4083            .target_to_account(UUID_ADMIN)
4084            .expect("account must exist");
4085
4086        // Create some fake UATs, then process them and see what claims fall out 🥳
4087        let session_id = uuid::Uuid::new_v4();
4088
4089        // For the different auth types, check that we get the correct claims:
4090
4091        // == anonymous
4092        let uat = account
4093            .to_userauthtoken(
4094                session_id,
4095                SessionScope::ReadWrite,
4096                ct,
4097                &ResolvedAccountPolicy::test_policy(),
4098            )
4099            .expect("Unable to create uat");
4100        let ident = idms_prox_write
4101            .process_uat_to_identity(&uat, ct, Source::Internal)
4102            .expect("Unable to process uat");
4103
4104        assert!(!ident.has_claim("authtype_anonymous"));
4105        // Does NOT have this
4106        assert!(!ident.has_claim("authlevel_strong"));
4107        assert!(!ident.has_claim("authclass_single"));
4108        assert!(!ident.has_claim("authclass_mfa"));
4109
4110        // == unixpassword
4111        let uat = account
4112            .to_userauthtoken(
4113                session_id,
4114                SessionScope::ReadWrite,
4115                ct,
4116                &ResolvedAccountPolicy::test_policy(),
4117            )
4118            .expect("Unable to create uat");
4119        let ident = idms_prox_write
4120            .process_uat_to_identity(&uat, ct, Source::Internal)
4121            .expect("Unable to process uat");
4122
4123        assert!(!ident.has_claim("authtype_unixpassword"));
4124        assert!(!ident.has_claim("authclass_single"));
4125        // Does NOT have this
4126        assert!(!ident.has_claim("authlevel_strong"));
4127        assert!(!ident.has_claim("authclass_mfa"));
4128
4129        // == password
4130        let uat = account
4131            .to_userauthtoken(
4132                session_id,
4133                SessionScope::ReadWrite,
4134                ct,
4135                &ResolvedAccountPolicy::test_policy(),
4136            )
4137            .expect("Unable to create uat");
4138        let ident = idms_prox_write
4139            .process_uat_to_identity(&uat, ct, Source::Internal)
4140            .expect("Unable to process uat");
4141
4142        assert!(!ident.has_claim("authtype_password"));
4143        assert!(!ident.has_claim("authclass_single"));
4144        // Does NOT have this
4145        assert!(!ident.has_claim("authlevel_strong"));
4146        assert!(!ident.has_claim("authclass_mfa"));
4147
4148        // == generatedpassword
4149        let uat = account
4150            .to_userauthtoken(
4151                session_id,
4152                SessionScope::ReadWrite,
4153                ct,
4154                &ResolvedAccountPolicy::test_policy(),
4155            )
4156            .expect("Unable to create uat");
4157        let ident = idms_prox_write
4158            .process_uat_to_identity(&uat, ct, Source::Internal)
4159            .expect("Unable to process uat");
4160
4161        assert!(!ident.has_claim("authtype_generatedpassword"));
4162        assert!(!ident.has_claim("authclass_single"));
4163        assert!(!ident.has_claim("authlevel_strong"));
4164        // Does NOT have this
4165        assert!(!ident.has_claim("authclass_mfa"));
4166
4167        // == webauthn
4168        let uat = account
4169            .to_userauthtoken(
4170                session_id,
4171                SessionScope::ReadWrite,
4172                ct,
4173                &ResolvedAccountPolicy::test_policy(),
4174            )
4175            .expect("Unable to create uat");
4176        let ident = idms_prox_write
4177            .process_uat_to_identity(&uat, ct, Source::Internal)
4178            .expect("Unable to process uat");
4179
4180        assert!(!ident.has_claim("authtype_webauthn"));
4181        assert!(!ident.has_claim("authclass_single"));
4182        assert!(!ident.has_claim("authlevel_strong"));
4183        // Does NOT have this
4184        assert!(!ident.has_claim("authclass_mfa"));
4185
4186        // == passwordmfa
4187        let uat = account
4188            .to_userauthtoken(
4189                session_id,
4190                SessionScope::ReadWrite,
4191                ct,
4192                &ResolvedAccountPolicy::test_policy(),
4193            )
4194            .expect("Unable to create uat");
4195        let ident = idms_prox_write
4196            .process_uat_to_identity(&uat, ct, Source::Internal)
4197            .expect("Unable to process uat");
4198
4199        assert!(!ident.has_claim("authtype_passwordmfa"));
4200        assert!(!ident.has_claim("authlevel_strong"));
4201        assert!(!ident.has_claim("authclass_mfa"));
4202        // Does NOT have this
4203        assert!(!ident.has_claim("authclass_single"));
4204    }
4205
4206    #[idm_test]
4207    async fn test_idm_uat_limits_account_policy(
4208        idms: &IdmServer,
4209        _idms_delayed: &mut IdmServerDelayed,
4210    ) {
4211        let ct = Duration::from_secs(TEST_CURRENT_TIME);
4212        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4213
4214        idms_prox_write
4215            .qs_write
4216            .internal_create(vec![E_TESTPERSON_1.clone()])
4217            .expect("Failed to create test person");
4218
4219        // get an account.
4220        let account = idms_prox_write
4221            .target_to_account(UUID_TESTPERSON_1)
4222            .expect("account must exist");
4223
4224        // Create a fake UATs
4225        let session_id = uuid::Uuid::new_v4();
4226
4227        let uat = account
4228            .to_userauthtoken(
4229                session_id,
4230                SessionScope::ReadWrite,
4231                ct,
4232                &ResolvedAccountPolicy::test_policy(),
4233            )
4234            .expect("Unable to create uat");
4235
4236        let ident = idms_prox_write
4237            .process_uat_to_identity(&uat, ct, Source::Internal)
4238            .expect("Unable to process uat");
4239
4240        assert_eq!(
4241            ident.limits().search_max_results,
4242            DEFAULT_LIMIT_SEARCH_MAX_RESULTS as usize
4243        );
4244        assert_eq!(
4245            ident.limits().search_max_filter_test,
4246            DEFAULT_LIMIT_SEARCH_MAX_FILTER_TEST as usize
4247        );
4248    }
4249
4250    #[idm_test]
4251    async fn test_idm_jwt_uat_token_key_reload(
4252        idms: &IdmServer,
4253        idms_delayed: &mut IdmServerDelayed,
4254    ) {
4255        let ct = duration_from_epoch_now();
4256
4257        init_testperson_w_password(idms, TEST_PASSWORD)
4258            .await
4259            .expect("Failed to setup admin account");
4260        let token = check_testperson_password(idms, TEST_PASSWORD, ct).await;
4261
4262        // Clear the session record
4263        let da = idms_delayed.try_recv().expect("invalid");
4264        assert!(matches!(da, DelayedAction::AuthSessionRecord(_)));
4265        idms_delayed.check_is_empty_or_panic();
4266
4267        let mut idms_prox_read = idms.proxy_read().await.unwrap();
4268
4269        // Check it's valid.
4270        idms_prox_read
4271            .validate_client_auth_info_to_ident(token.clone().into(), ct)
4272            .expect("Failed to validate");
4273
4274        drop(idms_prox_read);
4275
4276        // We need to get the token key id and revoke it.
4277        let revoke_kid = token.kid().expect("token does not contain a key id");
4278
4279        // Now revoke the token_key
4280        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4281        let me_reset_tokens = ModifyEvent::new_internal_invalid(
4282            filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(UUID_DOMAIN_INFO))),
4283            ModifyList::new_append(
4284                Attribute::KeyActionRevoke,
4285                Value::HexString(revoke_kid.to_string()),
4286            ),
4287        );
4288        assert!(idms_prox_write.qs_write.modify(&me_reset_tokens).is_ok());
4289        assert!(idms_prox_write.commit().is_ok());
4290
4291        let new_token = check_testperson_password(idms, TEST_PASSWORD, ct).await;
4292
4293        // Clear the session record
4294        let da = idms_delayed.try_recv().expect("invalid");
4295        assert!(matches!(da, DelayedAction::AuthSessionRecord(_)));
4296        idms_delayed.check_is_empty_or_panic();
4297
4298        let mut idms_prox_read = idms.proxy_read().await.unwrap();
4299
4300        // Check the old token is invalid, due to reload.
4301        assert!(idms_prox_read
4302            .validate_client_auth_info_to_ident(token.into(), ct)
4303            .is_err());
4304
4305        // A new token will work due to the matching key.
4306        idms_prox_read
4307            .validate_client_auth_info_to_ident(new_token.into(), ct)
4308            .expect("Failed to validate");
4309    }
4310
4311    #[idm_test]
4312    async fn test_idm_service_account_to_person(
4313        idms: &IdmServer,
4314        _idms_delayed: &mut IdmServerDelayed,
4315    ) {
4316        let ct = Duration::from_secs(TEST_CURRENT_TIME);
4317        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4318
4319        let ident = Identity::from_internal();
4320        let target_uuid = Uuid::new_v4();
4321
4322        // Create a service account
4323        let e = entry_init!(
4324            (Attribute::Class, EntryClass::Object.to_value()),
4325            (Attribute::Class, EntryClass::Account.to_value()),
4326            (Attribute::Class, EntryClass::ServiceAccount.to_value()),
4327            (Attribute::Name, Value::new_iname("testaccount")),
4328            (Attribute::Uuid, Value::Uuid(target_uuid)),
4329            (Attribute::Description, Value::new_utf8s("testaccount")),
4330            (Attribute::DisplayName, Value::new_utf8s("Test Account"))
4331        );
4332
4333        let ce = CreateEvent::new_internal(vec![e]);
4334        let cr = idms_prox_write.qs_write.create(&ce);
4335        assert!(cr.is_ok());
4336
4337        // Do the migrate.
4338        assert!(idms_prox_write
4339            .service_account_into_person(&ident, target_uuid)
4340            .is_ok());
4341
4342        // Any checks?
4343    }
4344
4345    async fn idm_fallback_auth_fixture(
4346        idms: &IdmServer,
4347        _idms_delayed: &mut IdmServerDelayed,
4348        has_posix_password: bool,
4349        allow_primary_cred_fallback: Option<bool>,
4350        expected: Option<()>,
4351    ) {
4352        let ct = Duration::from_secs(TEST_CURRENT_TIME);
4353        let target_uuid = Uuid::new_v4();
4354        let p = CryptoPolicy::minimum();
4355
4356        {
4357            let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4358
4359            if let Some(allow_primary_cred_fallback) = allow_primary_cred_fallback {
4360                idms_prox_write
4361                    .qs_write
4362                    .internal_modify_uuid(
4363                        UUID_IDM_ALL_ACCOUNTS,
4364                        &ModifyList::new_purge_and_set(
4365                            Attribute::AllowPrimaryCredFallback,
4366                            Value::new_bool(allow_primary_cred_fallback),
4367                        ),
4368                    )
4369                    .expect("Unable to change default session exp");
4370            }
4371
4372            let mut e = entry_init!(
4373                (Attribute::Class, EntryClass::Object.to_value()),
4374                (Attribute::Class, EntryClass::Account.to_value()),
4375                (Attribute::Class, EntryClass::Person.to_value()),
4376                (Attribute::Uuid, Value::Uuid(target_uuid)),
4377                (Attribute::Name, Value::new_iname("kevin")),
4378                (Attribute::DisplayName, Value::new_utf8s("Kevin")),
4379                (Attribute::Class, EntryClass::PosixAccount.to_value()),
4380                (
4381                    Attribute::PrimaryCredential,
4382                    Value::Cred(
4383                        "primary".to_string(),
4384                        Credential::new_password_only(&p, "banana", OffsetDateTime::UNIX_EPOCH)
4385                            .unwrap()
4386                    )
4387                )
4388            );
4389
4390            if has_posix_password {
4391                e.add_ava(
4392                    Attribute::UnixPassword,
4393                    Value::Cred(
4394                        "unix".to_string(),
4395                        Credential::new_password_only(&p, "kampai", OffsetDateTime::UNIX_EPOCH)
4396                            .unwrap(),
4397                    ),
4398                );
4399            }
4400
4401            let ce = CreateEvent::new_internal(vec![e]);
4402            let cr = idms_prox_write.qs_write.create(&ce);
4403            assert!(cr.is_ok());
4404            idms_prox_write.commit().expect("Must not fail");
4405        }
4406
4407        let result = idms
4408            .auth()
4409            .await
4410            .unwrap()
4411            .auth_ldap(
4412                &LdapAuthEvent {
4413                    target: target_uuid,
4414                    cleartext: if has_posix_password {
4415                        "kampai".to_string()
4416                    } else {
4417                        "banana".to_string()
4418                    },
4419                },
4420                ct,
4421            )
4422            .await;
4423
4424        assert!(result.is_ok());
4425        if expected.is_some() {
4426            assert!(result.unwrap().is_some());
4427        } else {
4428            assert!(result.unwrap().is_none());
4429        }
4430    }
4431
4432    #[idm_test]
4433    async fn test_idm_fallback_auth_no_pass_none_fallback(
4434        idms: &IdmServer,
4435        _idms_delayed: &mut IdmServerDelayed,
4436    ) {
4437        idm_fallback_auth_fixture(idms, _idms_delayed, false, None, None).await;
4438    }
4439    #[idm_test]
4440    async fn test_idm_fallback_auth_pass_none_fallback(
4441        idms: &IdmServer,
4442        _idms_delayed: &mut IdmServerDelayed,
4443    ) {
4444        idm_fallback_auth_fixture(idms, _idms_delayed, true, None, Some(())).await;
4445    }
4446    #[idm_test]
4447    async fn test_idm_fallback_auth_no_pass_true_fallback(
4448        idms: &IdmServer,
4449        _idms_delayed: &mut IdmServerDelayed,
4450    ) {
4451        idm_fallback_auth_fixture(idms, _idms_delayed, false, Some(true), Some(())).await;
4452    }
4453    #[idm_test]
4454    async fn test_idm_fallback_auth_pass_true_fallback(
4455        idms: &IdmServer,
4456        _idms_delayed: &mut IdmServerDelayed,
4457    ) {
4458        idm_fallback_auth_fixture(idms, _idms_delayed, true, Some(true), Some(())).await;
4459    }
4460    #[idm_test]
4461    async fn test_idm_fallback_auth_no_pass_false_fallback(
4462        idms: &IdmServer,
4463        _idms_delayed: &mut IdmServerDelayed,
4464    ) {
4465        idm_fallback_auth_fixture(idms, _idms_delayed, false, Some(false), None).await;
4466    }
4467    #[idm_test]
4468    async fn test_idm_fallback_auth_pass_false_fallback(
4469        idms: &IdmServer,
4470        _idms_delayed: &mut IdmServerDelayed,
4471    ) {
4472        idm_fallback_auth_fixture(idms, _idms_delayed, true, Some(false), Some(())).await;
4473    }
4474}