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::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            let result = kanidm_client.idm_group_delete(name).await;
636            match result {
637                Ok(()) => {}
638                Err(ClientError::Http(status, _, _)) if status == 403 => {
639                    debug!(
640                        msg =
641                            "group cannot be deleted (likely a built-in group), skipping deletion"
642                    );
643                }
644                Err(e) => {
645                    return Err(Error::KanidmClientError(
646                        format!(
647                            "failed to delete {name} from {namespace}/{kanidm}",
648                            namespace = self.kanidm_namespace(),
649                            kanidm = self.kanidm_name(),
650                        ),
651                        Box::new(e),
652                    ));
653                }
654            }
655        }
656        Ok(Action::requeue(idm_reconcile_interval()))
657    }
658
659    async fn update_status(
660        &self,
661        kanidm_client: Arc<KanidmClient>,
662        ctx: Arc<Context<KanidmGroup>>,
663    ) -> Result<KanidmGroupStatus> {
664        // safe unwrap: person is namespaced scoped
665        let namespace = self.get_namespace();
666        let name = self.kanidm_entity_name();
667        let current_group = kanidm_client
668            .idm_group_get(&name)
669            .map_err(|e| {
670                Error::KanidmClientError(
671                    format!(
672                        "failed to get {name} from {namespace}/{kanidm}",
673                        namespace = self.kanidm_namespace(),
674                        kanidm = self.kanidm_name(),
675                    ),
676                    Box::new(e),
677                )
678            })
679            .await?;
680
681        let status = self.generate_status(current_group)?;
682        let status_patch = Patch::Apply(KanidmGroup {
683            status: Some(status.clone()),
684            ..KanidmGroup::default()
685        });
686        debug!(msg = "updating status");
687        trace!(msg = format!("status patch {:?}", status_patch));
688        let patch = PatchParams::apply(GROUP_OPERATOR_NAME).force();
689        let kanidm_api = Api::<KanidmGroup>::namespaced(ctx.client.clone(), &namespace);
690        let _o = kanidm_api
691            .patch_status(&self.name_any(), &patch, &status_patch)
692            .await
693            .map_err(|e| {
694                Error::KubeError(
695                    format!(
696                        "failed to patch KanidmGroup/status {namespace}/{name}",
697                        name = self.name_any()
698                    ),
699                    Box::new(e),
700                )
701            })?;
702        Ok(status)
703    }
704
705    /// Generate account policy conditions by comparing desired spec with current state.
706    ///
707    /// Returns conditions for:
708    /// - AccountPolicyEnabled: Whether account policy is enabled on the group
709    /// - AccountPolicyUpdated: Whether all policy settings match desired state (only if policy is in spec)
710    fn generate_account_policy_conditions(
711        &self,
712        current: &KanidmGroupAccountPolicyAttributes,
713        now: Timestamp,
714    ) -> Vec<Condition> {
715        let mut conditions = Vec::new();
716
717        // Only generate conditions if account_policy is specified in the spec
718        if let Some(ref policy) = self.spec.account_policy {
719            // AccountPolicyEnabled condition - check if policy is enabled in Kanidm
720            let enabled_condition = if current.enabled {
721                Condition {
722                    type_: TYPE_ACCOUNT_POLICY_ENABLED.to_string(),
723                    status: CONDITION_TRUE.to_string(),
724                    reason: "AccountPolicyEnabled".to_string(),
725                    message: "Account policy is enabled on this group.".to_string(),
726                    last_transition_time: Time(now),
727                    observed_generation: self.metadata.generation,
728                }
729            } else {
730                Condition {
731                    type_: TYPE_ACCOUNT_POLICY_ENABLED.to_string(),
732                    status: CONDITION_FALSE.to_string(),
733                    reason: "AccountPolicyNotEnabled".to_string(),
734                    message: "Account policy is not enabled on this group.".to_string(),
735                    last_transition_time: Time(now),
736                    observed_generation: self.metadata.generation,
737                }
738            };
739            conditions.push(enabled_condition);
740
741            // AccountPolicyUpdated condition - check if all settings match
742            // Only check if policy is already enabled
743            if current.enabled {
744                let settings_match = self.account_policy_settings_match(policy, current);
745                let updated_condition = if settings_match {
746                    Condition {
747                        type_: TYPE_ACCOUNT_POLICY_UPDATED.to_string(),
748                        status: CONDITION_TRUE.to_string(),
749                        reason: REASON_ATTRIBUTES_MATCH.to_string(),
750                        message: "Account policy settings match desired state.".to_string(),
751                        last_transition_time: Time(now),
752                        observed_generation: self.metadata.generation,
753                    }
754                } else {
755                    Condition {
756                        type_: TYPE_ACCOUNT_POLICY_UPDATED.to_string(),
757                        status: CONDITION_FALSE.to_string(),
758                        reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
759                        message: "Account policy settings do not match desired state.".to_string(),
760                        last_transition_time: Time(now),
761                        observed_generation: self.metadata.generation,
762                    }
763                };
764                conditions.push(updated_condition);
765            }
766        }
767
768        conditions
769    }
770
771    /// Check if account policy settings in spec match current state in Kanidm.
772    /// When a setting is specified in spec, it must match the current state.
773    /// When a setting is None in spec, the current state should also be None (reset behavior).
774    fn account_policy_settings_match(
775        &self,
776        policy: &crate::crd::KanidmGroupAccountPolicy,
777        current: &KanidmGroupAccountPolicyAttributes,
778    ) -> bool {
779        // For each setting: if spec has Some(v), current must have Some(v)
780        // If spec has None, current must also be None (to ensure reset happened)
781        let auth_session_match = policy.auth_session_expiry == current.auth_session_expiry;
782
783        let cred_type_match = policy.credential_type_minimum == current.credential_type_minimum;
784
785        let password_len_match = policy.password_minimum_length == current.password_minimum_length;
786
787        let privilege_match = policy.privilege_expiry == current.privilege_expiry;
788
789        let webauthn_match =
790            policy.webauthn_attestation_ca_list == current.webauthn_attestation_ca_list;
791
792        let primary_cred_match =
793            policy.allow_primary_cred_fallback == current.allow_primary_cred_fallback;
794
795        let max_results_match = policy.limit_search_max_results == current.limit_search_max_results;
796
797        let max_filter_match =
798            policy.limit_search_max_filter_test == current.limit_search_max_filter_test;
799
800        auth_session_match
801            && cred_type_match
802            && password_len_match
803            && privilege_match
804            && webauthn_match
805            && primary_cred_match
806            && max_results_match
807            && max_filter_match
808    }
809
810    fn generate_status(&self, group: Option<Entry>) -> Result<KanidmGroupStatus> {
811        let now = Timestamp::now();
812        match group {
813            Some(g) => {
814                let exist_condition = Condition {
815                    type_: TYPE_EXISTS.to_string(),
816                    status: CONDITION_TRUE.to_string(),
817                    reason: "Exists".to_string(),
818                    message: "Group exists.".to_string(),
819                    last_transition_time: Time(now),
820                    observed_generation: self.metadata.generation,
821                };
822                let managed_by_condition = self.spec.entry_managed_by.as_ref().map(|managed_by| {
823                    if Some(managed_by)
824                        == get_first_cloned(&g, ATTR_ENTRY_MANAGED_BY)
825                            .as_ref()
826                            .map(|s| normalize_spn(s.as_str()))
827                            .as_ref()
828                    {
829                        Condition {
830                            type_: TYPE_MANAGED_UPDATED.to_string(),
831                            status: CONDITION_TRUE.to_string(),
832                            reason: REASON_ATTRIBUTE_MATCH.to_string(),
833                            message: format!(
834                                "Group exists with desired {ATTR_ENTRY_MANAGED_BY} attribute."
835                            ),
836                            last_transition_time: Time(now),
837                            observed_generation: self.metadata.generation,
838                        }
839                    } else {
840                        Condition {
841                            type_: TYPE_MANAGED_UPDATED.to_string(),
842                            status: CONDITION_FALSE.to_string(),
843                            reason: REASON_ATTRIBUTE_NOT_MATCH.to_string(),
844                            message: format!(
845                                "Group exists with different {ATTR_ENTRY_MANAGED_BY} attribute."
846                            ),
847                            last_transition_time: Time(now),
848                            observed_generation: self.metadata.generation,
849                        }
850                    }
851                });
852
853                let mail_condition = self.spec.mail.as_ref().map(|mail| {
854                    // comparison is ordered because first mail is primary
855                    if Some(mail) == g.attrs.get(ATTR_MAIL) {
856                        Condition {
857                            type_: TYPE_MAIL_UPDATED.to_string(),
858                            status: CONDITION_TRUE.to_string(),
859                            reason: REASON_ATTRIBUTE_MATCH.to_string(),
860                            message: format!("Group exists with desired {ATTR_MAIL} attribute."),
861                            last_transition_time: Time(now),
862                            observed_generation: self.metadata.generation,
863                        }
864                    } else {
865                        Condition {
866                            type_: TYPE_MAIL_UPDATED.to_string(),
867                            status: CONDITION_FALSE.to_string(),
868                            reason: REASON_ATTRIBUTE_NOT_MATCH.to_string(),
869                            message: format!("Group exists with different {ATTR_MAIL} attribute."),
870                            last_transition_time: Time(now),
871                            observed_generation: self.metadata.generation,
872                        }
873                    }
874                });
875
876                let members_condition = self.spec.members.as_ref().map(|members| {
877                    if compare_names(members, g.attrs.get(ATTR_MEMBER).unwrap_or(&Vec::new())) {
878                        Condition {
879                            type_: TYPE_MEMBERS_UPDATED.to_string(),
880                            status: CONDITION_TRUE.to_string(),
881                            reason: REASON_ATTRIBUTES_MATCH.to_string(),
882                            message: format!("Group exists with desired {ATTR_MEMBER} attributes."),
883                            last_transition_time: Time(now),
884                            observed_generation: self.metadata.generation,
885                        }
886                    } else {
887                        Condition {
888                            type_: TYPE_MEMBERS_UPDATED.to_string(),
889                            status: CONDITION_FALSE.to_string(),
890                            reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
891                            message: format!(
892                                "Group exists with different {ATTR_MEMBER} attributes."
893                            ),
894                            last_transition_time: Time(now),
895                            observed_generation: self.metadata.generation,
896                        }
897                    }
898                });
899
900                // Account policy conditions
901                let current_account_policy = KanidmGroupAccountPolicyAttributes::from(&g);
902                let account_policy_conditions =
903                    self.generate_account_policy_conditions(&current_account_policy, now);
904
905                let current_group_posix = KanidmGroupPosixAttributes::from(g);
906                let posix_initialized_condition = if current_group_posix.gidnumber.is_some() {
907                    Condition {
908                        type_: TYPE_POSIX_INITIALIZED.to_string(),
909                        status: CONDITION_TRUE.to_string(),
910                        reason: "PosixInitialized".to_string(),
911                        message: "Group exists with POSIX attributes.".to_string(),
912                        last_transition_time: Time(now),
913                        observed_generation: self.metadata.generation,
914                    }
915                } else {
916                    Condition {
917                        type_: TYPE_POSIX_INITIALIZED.to_string(),
918                        status: CONDITION_FALSE.to_string(),
919                        reason: "PosixNotInitialized".to_string(),
920                        message: "Group exists without POSIX attributes.".to_string(),
921                        last_transition_time: Time(now),
922                        observed_generation: self.metadata.generation,
923                    }
924                };
925
926                let posix_updated_condition = self.spec.posix_attributes.as_ref().map(|posix| {
927                    if posix == &current_group_posix {
928                        Condition {
929                            type_: TYPE_POSIX_UPDATED.to_string(),
930                            status: CONDITION_TRUE.to_string(),
931                            reason: REASON_ATTRIBUTES_MATCH.to_string(),
932                            message: "Group exists with desired POSIX attributes.".to_string(),
933                            last_transition_time: Time(now),
934                            observed_generation: self.metadata.generation,
935                        }
936                    } else {
937                        Condition {
938                            type_: TYPE_POSIX_UPDATED.to_string(),
939                            status: CONDITION_FALSE.to_string(),
940                            reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
941                            message: "Group exists with different POSIX attributes.".to_string(),
942                            last_transition_time: Time(now),
943                            observed_generation: self.metadata.generation,
944                        }
945                    }
946                });
947                let conditions = vec![exist_condition, posix_initialized_condition]
948                    .into_iter()
949                    .chain(managed_by_condition)
950                    .chain(mail_condition)
951                    .chain(members_condition)
952                    .chain(posix_updated_condition)
953                    .chain(account_policy_conditions)
954                    .collect::<Vec<_>>();
955                let status = conditions
956                    .iter()
957                    .filter(|c| {
958                        c.type_ != TYPE_POSIX_INITIALIZED && c.type_ != TYPE_ACCOUNT_POLICY_ENABLED
959                    })
960                    .all(|c| c.status == CONDITION_TRUE);
961                Ok(KanidmGroupStatus {
962                    conditions: Some(conditions),
963                    ready: status,
964                    gid: current_group_posix.gidnumber,
965                    kanidm_ref: self.kanidm_ref(),
966                })
967            }
968            None => {
969                let conditions = vec![Condition {
970                    type_: TYPE_EXISTS.to_string(),
971                    status: CONDITION_FALSE.to_string(),
972                    reason: "NotExists".to_string(),
973                    message: "Group is not present.".to_string(),
974                    last_transition_time: Time(now),
975                    observed_generation: self.metadata.generation,
976                }];
977                Ok(KanidmGroupStatus {
978                    conditions: Some(conditions),
979                    ready: false,
980                    gid: None,
981                    kanidm_ref: self.kanidm_ref(),
982                })
983            }
984        }
985    }
986}
987
988pub fn is_group(type_: &str, status: KanidmGroupStatus) -> bool {
989    status
990        .conditions
991        .unwrap_or_default()
992        .iter()
993        .any(|c| c.type_ == type_ && c.status == CONDITION_TRUE)
994}
995
996pub fn is_group_false(type_: &str, status: KanidmGroupStatus) -> bool {
997    status
998        .conditions
999        .unwrap_or_default()
1000        .iter()
1001        .any(|c| c.type_ == type_ && c.status == CONDITION_FALSE)
1002}