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