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