Skip to main content

kaniop_person/
reconcile.rs

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, 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::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, client::ScimSshPublicKeys};
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_SSH_PUBLIC_KEYS: &str = "SshPublicKeysUpdated";
49const TYPE_EXISTS: &str = "Exists";
50const TYPE_UPDATED: &str = "Updated";
51const TYPE_POSIX_INITIALIZED: &str = "PosixInitialized";
52const TYPE_POSIX_UPDATED: &str = "PosixUpdated";
53const TYPE_VALIDITY: &str = "Valid";
54const REASON_ATTRIBUTES_MATCH: &str = "AttributesMatch";
55const REASON_ATTRIBUTES_NOT_MATCH: &str = "AttributesNotMatch";
56const CONDITION_TRUE: &str = "True";
57const CONDITION_FALSE: &str = "False";
58const CONDITION_UNKNOWN: &str = "Unknown";
59
60fn credential_state_from_attributes(
61    primary: &Option<Vec<String>>,
62    passkeys: &Option<Vec<String>>,
63    attested_passkeys: &Option<Vec<String>>,
64) -> CredentialState {
65    if [primary, passkeys, attested_passkeys]
66        .into_iter()
67        .any(|values| {
68            values
69                .as_ref()
70                .is_some_and(|values| values.is_empty().not())
71        })
72    {
73        CredentialState::Present
74    } else {
75        CredentialState::Absent
76    }
77}
78
79fn scim_search_allows_all_credential_attributes(search: &serde_json::Value) -> bool {
80    match search {
81        serde_json::Value::String(access) => access == "Grant",
82        serde_json::Value::Object(access) => access
83            .get("Allow")
84            .and_then(serde_json::Value::as_array)
85            .is_some_and(|allowed| {
86                [
87                    ATTR_PRIMARY_CREDENTIAL,
88                    ATTR_PASSKEYS,
89                    ATTR_ATTESTED_PASSKEYS,
90                ]
91                .into_iter()
92                .all(|required| {
93                    allowed
94                        .iter()
95                        .any(|attribute| attribute.as_str() == Some(required))
96                })
97            }),
98        _ => false,
99    }
100}
101
102async fn credential_attributes_searchable(
103    kanidm_client: &KanidmClient,
104    name: &str,
105) -> std::result::Result<bool, kanidm_client::ClientError> {
106    let query = ScimEntryGetQuery {
107        attributes: Some(vec![
108            Attribute::PrimaryCredential,
109            Attribute::PassKeys,
110            Attribute::AttestedPasskeys,
111        ]),
112        ext_access_check: true,
113        ..Default::default()
114    };
115    let path = format!("/scim/v1/Person/{name}");
116    let entry: serde_json::Value = kanidm_client
117        .perform_get_request_query(&path, Some(query))
118        .await?;
119
120    Ok(entry
121        .get("extAccessCheck")
122        .and_then(|access| access.get("search"))
123        .is_some_and(scim_search_allows_all_credential_attributes))
124}
125
126fn ssh_public_keys_match(
127    desired: &BTreeMap<String, String>,
128    observed: &BTreeMap<String, String>,
129    managed_tags: &[String],
130) -> bool {
131    let desired_tags: BTreeSet<_> = desired.keys().collect();
132    let managed_tags: BTreeSet<_> = managed_tags.iter().collect();
133    desired_tags == managed_tags
134        && desired
135            .iter()
136            .all(|(tag, key)| observed.get(tag) == Some(key))
137}
138
139/// Read structured (tag, key) pairs, not authorized_keys output (which has no tags).
140/// Kanidm is authoritative for SSH key syntax and supported algorithms.
141async fn read_ssh_public_keys(
142    kanidm_client: &KanidmClient,
143    name: &str,
144) -> Result<BTreeMap<String, String>> {
145    let entry = kanidm_client
146        .scim_v1_person_get(
147            name,
148            Some(ScimEntryGetQuery {
149                attributes: Some(vec![Attribute::SshPublicKey]),
150                ..Default::default()
151            }),
152        )
153        .await
154        .map_err(|e| {
155            Error::KanidmClientError(
156                format!("failed to read SSH public keys for person {name}"),
157                Box::new(e),
158            )
159        })?;
160    let Some(raw_keys) = entry.attrs.get(&Attribute::SshPublicKey) else {
161        return Ok(BTreeMap::new());
162    };
163    let keys: ScimSshPublicKeys = serde_json::from_value(raw_keys.clone()).map_err(|e| {
164        Error::SerializationError(
165            format!("invalid SSH public key response from Kanidm for {name}"),
166            e,
167        )
168    })?;
169    Ok(keys
170        .into_iter()
171        .map(|k| (k.label, k.value.to_string()))
172        .collect())
173}
174
175fn bootstrap_token_expired(status: &CredentialBootstrapStatus) -> bool {
176    status
177        .token_expires_at
178        .as_ref()
179        .is_some_and(|expiry| expiry.0 <= Timestamp::now())
180}
181
182fn should_create_reset_token(
183    credential_state: CredentialState,
184    bootstrap: &CredentialBootstrapStatus,
185) -> bool {
186    if credential_state != CredentialState::Absent {
187        return false;
188    }
189
190    match bootstrap.state {
191        CredentialBootstrapState::Pending => true,
192        CredentialBootstrapState::TokenIssued => bootstrap_token_expired(bootstrap),
193        CredentialBootstrapState::Complete => false,
194    }
195}
196
197pub async fn watched_resource(person: &KanidmPersonAccount, ctx: Arc<Context>) -> bool {
198    let kanidm = if let Some(k) = ctx.kaniop_ctx.get_kanidm(person) {
199        k
200    } else {
201        trace!("no kanidm found");
202        return false;
203    };
204
205    is_resource_watched(
206        person,
207        &kanidm,
208        &ctx.kaniop_ctx.namespace_store,
209        &ctx.kaniop_ctx.client,
210    )
211    .await
212}
213
214#[instrument(skip(ctx, person))]
215pub async fn reconcile_person_account(
216    person: Arc<KanidmPersonAccount>,
217    ctx: Arc<Context>,
218) -> Result<(Action, bool)> {
219    let trace_id = telemetry::get_trace_id();
220    Span::current().record("trace_id", field::display(&trace_id));
221    let _timer = ctx
222        .kaniop_ctx
223        .metrics
224        .reconcile_count_and_measure(&trace_id);
225    if !ctx.kaniop_ctx.kanidm_write_allowed(&person) {
226        debug!("Kanidm restore in progress, pausing identity writes");
227        return Ok((Action::requeue(Duration::from_secs(5)), false));
228    }
229    let kanidm_client = ctx.get_idm_client(&person).await?;
230
231    if !watched_resource(&person, ctx.clone()).await {
232        debug!("resource not watched, skipping reconcile");
233        ctx.kaniop_ctx
234            .recorder
235            .publish(
236                &Event {
237                    type_: EventType::Warning,
238                    reason: "ResourceNotWatched".to_string(),
239                    note: Some("configure `personNamespaceSelector` on Kanidm resource to watch this namespace".to_string()),
240                    action: "Reconcile".to_string(),
241                    secondary: None,
242                },
243                &person.object_ref(&()),
244            )
245            .await
246            .map_err(|e| {
247                warn!(error = %e, "failed to publish ResourceNotWatched event");
248                Error::kube_error("publish", "event", person.get_namespace(), person.name_any(), e)
249            })?;
250        return Ok((Action::requeue(idm_reconcile_interval()), false));
251    }
252    info!("reconciling person account");
253
254    let namespace = person.get_namespace();
255    let status = person
256        .update_status(kanidm_client.clone(), ctx.clone())
257        .await
258        .map_err(|e| {
259            debug!(error = %e, "failed to reconcile status");
260            ctx.kaniop_ctx.metrics.status_update_errors_inc();
261            e
262        })?;
263    let persons_api: Api<KanidmPersonAccount> =
264        Api::namespaced(ctx.kaniop_ctx.client.clone(), &namespace);
265    let outcome = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
266    let outcome_clone = outcome.clone();
267    let action = finalizer(&persons_api, PERSON_FINALIZER, person, move |event| {
268        let outcome = outcome_clone.clone();
269        let ctx = ctx.clone();
270        let status = status.clone();
271        let kanidm_client = kanidm_client.clone();
272        async move {
273            match event {
274                Finalizer::Apply(p) => {
275                    let (action, changed) = p.reconcile(kanidm_client, status, ctx).await?;
276                    outcome.store(changed, std::sync::atomic::Ordering::Relaxed);
277                    Ok(action)
278                }
279                Finalizer::Cleanup(p) => {
280                    let (action, changed) = p.cleanup(kanidm_client, status, ctx).await?;
281                    outcome.store(changed, std::sync::atomic::Ordering::Relaxed);
282                    Ok(action)
283                }
284            }
285        }
286    })
287    .await
288    .or_else(|e| match e {
289        FinalizerError::RemoveFinalizer(kube::Error::Api(ae)) if ae.code == 404 => {
290            debug!("resource already removed during finalizer cleanup");
291            Ok(Action::requeue(idm_reconcile_interval()))
292        }
293        _ => Err(Error::FinalizerError(
294            "failed on person account finalizer".to_string(),
295            Box::new(e),
296        )),
297    })?;
298    let changed = outcome.load(std::sync::atomic::Ordering::Relaxed);
299    Ok((action, changed))
300}
301
302impl KanidmPersonAccount {
303    #[inline]
304    fn get_namespace(&self) -> String {
305        // safe unwrap: person is namespaced scoped
306        self.namespace().unwrap()
307    }
308
309    #[inline]
310    async fn reconcile(
311        &self,
312        kanidm_client: Arc<KanidmClient>,
313        status: KanidmPersonAccountStatus,
314        ctx: Arc<Context>,
315    ) -> Result<(Action, bool)> {
316        match self
317            .internal_reconcile(kanidm_client, status, ctx.clone())
318            .await
319        {
320            Ok(result) => Ok(result),
321            Err(e) => match e {
322                Error::KanidmClientError(_, _) => {
323                    ctx.kaniop_ctx
324                        .recorder
325                        .publish(
326                            &Event {
327                                type_: EventType::Warning,
328                                reason: "KanidmError".to_string(),
329                                note: Some(format!("{e:?}")),
330                                action: "KanidmRequest".to_string(),
331                                secondary: None,
332                            },
333                            &self.object_ref(&()),
334                        )
335                        .await
336                        .map_err(|e| {
337                            warn!(error = %e, "failed to publish KanidmError event");
338                            Error::kube_error(
339                                "publish",
340                                "event",
341                                self.get_namespace(),
342                                self.name_any(),
343                                e,
344                            )
345                        })?;
346                    Err(e)
347                }
348                _ => Err(e),
349            },
350        }
351    }
352
353    async fn internal_reconcile(
354        &self,
355        kanidm_client: Arc<KanidmClient>,
356        status: KanidmPersonAccountStatus,
357        ctx: Arc<Context>,
358    ) -> Result<(Action, bool)> {
359        let name = &self.kanidm_entity_name();
360        let metrics = &ctx.kaniop_ctx.metrics;
361
362        let mut require_status_update = false;
363        let mut changed = false;
364        let mut actions = Vec::new();
365        if is_person_false(TYPE_EXISTS, status.clone()) {
366            debug!(
367                condition = TYPE_EXISTS,
368                status = CONDITION_FALSE,
369                action = "create",
370                "condition triggered action"
371            );
372            record_kanidm_sdk_call(
373                metrics,
374                KANIDM_RESOURCE_PERSON,
375                KANIDM_OP_CREATE,
376                KANIDM_OUTCOME_CHANGED,
377                self.create(&kanidm_client, name),
378            )
379            .await?;
380            require_status_update = true;
381            changed = true;
382            actions.push("create");
383        }
384        if is_person_false(TYPE_UPDATED, status.clone()) {
385            debug!(
386                condition = TYPE_UPDATED,
387                status = CONDITION_FALSE,
388                action = "update",
389                "condition triggered action"
390            );
391            self.update(&kanidm_client, name, metrics).await?;
392            require_status_update = true;
393            changed = true;
394            actions.push("update");
395        }
396
397        if is_person_false(TYPE_POSIX_UPDATED, status.clone())
398            || (is_person_false(TYPE_POSIX_INITIALIZED, status.clone())
399                && is_person(TYPE_POSIX_UPDATED, status.clone()))
400        {
401            debug!(
402                condition = TYPE_POSIX_UPDATED,
403                status = CONDITION_FALSE,
404                action = "update_posix_attributes",
405                "condition triggered action"
406            );
407            record_kanidm_sdk_call(
408                metrics,
409                KANIDM_RESOURCE_PERSON,
410                KANIDM_OP_UNIX_EXTEND,
411                KANIDM_OUTCOME_CHANGED,
412                self.update_posix_attributes(&kanidm_client, name),
413            )
414            .await?;
415            require_status_update = true;
416            changed = true;
417            actions.push("update_posix");
418        }
419
420        if is_person_false(TYPE_SSH_PUBLIC_KEYS, status.clone()) {
421            self.sync_ssh_public_keys(&kanidm_client, name).await?;
422            require_status_update = true;
423            changed = true;
424            actions.push("update_ssh_public_keys");
425        }
426
427        if should_create_reset_token(status.credential_state, &status.credential_bootstrap) {
428            debug!(
429                credential_state = ?status.credential_state,
430                bootstrap_state = ?status.credential_bootstrap.state,
431                action = "create_reset_token",
432                "credential bootstrap triggered action"
433            );
434            let token_expires_at = record_kanidm_sdk_call(
435                metrics,
436                KANIDM_RESOURCE_PERSON,
437                KANIDM_OP_CREDENTIAL_UPDATE_INTENT,
438                KANIDM_OUTCOME_CHANGED,
439                self.create_reset_token(&kanidm_client, name, ctx.clone()),
440            )
441            .await?;
442            self.update_credential_bootstrap_status(
443                ctx.clone(),
444                CredentialBootstrapStatus {
445                    state: CredentialBootstrapState::TokenIssued,
446                    token_expires_at: Some(token_expires_at),
447                },
448            )
449            .await?;
450            changed = true;
451        }
452
453        if require_status_update {
454            debug!(actions = ?actions, "requeueing in 500ms after actions");
455            Ok((Action::requeue(Duration::from_millis(500)), changed))
456        } else {
457            debug!("reconciliation complete, requeueing for next interval");
458            Ok((Action::requeue(idm_reconcile_interval()), changed))
459        }
460    }
461
462    async fn create(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
463        debug!("create");
464        kanidm_client
465            .idm_person_account_create(name, &self.spec.person_attributes.displayname)
466            .await
467            .map_err(|e| {
468                Error::kanidm_client_error(
469                    "create",
470                    name,
471                    self.kanidm_namespace(),
472                    self.kanidm_name(),
473                    e,
474                )
475            })?;
476        Ok(())
477    }
478
479    async fn update(
480        &self,
481        kanidm_client: &KanidmClient,
482        name: &str,
483        metrics: &kaniop_operator::metrics::ControllerMetrics,
484    ) -> Result<()> {
485        debug!("update");
486        trace!(person_attributes = ?self.spec.person_attributes, "updating person attributes");
487        record_kanidm_sdk_call(
488            metrics,
489            KANIDM_RESOURCE_PERSON,
490            KANIDM_OP_UPDATE,
491            KANIDM_OUTCOME_CHANGED,
492            kanidm_client.idm_person_account_update(
493                name,
494                None,
495                Some(&self.spec.person_attributes.displayname),
496                self.spec.person_attributes.legalname.as_deref(),
497                self.spec.person_attributes.mail.as_deref(),
498            ),
499        )
500        .await
501        .map_err(|e| {
502            Error::kanidm_client_error(
503                "update",
504                name,
505                self.kanidm_namespace(),
506                self.kanidm_name(),
507                e,
508            )
509        })?;
510        let mut update_entry = Entry {
511            attrs: BTreeMap::new(),
512        };
513        if let Some(account_expire) = self.spec.person_attributes.account_expire.as_ref() {
514            update_entry.attrs.insert(
515                ATTR_ACCOUNT_EXPIRE.to_string(),
516                vec![account_expire.0.to_string()],
517            );
518        }
519        if let Some(account_valid_from) = self.spec.person_attributes.account_valid_from.as_ref() {
520            update_entry.attrs.insert(
521                ATTR_ACCOUNT_VALID_FROM.to_string(),
522                vec![account_valid_from.0.to_string()],
523            );
524        }
525
526        if update_entry.attrs.is_empty().not() {
527            let _: Entry = record_kanidm_sdk_call(
528                metrics,
529                KANIDM_RESOURCE_PERSON,
530                KANIDM_OP_UPDATE,
531                KANIDM_OUTCOME_CHANGED,
532                kanidm_client.perform_patch_request(&format!("/v1/person/{name}"), update_entry),
533            )
534            .await
535            .map_err(|e| {
536                Error::kanidm_client_error(
537                    "update",
538                    name,
539                    self.kanidm_namespace(),
540                    self.kanidm_name(),
541                    e,
542                )
543            })?;
544        }
545        Ok(())
546    }
547
548    async fn sync_ssh_public_keys(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
549        let Some(desired) = &self.spec.ssh_public_keys else {
550            return Ok(());
551        };
552        debug!("syncing SSH public keys");
553        let observed = read_ssh_public_keys(kanidm_client, name).await?;
554        // Use the original cached status (self.status), not the computed status from update_status.
555        // This ensures we have the tags from before update_status patched them.
556        let managed: BTreeSet<String> = self
557            .status
558            .as_ref()
559            .map(|s| s.managed_ssh_public_key_tags.iter().cloned().collect())
560            .unwrap_or_default();
561
562        trace!(
563            desired_tags = ?desired.keys().collect::<Vec<_>>(),
564            observed_tags = ?observed.keys().collect::<Vec<_>>(),
565            managed_tags = ?managed,
566            "SSH key state"
567        );
568
569        // Revoke keys that are in observed but not in desired.
570        // We revoke any key with a tag that was previously managed (in status) or is currently
571        // in observed but not in desired. This handles both the case where the operator
572        // previously managed the key and the case where the key exists in Kanidm but the
573        // spec no longer includes it.
574        for tag in observed
575            .keys()
576            .filter(|tag| !desired.contains_key(*tag))
577            .cloned()
578            .collect::<Vec<_>>()
579        {
580            // Only revoke if the tag was previously managed or is in the current managed set.
581            // This prevents revoking keys that were added manually and never managed by the operator.
582            if managed.contains(&tag) {
583                debug!(tag = %tag, "revoking managed SSH public key");
584                kanidm_client
585                    .idm_person_account_delete_ssh_pubkey(name, &tag)
586                    .await
587                    .map_err(|e| {
588                        Error::kanidm_client_error_attr(
589                            "delete",
590                            "SSH public key",
591                            name,
592                            self.kanidm_namespace(),
593                            self.kanidm_name(),
594                            e,
595                        )
596                    })?;
597            }
598        }
599
600        for (tag, key) in desired {
601            if observed.get(tag) != Some(key) {
602                // Kanidm does not overwrite an existing tag on insertion.
603                // Rotation therefore requires remove + add (not atomic).
604                if observed.contains_key(tag) {
605                    debug!(tag = %tag, "rotating SSH public key (delete existing)");
606                    kanidm_client
607                        .idm_person_account_delete_ssh_pubkey(name, tag)
608                        .await
609                        .map_err(|e| {
610                            Error::kanidm_client_error_attr(
611                                "delete",
612                                "SSH public key",
613                                name,
614                                self.kanidm_namespace(),
615                                self.kanidm_name(),
616                                e,
617                            )
618                        })?;
619                }
620                // Let Kanidm validate the entire SSH key; do not parse it here.
621                debug!(tag = %tag, "adding SSH public key");
622                kanidm_client
623                    .idm_person_account_post_ssh_pubkey(name, tag, key)
624                    .await
625                    .map_err(|e| {
626                        Error::kanidm_client_error_attr(
627                            "add",
628                            "SSH public key",
629                            name,
630                            self.kanidm_namespace(),
631                            self.kanidm_name(),
632                            e,
633                        )
634                    })?;
635            }
636        }
637        Ok(())
638    }
639
640    async fn update_posix_attributes(
641        &self,
642        kanidm_client: &KanidmClient,
643        name: &str,
644    ) -> Result<()> {
645        debug!("updating posix attributes");
646        trace!(posix_attributes = ?self.spec.posix_attributes, "updating posix attributes");
647        kanidm_client
648            .idm_person_account_unix_extend(
649                name,
650                self.spec
651                    .posix_attributes
652                    .as_ref()
653                    .and_then(|posix| posix.gidnumber),
654                self.spec
655                    .posix_attributes
656                    .as_ref()
657                    .and_then(|posix| posix.loginshell.as_deref()),
658            )
659            .await
660            .map_err(|e| {
661                Error::kanidm_client_error(
662                    "update",
663                    name,
664                    self.kanidm_namespace(),
665                    self.kanidm_name(),
666                    e,
667                )
668            })?;
669        Ok(())
670    }
671
672    async fn create_reset_token(
673        &self,
674        kanidm_client: &KanidmClient,
675        name: &str,
676        ctx: Arc<Context>,
677    ) -> Result<Time> {
678        debug!("create reset token");
679        let cu_token = kanidm_client
680            .idm_person_account_credential_update_intent(
681                name,
682                Some(self.spec.credentials_token_ttl),
683            )
684            .await
685            .map_err(|e| {
686                Error::kanidm_client_error(
687                    "create a credential reset token for",
688                    name,
689                    self.kanidm_namespace(),
690                    self.kanidm_name(),
691                    e,
692                )
693            })?;
694        let token = cu_token.token.as_str();
695        let url = if let Some(base_url) = ctx.kaniop_ctx.get_kanidm(self).map(|k| {
696            k.spec
697                .origin
698                .clone()
699                .unwrap_or_else(|| format!("https://{}", k.spec.domain))
700        }) {
701            format!("{base_url}/ui/reset?token={token}")
702        } else {
703            let mut url = kanidm_client.make_url("/ui/reset");
704            url.query_pairs_mut().append_pair("token", token);
705            url.to_string()
706        };
707        let local_offset = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
708        let expiry_time = cu_token.expiry_time.to_offset(local_offset);
709
710        let msg = format!(
711            "Update these user credentials with this link: {url}. This token will expire at: {}",
712            expiry_time
713                .format(&Rfc3339)
714                .unwrap_or_else(|_| expiry_time.to_string())
715        );
716        ctx.kaniop_ctx
717            .recorder
718            .publish(
719                &Event {
720                    type_: EventType::Normal,
721                    reason: "TokenCreated".to_string(),
722                    note: Some(msg),
723                    action: "CreateUpdateCredentialsToken".into(),
724                    secondary: None,
725                },
726                &self.object_ref(&()),
727            )
728            .await
729            .map_err(|e| {
730                warn!(error = %e, "failed to publish TokenCreated event");
731                Error::kube_error("publish", "event", self.get_namespace(), self.name_any(), e)
732            })?;
733
734        let expiry_timestamp = Timestamp::from_second(cu_token.expiry_time.unix_timestamp())
735            .map_err(|e| Error::ParseError(format!("failed to convert token expiry: {e}")))?;
736        Ok(Time(expiry_timestamp))
737    }
738
739    async fn update_credential_bootstrap_status(
740        &self,
741        ctx: Arc<Context>,
742        bootstrap: CredentialBootstrapStatus,
743    ) -> Result<()> {
744        let namespace = self.get_namespace();
745        let person_api =
746            Api::<KanidmPersonAccount>::namespaced(ctx.kaniop_ctx.client.clone(), &namespace);
747        person_api
748            .patch_status(
749                &self.name_any(),
750                &PatchParams::default(),
751                &Patch::Merge(serde_json::json!({
752                    "status": {
753                        "credentialBootstrap": bootstrap,
754                    }
755                })),
756            )
757            .await
758            .map_err(|e| {
759                Error::kube_status_error("KanidmPersonAccount", namespace, self.name_any(), e)
760            })?;
761        Ok(())
762    }
763
764    async fn cleanup(
765        &self,
766        kanidm_client: Arc<KanidmClient>,
767        status: KanidmPersonAccountStatus,
768        ctx: Arc<Context>,
769    ) -> Result<(Action, bool)> {
770        let name = &self.kanidm_entity_name();
771        let mut changed = false;
772
773        if is_person(TYPE_EXISTS, status.clone()) {
774            debug!("delete");
775            record_kanidm_sdk_call(
776                &ctx.kaniop_ctx.metrics,
777                KANIDM_RESOURCE_PERSON,
778                KANIDM_OP_DELETE,
779                KANIDM_OUTCOME_CHANGED,
780                kanidm_client.idm_person_account_delete(name),
781            )
782            .await
783            .map_err(|e| {
784                Error::kanidm_client_error(
785                    "delete",
786                    name,
787                    self.kanidm_namespace(),
788                    self.kanidm_name(),
789                    e,
790                )
791            })?;
792            changed = true;
793        }
794        Ok((Action::requeue(idm_reconcile_interval()), changed))
795    }
796
797    async fn update_status(
798        &self,
799        kanidm_client: Arc<KanidmClient>,
800        ctx: Arc<Context>,
801    ) -> Result<KanidmPersonAccountStatus> {
802        // safe unwrap: person is namespaced scoped
803        let namespace = self.get_namespace();
804        let name = self.kanidm_entity_name();
805        let metrics = &ctx.kaniop_ctx.metrics;
806        let start = tokio::time::Instant::now();
807        let current_person = kanidm_client
808            .idm_person_account_get(&name)
809            .await
810            .map_err(|e| {
811                let elapsed = start.elapsed();
812                metrics.record_kanidm_sdk_outcome(
813                    KANIDM_RESOURCE_PERSON,
814                    KANIDM_OP_GET,
815                    KANIDM_OUTCOME_ERROR,
816                    elapsed,
817                );
818                Error::kanidm_client_error(
819                    "get",
820                    name.as_str(),
821                    self.kanidm_namespace(),
822                    self.kanidm_name(),
823                    e,
824                )
825            })?;
826        metrics.record_kanidm_sdk_outcome(
827            KANIDM_RESOURCE_PERSON,
828            KANIDM_OP_GET,
829            KANIDM_OUTCOME_UNCHANGED,
830            start.elapsed(),
831        );
832
833        let credential_state = if current_person.is_some() {
834            let cred_start = tokio::time::Instant::now();
835            let probe = tokio::try_join!(
836                kanidm_client.idm_person_account_get_attr(&name, ATTR_PRIMARY_CREDENTIAL),
837                kanidm_client.idm_person_account_get_attr(&name, ATTR_PASSKEYS),
838                kanidm_client.idm_person_account_get_attr(&name, ATTR_ATTESTED_PASSKEYS),
839            );
840            match probe {
841                Ok((primary, passkeys, attested_passkeys)) => {
842                    let observed_state =
843                        credential_state_from_attributes(&primary, &passkeys, &attested_passkeys);
844                    let state = if observed_state == CredentialState::Present {
845                        CredentialState::Present
846                    } else {
847                        match credential_attributes_searchable(&kanidm_client, &name).await {
848                            Ok(true) => CredentialState::Absent,
849                            Ok(false) => {
850                                warn!(
851                                    "credential attributes are not searchable; leaving state unknown"
852                                );
853                                CredentialState::Unknown
854                            }
855                            Err(e) => {
856                                warn!(
857                                    error = ?e,
858                                    "credential effective-access probe failed; leaving state unknown"
859                                );
860                                CredentialState::Unknown
861                            }
862                        }
863                    };
864                    trace!(
865                        credential_state = ?state,
866                        primary_present = primary.as_ref().is_some_and(|v| v.is_empty().not()),
867                        passkeys_count = passkeys.as_ref().map_or(0, Vec::len),
868                        attested_passkeys_count = attested_passkeys.as_ref().map_or(0, Vec::len),
869                        "read-only credential status"
870                    );
871                    metrics.record_kanidm_sdk_outcome(
872                        KANIDM_RESOURCE_PERSON,
873                        KANIDM_OP_GET_CREDENTIAL_STATUS,
874                        if state == CredentialState::Unknown {
875                            KANIDM_OUTCOME_ERROR
876                        } else {
877                            KANIDM_OUTCOME_UNCHANGED
878                        },
879                        cred_start.elapsed(),
880                    );
881                    state
882                }
883                Err(e) => {
884                    warn!(
885                        error = ?e,
886                        "read-only credential status probe failed; leaving state unknown"
887                    );
888                    metrics.record_kanidm_sdk_outcome(
889                        KANIDM_RESOURCE_PERSON,
890                        KANIDM_OP_GET_CREDENTIAL_STATUS,
891                        KANIDM_OUTCOME_ERROR,
892                        cred_start.elapsed(),
893                    );
894                    CredentialState::Unknown
895                }
896            }
897        } else {
898            CredentialState::Unknown
899        };
900
901        let ssh_public_keys = if current_person.is_some() && self.spec.ssh_public_keys.is_some() {
902            Some(read_ssh_public_keys(&kanidm_client, &name).await?)
903        } else {
904            None
905        };
906
907        let status = self.generate_status(current_person, credential_state, ssh_public_keys)?;
908        if self.status.as_ref() == Some(&status) {
909            trace!("status unchanged, skipping patch");
910            return Ok(status);
911        }
912        if let Some(old) = self.status.as_ref() {
913            let old_conds: Vec<_> = old
914                .conditions
915                .iter()
916                .flatten()
917                .map(|c| format!("{}={}", c.type_, c.status))
918                .collect();
919            let new_conds: Vec<_> = status
920                .conditions
921                .iter()
922                .flatten()
923                .map(|c| format!("{}={}", c.type_, c.status))
924                .collect();
925            debug!(
926                old = ?old_conds,
927                new = ?new_conds,
928                old_ready = old.ready,
929                new_ready = status.ready,
930                old_credential_state = ?old.credential_state,
931                new_credential_state = ?status.credential_state,
932                "status changed"
933            );
934        } else {
935            debug!(conditions = ?status.conditions, "initial status patch");
936        }
937        let status_patch = Patch::Apply(KanidmPersonAccount {
938            status: Some(status.clone()),
939            ..KanidmPersonAccount::default()
940        });
941        debug!("updating status");
942        trace!(status_patch = ?status_patch, "status patch");
943        let patch = PatchParams::apply(PERSON_OPERATOR_NAME).force();
944        let kanidm_api =
945            Api::<KanidmPersonAccount>::namespaced(ctx.kaniop_ctx.client.clone(), &namespace);
946        let _o = kanidm_api
947            .patch_status(&self.name_any(), &patch, &status_patch)
948            .await
949            .map_err(|e| {
950                Error::kube_status_error("KanidmPersonAccount", namespace, self.name_any(), e)
951            })?;
952        Ok(status)
953    }
954
955    fn generate_status(
956        &self,
957        person: Option<Entry>,
958        credential_state: CredentialState,
959        ssh_public_keys: Option<BTreeMap<String, String>>,
960    ) -> Result<KanidmPersonAccountStatus> {
961        let now = Timestamp::now();
962        let current_conditions = self.status.as_ref().and_then(|s| s.conditions.as_ref());
963        let managed_ssh_public_key_tags = if let Some(desired) = &self.spec.ssh_public_keys {
964            // Tags this operator currently owns: union of:
965            // 1. Tags that were previously managed and are still in observed (need revocation if not in desired)
966            // 2. Tags that are in desired and match observed (new or existing managed tags)
967            // This ensures managed_tags includes tags pending revocation, preventing the SSH condition
968            // from becoming True prematurely and blocking sync_ssh_public_keys.
969            if let Some(observed) = ssh_public_keys.as_ref() {
970                let old_managed: BTreeSet<String> = self
971                    .status
972                    .as_ref()
973                    .map(|s| s.managed_ssh_public_key_tags.iter().cloned().collect())
974                    .unwrap_or_default();
975
976                // Tags that were previously managed and are still in observed
977                // (these need to be revoked if not in desired)
978                let still_in_observed: BTreeSet<String> = old_managed
979                    .iter()
980                    .filter(|tag| observed.contains_key(*tag))
981                    .cloned()
982                    .collect();
983
984                // Tags that are in desired and match observed (new or existing managed tags)
985                let new_managed: BTreeSet<String> = desired
986                    .iter()
987                    .filter(|(tag, key)| observed.get(*tag).map(String::as_str) == Some(key))
988                    .map(|(tag, _)| tag.clone())
989                    .collect();
990
991                still_in_observed.union(&new_managed).cloned().collect()
992            } else {
993                Vec::new()
994            }
995        } else {
996            // Removing the field opts out of management without revoking keys.
997            Vec::new()
998        };
999
1000        match person {
1001            Some(p) => {
1002                let exist_condition = Condition {
1003                    type_: TYPE_EXISTS.to_string(),
1004                    status: CONDITION_TRUE.to_string(),
1005                    reason: "Exists".to_string(),
1006                    message: "Person exists.".to_string(),
1007                    last_transition_time: last_transition_time(
1008                        current_conditions,
1009                        TYPE_EXISTS,
1010                        CONDITION_TRUE,
1011                        "Exists",
1012                    ),
1013                    observed_generation: self.metadata.generation,
1014                };
1015
1016                let current_person_attributes = KanidmPersonAttributes::from(p.clone());
1017                let updated_condition = if self.spec.person_attributes == current_person_attributes
1018                {
1019                    Condition {
1020                        type_: TYPE_UPDATED.to_string(),
1021                        status: CONDITION_TRUE.to_string(),
1022                        reason: REASON_ATTRIBUTES_MATCH.to_string(),
1023                        message: "Person exists with desired attributes.".to_string(),
1024                        last_transition_time: last_transition_time(
1025                            current_conditions,
1026                            TYPE_UPDATED,
1027                            CONDITION_TRUE,
1028                            REASON_ATTRIBUTES_MATCH,
1029                        ),
1030                        observed_generation: self.metadata.generation,
1031                    }
1032                } else {
1033                    let spec = &self.spec.person_attributes;
1034                    debug!(
1035                        displayname_spec = %spec.displayname,
1036                        displayname_actual = %current_person_attributes.displayname,
1037                        mail_spec = ?spec.mail,
1038                        mail_actual = ?current_person_attributes.mail,
1039                        legalname_spec = ?spec.legalname,
1040                        legalname_actual = ?current_person_attributes.legalname,
1041                        account_valid_from_spec = ?spec.account_valid_from,
1042                        account_valid_from_actual = ?current_person_attributes.account_valid_from,
1043                        account_expire_spec = ?spec.account_expire,
1044                        account_expire_actual = ?current_person_attributes.account_expire,
1045                        "person attributes mismatch"
1046                    );
1047                    Condition {
1048                        type_: TYPE_UPDATED.to_string(),
1049                        status: CONDITION_FALSE.to_string(),
1050                        reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
1051                        message: "Person exists with different attributes.".to_string(),
1052                        last_transition_time: last_transition_time(
1053                            current_conditions,
1054                            TYPE_UPDATED,
1055                            CONDITION_FALSE,
1056                            REASON_ATTRIBUTES_NOT_MATCH,
1057                        ),
1058                        observed_generation: self.metadata.generation,
1059                    }
1060                };
1061
1062                let current_person_posix = KanidmAccountPosixAttributes::from(p);
1063                let posix_initialized_condition = if current_person_posix.gidnumber.is_some() {
1064                    Condition {
1065                        type_: TYPE_POSIX_INITIALIZED.to_string(),
1066                        status: CONDITION_TRUE.to_string(),
1067                        reason: "PosixInitialized".to_string(),
1068                        message: "Person exists with POSIX attributes.".to_string(),
1069                        last_transition_time: last_transition_time(
1070                            current_conditions,
1071                            TYPE_POSIX_INITIALIZED,
1072                            CONDITION_TRUE,
1073                            "PosixInitialized",
1074                        ),
1075                        observed_generation: self.metadata.generation,
1076                    }
1077                } else {
1078                    Condition {
1079                        type_: TYPE_POSIX_INITIALIZED.to_string(),
1080                        status: CONDITION_FALSE.to_string(),
1081                        reason: "PosixNotInitialized".to_string(),
1082                        message: "Person exists without POSIX attributes.".to_string(),
1083                        last_transition_time: last_transition_time(
1084                            current_conditions,
1085                            TYPE_POSIX_INITIALIZED,
1086                            CONDITION_FALSE,
1087                            "PosixNotInitialized",
1088                        ),
1089                        observed_generation: self.metadata.generation,
1090                    }
1091                };
1092
1093                let posix_updated_condition = self.spec.posix_attributes.as_ref().map(|posix| {
1094                    if posix == &current_person_posix {
1095                        Condition {
1096                            type_: TYPE_POSIX_UPDATED.to_string(),
1097                            status: CONDITION_TRUE.to_string(),
1098                            reason: REASON_ATTRIBUTES_MATCH.to_string(),
1099                            message: "Person exists with desired POSIX attributes.".to_string(),
1100                            last_transition_time: last_transition_time(
1101                                current_conditions,
1102                                TYPE_POSIX_UPDATED,
1103                                CONDITION_TRUE,
1104                                REASON_ATTRIBUTES_MATCH,
1105                            ),
1106                            observed_generation: self.metadata.generation,
1107                        }
1108                    } else {
1109                        debug!(
1110                            gidnumber_spec = ?posix.gidnumber,
1111                            gidnumber_actual = ?current_person_posix.gidnumber,
1112                            loginshell_spec = ?posix.loginshell,
1113                            loginshell_actual = ?current_person_posix.loginshell,
1114                            "posix attributes mismatch"
1115                        );
1116                        Condition {
1117                            type_: TYPE_POSIX_UPDATED.to_string(),
1118                            status: CONDITION_FALSE.to_string(),
1119                            reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
1120                            message: "Person exists with different POSIX attributes.".to_string(),
1121                            last_transition_time: last_transition_time(
1122                                current_conditions,
1123                                TYPE_POSIX_UPDATED,
1124                                CONDITION_FALSE,
1125                                REASON_ATTRIBUTES_NOT_MATCH,
1126                            ),
1127                            observed_generation: self.metadata.generation,
1128                        }
1129                    }
1130                });
1131
1132                let (credential_condition_status, credential_reason, credential_message) =
1133                    match credential_state {
1134                        CredentialState::Present => {
1135                            (CONDITION_TRUE, "Present", "Credentials are present.")
1136                        }
1137                        CredentialState::Absent => (
1138                            CONDITION_FALSE,
1139                            "NotPresent",
1140                            "Credentials are not present.",
1141                        ),
1142                        CredentialState::Unknown => (
1143                            CONDITION_UNKNOWN,
1144                            "DetectionFailed",
1145                            "Credential presence could not be determined.",
1146                        ),
1147                    };
1148                let credentials_condition = Condition {
1149                    type_: TYPE_CREDENTIAL.to_string(),
1150                    status: credential_condition_status.to_string(),
1151                    reason: credential_reason.to_string(),
1152                    message: credential_message.to_string(),
1153                    last_transition_time: last_transition_time(
1154                        current_conditions,
1155                        TYPE_CREDENTIAL,
1156                        credential_condition_status,
1157                        credential_reason,
1158                    ),
1159                    observed_generation: self.metadata.generation,
1160                };
1161
1162                let credential_bootstrap = if credential_state == CredentialState::Present {
1163                    CredentialBootstrapStatus {
1164                        state: CredentialBootstrapState::Complete,
1165                        token_expires_at: None,
1166                    }
1167                } else {
1168                    self.status
1169                        .as_ref()
1170                        .map(|status| status.credential_bootstrap.clone())
1171                        .unwrap_or_default()
1172                };
1173
1174                let validity_condition = {
1175                    let valid = if let Some(valid_from) =
1176                        current_person_attributes.account_valid_from.as_ref()
1177                    {
1178                        now > valid_from.0
1179                    } else {
1180                        true
1181                    } && if let Some(expire) =
1182                        current_person_attributes.account_expire.as_ref()
1183                    {
1184                        now < expire.0
1185                    } else {
1186                        true
1187                    };
1188
1189                    if valid {
1190                        Condition {
1191                            type_: TYPE_VALIDITY.to_string(),
1192                            status: CONDITION_TRUE.to_string(),
1193                            reason: "Valid".to_string(),
1194                            message: "Account is valid.".to_string(),
1195                            last_transition_time: last_transition_time(
1196                                current_conditions,
1197                                TYPE_VALIDITY,
1198                                CONDITION_TRUE,
1199                                "Valid",
1200                            ),
1201                            observed_generation: self.metadata.generation,
1202                        }
1203                    } else {
1204                        Condition {
1205                            type_: TYPE_VALIDITY.to_string(),
1206                            status: CONDITION_FALSE.to_string(),
1207                            reason: "Invalid".to_string(),
1208                            message: "Account is invalid.".to_string(),
1209                            last_transition_time: last_transition_time(
1210                                current_conditions,
1211                                TYPE_VALIDITY,
1212                                CONDITION_FALSE,
1213                                "Invalid",
1214                            ),
1215                            observed_generation: self.metadata.generation,
1216                        }
1217                    }
1218                };
1219
1220                let old_managed_ssh_public_key_tags: Vec<String> = self
1221                    .status
1222                    .as_ref()
1223                    .map(|s| s.managed_ssh_public_key_tags.clone())
1224                    .unwrap_or_default();
1225
1226                let ssh_public_keys_condition = if let Some(desired) = &self.spec.ssh_public_keys {
1227                    let observed = ssh_public_keys.as_ref().ok_or_else(|| {
1228                        Error::MissingData("SSH key state was not fetched from Kanidm".to_string())
1229                    })?;
1230                    let matches =
1231                        ssh_public_keys_match(desired, observed, &old_managed_ssh_public_key_tags);
1232                    let (condition_status, reason, message) = if matches {
1233                        (
1234                            CONDITION_TRUE,
1235                            REASON_ATTRIBUTES_MATCH,
1236                            "Person has the desired managed SSH public keys.",
1237                        )
1238                    } else {
1239                        (
1240                            CONDITION_FALSE,
1241                            REASON_ATTRIBUTES_NOT_MATCH,
1242                            "Person SSH public keys differ from the managed keys.",
1243                        )
1244                    };
1245                    Some(Condition {
1246                        type_: TYPE_SSH_PUBLIC_KEYS.to_string(),
1247                        status: condition_status.to_string(),
1248                        reason: reason.to_string(),
1249                        message: message.to_string(),
1250                        last_transition_time: last_transition_time(
1251                            current_conditions,
1252                            TYPE_SSH_PUBLIC_KEYS,
1253                            condition_status,
1254                            reason,
1255                        ),
1256                        observed_generation: self.metadata.generation,
1257                    })
1258                } else {
1259                    None
1260                };
1261
1262                let conditions = vec![
1263                    exist_condition,
1264                    updated_condition,
1265                    posix_initialized_condition,
1266                    validity_condition,
1267                    credentials_condition,
1268                ]
1269                .into_iter()
1270                .chain(posix_updated_condition)
1271                .chain(ssh_public_keys_condition)
1272                .collect::<Vec<_>>();
1273                let status = conditions
1274                    .iter()
1275                    .filter(|c| {
1276                        c.type_ != TYPE_POSIX_INITIALIZED
1277                            && c.type_ != TYPE_CREDENTIAL
1278                            && c.type_ != TYPE_VALIDITY
1279                    })
1280                    .all(|c| c.status == CONDITION_TRUE);
1281                Ok(KanidmPersonAccountStatus {
1282                    conditions: Some(conditions),
1283                    ready: status,
1284                    gid: current_person_posix.gidnumber,
1285                    kanidm_ref: self.kanidm_ref(),
1286                    credential_state,
1287                    credential_bootstrap,
1288                    managed_ssh_public_key_tags,
1289                })
1290            }
1291            None => {
1292                let conditions = vec![Condition {
1293                    type_: TYPE_EXISTS.to_string(),
1294                    status: CONDITION_FALSE.to_string(),
1295                    reason: "NotExists".to_string(),
1296                    message: "Person is not present.".to_string(),
1297                    last_transition_time: last_transition_time(
1298                        current_conditions,
1299                        TYPE_EXISTS,
1300                        CONDITION_FALSE,
1301                        "NotExists",
1302                    ),
1303                    observed_generation: self.metadata.generation,
1304                }];
1305                Ok(KanidmPersonAccountStatus {
1306                    conditions: Some(conditions),
1307                    ready: false,
1308                    gid: None,
1309                    kanidm_ref: self.kanidm_ref(),
1310                    credential_state: CredentialState::Unknown,
1311                    credential_bootstrap: CredentialBootstrapStatus::default(),
1312                    managed_ssh_public_key_tags,
1313                })
1314            }
1315        }
1316    }
1317}
1318
1319pub fn is_person(type_: &str, status: KanidmPersonAccountStatus) -> bool {
1320    status
1321        .conditions
1322        .unwrap_or_default()
1323        .iter()
1324        .any(|c| c.type_ == type_ && c.status == CONDITION_TRUE)
1325}
1326
1327pub fn is_person_false(type_: &str, status: KanidmPersonAccountStatus) -> bool {
1328    status
1329        .conditions
1330        .unwrap_or_default()
1331        .iter()
1332        .any(|c| c.type_ == type_ && c.status == CONDITION_FALSE)
1333}
1334
1335#[cfg(test)]
1336mod tests {
1337    use super::*;
1338
1339    #[test]
1340    fn no_credential_attributes_is_absent() {
1341        assert_eq!(
1342            credential_state_from_attributes(&None, &None, &None),
1343            CredentialState::Absent
1344        );
1345    }
1346
1347    #[test]
1348    fn primary_credential_is_present() {
1349        assert_eq!(
1350            credential_state_from_attributes(&Some(vec!["primary".to_string()]), &None, &None,),
1351            CredentialState::Present
1352        );
1353    }
1354
1355    #[test]
1356    fn passkey_only_is_present() {
1357        assert_eq!(
1358            credential_state_from_attributes(&None, &Some(vec!["passkey".to_string()]), &None,),
1359            CredentialState::Present
1360        );
1361    }
1362
1363    #[test]
1364    fn attested_passkey_only_is_present() {
1365        assert_eq!(
1366            credential_state_from_attributes(
1367                &None,
1368                &None,
1369                &Some(vec!["attested-passkey".to_string()]),
1370            ),
1371            CredentialState::Present
1372        );
1373    }
1374
1375    #[test]
1376    fn scim_grant_allows_all_credential_attributes() {
1377        assert!(scim_search_allows_all_credential_attributes(
1378            &serde_json::json!("Grant")
1379        ));
1380    }
1381
1382    #[test]
1383    fn scim_allow_requires_all_credential_attributes() {
1384        assert!(scim_search_allows_all_credential_attributes(
1385            &serde_json::json!({
1386                "Allow": [
1387                    ATTR_PRIMARY_CREDENTIAL,
1388                    ATTR_PASSKEYS,
1389                    ATTR_ATTESTED_PASSKEYS
1390                ]
1391            })
1392        ));
1393        assert!(!scim_search_allows_all_credential_attributes(
1394            &serde_json::json!({
1395                "Allow": [ATTR_PRIMARY_CREDENTIAL, ATTR_PASSKEYS]
1396            })
1397        ));
1398    }
1399
1400    #[test]
1401    fn scim_deny_or_malformed_access_is_not_searchable() {
1402        assert!(!scim_search_allows_all_credential_attributes(
1403            &serde_json::json!("Deny")
1404        ));
1405        assert!(!scim_search_allows_all_credential_attributes(
1406            &serde_json::json!({})
1407        ));
1408    }
1409
1410    #[test]
1411    fn unknown_credential_state_never_creates_reset_token() {
1412        assert!(!should_create_reset_token(
1413            CredentialState::Unknown,
1414            &CredentialBootstrapStatus::default(),
1415        ));
1416    }
1417
1418    #[test]
1419    fn present_credential_state_never_creates_reset_token() {
1420        assert!(!should_create_reset_token(
1421            CredentialState::Present,
1422            &CredentialBootstrapStatus::default(),
1423        ));
1424    }
1425
1426    #[test]
1427    fn absent_pending_bootstrap_creates_reset_token() {
1428        assert!(should_create_reset_token(
1429            CredentialState::Absent,
1430            &CredentialBootstrapStatus::default(),
1431        ));
1432    }
1433
1434    #[test]
1435    fn complete_bootstrap_never_creates_reset_token() {
1436        assert!(!should_create_reset_token(
1437            CredentialState::Absent,
1438            &CredentialBootstrapStatus {
1439                state: CredentialBootstrapState::Complete,
1440                token_expires_at: None,
1441            },
1442        ));
1443    }
1444
1445    #[test]
1446    fn ssh_key_matching_tracks_ownership_without_touching_unmanaged_tags() {
1447        let desired = BTreeMap::from([("laptop".to_string(), "key-1".to_string())]);
1448        let observed = BTreeMap::from([
1449            ("laptop".to_string(), "key-1".to_string()),
1450            ("personal".to_string(), "key-2".to_string()),
1451        ]);
1452
1453        // Same public key does not imply ownership before it is adopted.
1454        assert!(!ssh_public_keys_match(&desired, &observed, &[]));
1455        assert!(ssh_public_keys_match(
1456            &desired,
1457            &observed,
1458            &["laptop".to_string()]
1459        ));
1460
1461        // A previously managed but no longer desired tag requires a cleanup.
1462        assert!(!ssh_public_keys_match(
1463            &BTreeMap::new(),
1464            &observed,
1465            &["laptop".to_string()],
1466        ));
1467        assert!(ssh_public_keys_match(&BTreeMap::new(), &observed, &[]));
1468
1469        let mut changed = observed;
1470        changed.insert("laptop".to_string(), "key-rotated".to_string());
1471        assert!(!ssh_public_keys_match(
1472            &desired,
1473            &changed,
1474            &["laptop".to_string()],
1475        ));
1476    }
1477}