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