Skip to main content

kaniop_group/
reconcile.rs

1use crate::crd::{
2    KanidmGroup, KanidmGroupAccountPolicyAttributes, KanidmGroupPosixAttributes, KanidmGroupStatus,
3};
4
5use kaniop_k8s_util::error::{Error, Result};
6use kaniop_k8s_util::types::{compare_names, get_first_cloned, normalize_spn};
7use kaniop_operator::controller::kanidm::{KanidmResource, is_resource_watched};
8use kaniop_operator::controller::{
9    context::{Context, IdmClientContext},
10    idm_reconcile_interval,
11};
12use kaniop_operator::telemetry;
13
14use std::sync::Arc;
15use std::time::Duration;
16
17use futures::TryFutureExt;
18use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, Time};
19use k8s_openapi::jiff::Timestamp;
20use kanidm_client::{ClientError, KanidmClient};
21use kanidm_proto::constants::{
22    ATTR_ALLOW_PRIMARY_CRED_FALLBACK, ATTR_CREDENTIAL_TYPE_MINIMUM, ATTR_ENTRY_MANAGED_BY,
23    ATTR_MAIL, ATTR_MEMBER,
24};
25use kanidm_proto::v1::Entry;
26use kube::api::{Api, Patch, PatchParams};
27use kube::runtime::controller::Action;
28use kube::runtime::events::{Event, EventType};
29use kube::runtime::finalizer::{Event as Finalizer, finalizer};
30use kube::{Resource, ResourceExt};
31use tracing::{Span, debug, field, info, instrument, trace, warn};
32
33pub static GROUP_OPERATOR_NAME: &str = "kanidmgroups.kaniop.rs";
34pub static GROUP_FINALIZER: &str = "kanidmgroups.kaniop.rs/finalizer";
35
36const TYPE_EXISTS: &str = "Exists";
37const TYPE_MAIL_UPDATED: &str = "MailUpdated";
38const TYPE_MANAGED_UPDATED: &str = "ManagedUpdated";
39const TYPE_MEMBERS_UPDATED: &str = "MembersUpdated";
40const TYPE_POSIX_INITIALIZED: &str = "PosixInitialized";
41const TYPE_POSIX_UPDATED: &str = "PosixUpdated";
42const TYPE_ACCOUNT_POLICY_ENABLED: &str = "AccountPolicyEnabled";
43const TYPE_ACCOUNT_POLICY_UPDATED: &str = "AccountPolicyUpdated";
44const REASON_ATTRIBUTE_MATCH: &str = "AttributeMatch";
45const REASON_ATTRIBUTE_NOT_MATCH: &str = "AttributeNotMatch";
46const REASON_ATTRIBUTES_MATCH: &str = "AttributesMatch";
47const REASON_ATTRIBUTES_NOT_MATCH: &str = "AttributesNotMatch";
48const CONDITION_TRUE: &str = "True";
49const CONDITION_FALSE: &str = "False";
50
51pub async fn watched_resource(group: &KanidmGroup, ctx: Arc<Context<KanidmGroup>>) -> bool {
52    let kanidm = if let Some(k) = ctx.get_kanidm(group) {
53        k
54    } else {
55        trace!(msg = "no kanidm found");
56        return false;
57    };
58
59    is_resource_watched(group, &kanidm, &ctx.namespace_store, &ctx.client).await
60}
61
62#[instrument(skip(ctx, group))]
63pub async fn reconcile_group(
64    group: Arc<KanidmGroup>,
65    ctx: Arc<Context<KanidmGroup>>,
66) -> Result<Action> {
67    let trace_id = telemetry::get_trace_id();
68    Span::current().record("trace_id", field::display(&trace_id));
69    let _timer = ctx.metrics.reconcile_count_and_measure(&trace_id);
70    let kanidm_client = ctx.get_idm_client(&group).await?;
71
72    if !watched_resource(&group, ctx.clone()).await {
73        debug!(msg = "resource not watched, skipping reconcile");
74        ctx.recorder
75        .publish(
76            &Event {
77                type_: EventType::Warning,
78                reason: "ResourceNotWatched".to_string(),
79                note: Some("configure `groupNamespaceSelector` on Kanidm resource to watch this namespace".to_string()),
80                action: "Reconcile".to_string(),
81                secondary: None,
82            },
83            &group.object_ref(&()),
84        )
85        .await
86        .map_err(|e| {
87            warn!(msg = "failed to publish ResourceNotWatched event", %e);
88            Error::kube_error("publish", "event", group.get_namespace(), group.name_any(), e)
89        })?;
90        return Ok(Action::requeue(idm_reconcile_interval()));
91    }
92
93    info!(msg = "reconciling group");
94
95    // safe unwrap: group is namespaced scoped
96    let namespace = group.get_namespace();
97    let status = group
98        .update_status(kanidm_client.clone(), ctx.clone())
99        .await
100        .map_err(|e| {
101            debug!(msg = "failed to reconcile status", %e);
102            ctx.metrics.status_update_errors_inc();
103            e
104        })?;
105    let groups_api: Api<KanidmGroup> = Api::namespaced(ctx.client.clone(), &namespace);
106    finalizer(&groups_api, GROUP_FINALIZER, group, |event| async {
107        match event {
108            Finalizer::Apply(g) => g.reconcile(kanidm_client, status, ctx).await,
109            Finalizer::Cleanup(g) => g.cleanup(kanidm_client, status).await,
110        }
111    })
112    .await
113    .map_err(|e| Error::FinalizerError("failed on group finalizer".to_string(), Box::new(e)))
114}
115
116impl KanidmGroup {
117    #[inline]
118    fn get_namespace(&self) -> String {
119        // safe unwrap: group is namespaced scoped
120        self.namespace().unwrap()
121    }
122
123    #[inline]
124    async fn reconcile(
125        &self,
126        kanidm_client: Arc<KanidmClient>,
127        status: KanidmGroupStatus,
128        ctx: Arc<Context<KanidmGroup>>,
129    ) -> Result<Action> {
130        match self.internal_reconcile(kanidm_client, status).await {
131            Ok(action) => Ok(action),
132            Err(e) => match e {
133                Error::KanidmClientError(_, _) => {
134                    ctx.recorder
135                        .publish(
136                            &Event {
137                                type_: EventType::Warning,
138                                reason: "KanidmError".to_string(),
139                                note: Some(format!("{e:?}")),
140                                action: "KanidmRequest".to_string(),
141                                secondary: None,
142                            },
143                            &self.object_ref(&()),
144                        )
145                        .await
146                        .map_err(|e| {
147                            warn!(msg = "failed to publish KanidmError event", %e);
148                            Error::kube_error(
149                                "publish",
150                                "event",
151                                self.get_namespace(),
152                                self.name_any(),
153                                e,
154                            )
155                        })?;
156                    Err(e)
157                }
158                _ => Err(e),
159            },
160        }
161    }
162
163    #[inline]
164    async fn internal_reconcile(
165        &self,
166        kanidm_client: Arc<KanidmClient>,
167        status: KanidmGroupStatus,
168    ) -> Result<Action> {
169        let name = &self.kanidm_entity_name();
170        let mut require_status_update = false;
171        if is_group_false(TYPE_EXISTS, status.clone()) {
172            self.create(&kanidm_client, name).await?;
173            require_status_update = true;
174        }
175
176        if is_group_false(TYPE_MANAGED_UPDATED, status.clone()) {
177            self.update_managed_by(&kanidm_client, name).await?;
178            require_status_update = true;
179        }
180
181        if is_group_false(TYPE_MAIL_UPDATED, status.clone()) {
182            self.update_mail(&kanidm_client, name).await?;
183            require_status_update = true;
184        }
185
186        if is_group_false(TYPE_MEMBERS_UPDATED, status.clone()) {
187            self.update_members(&kanidm_client, name).await?;
188            require_status_update = true;
189        }
190
191        if is_group_false(TYPE_POSIX_UPDATED, status.clone())
192            || (is_group_false(TYPE_POSIX_INITIALIZED, status.clone())
193                && is_group(TYPE_POSIX_UPDATED, status.clone()))
194        {
195            self.update_posix_attributes(&kanidm_client, name).await?;
196            require_status_update = true;
197        }
198
199        // Account policy reconciliation: enable first if needed, then update settings
200        if is_group_false(TYPE_ACCOUNT_POLICY_ENABLED, status.clone()) {
201            self.enable_account_policy(&kanidm_client, name).await?;
202            require_status_update = true;
203        }
204
205        if is_group_false(TYPE_ACCOUNT_POLICY_UPDATED, status.clone()) {
206            self.update_account_policy(&kanidm_client, name).await?;
207            require_status_update = true;
208        }
209
210        if require_status_update {
211            trace!(msg = "status update required, requeueing in 500ms");
212            Ok(Action::requeue(Duration::from_millis(500)))
213        } else {
214            Ok(Action::requeue(idm_reconcile_interval()))
215        }
216    }
217
218    async fn create(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
219        debug!(msg = "create");
220        kanidm_client
221            .idm_group_create(name, self.spec.entry_managed_by.as_deref())
222            .await
223            .map_err(|e| {
224                Error::kanidm_client_error(
225                    "create",
226                    name,
227                    self.kanidm_namespace(),
228                    self.kanidm_name(),
229                    e,
230                )
231            })?;
232        Ok(())
233    }
234
235    async fn update_managed_by(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
236        debug!(msg = format!("update {ATTR_ENTRY_MANAGED_BY} attribute"));
237        let entry_managed_by =
238            self.spec.entry_managed_by.as_ref().ok_or_else(|| {
239                Error::MissingData("group entryManagedBy is not defined".to_string())
240            })?;
241
242        kanidm_client
243            .idm_group_set_entry_managed_by(name, entry_managed_by)
244            .await
245            .map_err(|e| {
246                Error::kanidm_client_error_attr(
247                    "update",
248                    ATTR_ENTRY_MANAGED_BY,
249                    name,
250                    self.kanidm_namespace(),
251                    self.kanidm_name(),
252                    e,
253                )
254            })?;
255        Ok(())
256    }
257
258    async fn update_mail(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
259        debug!(msg = format!("update {ATTR_MAIL} attribute"));
260        let mail = self
261            .spec
262            .mail
263            .as_ref()
264            .ok_or_else(|| Error::MissingData("group mail is not defined".to_string()))?;
265
266        if mail.is_empty() {
267            kanidm_client
268                .idm_group_purge_mail(name)
269                .await
270                .map_err(|e| {
271                    Error::kanidm_client_error_attr(
272                        "purge",
273                        ATTR_MAIL,
274                        name,
275                        self.kanidm_namespace(),
276                        self.kanidm_name(),
277                        e,
278                    )
279                })?;
280        } else {
281            kanidm_client
282                .idm_group_set_mail(name, mail)
283                .await
284                .map_err(|e| {
285                    Error::kanidm_client_error_attr(
286                        "update",
287                        ATTR_MAIL,
288                        name,
289                        self.kanidm_namespace(),
290                        self.kanidm_name(),
291                        e,
292                    )
293                })?;
294        }
295        Ok(())
296    }
297
298    async fn update_members(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
299        debug!(msg = format!("update {ATTR_MEMBER} attribute"));
300        let members = self
301            .spec
302            .members
303            .as_ref()
304            .ok_or_else(|| Error::MissingData("group members is not defined".to_string()))?
305            .iter()
306            .map(|m| m.as_str())
307            .collect::<Vec<&str>>();
308
309        kanidm_client
310            .idm_group_set_members(name, &members)
311            .await
312            .map_err(|e| {
313                Error::kanidm_client_error_attr(
314                    "update",
315                    ATTR_MEMBER,
316                    name,
317                    self.kanidm_namespace(),
318                    self.kanidm_name(),
319                    e,
320                )
321            })?;
322        Ok(())
323    }
324
325    async fn update_posix_attributes(
326        &self,
327        kanidm_client: &KanidmClient,
328        name: &str,
329    ) -> Result<()> {
330        debug!(msg = "update posix attributes");
331        trace!(msg = format!("update posix attributes {:?}", self.spec.posix_attributes));
332        kanidm_client
333            .idm_group_unix_extend(
334                name,
335                self.spec
336                    .posix_attributes
337                    .as_ref()
338                    .and_then(|posix| posix.gidnumber),
339            )
340            .await
341            .map_err(|e| {
342                Error::kanidm_client_error(
343                    "unix extend",
344                    name,
345                    self.kanidm_namespace(),
346                    self.kanidm_name(),
347                    e,
348                )
349            })?;
350        Ok(())
351    }
352
353    async fn enable_account_policy(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
354        debug!(msg = "enable account policy");
355        kanidm_client
356            .group_account_policy_enable(name)
357            .await
358            .map_err(|e| {
359                Error::kanidm_client_error(
360                    "enable account policy for",
361                    name,
362                    self.kanidm_namespace(),
363                    self.kanidm_name(),
364                    e,
365                )
366            })?;
367        Ok(())
368    }
369
370    async fn update_account_policy(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
371        debug!(msg = "update account policy");
372        let policy =
373            self.spec.account_policy.as_ref().ok_or_else(|| {
374                Error::MissingData("group accountPolicy is not defined".to_string())
375            })?;
376        trace!(msg = format!("update account policy {:?}", policy));
377
378        // Update or reset auth session expiry
379        if let Some(expiry) = policy.auth_session_expiry {
380            kanidm_client
381                .group_account_policy_authsession_expiry_set(name, expiry)
382                .await
383                .map_err(|e| {
384                    Error::kanidm_client_error_attr(
385                        "set",
386                        "auth session expiry",
387                        name,
388                        self.kanidm_namespace(),
389                        self.kanidm_name(),
390                        e,
391                    )
392                })?;
393        } else {
394            kanidm_client
395                .group_account_policy_authsession_expiry_reset(name)
396                .await
397                .map_err(|e| {
398                    Error::kanidm_client_error_attr(
399                        "reset",
400                        "auth session expiry",
401                        name,
402                        self.kanidm_namespace(),
403                        self.kanidm_name(),
404                        e,
405                    )
406                })?;
407        }
408
409        // Update or reset credential type minimum
410        if let Some(ref cred_type) = policy.credential_type_minimum {
411            kanidm_client
412                .group_account_policy_credential_type_minimum_set(name, &cred_type.to_string())
413                .await
414                .map_err(|e| {
415                    Error::kanidm_client_error_attr(
416                        "set",
417                        ATTR_CREDENTIAL_TYPE_MINIMUM,
418                        name,
419                        self.kanidm_namespace(),
420                        self.kanidm_name(),
421                        e,
422                    )
423                })?;
424        } else {
425            kanidm_client
426                .idm_group_purge_attr(name, ATTR_CREDENTIAL_TYPE_MINIMUM)
427                .await
428                .map_err(|e| {
429                    Error::kanidm_client_error_attr(
430                        "reset",
431                        ATTR_CREDENTIAL_TYPE_MINIMUM,
432                        name,
433                        self.kanidm_namespace(),
434                        self.kanidm_name(),
435                        e,
436                    )
437                })?;
438        }
439
440        // Update or reset password minimum length
441        if let Some(length) = policy.password_minimum_length {
442            kanidm_client
443                .group_account_policy_password_minimum_length_set(name, length)
444                .await
445                .map_err(|e| {
446                    Error::kanidm_client_error_attr(
447                        "set",
448                        "password minimum length",
449                        name,
450                        self.kanidm_namespace(),
451                        self.kanidm_name(),
452                        e,
453                    )
454                })?;
455        } else {
456            kanidm_client
457                .group_account_policy_password_minimum_length_reset(name)
458                .await
459                .map_err(|e| {
460                    Error::kanidm_client_error_attr(
461                        "reset",
462                        "password minimum length",
463                        name,
464                        self.kanidm_namespace(),
465                        self.kanidm_name(),
466                        e,
467                    )
468                })?;
469        }
470
471        // Update or reset privilege expiry
472        if let Some(expiry) = policy.privilege_expiry {
473            kanidm_client
474                .group_account_policy_privilege_expiry_set(name, expiry)
475                .await
476                .map_err(|e| {
477                    Error::kanidm_client_error_attr(
478                        "set",
479                        "privilege expiry",
480                        name,
481                        self.kanidm_namespace(),
482                        self.kanidm_name(),
483                        e,
484                    )
485                })?;
486        } else {
487            kanidm_client
488                .group_account_policy_privilege_expiry_reset(name)
489                .await
490                .map_err(|e| {
491                    Error::kanidm_client_error_attr(
492                        "reset",
493                        "privilege expiry",
494                        name,
495                        self.kanidm_namespace(),
496                        self.kanidm_name(),
497                        e,
498                    )
499                })?;
500        }
501
502        // Update or reset webauthn attestation CA list
503        if let Some(ref ca_list) = policy.webauthn_attestation_ca_list {
504            kanidm_client
505                .group_account_policy_webauthn_attestation_set(name, ca_list)
506                .await
507                .map_err(|e| {
508                    Error::kanidm_client_error_attr(
509                        "set",
510                        "webauthn attestation CA list",
511                        name,
512                        self.kanidm_namespace(),
513                        self.kanidm_name(),
514                        e,
515                    )
516                })?;
517        } else {
518            kanidm_client
519                .group_account_policy_webauthn_attestation_reset(name)
520                .await
521                .map_err(|e| {
522                    Error::kanidm_client_error_attr(
523                        "reset",
524                        "webauthn attestation CA list",
525                        name,
526                        self.kanidm_namespace(),
527                        self.kanidm_name(),
528                        e,
529                    )
530                })?;
531        }
532
533        // Update or reset allow primary cred fallback
534        if let Some(allow) = policy.allow_primary_cred_fallback {
535            kanidm_client
536                .group_account_policy_allow_primary_cred_fallback(name, allow)
537                .await
538                .map_err(|e| {
539                    Error::kanidm_client_error_attr(
540                        "set",
541                        ATTR_ALLOW_PRIMARY_CRED_FALLBACK,
542                        name,
543                        self.kanidm_namespace(),
544                        self.kanidm_name(),
545                        e,
546                    )
547                })?;
548        } else {
549            kanidm_client
550                .idm_group_purge_attr(name, ATTR_ALLOW_PRIMARY_CRED_FALLBACK)
551                .await
552                .map_err(|e| {
553                    Error::kanidm_client_error_attr(
554                        "reset",
555                        ATTR_ALLOW_PRIMARY_CRED_FALLBACK,
556                        name,
557                        self.kanidm_namespace(),
558                        self.kanidm_name(),
559                        e,
560                    )
561                })?;
562        }
563
564        // Update or reset limit search max results
565        if let Some(max_results) = policy.limit_search_max_results {
566            kanidm_client
567                .group_account_policy_limit_search_max_results(name, max_results)
568                .await
569                .map_err(|e| {
570                    Error::kanidm_client_error_attr(
571                        "set",
572                        "limit search max results",
573                        name,
574                        self.kanidm_namespace(),
575                        self.kanidm_name(),
576                        e,
577                    )
578                })?;
579        } else {
580            kanidm_client
581                .group_account_policy_limit_search_max_results_reset(name)
582                .await
583                .map_err(|e| {
584                    Error::kanidm_client_error_attr(
585                        "reset",
586                        "limit search max results",
587                        name,
588                        self.kanidm_namespace(),
589                        self.kanidm_name(),
590                        e,
591                    )
592                })?;
593        }
594
595        // Update or reset limit search max filter test
596        if let Some(max_filter_test) = policy.limit_search_max_filter_test {
597            kanidm_client
598                .group_account_policy_limit_search_max_filter_test(name, max_filter_test)
599                .await
600                .map_err(|e| {
601                    Error::kanidm_client_error_attr(
602                        "set",
603                        "limit search max filter test",
604                        name,
605                        self.kanidm_namespace(),
606                        self.kanidm_name(),
607                        e,
608                    )
609                })?;
610        } else {
611            kanidm_client
612                .group_account_policy_limit_search_max_filter_test_reset(name)
613                .await
614                .map_err(|e| {
615                    Error::kanidm_client_error_attr(
616                        "reset",
617                        "limit search max filter test",
618                        name,
619                        self.kanidm_namespace(),
620                        self.kanidm_name(),
621                        e,
622                    )
623                })?;
624        }
625
626        Ok(())
627    }
628
629    async fn cleanup(
630        &self,
631        kanidm_client: Arc<KanidmClient>,
632        status: KanidmGroupStatus,
633    ) -> Result<Action> {
634        let name = &self.kanidm_entity_name();
635
636        if is_group(TYPE_EXISTS, status.clone()) {
637            debug!(msg = "delete");
638            let result = kanidm_client.idm_group_delete(name).await;
639            match result {
640                Ok(()) => {}
641                Err(ClientError::Http(status, _, _)) if status == 403 => {
642                    debug!(
643                        msg =
644                            "group cannot be deleted (likely a built-in group), skipping deletion"
645                    );
646                }
647                Err(e) => {
648                    return Err(Error::kanidm_client_error(
649                        "delete",
650                        name,
651                        self.kanidm_namespace(),
652                        self.kanidm_name(),
653                        e,
654                    ));
655                }
656            }
657        }
658        Ok(Action::requeue(idm_reconcile_interval()))
659    }
660
661    async fn update_status(
662        &self,
663        kanidm_client: Arc<KanidmClient>,
664        ctx: Arc<Context<KanidmGroup>>,
665    ) -> Result<KanidmGroupStatus> {
666        // safe unwrap: person is namespaced scoped
667        let namespace = self.get_namespace();
668        let name = self.kanidm_entity_name();
669        let current_group = kanidm_client
670            .idm_group_get(&name)
671            .map_err(|e| {
672                Error::kanidm_client_error(
673                    "get",
674                    &name,
675                    self.kanidm_namespace(),
676                    self.kanidm_name(),
677                    e,
678                )
679            })
680            .await?;
681
682        let status = self.generate_status(current_group)?;
683        let status_patch = Patch::Apply(KanidmGroup {
684            status: Some(status.clone()),
685            ..KanidmGroup::default()
686        });
687        debug!(msg = "updating status");
688        trace!(msg = format!("status patch {:?}", status_patch));
689        let patch = PatchParams::apply(GROUP_OPERATOR_NAME).force();
690        let kanidm_api = Api::<KanidmGroup>::namespaced(ctx.client.clone(), &namespace);
691        let _o = kanidm_api
692            .patch_status(&self.name_any(), &patch, &status_patch)
693            .await
694            .map_err(|e| Error::kube_status_error("KanidmGroup", namespace, self.name_any(), e))?;
695        Ok(status)
696    }
697
698    /// Generate account policy conditions by comparing desired spec with current state.
699    ///
700    /// Returns conditions for:
701    /// - AccountPolicyEnabled: Whether account policy is enabled on the group
702    /// - AccountPolicyUpdated: Whether all policy settings match desired state (only if policy is in spec)
703    fn generate_account_policy_conditions(
704        &self,
705        current: &KanidmGroupAccountPolicyAttributes,
706        now: Timestamp,
707    ) -> Vec<Condition> {
708        let mut conditions = Vec::new();
709
710        // Only generate conditions if account_policy is specified in the spec
711        if let Some(ref policy) = self.spec.account_policy {
712            // AccountPolicyEnabled condition - check if policy is enabled in Kanidm
713            let enabled_condition = if current.enabled {
714                Condition {
715                    type_: TYPE_ACCOUNT_POLICY_ENABLED.to_string(),
716                    status: CONDITION_TRUE.to_string(),
717                    reason: "AccountPolicyEnabled".to_string(),
718                    message: "Account policy is enabled on this group.".to_string(),
719                    last_transition_time: Time(now),
720                    observed_generation: self.metadata.generation,
721                }
722            } else {
723                Condition {
724                    type_: TYPE_ACCOUNT_POLICY_ENABLED.to_string(),
725                    status: CONDITION_FALSE.to_string(),
726                    reason: "AccountPolicyNotEnabled".to_string(),
727                    message: "Account policy is not enabled on this group.".to_string(),
728                    last_transition_time: Time(now),
729                    observed_generation: self.metadata.generation,
730                }
731            };
732            conditions.push(enabled_condition);
733
734            // AccountPolicyUpdated condition - check if all settings match
735            // Only check if policy is already enabled
736            if current.enabled {
737                let settings_match = self.account_policy_settings_match(policy, current);
738                let updated_condition = if settings_match {
739                    Condition {
740                        type_: TYPE_ACCOUNT_POLICY_UPDATED.to_string(),
741                        status: CONDITION_TRUE.to_string(),
742                        reason: REASON_ATTRIBUTES_MATCH.to_string(),
743                        message: "Account policy settings match desired state.".to_string(),
744                        last_transition_time: Time(now),
745                        observed_generation: self.metadata.generation,
746                    }
747                } else {
748                    Condition {
749                        type_: TYPE_ACCOUNT_POLICY_UPDATED.to_string(),
750                        status: CONDITION_FALSE.to_string(),
751                        reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
752                        message: "Account policy settings do not match desired state.".to_string(),
753                        last_transition_time: Time(now),
754                        observed_generation: self.metadata.generation,
755                    }
756                };
757                conditions.push(updated_condition);
758            }
759        }
760
761        conditions
762    }
763
764    /// Check if account policy settings in spec match current state in Kanidm.
765    /// When a setting is specified in spec, it must match the current state.
766    /// When a setting is None in spec, the current state should also be None (reset behavior).
767    fn account_policy_settings_match(
768        &self,
769        policy: &crate::crd::KanidmGroupAccountPolicy,
770        current: &KanidmGroupAccountPolicyAttributes,
771    ) -> bool {
772        // For each setting: if spec has Some(v), current must have Some(v)
773        // If spec has None, current must also be None (to ensure reset happened)
774        let auth_session_match = policy.auth_session_expiry == current.auth_session_expiry;
775
776        let cred_type_match = policy.credential_type_minimum == current.credential_type_minimum;
777
778        let password_len_match = policy.password_minimum_length == current.password_minimum_length;
779
780        let privilege_match = policy.privilege_expiry == current.privilege_expiry;
781
782        let webauthn_match =
783            policy.webauthn_attestation_ca_list == current.webauthn_attestation_ca_list;
784
785        let primary_cred_match =
786            policy.allow_primary_cred_fallback == current.allow_primary_cred_fallback;
787
788        let max_results_match = policy.limit_search_max_results == current.limit_search_max_results;
789
790        let max_filter_match =
791            policy.limit_search_max_filter_test == current.limit_search_max_filter_test;
792
793        auth_session_match
794            && cred_type_match
795            && password_len_match
796            && privilege_match
797            && webauthn_match
798            && primary_cred_match
799            && max_results_match
800            && max_filter_match
801    }
802
803    fn generate_status(&self, group: Option<Entry>) -> Result<KanidmGroupStatus> {
804        let now = Timestamp::now();
805        match group {
806            Some(g) => {
807                let exist_condition = Condition {
808                    type_: TYPE_EXISTS.to_string(),
809                    status: CONDITION_TRUE.to_string(),
810                    reason: "Exists".to_string(),
811                    message: "Group exists.".to_string(),
812                    last_transition_time: Time(now),
813                    observed_generation: self.metadata.generation,
814                };
815                let managed_by_condition = self.spec.entry_managed_by.as_ref().map(|managed_by| {
816                    if Some(managed_by)
817                        == get_first_cloned(&g, ATTR_ENTRY_MANAGED_BY)
818                            .as_ref()
819                            .map(|s| normalize_spn(s.as_str()))
820                            .as_ref()
821                    {
822                        Condition {
823                            type_: TYPE_MANAGED_UPDATED.to_string(),
824                            status: CONDITION_TRUE.to_string(),
825                            reason: REASON_ATTRIBUTE_MATCH.to_string(),
826                            message: format!(
827                                "Group exists with desired {ATTR_ENTRY_MANAGED_BY} attribute."
828                            ),
829                            last_transition_time: Time(now),
830                            observed_generation: self.metadata.generation,
831                        }
832                    } else {
833                        Condition {
834                            type_: TYPE_MANAGED_UPDATED.to_string(),
835                            status: CONDITION_FALSE.to_string(),
836                            reason: REASON_ATTRIBUTE_NOT_MATCH.to_string(),
837                            message: format!(
838                                "Group exists with different {ATTR_ENTRY_MANAGED_BY} attribute."
839                            ),
840                            last_transition_time: Time(now),
841                            observed_generation: self.metadata.generation,
842                        }
843                    }
844                });
845
846                let mail_condition = self.spec.mail.as_ref().map(|mail| {
847                    // comparison is ordered because first mail is primary
848                    if Some(mail) == g.attrs.get(ATTR_MAIL) {
849                        Condition {
850                            type_: TYPE_MAIL_UPDATED.to_string(),
851                            status: CONDITION_TRUE.to_string(),
852                            reason: REASON_ATTRIBUTE_MATCH.to_string(),
853                            message: format!("Group exists with desired {ATTR_MAIL} attribute."),
854                            last_transition_time: Time(now),
855                            observed_generation: self.metadata.generation,
856                        }
857                    } else {
858                        Condition {
859                            type_: TYPE_MAIL_UPDATED.to_string(),
860                            status: CONDITION_FALSE.to_string(),
861                            reason: REASON_ATTRIBUTE_NOT_MATCH.to_string(),
862                            message: format!("Group exists with different {ATTR_MAIL} attribute."),
863                            last_transition_time: Time(now),
864                            observed_generation: self.metadata.generation,
865                        }
866                    }
867                });
868
869                let members_condition = self.spec.members.as_ref().map(|members| {
870                    if compare_names(members, g.attrs.get(ATTR_MEMBER).unwrap_or(&Vec::new())) {
871                        Condition {
872                            type_: TYPE_MEMBERS_UPDATED.to_string(),
873                            status: CONDITION_TRUE.to_string(),
874                            reason: REASON_ATTRIBUTES_MATCH.to_string(),
875                            message: format!("Group exists with desired {ATTR_MEMBER} attributes."),
876                            last_transition_time: Time(now),
877                            observed_generation: self.metadata.generation,
878                        }
879                    } else {
880                        Condition {
881                            type_: TYPE_MEMBERS_UPDATED.to_string(),
882                            status: CONDITION_FALSE.to_string(),
883                            reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
884                            message: format!(
885                                "Group exists with different {ATTR_MEMBER} attributes."
886                            ),
887                            last_transition_time: Time(now),
888                            observed_generation: self.metadata.generation,
889                        }
890                    }
891                });
892
893                // Account policy conditions
894                let current_account_policy = KanidmGroupAccountPolicyAttributes::from(&g);
895                let account_policy_conditions =
896                    self.generate_account_policy_conditions(&current_account_policy, now);
897
898                let current_group_posix = KanidmGroupPosixAttributes::from(g);
899                let posix_initialized_condition = if current_group_posix.gidnumber.is_some() {
900                    Condition {
901                        type_: TYPE_POSIX_INITIALIZED.to_string(),
902                        status: CONDITION_TRUE.to_string(),
903                        reason: "PosixInitialized".to_string(),
904                        message: "Group exists with POSIX attributes.".to_string(),
905                        last_transition_time: Time(now),
906                        observed_generation: self.metadata.generation,
907                    }
908                } else {
909                    Condition {
910                        type_: TYPE_POSIX_INITIALIZED.to_string(),
911                        status: CONDITION_FALSE.to_string(),
912                        reason: "PosixNotInitialized".to_string(),
913                        message: "Group exists without POSIX attributes.".to_string(),
914                        last_transition_time: Time(now),
915                        observed_generation: self.metadata.generation,
916                    }
917                };
918
919                let posix_updated_condition = self.spec.posix_attributes.as_ref().map(|posix| {
920                    if posix == &current_group_posix {
921                        Condition {
922                            type_: TYPE_POSIX_UPDATED.to_string(),
923                            status: CONDITION_TRUE.to_string(),
924                            reason: REASON_ATTRIBUTES_MATCH.to_string(),
925                            message: "Group exists with desired POSIX attributes.".to_string(),
926                            last_transition_time: Time(now),
927                            observed_generation: self.metadata.generation,
928                        }
929                    } else {
930                        Condition {
931                            type_: TYPE_POSIX_UPDATED.to_string(),
932                            status: CONDITION_FALSE.to_string(),
933                            reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
934                            message: "Group exists with different POSIX attributes.".to_string(),
935                            last_transition_time: Time(now),
936                            observed_generation: self.metadata.generation,
937                        }
938                    }
939                });
940                let conditions = vec![exist_condition, posix_initialized_condition]
941                    .into_iter()
942                    .chain(managed_by_condition)
943                    .chain(mail_condition)
944                    .chain(members_condition)
945                    .chain(posix_updated_condition)
946                    .chain(account_policy_conditions)
947                    .collect::<Vec<_>>();
948                let status = conditions
949                    .iter()
950                    .filter(|c| {
951                        c.type_ != TYPE_POSIX_INITIALIZED && c.type_ != TYPE_ACCOUNT_POLICY_ENABLED
952                    })
953                    .all(|c| c.status == CONDITION_TRUE);
954                Ok(KanidmGroupStatus {
955                    conditions: Some(conditions),
956                    ready: status,
957                    gid: current_group_posix.gidnumber,
958                    kanidm_ref: self.kanidm_ref(),
959                })
960            }
961            None => {
962                let conditions = vec![Condition {
963                    type_: TYPE_EXISTS.to_string(),
964                    status: CONDITION_FALSE.to_string(),
965                    reason: "NotExists".to_string(),
966                    message: "Group is not present.".to_string(),
967                    last_transition_time: Time(now),
968                    observed_generation: self.metadata.generation,
969                }];
970                Ok(KanidmGroupStatus {
971                    conditions: Some(conditions),
972                    ready: false,
973                    gid: None,
974                    kanidm_ref: self.kanidm_ref(),
975                })
976            }
977        }
978    }
979}
980
981pub fn is_group(type_: &str, status: KanidmGroupStatus) -> bool {
982    status
983        .conditions
984        .unwrap_or_default()
985        .iter()
986        .any(|c| c.type_ == type_ && c.status == CONDITION_TRUE)
987}
988
989pub fn is_group_false(type_: &str, status: KanidmGroupStatus) -> bool {
990    status
991        .conditions
992        .unwrap_or_default()
993        .iter()
994        .any(|c| c.type_ == type_ && c.status == CONDITION_FALSE)
995}