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