Skip to main content

kaniop_group/
reconcile.rs

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