Skip to main content

kaniop_person/
reconcile.rs

1use crate::controller::Context;
2use crate::crd::{KanidmPersonAccount, KanidmPersonAccountStatus, KanidmPersonAttributes};
3
4use kaniop_k8s_util::error::{Error, Result};
5use kaniop_operator::controller::kanidm::{KanidmResource, is_resource_watched};
6use kaniop_operator::controller::{context::IdmClientContext, idm_reconcile_interval};
7use kaniop_operator::crd::KanidmAccountPosixAttributes;
8use kaniop_operator::metrics::{
9    KANIDM_OP_CREATE, KANIDM_OP_CREDENTIAL_UPDATE_INTENT, KANIDM_OP_DELETE, KANIDM_OP_GET,
10    KANIDM_OP_GET_CREDENTIAL_STATUS, KANIDM_OP_UNIX_EXTEND, KANIDM_OP_UPDATE,
11    KANIDM_OUTCOME_CHANGED, KANIDM_OUTCOME_ERROR, KANIDM_OUTCOME_UNCHANGED, KANIDM_RESOURCE_PERSON,
12    record_kanidm_sdk_call,
13};
14use kaniop_operator::telemetry;
15
16use std::collections::BTreeMap;
17use std::ops::Not;
18use std::sync::Arc;
19use std::time::Duration;
20
21use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, Time};
22use k8s_openapi::jiff::Timestamp;
23use kanidm_client::{ClientError, KanidmClient};
24use kanidm_proto::constants::{ATTR_ACCOUNT_EXPIRE, ATTR_ACCOUNT_VALID_FROM};
25use kanidm_proto::internal::CUStatus;
26use kanidm_proto::v1::Entry;
27use kube::api::{Api, Patch, PatchParams};
28use kube::runtime::controller::Action;
29use kube::runtime::events::{Event, EventType};
30use kube::runtime::finalizer::{Error as FinalizerError, Event as Finalizer, finalizer};
31use kube::runtime::reflector::ObjectRef;
32use kube::{Resource, ResourceExt};
33use time::format_description::well_known::Rfc3339;
34use time::{OffsetDateTime, UtcOffset};
35use tracing::{Span, debug, field, info, instrument, trace, warn};
36
37pub static PERSON_OPERATOR_NAME: &str = "kanidmpersonsaccounts.kaniop.rs";
38pub static PERSON_FINALIZER: &str = "kanidmpersonsaccounts.kaniop.rs/finalizer";
39
40const TYPE_CREDENTIAL: &str = "Credential";
41const TYPE_EXISTS: &str = "Exists";
42const TYPE_UPDATED: &str = "Updated";
43const TYPE_POSIX_INITIALIZED: &str = "PosixInitialized";
44const TYPE_POSIX_UPDATED: &str = "PosixUpdated";
45const TYPE_VALIDITY: &str = "Valid";
46const REASON_ATTRIBUTES_MATCH: &str = "AttributesMatch";
47const REASON_ATTRIBUTES_NOT_MATCH: &str = "AttributesNotMatch";
48const CONDITION_TRUE: &str = "True";
49const CONDITION_FALSE: &str = "False";
50
51fn credential_update_status_has_credentials(status: &CUStatus) -> bool {
52    status.primary.is_some()
53        || status.passkeys.is_empty().not()
54        || status.attested_passkeys.is_empty().not()
55}
56
57pub async fn watched_resource(person: &KanidmPersonAccount, ctx: Arc<Context>) -> bool {
58    let kanidm = if let Some(k) = ctx.kaniop_ctx.get_kanidm(person) {
59        k
60    } else {
61        trace!("no kanidm found");
62        return false;
63    };
64
65    is_resource_watched(
66        person,
67        &kanidm,
68        &ctx.kaniop_ctx.namespace_store,
69        &ctx.kaniop_ctx.client,
70    )
71    .await
72}
73
74#[instrument(skip(ctx, person))]
75pub async fn reconcile_person_account(
76    person: Arc<KanidmPersonAccount>,
77    ctx: Arc<Context>,
78) -> Result<(Action, bool)> {
79    let trace_id = telemetry::get_trace_id();
80    Span::current().record("trace_id", field::display(&trace_id));
81    let _timer = ctx
82        .kaniop_ctx
83        .metrics
84        .reconcile_count_and_measure(&trace_id);
85    if !ctx.kaniop_ctx.kanidm_write_allowed(&person) {
86        debug!("Kanidm restore in progress, pausing identity writes");
87        return Ok((Action::requeue(Duration::from_secs(5)), false));
88    }
89    let kanidm_client = ctx.get_idm_client(&person).await?;
90
91    if !watched_resource(&person, ctx.clone()).await {
92        debug!("resource not watched, skipping reconcile");
93        ctx.kaniop_ctx
94            .recorder
95            .publish(
96                &Event {
97                    type_: EventType::Warning,
98                    reason: "ResourceNotWatched".to_string(),
99                    note: Some("configure `personNamespaceSelector` on Kanidm resource to watch this namespace".to_string()),
100                    action: "Reconcile".to_string(),
101                    secondary: None,
102                },
103                &person.object_ref(&()),
104            )
105            .await
106            .map_err(|e| {
107                warn!(error = %e, "failed to publish ResourceNotWatched event");
108                Error::kube_error("publish", "event", person.get_namespace(), person.name_any(), e)
109            })?;
110        return Ok((Action::requeue(idm_reconcile_interval()), false));
111    }
112    info!("reconciling person account");
113
114    let namespace = person.get_namespace();
115    let status = person
116        .update_status(kanidm_client.clone(), ctx.clone())
117        .await
118        .map_err(|e| {
119            debug!(error = %e, "failed to reconcile status");
120            ctx.kaniop_ctx.metrics.status_update_errors_inc();
121            e
122        })?;
123    let persons_api: Api<KanidmPersonAccount> =
124        Api::namespaced(ctx.kaniop_ctx.client.clone(), &namespace);
125    let outcome = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
126    let outcome_clone = outcome.clone();
127    let action = finalizer(&persons_api, PERSON_FINALIZER, person, move |event| {
128        let outcome = outcome_clone.clone();
129        let ctx = ctx.clone();
130        let status = status.clone();
131        let kanidm_client = kanidm_client.clone();
132        async move {
133            match event {
134                Finalizer::Apply(p) => {
135                    let (action, changed) = p.reconcile(kanidm_client, status, ctx).await?;
136                    outcome.store(changed, std::sync::atomic::Ordering::Relaxed);
137                    Ok(action)
138                }
139                Finalizer::Cleanup(p) => {
140                    let (action, changed) = p.cleanup(kanidm_client, status, ctx).await?;
141                    outcome.store(changed, std::sync::atomic::Ordering::Relaxed);
142                    Ok(action)
143                }
144            }
145        }
146    })
147    .await
148    .or_else(|e| match e {
149        FinalizerError::RemoveFinalizer(kube::Error::Api(ae)) if ae.code == 404 => {
150            debug!("resource already removed during finalizer cleanup");
151            Ok(Action::requeue(idm_reconcile_interval()))
152        }
153        _ => Err(Error::FinalizerError(
154            "failed on person account finalizer".to_string(),
155            Box::new(e),
156        )),
157    })?;
158    let changed = outcome.load(std::sync::atomic::Ordering::Relaxed);
159    Ok((action, changed))
160}
161
162impl KanidmPersonAccount {
163    #[inline]
164    fn get_namespace(&self) -> String {
165        // safe unwrap: person is namespaced scoped
166        self.namespace().unwrap()
167    }
168
169    #[inline]
170    async fn reconcile(
171        &self,
172        kanidm_client: Arc<KanidmClient>,
173        status: KanidmPersonAccountStatus,
174        ctx: Arc<Context>,
175    ) -> Result<(Action, bool)> {
176        match self
177            .internal_reconcile(kanidm_client, status, ctx.clone())
178            .await
179        {
180            Ok(result) => Ok(result),
181            Err(e) => match e {
182                Error::KanidmClientError(_, _) => {
183                    ctx.kaniop_ctx
184                        .recorder
185                        .publish(
186                            &Event {
187                                type_: EventType::Warning,
188                                reason: "KanidmError".to_string(),
189                                note: Some(format!("{e:?}")),
190                                action: "KanidmRequest".to_string(),
191                                secondary: None,
192                            },
193                            &self.object_ref(&()),
194                        )
195                        .await
196                        .map_err(|e| {
197                            warn!(error = %e, "failed to publish KanidmError event");
198                            Error::kube_error(
199                                "publish",
200                                "event",
201                                self.get_namespace(),
202                                self.name_any(),
203                                e,
204                            )
205                        })?;
206                    Err(e)
207                }
208                _ => Err(e),
209            },
210        }
211    }
212
213    async fn internal_reconcile(
214        &self,
215        kanidm_client: Arc<KanidmClient>,
216        status: KanidmPersonAccountStatus,
217        ctx: Arc<Context>,
218    ) -> Result<(Action, bool)> {
219        let name = &self.kanidm_entity_name();
220        let metrics = &ctx.kaniop_ctx.metrics;
221
222        let mut require_status_update = false;
223        let mut changed = false;
224        let mut actions = Vec::new();
225        if is_person_false(TYPE_EXISTS, status.clone()) {
226            debug!(
227                condition = TYPE_EXISTS,
228                status = CONDITION_FALSE,
229                action = "create",
230                "condition triggered action"
231            );
232            record_kanidm_sdk_call(
233                metrics,
234                KANIDM_RESOURCE_PERSON,
235                KANIDM_OP_CREATE,
236                KANIDM_OUTCOME_CHANGED,
237                self.create(&kanidm_client, name),
238            )
239            .await?;
240            require_status_update = true;
241            changed = true;
242            actions.push("create");
243        }
244        if is_person_false(TYPE_UPDATED, status.clone()) {
245            debug!(
246                condition = TYPE_UPDATED,
247                status = CONDITION_FALSE,
248                action = "update",
249                "condition triggered action"
250            );
251            self.update(&kanidm_client, name, metrics).await?;
252            require_status_update = true;
253            changed = true;
254            actions.push("update");
255        }
256
257        if is_person_false(TYPE_POSIX_UPDATED, status.clone())
258            || (is_person_false(TYPE_POSIX_INITIALIZED, status.clone())
259                && is_person(TYPE_POSIX_UPDATED, status.clone()))
260        {
261            debug!(
262                condition = TYPE_POSIX_UPDATED,
263                status = CONDITION_FALSE,
264                action = "update_posix_attributes",
265                "condition triggered action"
266            );
267            record_kanidm_sdk_call(
268                metrics,
269                KANIDM_RESOURCE_PERSON,
270                KANIDM_OP_UNIX_EXTEND,
271                KANIDM_OUTCOME_CHANGED,
272                self.update_posix_attributes(&kanidm_client, name),
273            )
274            .await?;
275            require_status_update = true;
276            changed = true;
277            actions.push("update_posix");
278        }
279
280        if is_person_false(TYPE_CREDENTIAL, status) {
281            let create_token = match ctx.internal_cache.read().await.get(&ObjectRef::from(self)) {
282                Some(expiry) if expiry > &OffsetDateTime::now_utc() => {
283                    trace!("token not expired, skipping creation");
284                    false
285                }
286                _ => true,
287            };
288            if create_token {
289                debug!(
290                    condition = TYPE_CREDENTIAL,
291                    status = CONDITION_FALSE,
292                    action = "create_reset_token",
293                    "condition triggered action"
294                );
295                record_kanidm_sdk_call(
296                    metrics,
297                    KANIDM_RESOURCE_PERSON,
298                    KANIDM_OP_CREDENTIAL_UPDATE_INTENT,
299                    KANIDM_OUTCOME_CHANGED,
300                    self.create_reset_token(&kanidm_client, name, ctx.clone()),
301                )
302                .await?;
303                changed = true;
304            };
305        };
306
307        if require_status_update {
308            debug!(actions = ?actions, "requeueing in 500ms after actions");
309            Ok((Action::requeue(Duration::from_millis(500)), changed))
310        } else {
311            debug!("reconciliation complete, requeueing for next interval");
312            Ok((Action::requeue(idm_reconcile_interval()), changed))
313        }
314    }
315
316    async fn create(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
317        debug!("create");
318        kanidm_client
319            .idm_person_account_create(name, &self.spec.person_attributes.displayname)
320            .await
321            .map_err(|e| {
322                Error::kanidm_client_error(
323                    "create",
324                    name,
325                    self.kanidm_namespace(),
326                    self.kanidm_name(),
327                    e,
328                )
329            })?;
330        Ok(())
331    }
332
333    async fn update(
334        &self,
335        kanidm_client: &KanidmClient,
336        name: &str,
337        metrics: &kaniop_operator::metrics::ControllerMetrics,
338    ) -> Result<()> {
339        debug!("update");
340        trace!(person_attributes = ?self.spec.person_attributes, "updating person attributes");
341        record_kanidm_sdk_call(
342            metrics,
343            KANIDM_RESOURCE_PERSON,
344            KANIDM_OP_UPDATE,
345            KANIDM_OUTCOME_CHANGED,
346            kanidm_client.idm_person_account_update(
347                name,
348                None,
349                Some(&self.spec.person_attributes.displayname),
350                self.spec.person_attributes.legalname.as_deref(),
351                self.spec.person_attributes.mail.as_deref(),
352            ),
353        )
354        .await
355        .map_err(|e| {
356            Error::kanidm_client_error(
357                "update",
358                name,
359                self.kanidm_namespace(),
360                self.kanidm_name(),
361                e,
362            )
363        })?;
364        let mut update_entry = Entry {
365            attrs: BTreeMap::new(),
366        };
367        if let Some(account_expire) = self.spec.person_attributes.account_expire.as_ref() {
368            update_entry.attrs.insert(
369                ATTR_ACCOUNT_EXPIRE.to_string(),
370                vec![account_expire.0.to_string()],
371            );
372        }
373        if let Some(account_valid_from) = self.spec.person_attributes.account_valid_from.as_ref() {
374            update_entry.attrs.insert(
375                ATTR_ACCOUNT_VALID_FROM.to_string(),
376                vec![account_valid_from.0.to_string()],
377            );
378        }
379
380        if update_entry.attrs.is_empty().not() {
381            let _: Entry = record_kanidm_sdk_call(
382                metrics,
383                KANIDM_RESOURCE_PERSON,
384                KANIDM_OP_UPDATE,
385                KANIDM_OUTCOME_CHANGED,
386                kanidm_client.perform_patch_request(&format!("/v1/person/{name}"), update_entry),
387            )
388            .await
389            .map_err(|e| {
390                Error::kanidm_client_error(
391                    "update",
392                    name,
393                    self.kanidm_namespace(),
394                    self.kanidm_name(),
395                    e,
396                )
397            })?;
398        }
399        Ok(())
400    }
401
402    async fn update_posix_attributes(
403        &self,
404        kanidm_client: &KanidmClient,
405        name: &str,
406    ) -> Result<()> {
407        debug!("updating posix attributes");
408        trace!(posix_attributes = ?self.spec.posix_attributes, "updating posix attributes");
409        kanidm_client
410            .idm_person_account_unix_extend(
411                name,
412                self.spec
413                    .posix_attributes
414                    .as_ref()
415                    .and_then(|posix| posix.gidnumber),
416                self.spec
417                    .posix_attributes
418                    .as_ref()
419                    .and_then(|posix| posix.loginshell.as_deref()),
420            )
421            .await
422            .map_err(|e| {
423                Error::kanidm_client_error(
424                    "update",
425                    name,
426                    self.kanidm_namespace(),
427                    self.kanidm_name(),
428                    e,
429                )
430            })?;
431        Ok(())
432    }
433
434    async fn create_reset_token(
435        &self,
436        kanidm_client: &KanidmClient,
437        name: &str,
438        ctx: Arc<Context>,
439    ) -> Result<()> {
440        debug!("create reset token");
441        let cu_token = kanidm_client
442            .idm_person_account_credential_update_intent(
443                name,
444                Some(self.spec.credentials_token_ttl),
445            )
446            .await
447            .map_err(|e| {
448                Error::kanidm_client_error(
449                    "create a credential reset token for",
450                    name,
451                    self.kanidm_namespace(),
452                    self.kanidm_name(),
453                    e,
454                )
455            })?;
456        let token = cu_token.token.as_str();
457        let url = if let Some(base_url) = ctx.kaniop_ctx.get_kanidm(self).map(|k| {
458            k.spec
459                .origin
460                .clone()
461                .unwrap_or_else(|| format!("https://{}", k.spec.domain))
462        }) {
463            format!("{base_url}/ui/reset?token={token}")
464        } else {
465            let mut url = kanidm_client.make_url("/ui/reset");
466            url.query_pairs_mut().append_pair("token", token);
467            url.to_string()
468        };
469        let local_offset = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
470        let expiry_time = cu_token.expiry_time.to_offset(local_offset);
471
472        let msg = format!(
473            "Update these user credentials with this link: {url}. This token will expire at: {}",
474            expiry_time
475                .format(&Rfc3339)
476                .unwrap_or_else(|_| expiry_time.to_string())
477        );
478        ctx.kaniop_ctx
479            .recorder
480            .publish(
481                &Event {
482                    type_: EventType::Normal,
483                    reason: "TokenCreated".to_string(),
484                    note: Some(msg),
485                    action: "CreateUpdateCredentialsToken".into(),
486                    secondary: None,
487                },
488                &self.object_ref(&()),
489            )
490            .await
491            .map_err(|e| {
492                warn!(error = %e, "failed to publish TokenCreated event");
493                Error::kube_error("publish", "event", self.get_namespace(), self.name_any(), e)
494            })?;
495        ctx.internal_cache
496            .write()
497            .await
498            .insert(ObjectRef::from(self), expiry_time);
499        Ok(())
500    }
501
502    async fn cleanup(
503        &self,
504        kanidm_client: Arc<KanidmClient>,
505        status: KanidmPersonAccountStatus,
506        ctx: Arc<Context>,
507    ) -> Result<(Action, bool)> {
508        let name = &self.kanidm_entity_name();
509        let mut changed = false;
510
511        if is_person(TYPE_EXISTS, status.clone()) {
512            debug!("delete");
513            record_kanidm_sdk_call(
514                &ctx.kaniop_ctx.metrics,
515                KANIDM_RESOURCE_PERSON,
516                KANIDM_OP_DELETE,
517                KANIDM_OUTCOME_CHANGED,
518                kanidm_client.idm_person_account_delete(name),
519            )
520            .await
521            .map_err(|e| {
522                Error::kanidm_client_error(
523                    "delete",
524                    name,
525                    self.kanidm_namespace(),
526                    self.kanidm_name(),
527                    e,
528                )
529            })?;
530            changed = true;
531
532            ctx.internal_cache
533                .write()
534                .await
535                .remove(&ObjectRef::from(self));
536        }
537        Ok((Action::requeue(idm_reconcile_interval()), changed))
538    }
539
540    async fn update_status(
541        &self,
542        kanidm_client: Arc<KanidmClient>,
543        ctx: Arc<Context>,
544    ) -> Result<KanidmPersonAccountStatus> {
545        // safe unwrap: person is namespaced scoped
546        let namespace = self.get_namespace();
547        let name = self.kanidm_entity_name();
548        let metrics = &ctx.kaniop_ctx.metrics;
549        let start = tokio::time::Instant::now();
550        let current_person = kanidm_client
551            .idm_person_account_get(&name)
552            .await
553            .map_err(|e| {
554                let elapsed = start.elapsed();
555                metrics.record_kanidm_sdk_outcome(
556                    KANIDM_RESOURCE_PERSON,
557                    KANIDM_OP_GET,
558                    KANIDM_OUTCOME_ERROR,
559                    elapsed,
560                );
561                Error::kanidm_client_error(
562                    "get",
563                    name.as_str(),
564                    self.kanidm_namespace(),
565                    self.kanidm_name(),
566                    e,
567                )
568            })?;
569        metrics.record_kanidm_sdk_outcome(
570            KANIDM_RESOURCE_PERSON,
571            KANIDM_OP_GET,
572            KANIDM_OUTCOME_UNCHANGED,
573            start.elapsed(),
574        );
575        let cred_start = tokio::time::Instant::now();
576        let credential_present = match kanidm_client
577            .idm_person_account_get_credential_status(&name)
578            .await
579        {
580            Ok(cs) => {
581                let present = cs.creds.is_empty().not();
582                trace!(
583                    credential_present = present,
584                    creds_count = cs.creds.len(),
585                    "credential status"
586                );
587                metrics.record_kanidm_sdk_outcome(
588                    KANIDM_RESOURCE_PERSON,
589                    KANIDM_OP_GET_CREDENTIAL_STATUS,
590                    KANIDM_OUTCOME_UNCHANGED,
591                    cred_start.elapsed(),
592                );
593                Some(present)
594            }
595            Err(ClientError::EmptyResponse) => {
596                // Kanidm's legacy credential status endpoint only reports the primary
597                // credential. Passkey-only accounts therefore return EmptyResponse
598                // (https://github.com/kanidm/kanidm/issues/3090). Inspect the complete
599                // credential-update status before deciding that credentials are absent.
600                match kanidm_client
601                    .idm_account_credential_update_begin(&name)
602                    .await
603                {
604                    Ok((session_token, status)) => {
605                        let present = credential_update_status_has_credentials(&status);
606                        trace!(
607                            credential_present = present,
608                            primary_present = status.primary.is_some(),
609                            passkeys_count = status.passkeys.len(),
610                            attested_passkeys_count = status.attested_passkeys.len(),
611                            "credential status fallback"
612                        );
613
614                        let cancel_result: std::result::Result<(), ClientError> = kanidm_client
615                            .perform_post_request("/v1/credential/_cancel", session_token)
616                            .await;
617                        if let Err(e) = cancel_result {
618                            warn!(
619                                error = ?e,
620                                "failed to cancel credential status fallback session"
621                            );
622                        }
623
624                        metrics.record_kanidm_sdk_outcome(
625                            KANIDM_RESOURCE_PERSON,
626                            KANIDM_OP_GET_CREDENTIAL_STATUS,
627                            KANIDM_OUTCOME_UNCHANGED,
628                            cred_start.elapsed(),
629                        );
630                        Some(present)
631                    }
632                    Err(e) => {
633                        trace!(error = ?e, "credential status fallback error");
634                        metrics.record_kanidm_sdk_outcome(
635                            KANIDM_RESOURCE_PERSON,
636                            KANIDM_OP_GET_CREDENTIAL_STATUS,
637                            KANIDM_OUTCOME_ERROR,
638                            cred_start.elapsed(),
639                        );
640                        None
641                    }
642                }
643            }
644            Err(e) => {
645                trace!(error = ?e, "credential status error");
646                metrics.record_kanidm_sdk_outcome(
647                    KANIDM_RESOURCE_PERSON,
648                    KANIDM_OP_GET_CREDENTIAL_STATUS,
649                    KANIDM_OUTCOME_ERROR,
650                    cred_start.elapsed(),
651                );
652                None
653            }
654        };
655
656        let status = self.generate_status(current_person, credential_present)?;
657        if self.status.as_ref() == Some(&status) {
658            trace!("status unchanged, skipping patch");
659            return Ok(status);
660        }
661        if let Some(old) = self.status.as_ref() {
662            let old_conds: Vec<_> = old
663                .conditions
664                .iter()
665                .flatten()
666                .map(|c| format!("{}={}", c.type_, c.status))
667                .collect();
668            let new_conds: Vec<_> = status
669                .conditions
670                .iter()
671                .flatten()
672                .map(|c| format!("{}={}", c.type_, c.status))
673                .collect();
674            debug!(old = ?old_conds, new = ?new_conds, old_ready = old.ready, new_ready = status.ready, "status changed");
675        } else {
676            debug!(conditions = ?status.conditions, "initial status patch");
677        }
678        let status_patch = Patch::Apply(KanidmPersonAccount {
679            status: Some(status.clone()),
680            ..KanidmPersonAccount::default()
681        });
682        debug!("updating status");
683        trace!(status_patch = ?status_patch, "status patch");
684        let patch = PatchParams::apply(PERSON_OPERATOR_NAME).force();
685        let kanidm_api =
686            Api::<KanidmPersonAccount>::namespaced(ctx.kaniop_ctx.client.clone(), &namespace);
687        let _o = kanidm_api
688            .patch_status(&self.name_any(), &patch, &status_patch)
689            .await
690            .map_err(|e| {
691                Error::kube_status_error("KanidmPersonAccount", namespace, self.name_any(), e)
692            })?;
693        Ok(status)
694    }
695
696    fn generate_status(
697        &self,
698        person: Option<Entry>,
699        credential_present: Option<bool>,
700    ) -> Result<KanidmPersonAccountStatus> {
701        let now = Timestamp::now();
702        let current_conditions = self.status.as_ref().and_then(|s| s.conditions.as_ref());
703
704        // Helper function to determine the last transition time
705        fn last_transition_time(
706            current_conditions: Option<&Vec<Condition>>,
707            type_: &str,
708            new_status: &str,
709            new_reason: &str,
710        ) -> Time {
711            let now_time = Time(Timestamp::now());
712            if let Some(conditions) = current_conditions {
713                for c in conditions {
714                    if c.type_ == type_ && c.status == new_status && c.reason == new_reason {
715                        return c.last_transition_time.clone();
716                    }
717                }
718            }
719            now_time
720        }
721
722        match person {
723            Some(p) => {
724                let exist_condition = Condition {
725                    type_: TYPE_EXISTS.to_string(),
726                    status: CONDITION_TRUE.to_string(),
727                    reason: "Exists".to_string(),
728                    message: "Person exists.".to_string(),
729                    last_transition_time: last_transition_time(
730                        current_conditions,
731                        TYPE_EXISTS,
732                        CONDITION_TRUE,
733                        "Exists",
734                    ),
735                    observed_generation: self.metadata.generation,
736                };
737
738                let current_person_attributes = KanidmPersonAttributes::from(p.clone());
739                let updated_condition = if self.spec.person_attributes == current_person_attributes
740                {
741                    Condition {
742                        type_: TYPE_UPDATED.to_string(),
743                        status: CONDITION_TRUE.to_string(),
744                        reason: REASON_ATTRIBUTES_MATCH.to_string(),
745                        message: "Person exists with desired attributes.".to_string(),
746                        last_transition_time: last_transition_time(
747                            current_conditions,
748                            TYPE_UPDATED,
749                            CONDITION_TRUE,
750                            REASON_ATTRIBUTES_MATCH,
751                        ),
752                        observed_generation: self.metadata.generation,
753                    }
754                } else {
755                    let spec = &self.spec.person_attributes;
756                    debug!(
757                        displayname_spec = %spec.displayname,
758                        displayname_actual = %current_person_attributes.displayname,
759                        mail_spec = ?spec.mail,
760                        mail_actual = ?current_person_attributes.mail,
761                        legalname_spec = ?spec.legalname,
762                        legalname_actual = ?current_person_attributes.legalname,
763                        account_valid_from_spec = ?spec.account_valid_from,
764                        account_valid_from_actual = ?current_person_attributes.account_valid_from,
765                        account_expire_spec = ?spec.account_expire,
766                        account_expire_actual = ?current_person_attributes.account_expire,
767                        "person attributes mismatch"
768                    );
769                    Condition {
770                        type_: TYPE_UPDATED.to_string(),
771                        status: CONDITION_FALSE.to_string(),
772                        reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
773                        message: "Person exists with different attributes.".to_string(),
774                        last_transition_time: last_transition_time(
775                            current_conditions,
776                            TYPE_UPDATED,
777                            CONDITION_FALSE,
778                            REASON_ATTRIBUTES_NOT_MATCH,
779                        ),
780                        observed_generation: self.metadata.generation,
781                    }
782                };
783
784                let current_person_posix = KanidmAccountPosixAttributes::from(p);
785                let posix_initialized_condition = if current_person_posix.gidnumber.is_some() {
786                    Condition {
787                        type_: TYPE_POSIX_INITIALIZED.to_string(),
788                        status: CONDITION_TRUE.to_string(),
789                        reason: "PosixInitialized".to_string(),
790                        message: "Person exists with POSIX attributes.".to_string(),
791                        last_transition_time: last_transition_time(
792                            current_conditions,
793                            TYPE_POSIX_INITIALIZED,
794                            CONDITION_TRUE,
795                            "PosixInitialized",
796                        ),
797                        observed_generation: self.metadata.generation,
798                    }
799                } else {
800                    Condition {
801                        type_: TYPE_POSIX_INITIALIZED.to_string(),
802                        status: CONDITION_FALSE.to_string(),
803                        reason: "PosixNotInitialized".to_string(),
804                        message: "Person exists without POSIX attributes.".to_string(),
805                        last_transition_time: last_transition_time(
806                            current_conditions,
807                            TYPE_POSIX_INITIALIZED,
808                            CONDITION_FALSE,
809                            "PosixNotInitialized",
810                        ),
811                        observed_generation: self.metadata.generation,
812                    }
813                };
814
815                let posix_updated_condition = self.spec.posix_attributes.as_ref().map(|posix| {
816                    if posix == &current_person_posix {
817                        Condition {
818                            type_: TYPE_POSIX_UPDATED.to_string(),
819                            status: CONDITION_TRUE.to_string(),
820                            reason: REASON_ATTRIBUTES_MATCH.to_string(),
821                            message: "Person exists with desired POSIX attributes.".to_string(),
822                            last_transition_time: last_transition_time(
823                                current_conditions,
824                                TYPE_POSIX_UPDATED,
825                                CONDITION_TRUE,
826                                REASON_ATTRIBUTES_MATCH,
827                            ),
828                            observed_generation: self.metadata.generation,
829                        }
830                    } else {
831                        debug!(
832                            gidnumber_spec = ?posix.gidnumber,
833                            gidnumber_actual = ?current_person_posix.gidnumber,
834                            loginshell_spec = ?posix.loginshell,
835                            loginshell_actual = ?current_person_posix.loginshell,
836                            "posix attributes mismatch"
837                        );
838                        Condition {
839                            type_: TYPE_POSIX_UPDATED.to_string(),
840                            status: CONDITION_FALSE.to_string(),
841                            reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
842                            message: "Person exists with different POSIX attributes.".to_string(),
843                            last_transition_time: last_transition_time(
844                                current_conditions,
845                                TYPE_POSIX_UPDATED,
846                                CONDITION_FALSE,
847                                REASON_ATTRIBUTES_NOT_MATCH,
848                            ),
849                            observed_generation: self.metadata.generation,
850                        }
851                    }
852                });
853
854                let credentials_condition = credential_present.map(|c| {
855                    if c {
856                        Condition {
857                            type_: TYPE_CREDENTIAL.to_string(),
858                            status: CONDITION_TRUE.to_string(),
859                            reason: "Present".to_string(),
860                            message: "Credentials are present.".to_string(),
861                            last_transition_time: last_transition_time(
862                                current_conditions,
863                                TYPE_CREDENTIAL,
864                                CONDITION_TRUE,
865                                "Present",
866                            ),
867                            observed_generation: self.metadata.generation,
868                        }
869                    } else {
870                        Condition {
871                            type_: TYPE_CREDENTIAL.to_string(),
872                            status: CONDITION_FALSE.to_string(),
873                            reason: "NotPresent".to_string(),
874                            message: "Credentials are not present.".to_string(),
875                            last_transition_time: last_transition_time(
876                                current_conditions,
877                                TYPE_CREDENTIAL,
878                                CONDITION_FALSE,
879                                "NotPresent",
880                            ),
881                            observed_generation: self.metadata.generation,
882                        }
883                    }
884                });
885
886                let validity_condition = {
887                    let valid = if let Some(valid_from) =
888                        current_person_attributes.account_valid_from.as_ref()
889                    {
890                        now > valid_from.0
891                    } else {
892                        true
893                    } && if let Some(expire) =
894                        current_person_attributes.account_expire.as_ref()
895                    {
896                        now < expire.0
897                    } else {
898                        true
899                    };
900
901                    if valid {
902                        Condition {
903                            type_: TYPE_VALIDITY.to_string(),
904                            status: CONDITION_TRUE.to_string(),
905                            reason: "Valid".to_string(),
906                            message: "Account is valid.".to_string(),
907                            last_transition_time: last_transition_time(
908                                current_conditions,
909                                TYPE_VALIDITY,
910                                CONDITION_TRUE,
911                                "Valid",
912                            ),
913                            observed_generation: self.metadata.generation,
914                        }
915                    } else {
916                        Condition {
917                            type_: TYPE_VALIDITY.to_string(),
918                            status: CONDITION_FALSE.to_string(),
919                            reason: "Invalid".to_string(),
920                            message: "Account is invalid.".to_string(),
921                            last_transition_time: last_transition_time(
922                                current_conditions,
923                                TYPE_VALIDITY,
924                                CONDITION_FALSE,
925                                "Invalid",
926                            ),
927                            observed_generation: self.metadata.generation,
928                        }
929                    }
930                };
931                let conditions = vec![
932                    exist_condition,
933                    updated_condition,
934                    posix_initialized_condition,
935                    validity_condition,
936                ]
937                .into_iter()
938                .chain(credentials_condition)
939                .chain(posix_updated_condition)
940                .collect::<Vec<_>>();
941                let status = conditions
942                    .iter()
943                    .filter(|c| {
944                        c.type_ != TYPE_POSIX_INITIALIZED
945                            && c.type_ != TYPE_CREDENTIAL
946                            && c.type_ != TYPE_VALIDITY
947                    })
948                    .all(|c| c.status == CONDITION_TRUE);
949                Ok(KanidmPersonAccountStatus {
950                    conditions: Some(conditions),
951                    ready: status,
952                    gid: current_person_posix.gidnumber,
953                    kanidm_ref: self.kanidm_ref(),
954                })
955            }
956            None => {
957                let conditions = vec![Condition {
958                    type_: TYPE_EXISTS.to_string(),
959                    status: CONDITION_FALSE.to_string(),
960                    reason: "NotExists".to_string(),
961                    message: "Person is not present.".to_string(),
962                    last_transition_time: last_transition_time(
963                        current_conditions,
964                        TYPE_EXISTS,
965                        CONDITION_FALSE,
966                        "NotExists",
967                    ),
968                    observed_generation: self.metadata.generation,
969                }];
970                Ok(KanidmPersonAccountStatus {
971                    conditions: Some(conditions),
972                    ready: false,
973                    gid: None,
974                    kanidm_ref: self.kanidm_ref(),
975                })
976            }
977        }
978    }
979}
980
981pub fn is_person(type_: &str, status: KanidmPersonAccountStatus) -> bool {
982    status
983        .conditions
984        .unwrap_or_default()
985        .iter()
986        .any(|c| c.type_ == type_ && c.status == CONDITION_TRUE)
987}
988
989pub fn is_person_false(type_: &str, status: KanidmPersonAccountStatus) -> bool {
990    status
991        .conditions
992        .unwrap_or_default()
993        .iter()
994        .any(|c| c.type_ == type_ && c.status == CONDITION_FALSE)
995}
996
997#[cfg(test)]
998mod tests {
999    use super::*;
1000    use kanidm_proto::internal::{CUCredState, CUExtPortal, CURegState, PasskeyDetail};
1001
1002    fn empty_credential_update_status() -> CUStatus {
1003        CUStatus {
1004            spn: "test@example.com".to_string(),
1005            displayname: "Test".to_string(),
1006            ext_cred_portal: CUExtPortal::None,
1007            mfaregstate: CURegState::None,
1008            can_commit: true,
1009            warnings: Vec::new(),
1010            dirty: false,
1011            primary: None,
1012            primary_state: CUCredState::Modifiable,
1013            passkeys: Vec::new(),
1014            passkeys_state: CUCredState::Modifiable,
1015            attested_passkeys: Vec::new(),
1016            attested_passkeys_state: CUCredState::Modifiable,
1017            attested_passkeys_allowed_devices: Vec::new(),
1018            unixcred: None,
1019            unixcred_state: CUCredState::Modifiable,
1020            sshkeys: BTreeMap::new(),
1021            sshkeys_state: CUCredState::Modifiable,
1022        }
1023    }
1024
1025    #[test]
1026    fn passkey_only_credential_update_status_has_credentials() {
1027        let mut status = empty_credential_update_status();
1028        status.passkeys.push(PasskeyDetail {
1029            uuid: Default::default(),
1030            tag: "passkey".to_string(),
1031        });
1032
1033        assert!(credential_update_status_has_credentials(&status));
1034    }
1035
1036    #[test]
1037    fn attested_passkey_only_credential_update_status_has_credentials() {
1038        let mut status = empty_credential_update_status();
1039        status.attested_passkeys.push(PasskeyDetail {
1040            uuid: Default::default(),
1041            tag: "attested-passkey".to_string(),
1042        });
1043
1044        assert!(credential_update_status_has_credentials(&status));
1045    }
1046
1047    #[test]
1048    fn empty_credential_update_status_has_no_credentials() {
1049        let status = empty_credential_update_status();
1050
1051        assert!(credential_update_status_has_credentials(&status).not());
1052    }
1053}