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