Skip to main content

kaniop_person/
reconcile.rs

1use crate::controller::Context;
2use crate::crd::{
3    CredentialBootstrapDelivery, CredentialBootstrapState, CredentialBootstrapStatus,
4    CredentialState, KanidmPersonAccount, 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_CREDENTIAL_UPDATE_SEND_INTENT,
14    KANIDM_OP_DELETE, KANIDM_OP_GET, KANIDM_OP_GET_CREDENTIAL_STATUS, KANIDM_OP_UNIX_EXTEND,
15    KANIDM_OP_UPDATE, KANIDM_OUTCOME_CHANGED, KANIDM_OUTCOME_ERROR, KANIDM_OUTCOME_UNCHANGED,
16    KANIDM_RESOURCE_PERSON, record_kanidm_sdk_call,
17};
18use kaniop_operator::telemetry;
19
20use std::collections::{BTreeMap, BTreeSet};
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::{ClientError, 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::internal::OperationError;
34use kanidm_proto::scim_v1::{ScimEntryGetQuery, client::ScimSshPublicKeys};
35use kanidm_proto::v1::Entry;
36use kube::api::{Api, Patch, PatchParams};
37use kube::runtime::controller::Action;
38use kube::runtime::events::{Event, EventType};
39use kube::runtime::finalizer::{Error as FinalizerError, Event as Finalizer, finalizer};
40use kube::{Resource, ResourceExt};
41use time::UtcOffset;
42use time::format_description::well_known::Rfc3339;
43use tracing::{Span, debug, field, info, instrument, trace, warn};
44
45pub static PERSON_OPERATOR_NAME: &str = "kanidmpersonsaccounts.kaniop.rs";
46pub static PERSON_FINALIZER: &str = "kanidmpersonsaccounts.kaniop.rs/finalizer";
47
48const TYPE_CREDENTIAL: &str = "Credential";
49const TYPE_CREDENTIAL_BOOTSTRAP_DELIVERY: &str = "CredentialBootstrapDelivery";
50const ANNOTATION_CREDENTIAL_BOOTSTRAP_RESEND_REVISION: &str =
51    "kaniop.rs/credential-bootstrap-resend-revision";
52const TYPE_SSH_PUBLIC_KEYS: &str = "SshPublicKeysUpdated";
53const TYPE_EXISTS: &str = "Exists";
54const TYPE_UPDATED: &str = "Updated";
55const TYPE_POSIX_INITIALIZED: &str = "PosixInitialized";
56const TYPE_POSIX_UPDATED: &str = "PosixUpdated";
57const TYPE_VALIDITY: &str = "Valid";
58const REASON_ATTRIBUTES_MATCH: &str = "AttributesMatch";
59const REASON_ATTRIBUTES_NOT_MATCH: &str = "AttributesNotMatch";
60const CONDITION_TRUE: &str = "True";
61const CONDITION_FALSE: &str = "False";
62const CONDITION_UNKNOWN: &str = "Unknown";
63
64fn credential_state_from_attributes(
65    primary: &Option<Vec<String>>,
66    passkeys: &Option<Vec<String>>,
67    attested_passkeys: &Option<Vec<String>>,
68) -> CredentialState {
69    if [primary, passkeys, attested_passkeys]
70        .into_iter()
71        .any(|values| {
72            values
73                .as_ref()
74                .is_some_and(|values| values.is_empty().not())
75        })
76    {
77        CredentialState::Present
78    } else {
79        CredentialState::Absent
80    }
81}
82
83fn scim_search_allows_all_credential_attributes(search: &serde_json::Value) -> bool {
84    match search {
85        serde_json::Value::String(access) => access == "Grant",
86        serde_json::Value::Object(access) => access
87            .get("Allow")
88            .and_then(serde_json::Value::as_array)
89            .is_some_and(|allowed| {
90                [
91                    ATTR_PRIMARY_CREDENTIAL,
92                    ATTR_PASSKEYS,
93                    ATTR_ATTESTED_PASSKEYS,
94                ]
95                .into_iter()
96                .all(|required| {
97                    allowed
98                        .iter()
99                        .any(|attribute| attribute.as_str() == Some(required))
100                })
101            }),
102        _ => false,
103    }
104}
105
106async fn credential_attributes_searchable(
107    kanidm_client: &KanidmClient,
108    name: &str,
109) -> std::result::Result<bool, kanidm_client::ClientError> {
110    let query = ScimEntryGetQuery {
111        attributes: Some(vec![
112            Attribute::PrimaryCredential,
113            Attribute::PassKeys,
114            Attribute::AttestedPasskeys,
115        ]),
116        ext_access_check: true,
117        ..Default::default()
118    };
119    let path = format!("/scim/v1/Person/{name}");
120    let entry: serde_json::Value = kanidm_client
121        .perform_get_request_query(&path, Some(query))
122        .await?;
123
124    Ok(entry
125        .get("extAccessCheck")
126        .and_then(|access| access.get("search"))
127        .is_some_and(scim_search_allows_all_credential_attributes))
128}
129
130fn ssh_public_keys_match(
131    desired: &BTreeMap<String, String>,
132    observed: &BTreeMap<String, String>,
133    managed_tags: &[String],
134) -> bool {
135    let desired_tags: BTreeSet<_> = desired.keys().collect();
136    let managed_tags: BTreeSet<_> = managed_tags.iter().collect();
137    desired_tags == managed_tags
138        && desired
139            .iter()
140            .all(|(tag, key)| observed.get(tag) == Some(key))
141}
142
143/// Read structured (tag, key) pairs, not authorized_keys output (which has no tags).
144/// Kanidm is authoritative for SSH key syntax and supported algorithms.
145async fn read_ssh_public_keys(
146    kanidm_client: &KanidmClient,
147    name: &str,
148) -> Result<BTreeMap<String, String>> {
149    let entry = kanidm_client
150        .scim_v1_person_get(
151            name,
152            Some(ScimEntryGetQuery {
153                attributes: Some(vec![Attribute::SshPublicKey]),
154                ..Default::default()
155            }),
156        )
157        .await
158        .map_err(|e| {
159            Error::KanidmClientError(
160                format!("failed to read SSH public keys for person {name}"),
161                Box::new(e),
162            )
163        })?;
164    let Some(raw_keys) = entry.attrs.get(&Attribute::SshPublicKey) else {
165        return Ok(BTreeMap::new());
166    };
167    let keys: ScimSshPublicKeys = serde_json::from_value(raw_keys.clone()).map_err(|e| {
168        Error::SerializationError(
169            format!("invalid SSH public key response from Kanidm for {name}"),
170            e,
171        )
172    })?;
173    Ok(keys
174        .into_iter()
175        .map(|k| (k.label, k.value.to_string()))
176        .collect())
177}
178
179fn bootstrap_token_expired(status: &CredentialBootstrapStatus) -> bool {
180    status
181        .token_expires_at
182        .as_ref()
183        .is_some_and(|expiry| expiry.0 <= Timestamp::now())
184}
185
186fn should_create_reset_token(
187    credential_state: CredentialState,
188    bootstrap: &CredentialBootstrapStatus,
189) -> bool {
190    if credential_state != CredentialState::Absent {
191        return false;
192    }
193
194    match bootstrap.state {
195        CredentialBootstrapState::Pending => true,
196        CredentialBootstrapState::TokenIssued => bootstrap_token_expired(bootstrap),
197        CredentialBootstrapState::Complete => false,
198    }
199}
200
201/// A missing annotation is revision zero. Invalid values never trigger an email;
202/// the delivery condition explains the invalid request.
203fn requested_bootstrap_resend_revision(person: &KanidmPersonAccount) -> Option<u32> {
204    person
205        .metadata
206        .annotations
207        .as_ref()
208        .and_then(|annotations| annotations.get(ANNOTATION_CREDENTIAL_BOOTSTRAP_RESEND_REVISION))
209        .map_or(Some(0), |revision| revision.parse::<u32>().ok())
210}
211
212fn should_send_bootstrap_email(
213    credential_state: CredentialState,
214    bootstrap: &CredentialBootstrapStatus,
215    requested_revision: Option<u32>,
216) -> bool {
217    if credential_state != CredentialState::Absent
218        || bootstrap.state == CredentialBootstrapState::Complete
219    {
220        return false;
221    }
222
223    // A previously queued email stays queued even if delivery temporarily switches
224    // to Events. Only an explicit, strictly higher resend revision queues another.
225    requested_revision.is_some_and(|revision| {
226        bootstrap
227            .last_queued_resend_revision
228            .is_none_or(|last_queued| revision > last_queued)
229    })
230}
231
232/// Report whether the requested email has already been accepted, independently
233/// from the last transport used or an error from a *newer* resend request.
234fn bootstrap_email_condition(
235    credential_state: CredentialState,
236    bootstrap: &CredentialBootstrapStatus,
237    requested_revision: Option<u32>,
238) -> (&'static str, &str, &'static str) {
239    if bootstrap.state == CredentialBootstrapState::Complete {
240        return (
241            CONDITION_TRUE,
242            "Complete",
243            "Credential bootstrap completed.",
244        );
245    }
246    if credential_state == CredentialState::Unknown {
247        return (
248            CONDITION_UNKNOWN,
249            "CredentialStateUnknown",
250            "Credential status is unknown; no email will be queued.",
251        );
252    }
253    let Some(requested_revision) = requested_revision else {
254        return (
255            CONDITION_FALSE,
256            "InvalidResendRevision",
257            "The credential-bootstrap-resend-revision annotation must be a non-negative integer within the u32 range.",
258        );
259    };
260    if credential_state == CredentialState::Absent {
261        if let Some(queued_revision) = bootstrap.last_queued_resend_revision {
262            if requested_revision < queued_revision {
263                return (
264                    CONDITION_TRUE,
265                    "StaleResendIgnored",
266                    "The requested resend revision is older than the last queued revision; no new email was queued.",
267                );
268            }
269            if requested_revision == queued_revision {
270                return (
271                    CONDITION_TRUE,
272                    "EmailQueued",
273                    "Kanidm accepted the email request; SMTP delivery is not confirmed.",
274                );
275            }
276        }
277    }
278    if let Some(error) = bootstrap.delivery_error.as_deref() {
279        return (
280            CONDITION_FALSE,
281            error,
282            "Credential bootstrap email is blocked; inspect mail sender and account email.",
283        );
284    }
285    (
286        CONDITION_FALSE,
287        "Pending",
288        "Credential bootstrap email has not been queued yet.",
289    )
290}
291
292fn should_create_event_token(
293    credential_state: CredentialState,
294    bootstrap: &CredentialBootstrapStatus,
295) -> bool {
296    if credential_state != CredentialState::Absent
297        || bootstrap.state == CredentialBootstrapState::Complete
298    {
299        return false;
300    }
301    bootstrap.delivery_method == Some(CredentialBootstrapDelivery::Email)
302        || should_create_reset_token(credential_state, bootstrap)
303}
304
305// JSON Merge Patch requires an explicit null to remove a previously stored field.
306// Serde omits None fields from CredentialBootstrapStatus, so serializing the struct
307// directly would leave stale delivery errors and delivery-mode metadata in status.
308fn credential_bootstrap_merge_patch(bootstrap: &CredentialBootstrapStatus) -> serde_json::Value {
309    serde_json::json!({
310        "status": {
311            "credentialBootstrap": {
312                "state": bootstrap.state,
313                "tokenExpiresAt": bootstrap.token_expires_at.as_ref(),
314                "deliveryMethod": bootstrap.delivery_method,
315                "lastQueuedResendRevision": bootstrap.last_queued_resend_revision,
316                "emailQueuedAt": bootstrap.email_queued_at.as_ref(),
317                "deliveryError": bootstrap.delivery_error.as_deref(),
318            }
319        }
320    })
321}
322
323pub async fn watched_resource(person: &KanidmPersonAccount, ctx: Arc<Context>) -> bool {
324    let kanidm = if let Some(k) = ctx.kaniop_ctx.get_kanidm(person) {
325        k
326    } else {
327        trace!("no kanidm found");
328        return false;
329    };
330
331    is_resource_watched(
332        person,
333        &kanidm,
334        &ctx.kaniop_ctx.namespace_store,
335        &ctx.kaniop_ctx.client,
336    )
337    .await
338}
339
340#[instrument(skip(ctx, person))]
341pub async fn reconcile_person_account(
342    person: Arc<KanidmPersonAccount>,
343    ctx: Arc<Context>,
344) -> Result<(Action, bool)> {
345    let trace_id = telemetry::get_trace_id();
346    Span::current().record("trace_id", field::display(&trace_id));
347    let _timer = ctx
348        .kaniop_ctx
349        .metrics
350        .reconcile_count_and_measure(&trace_id);
351    if !ctx.kaniop_ctx.kanidm_write_allowed(&person) {
352        debug!("Kanidm restore in progress, pausing identity writes");
353        return Ok((Action::requeue(Duration::from_secs(5)), false));
354    }
355    let kanidm_client = ctx.get_idm_client(&person).await?;
356
357    if !watched_resource(&person, ctx.clone()).await {
358        debug!("resource not watched, skipping reconcile");
359        ctx.kaniop_ctx
360            .recorder
361            .publish(
362                &Event {
363                    type_: EventType::Warning,
364                    reason: "ResourceNotWatched".to_string(),
365                    note: Some("configure `personNamespaceSelector` on Kanidm resource to watch this namespace".to_string()),
366                    action: "Reconcile".to_string(),
367                    secondary: None,
368                },
369                &person.object_ref(&()),
370            )
371            .await
372            .map_err(|e| {
373                warn!(error = %e, "failed to publish ResourceNotWatched event");
374                Error::kube_error("publish", "event", person.get_namespace(), person.name_any(), e)
375            })?;
376        return Ok((Action::requeue(idm_reconcile_interval()), false));
377    }
378    info!("reconciling person account");
379
380    let namespace = person.get_namespace();
381    let status = person
382        .update_status(kanidm_client.clone(), ctx.clone())
383        .await
384        .map_err(|e| {
385            debug!(error = %e, "failed to reconcile status");
386            ctx.kaniop_ctx.metrics.status_update_errors_inc();
387            e
388        })?;
389    let persons_api: Api<KanidmPersonAccount> =
390        Api::namespaced(ctx.kaniop_ctx.client.clone(), &namespace);
391    let outcome = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
392    let outcome_clone = outcome.clone();
393    let action = finalizer(&persons_api, PERSON_FINALIZER, person, move |event| {
394        let outcome = outcome_clone.clone();
395        let ctx = ctx.clone();
396        let status = status.clone();
397        let kanidm_client = kanidm_client.clone();
398        async move {
399            match event {
400                Finalizer::Apply(p) => {
401                    let (action, changed) = p.reconcile(kanidm_client, status, ctx).await?;
402                    outcome.store(changed, std::sync::atomic::Ordering::Relaxed);
403                    Ok(action)
404                }
405                Finalizer::Cleanup(p) => {
406                    let (action, changed) = p.cleanup(kanidm_client, status, ctx).await?;
407                    outcome.store(changed, std::sync::atomic::Ordering::Relaxed);
408                    Ok(action)
409                }
410            }
411        }
412    })
413    .await
414    .or_else(|e| match e {
415        FinalizerError::RemoveFinalizer(kube::Error::Api(ae)) if ae.code == 404 => {
416            debug!("resource already removed during finalizer cleanup");
417            Ok(Action::requeue(idm_reconcile_interval()))
418        }
419        _ => Err(Error::FinalizerError(
420            "failed on person account finalizer".to_string(),
421            Box::new(e),
422        )),
423    })?;
424    let changed = outcome.load(std::sync::atomic::Ordering::Relaxed);
425    Ok((action, changed))
426}
427
428impl KanidmPersonAccount {
429    #[inline]
430    fn get_namespace(&self) -> String {
431        // safe unwrap: person is namespaced scoped
432        self.namespace().unwrap()
433    }
434
435    #[inline]
436    async fn reconcile(
437        &self,
438        kanidm_client: Arc<KanidmClient>,
439        status: KanidmPersonAccountStatus,
440        ctx: Arc<Context>,
441    ) -> Result<(Action, bool)> {
442        match self
443            .internal_reconcile(kanidm_client, status, ctx.clone())
444            .await
445        {
446            Ok(result) => Ok(result),
447            Err(e) => match e {
448                Error::KanidmClientError(_, _) => {
449                    ctx.kaniop_ctx
450                        .recorder
451                        .publish(
452                            &Event {
453                                type_: EventType::Warning,
454                                reason: "KanidmError".to_string(),
455                                note: Some(format!("{e:?}")),
456                                action: "KanidmRequest".to_string(),
457                                secondary: None,
458                            },
459                            &self.object_ref(&()),
460                        )
461                        .await
462                        .map_err(|e| {
463                            warn!(error = %e, "failed to publish KanidmError event");
464                            Error::kube_error(
465                                "publish",
466                                "event",
467                                self.get_namespace(),
468                                self.name_any(),
469                                e,
470                            )
471                        })?;
472                    Err(e)
473                }
474                _ => Err(e),
475            },
476        }
477    }
478
479    async fn internal_reconcile(
480        &self,
481        kanidm_client: Arc<KanidmClient>,
482        status: KanidmPersonAccountStatus,
483        ctx: Arc<Context>,
484    ) -> Result<(Action, bool)> {
485        let name = &self.kanidm_entity_name();
486        let metrics = &ctx.kaniop_ctx.metrics;
487
488        let mut require_status_update = false;
489        let mut changed = false;
490        let mut actions = Vec::new();
491        if is_person_false(TYPE_EXISTS, status.clone()) {
492            debug!(
493                condition = TYPE_EXISTS,
494                status = CONDITION_FALSE,
495                action = "create",
496                "condition triggered action"
497            );
498            record_kanidm_sdk_call(
499                metrics,
500                KANIDM_RESOURCE_PERSON,
501                KANIDM_OP_CREATE,
502                KANIDM_OUTCOME_CHANGED,
503                self.create(&kanidm_client, name),
504            )
505            .await?;
506            require_status_update = true;
507            changed = true;
508            actions.push("create");
509        }
510        if is_person_false(TYPE_UPDATED, status.clone()) {
511            debug!(
512                condition = TYPE_UPDATED,
513                status = CONDITION_FALSE,
514                action = "update",
515                "condition triggered action"
516            );
517            self.update(&kanidm_client, name, metrics).await?;
518            require_status_update = true;
519            changed = true;
520            actions.push("update");
521        }
522
523        if is_person_false(TYPE_POSIX_UPDATED, status.clone())
524            || (is_person_false(TYPE_POSIX_INITIALIZED, status.clone())
525                && is_person(TYPE_POSIX_UPDATED, status.clone()))
526        {
527            debug!(
528                condition = TYPE_POSIX_UPDATED,
529                status = CONDITION_FALSE,
530                action = "update_posix_attributes",
531                "condition triggered action"
532            );
533            record_kanidm_sdk_call(
534                metrics,
535                KANIDM_RESOURCE_PERSON,
536                KANIDM_OP_UNIX_EXTEND,
537                KANIDM_OUTCOME_CHANGED,
538                self.update_posix_attributes(&kanidm_client, name),
539            )
540            .await?;
541            require_status_update = true;
542            changed = true;
543            actions.push("update_posix");
544        }
545
546        if is_person_false(TYPE_SSH_PUBLIC_KEYS, status.clone()) {
547            self.sync_ssh_public_keys(&kanidm_client, name).await?;
548            require_status_update = true;
549            changed = true;
550            actions.push("update_ssh_public_keys");
551        }
552
553        if self.spec.credential_bootstrap_delivery == CredentialBootstrapDelivery::Email {
554            let requested_revision = requested_bootstrap_resend_revision(self);
555            if should_send_bootstrap_email(
556                status.credential_state,
557                &status.credential_bootstrap,
558                requested_revision,
559            ) {
560                // Fail closed: an opt-in email never falls back to a bearer URL in Events.
561                let sender_configured = ctx
562                    .kaniop_ctx
563                    .get_kanidm(self)
564                    .is_some_and(|kanidm| kanidm.spec.mail_sender.is_some());
565                if !sender_configured {
566                    self.record_bootstrap_delivery_error(
567                        &status.credential_bootstrap,
568                        "MailSenderNotConfigured",
569                        ctx.clone(),
570                    )
571                    .await?;
572                    changed = true;
573                } else {
574                    let send_result = record_kanidm_sdk_call(
575                        metrics,
576                        KANIDM_RESOURCE_PERSON,
577                        KANIDM_OP_CREDENTIAL_UPDATE_SEND_INTENT,
578                        KANIDM_OUTCOME_CHANGED,
579                        kanidm_client.idm_person_account_credential_update_send_intent(
580                            name,
581                            Some(u64::from(self.spec.credentials_token_ttl)),
582                            None,
583                        ),
584                    )
585                    .await;
586
587                    match send_result {
588                        Ok(_) => {
589                            let mut bootstrap = status.credential_bootstrap.clone();
590                            bootstrap.state = CredentialBootstrapState::TokenIssued;
591                            bootstrap.token_expires_at = None;
592                            bootstrap.delivery_method = Some(CredentialBootstrapDelivery::Email);
593                            // Preserve the highest queued revision across GitOps rollbacks
594                            // and delivery-mode switches.
595                            bootstrap.last_queued_resend_revision = Some(
596                                bootstrap
597                                    .last_queued_resend_revision
598                                    .unwrap_or_default()
599                                    .max(requested_revision.expect("validated resend revision")),
600                            );
601                            bootstrap.email_queued_at = Some(Time(Timestamp::now()));
602                            bootstrap.delivery_error = None;
603                            let queued_revision =
604                                bootstrap.last_queued_resend_revision.unwrap_or_default();
605                            self.update_credential_bootstrap_status(ctx.clone(), bootstrap)
606                                .await?;
607                            ctx.kaniop_ctx.recorder.publish(
608                                &Event {
609                                    type_: EventType::Normal,
610                                    reason: "CredentialEmailQueued".to_string(),
611                                    note: Some(format!(
612                                        "Kanidm accepted the credential reset email (resend revision {queued_revision}) into its outgoing queue; SMTP delivery is not confirmed."
613                                    )),
614                                    action: format!("QueueCredentialBootstrapEmail revision {queued_revision}"),
615                                    secondary: None,
616                                },
617                                &self.object_ref(&()),
618                            ).await.map_err(|e| Error::kube_error(
619                                "publish", "event", self.get_namespace(), self.name_any(), e
620                            ))?;
621                            changed = true;
622                        }
623                        Err(ClientError::Http(
624                            _,
625                            Some(OperationError::CU0008AccountMissingEmail),
626                            _,
627                        )) => {
628                            self.record_bootstrap_delivery_error(
629                                &status.credential_bootstrap,
630                                "MissingEmail",
631                                ctx.clone(),
632                            )
633                            .await?;
634                            changed = true;
635                        }
636                        Err(e) => {
637                            return Err(Error::kanidm_client_error(
638                                "queue a credential reset email for",
639                                name,
640                                self.kanidm_namespace(),
641                                self.kanidm_name(),
642                                e,
643                            ));
644                        }
645                    }
646                }
647            }
648        } else if should_create_event_token(status.credential_state, &status.credential_bootstrap) {
649            let token_expires_at = record_kanidm_sdk_call(
650                metrics,
651                KANIDM_RESOURCE_PERSON,
652                KANIDM_OP_CREDENTIAL_UPDATE_INTENT,
653                KANIDM_OUTCOME_CHANGED,
654                self.create_reset_token(&kanidm_client, name, ctx.clone()),
655            )
656            .await?;
657            self.update_credential_bootstrap_status(
658                ctx.clone(),
659                CredentialBootstrapStatus {
660                    state: CredentialBootstrapState::TokenIssued,
661                    token_expires_at: Some(token_expires_at),
662                    delivery_method: Some(CredentialBootstrapDelivery::Event),
663                    last_queued_resend_revision: status
664                        .credential_bootstrap
665                        .last_queued_resend_revision,
666                    email_queued_at: status.credential_bootstrap.email_queued_at.clone(),
667                    ..Default::default()
668                },
669            )
670            .await?;
671            changed = true;
672        }
673
674        if require_status_update {
675            debug!(actions = ?actions, "requeueing in 500ms after actions");
676            Ok((Action::requeue(Duration::from_millis(500)), changed))
677        } else {
678            debug!("reconciliation complete, requeueing for next interval");
679            Ok((Action::requeue(idm_reconcile_interval()), changed))
680        }
681    }
682
683    async fn create(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
684        debug!("create");
685        kanidm_client
686            .idm_person_account_create(name, &self.spec.person_attributes.displayname)
687            .await
688            .map_err(|e| {
689                Error::kanidm_client_error(
690                    "create",
691                    name,
692                    self.kanidm_namespace(),
693                    self.kanidm_name(),
694                    e,
695                )
696            })?;
697        Ok(())
698    }
699
700    async fn update(
701        &self,
702        kanidm_client: &KanidmClient,
703        name: &str,
704        metrics: &kaniop_operator::metrics::ControllerMetrics,
705    ) -> Result<()> {
706        debug!("update");
707        trace!(person_attributes = ?self.spec.person_attributes, "updating person attributes");
708        record_kanidm_sdk_call(
709            metrics,
710            KANIDM_RESOURCE_PERSON,
711            KANIDM_OP_UPDATE,
712            KANIDM_OUTCOME_CHANGED,
713            kanidm_client.idm_person_account_update(
714                name,
715                None,
716                Some(&self.spec.person_attributes.displayname),
717                self.spec.person_attributes.legalname.as_deref(),
718                self.spec.person_attributes.mail.as_deref(),
719            ),
720        )
721        .await
722        .map_err(|e| {
723            Error::kanidm_client_error(
724                "update",
725                name,
726                self.kanidm_namespace(),
727                self.kanidm_name(),
728                e,
729            )
730        })?;
731        let mut update_entry = Entry {
732            attrs: BTreeMap::new(),
733        };
734        if let Some(account_expire) = self.spec.person_attributes.account_expire.as_ref() {
735            update_entry.attrs.insert(
736                ATTR_ACCOUNT_EXPIRE.to_string(),
737                vec![account_expire.0.to_string()],
738            );
739        }
740        if let Some(account_valid_from) = self.spec.person_attributes.account_valid_from.as_ref() {
741            update_entry.attrs.insert(
742                ATTR_ACCOUNT_VALID_FROM.to_string(),
743                vec![account_valid_from.0.to_string()],
744            );
745        }
746
747        if update_entry.attrs.is_empty().not() {
748            let _: Entry = record_kanidm_sdk_call(
749                metrics,
750                KANIDM_RESOURCE_PERSON,
751                KANIDM_OP_UPDATE,
752                KANIDM_OUTCOME_CHANGED,
753                kanidm_client.perform_patch_request(&format!("/v1/person/{name}"), update_entry),
754            )
755            .await
756            .map_err(|e| {
757                Error::kanidm_client_error(
758                    "update",
759                    name,
760                    self.kanidm_namespace(),
761                    self.kanidm_name(),
762                    e,
763                )
764            })?;
765        }
766        Ok(())
767    }
768
769    async fn sync_ssh_public_keys(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
770        let Some(desired) = &self.spec.ssh_public_keys else {
771            return Ok(());
772        };
773        debug!("syncing SSH public keys");
774        let observed = read_ssh_public_keys(kanidm_client, name).await?;
775        // Use the original cached status (self.status), not the computed status from update_status.
776        // This ensures we have the tags from before update_status patched them.
777        let managed: BTreeSet<String> = self
778            .status
779            .as_ref()
780            .map(|s| s.managed_ssh_public_key_tags.iter().cloned().collect())
781            .unwrap_or_default();
782
783        trace!(
784            desired_tags = ?desired.keys().collect::<Vec<_>>(),
785            observed_tags = ?observed.keys().collect::<Vec<_>>(),
786            managed_tags = ?managed,
787            "SSH key state"
788        );
789
790        // Revoke keys that are in observed but not in desired.
791        // We revoke any key with a tag that was previously managed (in status) or is currently
792        // in observed but not in desired. This handles both the case where the operator
793        // previously managed the key and the case where the key exists in Kanidm but the
794        // spec no longer includes it.
795        for tag in observed
796            .keys()
797            .filter(|tag| !desired.contains_key(*tag))
798            .cloned()
799            .collect::<Vec<_>>()
800        {
801            // Only revoke if the tag was previously managed or is in the current managed set.
802            // This prevents revoking keys that were added manually and never managed by the operator.
803            if managed.contains(&tag) {
804                debug!(tag = %tag, "revoking managed SSH public key");
805                kanidm_client
806                    .idm_person_account_delete_ssh_pubkey(name, &tag)
807                    .await
808                    .map_err(|e| {
809                        Error::kanidm_client_error_attr(
810                            "delete",
811                            "SSH public key",
812                            name,
813                            self.kanidm_namespace(),
814                            self.kanidm_name(),
815                            e,
816                        )
817                    })?;
818            }
819        }
820
821        for (tag, key) in desired {
822            if observed.get(tag) != Some(key) {
823                // Kanidm does not overwrite an existing tag on insertion.
824                // Rotation therefore requires remove + add (not atomic).
825                if observed.contains_key(tag) {
826                    debug!(tag = %tag, "rotating SSH public key (delete existing)");
827                    kanidm_client
828                        .idm_person_account_delete_ssh_pubkey(name, tag)
829                        .await
830                        .map_err(|e| {
831                            Error::kanidm_client_error_attr(
832                                "delete",
833                                "SSH public key",
834                                name,
835                                self.kanidm_namespace(),
836                                self.kanidm_name(),
837                                e,
838                            )
839                        })?;
840                }
841                // Let Kanidm validate the entire SSH key; do not parse it here.
842                debug!(tag = %tag, "adding SSH public key");
843                kanidm_client
844                    .idm_person_account_post_ssh_pubkey(name, tag, key)
845                    .await
846                    .map_err(|e| {
847                        Error::kanidm_client_error_attr(
848                            "add",
849                            "SSH public key",
850                            name,
851                            self.kanidm_namespace(),
852                            self.kanidm_name(),
853                            e,
854                        )
855                    })?;
856            }
857        }
858        Ok(())
859    }
860
861    async fn update_posix_attributes(
862        &self,
863        kanidm_client: &KanidmClient,
864        name: &str,
865    ) -> Result<()> {
866        debug!("updating posix attributes");
867        trace!(posix_attributes = ?self.spec.posix_attributes, "updating posix attributes");
868        kanidm_client
869            .idm_person_account_unix_extend(
870                name,
871                self.spec
872                    .posix_attributes
873                    .as_ref()
874                    .and_then(|posix| posix.gidnumber),
875                self.spec
876                    .posix_attributes
877                    .as_ref()
878                    .and_then(|posix| posix.loginshell.as_deref()),
879            )
880            .await
881            .map_err(|e| {
882                Error::kanidm_client_error(
883                    "update",
884                    name,
885                    self.kanidm_namespace(),
886                    self.kanidm_name(),
887                    e,
888                )
889            })?;
890        Ok(())
891    }
892
893    async fn create_reset_token(
894        &self,
895        kanidm_client: &KanidmClient,
896        name: &str,
897        ctx: Arc<Context>,
898    ) -> Result<Time> {
899        debug!("create reset token");
900        let cu_token = kanidm_client
901            .idm_person_account_credential_update_intent(
902                name,
903                Some(self.spec.credentials_token_ttl),
904            )
905            .await
906            .map_err(|e| {
907                Error::kanidm_client_error(
908                    "create a credential reset token for",
909                    name,
910                    self.kanidm_namespace(),
911                    self.kanidm_name(),
912                    e,
913                )
914            })?;
915        let token = cu_token.token.as_str();
916        let url = if let Some(base_url) = ctx.kaniop_ctx.get_kanidm(self).map(|k| {
917            k.spec
918                .origin
919                .clone()
920                .unwrap_or_else(|| format!("https://{}", k.spec.domain))
921        }) {
922            format!("{base_url}/ui/reset?token={token}")
923        } else {
924            let mut url = kanidm_client.make_url("/ui/reset");
925            url.query_pairs_mut().append_pair("token", token);
926            url.to_string()
927        };
928        let local_offset = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
929        let expiry_time = cu_token.expiry_time.to_offset(local_offset);
930
931        let msg = format!(
932            "Update these user credentials with this link: {url}. This token will expire at: {}",
933            expiry_time
934                .format(&Rfc3339)
935                .unwrap_or_else(|_| expiry_time.to_string())
936        );
937        ctx.kaniop_ctx
938            .recorder
939            .publish(
940                &Event {
941                    type_: EventType::Normal,
942                    reason: "TokenCreated".to_string(),
943                    note: Some(msg),
944                    action: "CreateUpdateCredentialsToken".into(),
945                    secondary: None,
946                },
947                &self.object_ref(&()),
948            )
949            .await
950            .map_err(|e| {
951                warn!(error = %e, "failed to publish TokenCreated event");
952                Error::kube_error("publish", "event", self.get_namespace(), self.name_any(), e)
953            })?;
954
955        let expiry_timestamp = Timestamp::from_second(cu_token.expiry_time.unix_timestamp())
956            .map_err(|e| Error::ParseError(format!("failed to convert token expiry: {e}")))?;
957        Ok(Time(expiry_timestamp))
958    }
959
960    async fn record_bootstrap_delivery_error(
961        &self,
962        previous: &CredentialBootstrapStatus,
963        reason: &str,
964        ctx: Arc<Context>,
965    ) -> Result<()> {
966        if previous.delivery_error.as_deref() == Some(reason) {
967            return Ok(());
968        }
969        let mut bootstrap = previous.clone();
970        bootstrap.delivery_error = Some(reason.to_string());
971        self.update_credential_bootstrap_status(ctx.clone(), bootstrap)
972            .await?;
973        ctx.kaniop_ctx
974            .recorder
975            .publish(
976                &Event {
977                    type_: EventType::Warning,
978                    reason: reason.to_string(),
979                    note: Some(format!("Credential email bootstrap blocked: {reason}")),
980                    action: "QueueCredentialBootstrapEmail".into(),
981                    secondary: None,
982                },
983                &self.object_ref(&()),
984            )
985            .await
986            .map_err(|e| {
987                Error::kube_error("publish", "event", self.get_namespace(), self.name_any(), e)
988            })?;
989        Ok(())
990    }
991
992    async fn update_credential_bootstrap_status(
993        &self,
994        ctx: Arc<Context>,
995        bootstrap: CredentialBootstrapStatus,
996    ) -> Result<()> {
997        let namespace = self.get_namespace();
998        let person_api =
999            Api::<KanidmPersonAccount>::namespaced(ctx.kaniop_ctx.client.clone(), &namespace);
1000        person_api
1001            .patch_status(
1002                &self.name_any(),
1003                &PatchParams::default(),
1004                &Patch::Merge(credential_bootstrap_merge_patch(&bootstrap)),
1005            )
1006            .await
1007            .map_err(|e| {
1008                Error::kube_status_error("KanidmPersonAccount", namespace, self.name_any(), e)
1009            })?;
1010        Ok(())
1011    }
1012
1013    async fn cleanup(
1014        &self,
1015        kanidm_client: Arc<KanidmClient>,
1016        status: KanidmPersonAccountStatus,
1017        ctx: Arc<Context>,
1018    ) -> Result<(Action, bool)> {
1019        let name = &self.kanidm_entity_name();
1020        let mut changed = false;
1021
1022        if is_person(TYPE_EXISTS, status.clone()) {
1023            debug!("delete");
1024            record_kanidm_sdk_call(
1025                &ctx.kaniop_ctx.metrics,
1026                KANIDM_RESOURCE_PERSON,
1027                KANIDM_OP_DELETE,
1028                KANIDM_OUTCOME_CHANGED,
1029                kanidm_client.idm_person_account_delete(name),
1030            )
1031            .await
1032            .map_err(|e| {
1033                Error::kanidm_client_error(
1034                    "delete",
1035                    name,
1036                    self.kanidm_namespace(),
1037                    self.kanidm_name(),
1038                    e,
1039                )
1040            })?;
1041            changed = true;
1042        }
1043        Ok((Action::requeue(idm_reconcile_interval()), changed))
1044    }
1045
1046    async fn update_status(
1047        &self,
1048        kanidm_client: Arc<KanidmClient>,
1049        ctx: Arc<Context>,
1050    ) -> Result<KanidmPersonAccountStatus> {
1051        // safe unwrap: person is namespaced scoped
1052        let namespace = self.get_namespace();
1053        let name = self.kanidm_entity_name();
1054        let metrics = &ctx.kaniop_ctx.metrics;
1055        let start = tokio::time::Instant::now();
1056        let current_person = kanidm_client
1057            .idm_person_account_get(&name)
1058            .await
1059            .map_err(|e| {
1060                let elapsed = start.elapsed();
1061                metrics.record_kanidm_sdk_outcome(
1062                    KANIDM_RESOURCE_PERSON,
1063                    KANIDM_OP_GET,
1064                    KANIDM_OUTCOME_ERROR,
1065                    elapsed,
1066                );
1067                Error::kanidm_client_error(
1068                    "get",
1069                    name.as_str(),
1070                    self.kanidm_namespace(),
1071                    self.kanidm_name(),
1072                    e,
1073                )
1074            })?;
1075        metrics.record_kanidm_sdk_outcome(
1076            KANIDM_RESOURCE_PERSON,
1077            KANIDM_OP_GET,
1078            KANIDM_OUTCOME_UNCHANGED,
1079            start.elapsed(),
1080        );
1081
1082        let credential_state = if current_person.is_some() {
1083            let cred_start = tokio::time::Instant::now();
1084            let probe = tokio::try_join!(
1085                kanidm_client.idm_person_account_get_attr(&name, ATTR_PRIMARY_CREDENTIAL),
1086                kanidm_client.idm_person_account_get_attr(&name, ATTR_PASSKEYS),
1087                kanidm_client.idm_person_account_get_attr(&name, ATTR_ATTESTED_PASSKEYS),
1088            );
1089            match probe {
1090                Ok((primary, passkeys, attested_passkeys)) => {
1091                    let observed_state =
1092                        credential_state_from_attributes(&primary, &passkeys, &attested_passkeys);
1093                    let state = if observed_state == CredentialState::Present {
1094                        CredentialState::Present
1095                    } else {
1096                        match credential_attributes_searchable(&kanidm_client, &name).await {
1097                            Ok(true) => CredentialState::Absent,
1098                            Ok(false) => {
1099                                warn!(
1100                                    "credential attributes are not searchable; leaving state unknown"
1101                                );
1102                                CredentialState::Unknown
1103                            }
1104                            Err(e) => {
1105                                warn!(
1106                                    error = ?e,
1107                                    "credential effective-access probe failed; leaving state unknown"
1108                                );
1109                                CredentialState::Unknown
1110                            }
1111                        }
1112                    };
1113                    trace!(
1114                        credential_state = ?state,
1115                        primary_present = primary.as_ref().is_some_and(|v| v.is_empty().not()),
1116                        passkeys_count = passkeys.as_ref().map_or(0, Vec::len),
1117                        attested_passkeys_count = attested_passkeys.as_ref().map_or(0, Vec::len),
1118                        "read-only credential status"
1119                    );
1120                    metrics.record_kanidm_sdk_outcome(
1121                        KANIDM_RESOURCE_PERSON,
1122                        KANIDM_OP_GET_CREDENTIAL_STATUS,
1123                        if state == CredentialState::Unknown {
1124                            KANIDM_OUTCOME_ERROR
1125                        } else {
1126                            KANIDM_OUTCOME_UNCHANGED
1127                        },
1128                        cred_start.elapsed(),
1129                    );
1130                    state
1131                }
1132                Err(e) => {
1133                    warn!(
1134                        error = ?e,
1135                        "read-only credential status probe failed; leaving state unknown"
1136                    );
1137                    metrics.record_kanidm_sdk_outcome(
1138                        KANIDM_RESOURCE_PERSON,
1139                        KANIDM_OP_GET_CREDENTIAL_STATUS,
1140                        KANIDM_OUTCOME_ERROR,
1141                        cred_start.elapsed(),
1142                    );
1143                    CredentialState::Unknown
1144                }
1145            }
1146        } else {
1147            CredentialState::Unknown
1148        };
1149
1150        let ssh_public_keys = if current_person.is_some() && self.spec.ssh_public_keys.is_some() {
1151            Some(read_ssh_public_keys(&kanidm_client, &name).await?)
1152        } else {
1153            None
1154        };
1155
1156        let status = self.generate_status(current_person, credential_state, ssh_public_keys)?;
1157        if self.status.as_ref() == Some(&status) {
1158            trace!("status unchanged, skipping patch");
1159            return Ok(status);
1160        }
1161        if let Some(old) = self.status.as_ref() {
1162            let old_conds: Vec<_> = old
1163                .conditions
1164                .iter()
1165                .flatten()
1166                .map(|c| format!("{}={}", c.type_, c.status))
1167                .collect();
1168            let new_conds: Vec<_> = status
1169                .conditions
1170                .iter()
1171                .flatten()
1172                .map(|c| format!("{}={}", c.type_, c.status))
1173                .collect();
1174            debug!(
1175                old = ?old_conds,
1176                new = ?new_conds,
1177                old_ready = old.ready,
1178                new_ready = status.ready,
1179                old_credential_state = ?old.credential_state,
1180                new_credential_state = ?status.credential_state,
1181                "status changed"
1182            );
1183        } else {
1184            debug!(conditions = ?status.conditions, "initial status patch");
1185        }
1186        let status_patch = Patch::Apply(KanidmPersonAccount {
1187            status: Some(status.clone()),
1188            ..KanidmPersonAccount::default()
1189        });
1190        debug!("updating status");
1191        trace!(status_patch = ?status_patch, "status patch");
1192        let patch = PatchParams::apply(PERSON_OPERATOR_NAME).force();
1193        let kanidm_api =
1194            Api::<KanidmPersonAccount>::namespaced(ctx.kaniop_ctx.client.clone(), &namespace);
1195        let _o = kanidm_api
1196            .patch_status(&self.name_any(), &patch, &status_patch)
1197            .await
1198            .map_err(|e| {
1199                Error::kube_status_error("KanidmPersonAccount", namespace, self.name_any(), e)
1200            })?;
1201        Ok(status)
1202    }
1203
1204    fn generate_status(
1205        &self,
1206        person: Option<Entry>,
1207        credential_state: CredentialState,
1208        ssh_public_keys: Option<BTreeMap<String, String>>,
1209    ) -> Result<KanidmPersonAccountStatus> {
1210        let now = Timestamp::now();
1211        let current_conditions = self.status.as_ref().and_then(|s| s.conditions.as_ref());
1212        let managed_ssh_public_key_tags = if let Some(desired) = &self.spec.ssh_public_keys {
1213            // Tags this operator currently owns: union of:
1214            // 1. Tags that were previously managed and are still in observed (need revocation if not in desired)
1215            // 2. Tags that are in desired and match observed (new or existing managed tags)
1216            // This ensures managed_tags includes tags pending revocation, preventing the SSH condition
1217            // from becoming True prematurely and blocking sync_ssh_public_keys.
1218            if let Some(observed) = ssh_public_keys.as_ref() {
1219                let old_managed: BTreeSet<String> = self
1220                    .status
1221                    .as_ref()
1222                    .map(|s| s.managed_ssh_public_key_tags.iter().cloned().collect())
1223                    .unwrap_or_default();
1224
1225                // Tags that were previously managed and are still in observed
1226                // (these need to be revoked if not in desired)
1227                let still_in_observed: BTreeSet<String> = old_managed
1228                    .iter()
1229                    .filter(|tag| observed.contains_key(*tag))
1230                    .cloned()
1231                    .collect();
1232
1233                // Tags that are in desired and match observed (new or existing managed tags)
1234                let new_managed: BTreeSet<String> = desired
1235                    .iter()
1236                    .filter(|(tag, key)| observed.get(*tag).map(String::as_str) == Some(key))
1237                    .map(|(tag, _)| tag.clone())
1238                    .collect();
1239
1240                still_in_observed.union(&new_managed).cloned().collect()
1241            } else {
1242                Vec::new()
1243            }
1244        } else {
1245            // Removing the field opts out of management without revoking keys.
1246            Vec::new()
1247        };
1248
1249        match person {
1250            Some(p) => {
1251                let exist_condition = Condition {
1252                    type_: TYPE_EXISTS.to_string(),
1253                    status: CONDITION_TRUE.to_string(),
1254                    reason: "Exists".to_string(),
1255                    message: "Person exists.".to_string(),
1256                    last_transition_time: last_transition_time(
1257                        current_conditions,
1258                        TYPE_EXISTS,
1259                        CONDITION_TRUE,
1260                        "Exists",
1261                    ),
1262                    observed_generation: self.metadata.generation,
1263                };
1264
1265                let current_person_attributes = KanidmPersonAttributes::from(p.clone());
1266                let updated_condition = if self.spec.person_attributes == current_person_attributes
1267                {
1268                    Condition {
1269                        type_: TYPE_UPDATED.to_string(),
1270                        status: CONDITION_TRUE.to_string(),
1271                        reason: REASON_ATTRIBUTES_MATCH.to_string(),
1272                        message: "Person exists with desired attributes.".to_string(),
1273                        last_transition_time: last_transition_time(
1274                            current_conditions,
1275                            TYPE_UPDATED,
1276                            CONDITION_TRUE,
1277                            REASON_ATTRIBUTES_MATCH,
1278                        ),
1279                        observed_generation: self.metadata.generation,
1280                    }
1281                } else {
1282                    let spec = &self.spec.person_attributes;
1283                    debug!(
1284                        displayname_spec = %spec.displayname,
1285                        displayname_actual = %current_person_attributes.displayname,
1286                        mail_spec = ?spec.mail,
1287                        mail_actual = ?current_person_attributes.mail,
1288                        legalname_spec = ?spec.legalname,
1289                        legalname_actual = ?current_person_attributes.legalname,
1290                        account_valid_from_spec = ?spec.account_valid_from,
1291                        account_valid_from_actual = ?current_person_attributes.account_valid_from,
1292                        account_expire_spec = ?spec.account_expire,
1293                        account_expire_actual = ?current_person_attributes.account_expire,
1294                        "person attributes mismatch"
1295                    );
1296                    Condition {
1297                        type_: TYPE_UPDATED.to_string(),
1298                        status: CONDITION_FALSE.to_string(),
1299                        reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
1300                        message: "Person exists with different attributes.".to_string(),
1301                        last_transition_time: last_transition_time(
1302                            current_conditions,
1303                            TYPE_UPDATED,
1304                            CONDITION_FALSE,
1305                            REASON_ATTRIBUTES_NOT_MATCH,
1306                        ),
1307                        observed_generation: self.metadata.generation,
1308                    }
1309                };
1310
1311                let current_person_posix = KanidmAccountPosixAttributes::from(p);
1312                let posix_initialized_condition = if current_person_posix.gidnumber.is_some() {
1313                    Condition {
1314                        type_: TYPE_POSIX_INITIALIZED.to_string(),
1315                        status: CONDITION_TRUE.to_string(),
1316                        reason: "PosixInitialized".to_string(),
1317                        message: "Person exists with POSIX attributes.".to_string(),
1318                        last_transition_time: last_transition_time(
1319                            current_conditions,
1320                            TYPE_POSIX_INITIALIZED,
1321                            CONDITION_TRUE,
1322                            "PosixInitialized",
1323                        ),
1324                        observed_generation: self.metadata.generation,
1325                    }
1326                } else {
1327                    Condition {
1328                        type_: TYPE_POSIX_INITIALIZED.to_string(),
1329                        status: CONDITION_FALSE.to_string(),
1330                        reason: "PosixNotInitialized".to_string(),
1331                        message: "Person exists without POSIX attributes.".to_string(),
1332                        last_transition_time: last_transition_time(
1333                            current_conditions,
1334                            TYPE_POSIX_INITIALIZED,
1335                            CONDITION_FALSE,
1336                            "PosixNotInitialized",
1337                        ),
1338                        observed_generation: self.metadata.generation,
1339                    }
1340                };
1341
1342                let posix_updated_condition = self.spec.posix_attributes.as_ref().map(|posix| {
1343                    if posix == &current_person_posix {
1344                        Condition {
1345                            type_: TYPE_POSIX_UPDATED.to_string(),
1346                            status: CONDITION_TRUE.to_string(),
1347                            reason: REASON_ATTRIBUTES_MATCH.to_string(),
1348                            message: "Person exists with desired POSIX attributes.".to_string(),
1349                            last_transition_time: last_transition_time(
1350                                current_conditions,
1351                                TYPE_POSIX_UPDATED,
1352                                CONDITION_TRUE,
1353                                REASON_ATTRIBUTES_MATCH,
1354                            ),
1355                            observed_generation: self.metadata.generation,
1356                        }
1357                    } else {
1358                        debug!(
1359                            gidnumber_spec = ?posix.gidnumber,
1360                            gidnumber_actual = ?current_person_posix.gidnumber,
1361                            loginshell_spec = ?posix.loginshell,
1362                            loginshell_actual = ?current_person_posix.loginshell,
1363                            "posix attributes mismatch"
1364                        );
1365                        Condition {
1366                            type_: TYPE_POSIX_UPDATED.to_string(),
1367                            status: CONDITION_FALSE.to_string(),
1368                            reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
1369                            message: "Person exists with different POSIX attributes.".to_string(),
1370                            last_transition_time: last_transition_time(
1371                                current_conditions,
1372                                TYPE_POSIX_UPDATED,
1373                                CONDITION_FALSE,
1374                                REASON_ATTRIBUTES_NOT_MATCH,
1375                            ),
1376                            observed_generation: self.metadata.generation,
1377                        }
1378                    }
1379                });
1380
1381                let (credential_condition_status, credential_reason, credential_message) =
1382                    match credential_state {
1383                        CredentialState::Present => {
1384                            (CONDITION_TRUE, "Present", "Credentials are present.")
1385                        }
1386                        CredentialState::Absent => (
1387                            CONDITION_FALSE,
1388                            "NotPresent",
1389                            "Credentials are not present.",
1390                        ),
1391                        CredentialState::Unknown => (
1392                            CONDITION_UNKNOWN,
1393                            "DetectionFailed",
1394                            "Credential presence could not be determined.",
1395                        ),
1396                    };
1397                let credentials_condition = Condition {
1398                    type_: TYPE_CREDENTIAL.to_string(),
1399                    status: credential_condition_status.to_string(),
1400                    reason: credential_reason.to_string(),
1401                    message: credential_message.to_string(),
1402                    last_transition_time: last_transition_time(
1403                        current_conditions,
1404                        TYPE_CREDENTIAL,
1405                        credential_condition_status,
1406                        credential_reason,
1407                    ),
1408                    observed_generation: self.metadata.generation,
1409                };
1410
1411                let mut credential_bootstrap = self
1412                    .status
1413                    .as_ref()
1414                    .map(|status| status.credential_bootstrap.clone())
1415                    .unwrap_or_default();
1416                if credential_state == CredentialState::Present {
1417                    credential_bootstrap.state = CredentialBootstrapState::Complete;
1418                    credential_bootstrap.token_expires_at = None;
1419                    credential_bootstrap.delivery_error = None;
1420                }
1421
1422                let validity_condition = {
1423                    let valid = if let Some(valid_from) =
1424                        current_person_attributes.account_valid_from.as_ref()
1425                    {
1426                        now > valid_from.0
1427                    } else {
1428                        true
1429                    } && if let Some(expire) =
1430                        current_person_attributes.account_expire.as_ref()
1431                    {
1432                        now < expire.0
1433                    } else {
1434                        true
1435                    };
1436
1437                    if valid {
1438                        Condition {
1439                            type_: TYPE_VALIDITY.to_string(),
1440                            status: CONDITION_TRUE.to_string(),
1441                            reason: "Valid".to_string(),
1442                            message: "Account is valid.".to_string(),
1443                            last_transition_time: last_transition_time(
1444                                current_conditions,
1445                                TYPE_VALIDITY,
1446                                CONDITION_TRUE,
1447                                "Valid",
1448                            ),
1449                            observed_generation: self.metadata.generation,
1450                        }
1451                    } else {
1452                        Condition {
1453                            type_: TYPE_VALIDITY.to_string(),
1454                            status: CONDITION_FALSE.to_string(),
1455                            reason: "Invalid".to_string(),
1456                            message: "Account is invalid.".to_string(),
1457                            last_transition_time: last_transition_time(
1458                                current_conditions,
1459                                TYPE_VALIDITY,
1460                                CONDITION_FALSE,
1461                                "Invalid",
1462                            ),
1463                            observed_generation: self.metadata.generation,
1464                        }
1465                    }
1466                };
1467
1468                let old_managed_ssh_public_key_tags: Vec<String> = self
1469                    .status
1470                    .as_ref()
1471                    .map(|s| s.managed_ssh_public_key_tags.clone())
1472                    .unwrap_or_default();
1473
1474                let ssh_public_keys_condition = if let Some(desired) = &self.spec.ssh_public_keys {
1475                    let observed = ssh_public_keys.as_ref().ok_or_else(|| {
1476                        Error::MissingData("SSH key state was not fetched from Kanidm".to_string())
1477                    })?;
1478                    let matches =
1479                        ssh_public_keys_match(desired, observed, &old_managed_ssh_public_key_tags);
1480                    let (condition_status, reason, message) = if matches {
1481                        (
1482                            CONDITION_TRUE,
1483                            REASON_ATTRIBUTES_MATCH,
1484                            "Person has the desired managed SSH public keys.",
1485                        )
1486                    } else {
1487                        (
1488                            CONDITION_FALSE,
1489                            REASON_ATTRIBUTES_NOT_MATCH,
1490                            "Person SSH public keys differ from the managed keys.",
1491                        )
1492                    };
1493                    Some(Condition {
1494                        type_: TYPE_SSH_PUBLIC_KEYS.to_string(),
1495                        status: condition_status.to_string(),
1496                        reason: reason.to_string(),
1497                        message: message.to_string(),
1498                        last_transition_time: last_transition_time(
1499                            current_conditions,
1500                            TYPE_SSH_PUBLIC_KEYS,
1501                            condition_status,
1502                            reason,
1503                        ),
1504                        observed_generation: self.metadata.generation,
1505                    })
1506                } else {
1507                    None
1508                };
1509
1510                let delivery_condition = (self.spec.credential_bootstrap_delivery
1511                    == CredentialBootstrapDelivery::Email)
1512                    .then(|| {
1513                        let (condition_status, reason, message) = bootstrap_email_condition(
1514                            credential_state,
1515                            &credential_bootstrap,
1516                            requested_bootstrap_resend_revision(self),
1517                        );
1518                        Condition {
1519                            type_: TYPE_CREDENTIAL_BOOTSTRAP_DELIVERY.to_string(),
1520                            status: condition_status.to_string(),
1521                            reason: reason.to_string(),
1522                            message: message.to_string(),
1523                            last_transition_time: last_transition_time(
1524                                current_conditions,
1525                                TYPE_CREDENTIAL_BOOTSTRAP_DELIVERY,
1526                                condition_status,
1527                                reason,
1528                            ),
1529                            observed_generation: self.metadata.generation,
1530                        }
1531                    });
1532
1533                let conditions = vec![
1534                    exist_condition,
1535                    updated_condition,
1536                    posix_initialized_condition,
1537                    validity_condition,
1538                    credentials_condition,
1539                ]
1540                .into_iter()
1541                .chain(posix_updated_condition)
1542                .chain(ssh_public_keys_condition)
1543                .chain(delivery_condition)
1544                .collect::<Vec<_>>();
1545                let status = conditions
1546                    .iter()
1547                    .filter(|c| {
1548                        c.type_ != TYPE_POSIX_INITIALIZED
1549                            && c.type_ != TYPE_CREDENTIAL
1550                            && c.type_ != TYPE_VALIDITY
1551                    })
1552                    .all(|c| c.status == CONDITION_TRUE);
1553                Ok(KanidmPersonAccountStatus {
1554                    conditions: Some(conditions),
1555                    ready: status,
1556                    gid: current_person_posix.gidnumber,
1557                    kanidm_ref: self.kanidm_ref(),
1558                    credential_state,
1559                    credential_bootstrap,
1560                    managed_ssh_public_key_tags,
1561                })
1562            }
1563            None => {
1564                let conditions = vec![Condition {
1565                    type_: TYPE_EXISTS.to_string(),
1566                    status: CONDITION_FALSE.to_string(),
1567                    reason: "NotExists".to_string(),
1568                    message: "Person is not present.".to_string(),
1569                    last_transition_time: last_transition_time(
1570                        current_conditions,
1571                        TYPE_EXISTS,
1572                        CONDITION_FALSE,
1573                        "NotExists",
1574                    ),
1575                    observed_generation: self.metadata.generation,
1576                }];
1577                Ok(KanidmPersonAccountStatus {
1578                    conditions: Some(conditions),
1579                    ready: false,
1580                    gid: None,
1581                    kanidm_ref: self.kanidm_ref(),
1582                    credential_state: CredentialState::Unknown,
1583                    credential_bootstrap: CredentialBootstrapStatus::default(),
1584                    managed_ssh_public_key_tags,
1585                })
1586            }
1587        }
1588    }
1589}
1590
1591pub fn is_person(type_: &str, status: KanidmPersonAccountStatus) -> bool {
1592    status
1593        .conditions
1594        .unwrap_or_default()
1595        .iter()
1596        .any(|c| c.type_ == type_ && c.status == CONDITION_TRUE)
1597}
1598
1599pub fn is_person_false(type_: &str, status: KanidmPersonAccountStatus) -> bool {
1600    status
1601        .conditions
1602        .unwrap_or_default()
1603        .iter()
1604        .any(|c| c.type_ == type_ && c.status == CONDITION_FALSE)
1605}
1606
1607#[cfg(test)]
1608mod tests {
1609    use super::*;
1610
1611    #[test]
1612    fn bootstrap_merge_patch_explicitly_clears_optional_fields() {
1613        let patch = credential_bootstrap_merge_patch(&CredentialBootstrapStatus::default());
1614        let status = &patch["status"]["credentialBootstrap"];
1615        assert_eq!(status["state"], "pending");
1616        for field in [
1617            "tokenExpiresAt",
1618            "deliveryMethod",
1619            "lastQueuedResendRevision",
1620            "emailQueuedAt",
1621            "deliveryError",
1622        ] {
1623            assert_eq!(
1624                status.get(field),
1625                Some(&serde_json::Value::Null),
1626                "missing explicit null for {field}"
1627            );
1628        }
1629
1630        let patch = credential_bootstrap_merge_patch(&CredentialBootstrapStatus {
1631            state: CredentialBootstrapState::TokenIssued,
1632            delivery_method: Some(CredentialBootstrapDelivery::Email),
1633            last_queued_resend_revision: Some(1),
1634            delivery_error: Some("MissingEmail".into()),
1635            ..Default::default()
1636        });
1637        let status = &patch["status"]["credentialBootstrap"];
1638        assert_eq!(status["state"], "tokenIssued");
1639        assert_eq!(status["deliveryMethod"], "email");
1640        assert_eq!(status["lastQueuedResendRevision"], 1);
1641        assert_eq!(status["deliveryError"], "MissingEmail");
1642    }
1643
1644    #[test]
1645    fn email_bootstrap_only_queues_initial_email_and_higher_annotated_revisions() {
1646        let mut person = KanidmPersonAccount::default();
1647        assert_eq!(requested_bootstrap_resend_revision(&person), Some(0));
1648        person.metadata.annotations = Some(std::collections::BTreeMap::from([(
1649            ANNOTATION_CREDENTIAL_BOOTSTRAP_RESEND_REVISION.to_string(),
1650            "2".to_string(),
1651        )]));
1652        assert_eq!(requested_bootstrap_resend_revision(&person), Some(2));
1653        person.metadata.annotations.as_mut().unwrap().insert(
1654            ANNOTATION_CREDENTIAL_BOOTSTRAP_RESEND_REVISION.to_string(),
1655            "invalid".to_string(),
1656        );
1657        assert_eq!(requested_bootstrap_resend_revision(&person), None);
1658
1659        let mut status = CredentialBootstrapStatus::default();
1660        assert!(should_send_bootstrap_email(
1661            CredentialState::Absent,
1662            &status,
1663            Some(0)
1664        ));
1665        assert!(!should_send_bootstrap_email(
1666            CredentialState::Absent,
1667            &status,
1668            None
1669        ));
1670        assert!(!should_send_bootstrap_email(
1671            CredentialState::Unknown,
1672            &status,
1673            Some(0)
1674        ));
1675        assert!(!should_send_bootstrap_email(
1676            CredentialState::Present,
1677            &status,
1678            Some(0)
1679        ));
1680
1681        // The first switch from Events to Email still queues the initial invite.
1682        status.state = CredentialBootstrapState::TokenIssued;
1683        status.delivery_method = Some(CredentialBootstrapDelivery::Event);
1684        assert!(should_send_bootstrap_email(
1685            CredentialState::Absent,
1686            &status,
1687            Some(0)
1688        ));
1689        status.delivery_method = Some(CredentialBootstrapDelivery::Email);
1690        status.last_queued_resend_revision = Some(0);
1691        assert!(!should_send_bootstrap_email(
1692            CredentialState::Absent,
1693            &status,
1694            Some(0)
1695        ));
1696        assert!(should_send_bootstrap_email(
1697            CredentialState::Absent,
1698            &status,
1699            Some(1)
1700        ));
1701
1702        status.last_queued_resend_revision = Some(2);
1703        assert!(!should_send_bootstrap_email(
1704            CredentialState::Absent,
1705            &status,
1706            Some(2)
1707        ));
1708        assert!(!should_send_bootstrap_email(
1709            CredentialState::Absent,
1710            &status,
1711            Some(1)
1712        ));
1713        assert!(!should_send_bootstrap_email(
1714            CredentialState::Absent,
1715            &status,
1716            Some(0)
1717        ));
1718        assert!(should_send_bootstrap_email(
1719            CredentialState::Absent,
1720            &status,
1721            Some(3)
1722        ));
1723
1724        // Delivery-mode switches are not resend requests.
1725        status.delivery_method = Some(CredentialBootstrapDelivery::Event);
1726        assert!(!should_send_bootstrap_email(
1727            CredentialState::Absent,
1728            &status,
1729            Some(0)
1730        ));
1731        assert!(!should_send_bootstrap_email(
1732            CredentialState::Absent,
1733            &status,
1734            Some(2)
1735        ));
1736        assert!(should_send_bootstrap_email(
1737            CredentialState::Absent,
1738            &status,
1739            Some(3)
1740        ));
1741        status.state = CredentialBootstrapState::Complete;
1742        assert!(!should_send_bootstrap_email(
1743            CredentialState::Absent,
1744            &status,
1745            Some(3)
1746        ));
1747    }
1748
1749    #[test]
1750    fn stale_resend_does_not_make_account_unready_after_failed_newer_request() {
1751        let status = CredentialBootstrapStatus {
1752            state: CredentialBootstrapState::TokenIssued,
1753            delivery_method: Some(CredentialBootstrapDelivery::Email),
1754            last_queued_resend_revision: Some(2),
1755            delivery_error: Some("MailSenderNotConfigured".to_string()),
1756            ..Default::default()
1757        };
1758        let stale = bootstrap_email_condition(CredentialState::Absent, &status, Some(1));
1759        assert_eq!((stale.0, stale.1), (CONDITION_TRUE, "StaleResendIgnored"));
1760
1761        let already_sent = bootstrap_email_condition(CredentialState::Absent, &status, Some(2));
1762        assert_eq!(
1763            (already_sent.0, already_sent.1),
1764            (CONDITION_TRUE, "EmailQueued")
1765        );
1766
1767        let pending_failure = bootstrap_email_condition(CredentialState::Absent, &status, Some(3));
1768        assert_eq!(
1769            (pending_failure.0, pending_failure.1),
1770            (CONDITION_FALSE, "MailSenderNotConfigured")
1771        );
1772        let invalid = bootstrap_email_condition(CredentialState::Absent, &status, None);
1773        assert_eq!(
1774            (invalid.0, invalid.1),
1775            (CONDITION_FALSE, "InvalidResendRevision")
1776        );
1777    }
1778
1779    #[test]
1780    fn event_mode_renews_after_expiry_and_switches_back_from_email() {
1781        let mut status = CredentialBootstrapStatus::default();
1782        assert!(should_create_event_token(CredentialState::Absent, &status));
1783        status.state = CredentialBootstrapState::TokenIssued;
1784        status.delivery_method = Some(CredentialBootstrapDelivery::Email);
1785        assert!(should_create_event_token(CredentialState::Absent, &status));
1786        status.delivery_method = Some(CredentialBootstrapDelivery::Event);
1787        assert!(!should_create_event_token(CredentialState::Absent, &status));
1788        status.token_expires_at = Some(Time(Timestamp::from_second(1_600_000_000).unwrap()));
1789        assert!(should_create_event_token(CredentialState::Absent, &status));
1790        status.state = CredentialBootstrapState::Complete;
1791        assert!(!should_create_event_token(CredentialState::Absent, &status));
1792    }
1793
1794    #[test]
1795    fn no_credential_attributes_is_absent() {
1796        assert_eq!(
1797            credential_state_from_attributes(&None, &None, &None),
1798            CredentialState::Absent
1799        );
1800    }
1801
1802    #[test]
1803    fn primary_credential_is_present() {
1804        assert_eq!(
1805            credential_state_from_attributes(&Some(vec!["primary".to_string()]), &None, &None,),
1806            CredentialState::Present
1807        );
1808    }
1809
1810    #[test]
1811    fn passkey_only_is_present() {
1812        assert_eq!(
1813            credential_state_from_attributes(&None, &Some(vec!["passkey".to_string()]), &None,),
1814            CredentialState::Present
1815        );
1816    }
1817
1818    #[test]
1819    fn attested_passkey_only_is_present() {
1820        assert_eq!(
1821            credential_state_from_attributes(
1822                &None,
1823                &None,
1824                &Some(vec!["attested-passkey".to_string()]),
1825            ),
1826            CredentialState::Present
1827        );
1828    }
1829
1830    #[test]
1831    fn scim_grant_allows_all_credential_attributes() {
1832        assert!(scim_search_allows_all_credential_attributes(
1833            &serde_json::json!("Grant")
1834        ));
1835    }
1836
1837    #[test]
1838    fn scim_allow_requires_all_credential_attributes() {
1839        assert!(scim_search_allows_all_credential_attributes(
1840            &serde_json::json!({
1841                "Allow": [
1842                    ATTR_PRIMARY_CREDENTIAL,
1843                    ATTR_PASSKEYS,
1844                    ATTR_ATTESTED_PASSKEYS
1845                ]
1846            })
1847        ));
1848        assert!(!scim_search_allows_all_credential_attributes(
1849            &serde_json::json!({
1850                "Allow": [ATTR_PRIMARY_CREDENTIAL, ATTR_PASSKEYS]
1851            })
1852        ));
1853    }
1854
1855    #[test]
1856    fn scim_deny_or_malformed_access_is_not_searchable() {
1857        assert!(!scim_search_allows_all_credential_attributes(
1858            &serde_json::json!("Deny")
1859        ));
1860        assert!(!scim_search_allows_all_credential_attributes(
1861            &serde_json::json!({})
1862        ));
1863    }
1864
1865    #[test]
1866    fn unknown_credential_state_never_creates_reset_token() {
1867        assert!(!should_create_reset_token(
1868            CredentialState::Unknown,
1869            &CredentialBootstrapStatus::default(),
1870        ));
1871    }
1872
1873    #[test]
1874    fn present_credential_state_never_creates_reset_token() {
1875        assert!(!should_create_reset_token(
1876            CredentialState::Present,
1877            &CredentialBootstrapStatus::default(),
1878        ));
1879    }
1880
1881    #[test]
1882    fn absent_pending_bootstrap_creates_reset_token() {
1883        assert!(should_create_reset_token(
1884            CredentialState::Absent,
1885            &CredentialBootstrapStatus::default(),
1886        ));
1887    }
1888
1889    #[test]
1890    fn complete_bootstrap_never_creates_reset_token() {
1891        assert!(!should_create_reset_token(
1892            CredentialState::Absent,
1893            &CredentialBootstrapStatus {
1894                state: CredentialBootstrapState::Complete,
1895                token_expires_at: None,
1896                ..Default::default()
1897            },
1898        ));
1899    }
1900
1901    #[test]
1902    fn ssh_key_matching_tracks_ownership_without_touching_unmanaged_tags() {
1903        let desired = BTreeMap::from([("laptop".to_string(), "key-1".to_string())]);
1904        let observed = BTreeMap::from([
1905            ("laptop".to_string(), "key-1".to_string()),
1906            ("personal".to_string(), "key-2".to_string()),
1907        ]);
1908
1909        // Same public key does not imply ownership before it is adopted.
1910        assert!(!ssh_public_keys_match(&desired, &observed, &[]));
1911        assert!(ssh_public_keys_match(
1912            &desired,
1913            &observed,
1914            &["laptop".to_string()]
1915        ));
1916
1917        // A previously managed but no longer desired tag requires a cleanup.
1918        assert!(!ssh_public_keys_match(
1919            &BTreeMap::new(),
1920            &observed,
1921            &["laptop".to_string()],
1922        ));
1923        assert!(ssh_public_keys_match(&BTreeMap::new(), &observed, &[]));
1924
1925        let mut changed = observed;
1926        changed.insert("laptop".to_string(), "key-rotated".to_string());
1927        assert!(!ssh_public_keys_match(
1928            &desired,
1929            &changed,
1930            &["laptop".to_string()],
1931        ));
1932    }
1933}