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