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