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::telemetry;
9
10use std::collections::BTreeMap;
11use std::ops::Not;
12use std::sync::Arc;
13use std::time::Duration;
14
15use futures::TryFutureExt;
16use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, Time};
17use k8s_openapi::jiff::Timestamp;
18use kanidm_client::{ClientError, KanidmClient};
19use kanidm_proto::constants::{ATTR_ACCOUNT_EXPIRE, ATTR_ACCOUNT_VALID_FROM};
20use kanidm_proto::v1::Entry;
21use kube::api::{Api, Patch, PatchParams};
22use kube::runtime::controller::Action;
23use kube::runtime::events::{Event, EventType};
24use kube::runtime::finalizer::{Error as FinalizerError, Event as Finalizer, finalizer};
25use kube::runtime::reflector::ObjectRef;
26use kube::{Resource, ResourceExt};
27use time::format_description::well_known::Rfc3339;
28use time::{OffsetDateTime, UtcOffset};
29use tracing::{Span, debug, field, info, instrument, trace, warn};
30
31pub static PERSON_OPERATOR_NAME: &str = "kanidmpersonsaccounts.kaniop.rs";
32pub static PERSON_FINALIZER: &str = "kanidmpersonsaccounts.kaniop.rs/finalizer";
33
34const TYPE_CREDENTIAL: &str = "Credential";
35const TYPE_EXISTS: &str = "Exists";
36const TYPE_UPDATED: &str = "Updated";
37const TYPE_POSIX_INITIALIZED: &str = "PosixInitialized";
38const TYPE_POSIX_UPDATED: &str = "PosixUpdated";
39const TYPE_VALIDITY: &str = "Valid";
40const REASON_ATTRIBUTES_MATCH: &str = "AttributesMatch";
41const REASON_ATTRIBUTES_NOT_MATCH: &str = "AttributesNotMatch";
42const CONDITION_TRUE: &str = "True";
43const CONDITION_FALSE: &str = "False";
44
45pub async fn watched_resource(person: &KanidmPersonAccount, ctx: Arc<Context>) -> bool {
46    let kanidm = if let Some(k) = ctx.kaniop_ctx.get_kanidm(person) {
47        k
48    } else {
49        trace!(msg = "no kanidm found");
50        return false;
51    };
52
53    is_resource_watched(
54        person,
55        &kanidm,
56        &ctx.kaniop_ctx.namespace_store,
57        &ctx.kaniop_ctx.client,
58    )
59    .await
60}
61
62#[instrument(skip(ctx, person))]
63pub async fn reconcile_person_account(
64    person: Arc<KanidmPersonAccount>,
65    ctx: Arc<Context>,
66) -> Result<Action> {
67    let trace_id = telemetry::get_trace_id();
68    Span::current().record("trace_id", field::display(&trace_id));
69    let _timer = ctx
70        .kaniop_ctx
71        .metrics
72        .reconcile_count_and_measure(&trace_id);
73    let kanidm_client = ctx.get_idm_client(&person).await?;
74
75    if !watched_resource(&person, ctx.clone()).await {
76        debug!(msg = "resource not watched, skipping reconcile");
77        ctx.kaniop_ctx
78            .recorder
79            .publish(
80                &Event {
81                    type_: EventType::Warning,
82                    reason: "ResourceNotWatched".to_string(),
83                    note: Some("configure `personNamespaceSelector` on Kanidm resource to watch this namespace".to_string()),
84                    action: "Reconcile".to_string(),
85                    secondary: None,
86                },
87                &person.object_ref(&()),
88            )
89            .await
90.map_err(|e| {
91            warn!(msg = "failed to publish ResourceNotWatched event", %e);
92            Error::kube_error("publish", "event", person.get_namespace(), person.name_any(), e)
93        })?;
94        return Ok(Action::requeue(idm_reconcile_interval()));
95    }
96    info!(msg = "reconciling person account");
97
98    let namespace = person.get_namespace();
99    let status = person
100        .update_status(kanidm_client.clone(), ctx.clone())
101        .await
102        .map_err(|e| {
103            debug!(msg = "failed to reconcile status", %e);
104            ctx.kaniop_ctx.metrics.status_update_errors_inc();
105            e
106        })?;
107    let persons_api: Api<KanidmPersonAccount> =
108        Api::namespaced(ctx.kaniop_ctx.client.clone(), &namespace);
109    finalizer(&persons_api, PERSON_FINALIZER, person, |event| async {
110        match event {
111            Finalizer::Apply(p) => p.reconcile(kanidm_client, status, ctx).await,
112            Finalizer::Cleanup(p) => p.cleanup(kanidm_client, status, ctx).await,
113        }
114    })
115    .await
116    .or_else(|e| match e {
117        FinalizerError::RemoveFinalizer(kube::Error::Api(ae)) if ae.code == 404 => {
118            debug!(msg = "resource already removed during finalizer cleanup");
119            Ok(Action::requeue(idm_reconcile_interval()))
120        }
121        _ => Err(Error::FinalizerError(
122            "failed on person account finalizer".to_string(),
123            Box::new(e),
124        )),
125    })
126}
127
128impl KanidmPersonAccount {
129    #[inline]
130    fn get_namespace(&self) -> String {
131        // safe unwrap: person is namespaced scoped
132        self.namespace().unwrap()
133    }
134
135    #[inline]
136    async fn reconcile(
137        &self,
138        kanidm_client: Arc<KanidmClient>,
139        status: KanidmPersonAccountStatus,
140        ctx: Arc<Context>,
141    ) -> Result<Action> {
142        match self
143            .internal_reconcile(kanidm_client, status, ctx.clone())
144            .await
145        {
146            Ok(action) => Ok(action),
147            Err(e) => match e {
148                Error::KanidmClientError(_, _) => {
149                    ctx.kaniop_ctx
150                        .recorder
151                        .publish(
152                            &Event {
153                                type_: EventType::Warning,
154                                reason: "KanidmError".to_string(),
155                                note: Some(format!("{e:?}")),
156                                action: "KanidmRequest".to_string(),
157                                secondary: None,
158                            },
159                            &self.object_ref(&()),
160                        )
161                        .await
162                        .map_err(|e| {
163                            warn!(msg = "failed to publish KanidmError event", %e);
164                            Error::kube_error(
165                                "publish",
166                                "event",
167                                self.get_namespace(),
168                                self.name_any(),
169                                e,
170                            )
171                        })?;
172                    Err(e)
173                }
174                _ => Err(e),
175            },
176        }
177    }
178
179    async fn internal_reconcile(
180        &self,
181        kanidm_client: Arc<KanidmClient>,
182        status: KanidmPersonAccountStatus,
183        ctx: Arc<Context>,
184    ) -> Result<Action> {
185        let name = &self.kanidm_entity_name();
186
187        let mut require_status_update = false;
188        let mut actions = Vec::new();
189        if is_person_false(TYPE_EXISTS, status.clone()) {
190            debug!(
191                msg = "condition triggered action",
192                condition = TYPE_EXISTS,
193                status = CONDITION_FALSE,
194                action = "create"
195            );
196            self.create(&kanidm_client, name).await?;
197            require_status_update = true;
198            actions.push("create");
199        }
200        if is_person_false(TYPE_UPDATED, status.clone()) {
201            debug!(
202                msg = "condition triggered action",
203                condition = TYPE_UPDATED,
204                status = CONDITION_FALSE,
205                action = "update"
206            );
207            self.update(&kanidm_client, name).await?;
208            require_status_update = true;
209            actions.push("update");
210        }
211
212        if is_person_false(TYPE_POSIX_UPDATED, status.clone())
213            || (is_person_false(TYPE_POSIX_INITIALIZED, status.clone())
214                && is_person(TYPE_POSIX_UPDATED, status.clone()))
215        {
216            debug!(
217                msg = "condition triggered action",
218                condition = TYPE_POSIX_UPDATED,
219                status = CONDITION_FALSE,
220                action = "update_posix_attributes"
221            );
222            self.update_posix_attributes(&kanidm_client, name).await?;
223            require_status_update = true;
224            actions.push("update_posix");
225        }
226
227        if is_person_false(TYPE_CREDENTIAL, status) {
228            let create_token = match ctx.internal_cache.read().await.get(&ObjectRef::from(self)) {
229                Some(expiry) if expiry > &OffsetDateTime::now_utc() => {
230                    trace!(msg = "token not expired, skipping creation");
231                    false
232                }
233                _ => true,
234            };
235            if create_token {
236                debug!(
237                    msg = "condition triggered action",
238                    condition = TYPE_CREDENTIAL,
239                    status = CONDITION_FALSE,
240                    action = "create_reset_token"
241                );
242                self.create_reset_token(&kanidm_client, name, ctx).await?;
243            };
244        };
245
246        if require_status_update {
247            debug!(msg = "requeueing in 500ms after actions", actions = ?actions);
248            Ok(Action::requeue(Duration::from_millis(500)))
249        } else {
250            debug!(msg = "reconciliation complete, requeueing for next interval");
251            Ok(Action::requeue(idm_reconcile_interval()))
252        }
253    }
254
255    async fn create(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
256        debug!(msg = "create");
257        kanidm_client
258            .idm_person_account_create(name, &self.spec.person_attributes.displayname)
259            .await
260            .map_err(|e| {
261                Error::kanidm_client_error(
262                    "create",
263                    name,
264                    self.kanidm_namespace(),
265                    self.kanidm_name(),
266                    e,
267                )
268            })?;
269        Ok(())
270    }
271
272    async fn update(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
273        debug!(msg = "update");
274        trace!(msg = format!("update person attributes {:?}", self.spec.person_attributes));
275        kanidm_client
276            .idm_person_account_update(
277                name,
278                None,
279                Some(&self.spec.person_attributes.displayname),
280                self.spec.person_attributes.legalname.as_deref(),
281                self.spec.person_attributes.mail.as_deref(),
282            )
283            .await
284            .map_err(|e| {
285                Error::kanidm_client_error(
286                    "update",
287                    name,
288                    self.kanidm_namespace(),
289                    self.kanidm_name(),
290                    e,
291                )
292            })?;
293        let mut update_entry = Entry {
294            attrs: BTreeMap::new(),
295        };
296        if let Some(account_expire) = self.spec.person_attributes.account_expire.as_ref() {
297            update_entry.attrs.insert(
298                ATTR_ACCOUNT_EXPIRE.to_string(),
299                vec![account_expire.0.to_string()],
300            );
301        }
302        if let Some(account_valid_from) = self.spec.person_attributes.account_valid_from.as_ref() {
303            update_entry.attrs.insert(
304                ATTR_ACCOUNT_VALID_FROM.to_string(),
305                vec![account_valid_from.0.to_string()],
306            );
307        }
308
309        if update_entry.attrs.is_empty().not() {
310            let _: Entry = kanidm_client
311                .perform_patch_request(&format!("/v1/person/{name}"), update_entry)
312                .await
313                .map_err(|e| {
314                    Error::kanidm_client_error(
315                        "update",
316                        name,
317                        self.kanidm_namespace(),
318                        self.kanidm_name(),
319                        e,
320                    )
321                })?;
322        }
323        Ok(())
324    }
325
326    async fn update_posix_attributes(
327        &self,
328        kanidm_client: &KanidmClient,
329        name: &str,
330    ) -> Result<()> {
331        debug!(msg = "update posix attributes");
332        trace!(msg = format!("update posix attributes {:?}", self.spec.posix_attributes));
333        kanidm_client
334            .idm_person_account_unix_extend(
335                name,
336                self.spec
337                    .posix_attributes
338                    .as_ref()
339                    .and_then(|posix| posix.gidnumber),
340                self.spec
341                    .posix_attributes
342                    .as_ref()
343                    .and_then(|posix| posix.loginshell.as_deref()),
344            )
345            .await
346            .map_err(|e| {
347                Error::kanidm_client_error(
348                    "update",
349                    name,
350                    self.kanidm_namespace(),
351                    self.kanidm_name(),
352                    e,
353                )
354            })?;
355        Ok(())
356    }
357
358    async fn create_reset_token(
359        &self,
360        kanidm_client: &KanidmClient,
361        name: &str,
362        ctx: Arc<Context>,
363    ) -> Result<()> {
364        debug!(msg = "create reset token");
365        let cu_token = kanidm_client
366            .idm_person_account_credential_update_intent(
367                name,
368                Some(self.spec.credentials_token_ttl),
369            )
370            .await
371            .map_err(|e| {
372                Error::kanidm_client_error(
373                    "create a credential reset token for",
374                    name,
375                    self.kanidm_namespace(),
376                    self.kanidm_name(),
377                    e,
378                )
379            })?;
380        let token = cu_token.token.as_str();
381        let url = if let Some(base_url) = ctx.kaniop_ctx.get_kanidm(self).map(|k| {
382            k.spec
383                .origin
384                .clone()
385                .unwrap_or_else(|| format!("https://{}", k.spec.domain))
386        }) {
387            format!("{base_url}/ui/reset?token={token}")
388        } else {
389            let mut url = kanidm_client.make_url("/ui/reset");
390            url.query_pairs_mut().append_pair("token", token);
391            url.to_string()
392        };
393        let local_offset = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
394        let expiry_time = cu_token.expiry_time.to_offset(local_offset);
395
396        let msg = format!(
397            "Update these user credentials with this link: {url}. This token will expire at: {}",
398            expiry_time
399                .format(&Rfc3339)
400                .unwrap_or_else(|_| expiry_time.to_string())
401        );
402        ctx.kaniop_ctx
403            .recorder
404            .publish(
405                &Event {
406                    type_: EventType::Normal,
407                    reason: "TokenCreated".to_string(),
408                    note: Some(msg),
409                    action: "CreateUpdateCredentialsToken".into(),
410                    secondary: None,
411                },
412                &self.object_ref(&()),
413            )
414            .await
415            .map_err(|e| {
416                warn!(msg = "failed to publish TokenCreated event", %e);
417                Error::kube_error("publish", "event", self.get_namespace(), self.name_any(), e)
418            })?;
419        ctx.internal_cache
420            .write()
421            .await
422            .insert(ObjectRef::from(self), expiry_time);
423        Ok(())
424    }
425
426    async fn cleanup(
427        &self,
428        kanidm_client: Arc<KanidmClient>,
429        status: KanidmPersonAccountStatus,
430        ctx: Arc<Context>,
431    ) -> Result<Action> {
432        let name = &self.kanidm_entity_name();
433
434        if is_person(TYPE_EXISTS, status.clone()) {
435            debug!(msg = "delete");
436            kanidm_client
437                .idm_person_account_delete(name)
438                .await
439                .map_err(|e| {
440                    Error::kanidm_client_error(
441                        "delete",
442                        name,
443                        self.kanidm_namespace(),
444                        self.kanidm_name(),
445                        e,
446                    )
447                })?;
448
449            ctx.internal_cache
450                .write()
451                .await
452                .remove(&ObjectRef::from(self));
453        }
454        Ok(Action::requeue(idm_reconcile_interval()))
455    }
456
457    async fn update_status(
458        &self,
459        kanidm_client: Arc<KanidmClient>,
460        ctx: Arc<Context>,
461    ) -> Result<KanidmPersonAccountStatus> {
462        // safe unwrap: person is namespaced scoped
463        let namespace = self.get_namespace();
464        let name = self.kanidm_entity_name();
465        let current_person = kanidm_client
466            .idm_person_account_get(&name)
467            .map_err(|e| {
468                Error::kanidm_client_error(
469                    "get",
470                    name.as_str(),
471                    self.kanidm_namespace(),
472                    self.kanidm_name(),
473                    e,
474                )
475            })
476            .await?;
477        let credential_present = match kanidm_client
478            .idm_person_account_get_credential_status(&name)
479            .await
480        {
481            Ok(cs) => {
482                let present = cs.creds.is_empty().not();
483                trace!(
484                    msg = "credential status",
485                    credential_present = present,
486                    creds_count = cs.creds.len()
487                );
488                Some(present)
489            }
490            Err(ClientError::EmptyResponse) => {
491                trace!(
492                    msg = "credential status",
493                    credential_present = false,
494                    reason = "EmptyResponse"
495                );
496                Some(false)
497            }
498            Err(e) => {
499                trace!(msg = "credential status error", error = ?e);
500                None
501            }
502        };
503
504        let status = self.generate_status(current_person, credential_present)?;
505        if self.status.as_ref() == Some(&status) {
506            trace!(msg = "status unchanged, skipping patch");
507            return Ok(status);
508        }
509        if let Some(old) = self.status.as_ref() {
510            let old_conds: Vec<_> = old
511                .conditions
512                .iter()
513                .flatten()
514                .map(|c| format!("{}={}", c.type_, c.status))
515                .collect();
516            let new_conds: Vec<_> = status
517                .conditions
518                .iter()
519                .flatten()
520                .map(|c| format!("{}={}", c.type_, c.status))
521                .collect();
522            debug!(msg = "status changed", old = ?old_conds, new = ?new_conds, old_ready = old.ready, new_ready = status.ready);
523        } else {
524            debug!(msg = "initial status patch", conditions = ?status.conditions);
525        }
526        let status_patch = Patch::Apply(KanidmPersonAccount {
527            status: Some(status.clone()),
528            ..KanidmPersonAccount::default()
529        });
530        debug!(msg = "updating status");
531        trace!(msg = format!("status patch {:?}", status_patch));
532        let patch = PatchParams::apply(PERSON_OPERATOR_NAME).force();
533        let kanidm_api =
534            Api::<KanidmPersonAccount>::namespaced(ctx.kaniop_ctx.client.clone(), &namespace);
535        let _o = kanidm_api
536            .patch_status(&self.name_any(), &patch, &status_patch)
537            .await
538            .map_err(|e| {
539                Error::kube_status_error("KanidmPersonAccount", namespace, self.name_any(), e)
540            })?;
541        Ok(status)
542    }
543
544    fn generate_status(
545        &self,
546        person: Option<Entry>,
547        credential_present: Option<bool>,
548    ) -> Result<KanidmPersonAccountStatus> {
549        let now = Timestamp::now();
550        let current_conditions = self.status.as_ref().and_then(|s| s.conditions.as_ref());
551
552        // Helper function to determine the last transition time
553        fn last_transition_time(
554            current_conditions: Option<&Vec<Condition>>,
555            type_: &str,
556            new_status: &str,
557            new_reason: &str,
558        ) -> Time {
559            let now_time = Time(Timestamp::now());
560            if let Some(conditions) = current_conditions {
561                for c in conditions {
562                    if c.type_ == type_ && c.status == new_status && c.reason == new_reason {
563                        return c.last_transition_time.clone();
564                    }
565                }
566            }
567            now_time
568        }
569
570        match person {
571            Some(p) => {
572                let exist_condition = Condition {
573                    type_: TYPE_EXISTS.to_string(),
574                    status: CONDITION_TRUE.to_string(),
575                    reason: "Exists".to_string(),
576                    message: "Person exists.".to_string(),
577                    last_transition_time: last_transition_time(
578                        current_conditions,
579                        TYPE_EXISTS,
580                        CONDITION_TRUE,
581                        "Exists",
582                    ),
583                    observed_generation: self.metadata.generation,
584                };
585
586                let current_person_attributes = KanidmPersonAttributes::from(p.clone());
587                let updated_condition = if self.spec.person_attributes == current_person_attributes
588                {
589                    Condition {
590                        type_: TYPE_UPDATED.to_string(),
591                        status: CONDITION_TRUE.to_string(),
592                        reason: REASON_ATTRIBUTES_MATCH.to_string(),
593                        message: "Person exists with desired attributes.".to_string(),
594                        last_transition_time: last_transition_time(
595                            current_conditions,
596                            TYPE_UPDATED,
597                            CONDITION_TRUE,
598                            REASON_ATTRIBUTES_MATCH,
599                        ),
600                        observed_generation: self.metadata.generation,
601                    }
602                } else {
603                    let spec = &self.spec.person_attributes;
604                    debug!(
605                        msg = "person attributes mismatch",
606                        displayname_spec = %spec.displayname,
607                        displayname_actual = %current_person_attributes.displayname,
608                        mail_spec = ?spec.mail,
609                        mail_actual = ?current_person_attributes.mail,
610                        legalname_spec = ?spec.legalname,
611                        legalname_actual = ?current_person_attributes.legalname,
612                        account_valid_from_spec = ?spec.account_valid_from,
613                        account_valid_from_actual = ?current_person_attributes.account_valid_from,
614                        account_expire_spec = ?spec.account_expire,
615                        account_expire_actual = ?current_person_attributes.account_expire,
616                    );
617                    Condition {
618                        type_: TYPE_UPDATED.to_string(),
619                        status: CONDITION_FALSE.to_string(),
620                        reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
621                        message: "Person exists with different attributes.".to_string(),
622                        last_transition_time: last_transition_time(
623                            current_conditions,
624                            TYPE_UPDATED,
625                            CONDITION_FALSE,
626                            REASON_ATTRIBUTES_NOT_MATCH,
627                        ),
628                        observed_generation: self.metadata.generation,
629                    }
630                };
631
632                let current_person_posix = KanidmAccountPosixAttributes::from(p);
633                let posix_initialized_condition = if current_person_posix.gidnumber.is_some() {
634                    Condition {
635                        type_: TYPE_POSIX_INITIALIZED.to_string(),
636                        status: CONDITION_TRUE.to_string(),
637                        reason: "PosixInitialized".to_string(),
638                        message: "Person exists with POSIX attributes.".to_string(),
639                        last_transition_time: last_transition_time(
640                            current_conditions,
641                            TYPE_POSIX_INITIALIZED,
642                            CONDITION_TRUE,
643                            "PosixInitialized",
644                        ),
645                        observed_generation: self.metadata.generation,
646                    }
647                } else {
648                    Condition {
649                        type_: TYPE_POSIX_INITIALIZED.to_string(),
650                        status: CONDITION_FALSE.to_string(),
651                        reason: "PosixNotInitialized".to_string(),
652                        message: "Person exists without POSIX attributes.".to_string(),
653                        last_transition_time: last_transition_time(
654                            current_conditions,
655                            TYPE_POSIX_INITIALIZED,
656                            CONDITION_FALSE,
657                            "PosixNotInitialized",
658                        ),
659                        observed_generation: self.metadata.generation,
660                    }
661                };
662
663                let posix_updated_condition = self.spec.posix_attributes.as_ref().map(|posix| {
664                    if posix == &current_person_posix {
665                        Condition {
666                            type_: TYPE_POSIX_UPDATED.to_string(),
667                            status: CONDITION_TRUE.to_string(),
668                            reason: REASON_ATTRIBUTES_MATCH.to_string(),
669                            message: "Person exists with desired POSIX attributes.".to_string(),
670                            last_transition_time: last_transition_time(
671                                current_conditions,
672                                TYPE_POSIX_UPDATED,
673                                CONDITION_TRUE,
674                                REASON_ATTRIBUTES_MATCH,
675                            ),
676                            observed_generation: self.metadata.generation,
677                        }
678                    } else {
679                        debug!(
680                            msg = "posix attributes mismatch",
681                            gidnumber_spec = ?posix.gidnumber,
682                            gidnumber_actual = ?current_person_posix.gidnumber,
683                            loginshell_spec = ?posix.loginshell,
684                            loginshell_actual = ?current_person_posix.loginshell,
685                        );
686                        Condition {
687                            type_: TYPE_POSIX_UPDATED.to_string(),
688                            status: CONDITION_FALSE.to_string(),
689                            reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
690                            message: "Person exists with different POSIX attributes.".to_string(),
691                            last_transition_time: last_transition_time(
692                                current_conditions,
693                                TYPE_POSIX_UPDATED,
694                                CONDITION_FALSE,
695                                REASON_ATTRIBUTES_NOT_MATCH,
696                            ),
697                            observed_generation: self.metadata.generation,
698                        }
699                    }
700                });
701
702                let credentials_condition = credential_present.map(|c| {
703                    if c {
704                        Condition {
705                            type_: TYPE_CREDENTIAL.to_string(),
706                            status: CONDITION_TRUE.to_string(),
707                            reason: "Present".to_string(),
708                            message: "Credentials are present.".to_string(),
709                            last_transition_time: last_transition_time(
710                                current_conditions,
711                                TYPE_CREDENTIAL,
712                                CONDITION_TRUE,
713                                "Present",
714                            ),
715                            observed_generation: self.metadata.generation,
716                        }
717                    } else {
718                        Condition {
719                            type_: TYPE_CREDENTIAL.to_string(),
720                            status: CONDITION_FALSE.to_string(),
721                            reason: "NotPresent".to_string(),
722                            message: "Credentials are not present.".to_string(),
723                            last_transition_time: last_transition_time(
724                                current_conditions,
725                                TYPE_CREDENTIAL,
726                                CONDITION_FALSE,
727                                "NotPresent",
728                            ),
729                            observed_generation: self.metadata.generation,
730                        }
731                    }
732                });
733
734                let validity_condition = {
735                    let valid = if let Some(valid_from) =
736                        current_person_attributes.account_valid_from.as_ref()
737                    {
738                        now > valid_from.0
739                    } else {
740                        true
741                    } && if let Some(expire) =
742                        current_person_attributes.account_expire.as_ref()
743                    {
744                        now < expire.0
745                    } else {
746                        true
747                    };
748
749                    if valid {
750                        Condition {
751                            type_: TYPE_VALIDITY.to_string(),
752                            status: CONDITION_TRUE.to_string(),
753                            reason: "Valid".to_string(),
754                            message: "Account is valid.".to_string(),
755                            last_transition_time: last_transition_time(
756                                current_conditions,
757                                TYPE_VALIDITY,
758                                CONDITION_TRUE,
759                                "Valid",
760                            ),
761                            observed_generation: self.metadata.generation,
762                        }
763                    } else {
764                        Condition {
765                            type_: TYPE_VALIDITY.to_string(),
766                            status: CONDITION_FALSE.to_string(),
767                            reason: "Invalid".to_string(),
768                            message: "Account is invalid.".to_string(),
769                            last_transition_time: last_transition_time(
770                                current_conditions,
771                                TYPE_VALIDITY,
772                                CONDITION_FALSE,
773                                "Invalid",
774                            ),
775                            observed_generation: self.metadata.generation,
776                        }
777                    }
778                };
779                let conditions = vec![
780                    exist_condition,
781                    updated_condition,
782                    posix_initialized_condition,
783                    validity_condition,
784                ]
785                .into_iter()
786                .chain(credentials_condition)
787                .chain(posix_updated_condition)
788                .collect::<Vec<_>>();
789                let status = conditions
790                    .iter()
791                    .filter(|c| {
792                        c.type_ != TYPE_POSIX_INITIALIZED
793                            && c.type_ != TYPE_CREDENTIAL
794                            && c.type_ != TYPE_VALIDITY
795                    })
796                    .all(|c| c.status == CONDITION_TRUE);
797                Ok(KanidmPersonAccountStatus {
798                    conditions: Some(conditions),
799                    ready: status,
800                    gid: current_person_posix.gidnumber,
801                    kanidm_ref: self.kanidm_ref(),
802                })
803            }
804            None => {
805                let conditions = vec![Condition {
806                    type_: TYPE_EXISTS.to_string(),
807                    status: CONDITION_FALSE.to_string(),
808                    reason: "NotExists".to_string(),
809                    message: "Person is not present.".to_string(),
810                    last_transition_time: last_transition_time(
811                        current_conditions,
812                        TYPE_EXISTS,
813                        CONDITION_FALSE,
814                        "NotExists",
815                    ),
816                    observed_generation: self.metadata.generation,
817                }];
818                Ok(KanidmPersonAccountStatus {
819                    conditions: Some(conditions),
820                    ready: false,
821                    gid: None,
822                    kanidm_ref: self.kanidm_ref(),
823                })
824            }
825        }
826    }
827}
828
829pub fn is_person(type_: &str, status: KanidmPersonAccountStatus) -> bool {
830    status
831        .conditions
832        .unwrap_or_default()
833        .iter()
834        .any(|c| c.type_ == type_ && c.status == CONDITION_TRUE)
835}
836
837pub fn is_person_false(type_: &str, status: KanidmPersonAccountStatus) -> bool {
838    status
839        .conditions
840        .unwrap_or_default()
841        .iter()
842        .any(|c| c.type_ == type_ && c.status == CONDITION_FALSE)
843}