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!("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!("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!("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!(error = %e, "failed to publish ResourceNotWatched event");
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!("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!(error = %e, "failed to reconcile status");
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!("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!(error = %e, "failed to publish KanidmError event");
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!("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!("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!(attribute = ATTR_ENTRY_MANAGED_BY, "updating 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!(attribute = ATTR_MAIL, "updating 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!(attribute = ATTR_MEMBER, "updating 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!("updating posix attributes");
423        trace!(posix_attributes = ?self.spec.posix_attributes, "updating 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!("enabling 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!("updating 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!(policy = ?policy, "updating account 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!("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!("group cannot be deleted (likely a built-in group), skipping deletion");
833                    ctx.metrics.record_kanidm_sdk_outcome(
834                        KANIDM_RESOURCE_GROUP,
835                        KANIDM_OP_DELETE,
836                        KANIDM_OUTCOME_UNCHANGED,
837                        start.elapsed(),
838                    );
839                }
840                Err(e) => {
841                    ctx.metrics.record_kanidm_sdk_outcome(
842                        KANIDM_RESOURCE_GROUP,
843                        KANIDM_OP_DELETE,
844                        KANIDM_OUTCOME_ERROR,
845                        start.elapsed(),
846                    );
847                    return Err(Error::kanidm_client_error(
848                        "delete",
849                        name,
850                        self.kanidm_namespace(),
851                        self.kanidm_name(),
852                        e,
853                    ));
854                }
855            }
856        }
857        Ok((Action::requeue(idm_reconcile_interval()), changed))
858    }
859
860    async fn update_status(
861        &self,
862        kanidm_client: Arc<KanidmClient>,
863        ctx: Arc<Context<KanidmGroup>>,
864    ) -> Result<KanidmGroupStatus> {
865        // safe unwrap: person is namespaced scoped
866        let namespace = self.get_namespace();
867        let name = self.kanidm_entity_name();
868        let start = tokio::time::Instant::now();
869        let current_group = kanidm_client.idm_group_get(&name).await.map_err(|e| {
870            ctx.metrics.record_kanidm_sdk_outcome(
871                KANIDM_RESOURCE_GROUP,
872                KANIDM_OP_GET,
873                KANIDM_OUTCOME_ERROR,
874                start.elapsed(),
875            );
876            Error::kanidm_client_error("get", &name, self.kanidm_namespace(), self.kanidm_name(), e)
877        })?;
878        ctx.metrics.record_kanidm_sdk_outcome(
879            KANIDM_RESOURCE_GROUP,
880            KANIDM_OP_GET,
881            KANIDM_OUTCOME_UNCHANGED,
882            start.elapsed(),
883        );
884
885        let status = self.generate_status(current_group)?;
886        let status_patch = Patch::Apply(KanidmGroup {
887            status: Some(status.clone()),
888            ..KanidmGroup::default()
889        });
890        debug!("updating status");
891        trace!(status_patch = ?status_patch, "status patch");
892        let patch = PatchParams::apply(GROUP_OPERATOR_NAME).force();
893        let kanidm_api = Api::<KanidmGroup>::namespaced(ctx.client.clone(), &namespace);
894        let _o = kanidm_api
895            .patch_status(&self.name_any(), &patch, &status_patch)
896            .await
897            .map_err(|e| Error::kube_status_error("KanidmGroup", namespace, self.name_any(), e))?;
898        Ok(status)
899    }
900
901    /// Generate account policy conditions by comparing desired spec with current state.
902    ///
903    /// Returns conditions for:
904    /// - AccountPolicyEnabled: Whether account policy is enabled on the group
905    /// - AccountPolicyUpdated: Whether all policy settings match desired state (only if policy is in spec)
906    fn generate_account_policy_conditions(
907        &self,
908        current: &KanidmGroupAccountPolicyAttributes,
909        now: Timestamp,
910    ) -> Vec<Condition> {
911        let mut conditions = Vec::new();
912
913        // Only generate conditions if account_policy is specified in the spec
914        if let Some(ref policy) = self.spec.account_policy {
915            // AccountPolicyEnabled condition - check if policy is enabled in Kanidm
916            let enabled_condition = if current.enabled {
917                Condition {
918                    type_: TYPE_ACCOUNT_POLICY_ENABLED.to_string(),
919                    status: CONDITION_TRUE.to_string(),
920                    reason: "AccountPolicyEnabled".to_string(),
921                    message: "Account policy is enabled on this group.".to_string(),
922                    last_transition_time: Time(now),
923                    observed_generation: self.metadata.generation,
924                }
925            } else {
926                Condition {
927                    type_: TYPE_ACCOUNT_POLICY_ENABLED.to_string(),
928                    status: CONDITION_FALSE.to_string(),
929                    reason: "AccountPolicyNotEnabled".to_string(),
930                    message: "Account policy is not enabled on this group.".to_string(),
931                    last_transition_time: Time(now),
932                    observed_generation: self.metadata.generation,
933                }
934            };
935            conditions.push(enabled_condition);
936
937            // AccountPolicyUpdated condition - check if all settings match
938            // Only check if policy is already enabled
939            if current.enabled {
940                let settings_match = self.account_policy_settings_match(policy, current);
941                let updated_condition = if settings_match {
942                    Condition {
943                        type_: TYPE_ACCOUNT_POLICY_UPDATED.to_string(),
944                        status: CONDITION_TRUE.to_string(),
945                        reason: REASON_ATTRIBUTES_MATCH.to_string(),
946                        message: "Account policy settings match desired state.".to_string(),
947                        last_transition_time: Time(now),
948                        observed_generation: self.metadata.generation,
949                    }
950                } else {
951                    Condition {
952                        type_: TYPE_ACCOUNT_POLICY_UPDATED.to_string(),
953                        status: CONDITION_FALSE.to_string(),
954                        reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
955                        message: "Account policy settings do not match desired state.".to_string(),
956                        last_transition_time: Time(now),
957                        observed_generation: self.metadata.generation,
958                    }
959                };
960                conditions.push(updated_condition);
961            }
962        }
963
964        conditions
965    }
966
967    /// Check if account policy settings in spec match current state in Kanidm.
968    /// When a setting is specified in spec, it must match the current state.
969    /// When a setting is None in spec, the current state should also be None (reset behavior).
970    fn account_policy_settings_match(
971        &self,
972        policy: &crate::crd::KanidmGroupAccountPolicy,
973        current: &KanidmGroupAccountPolicyAttributes,
974    ) -> bool {
975        // For each setting: if spec has Some(v), current must have Some(v)
976        // If spec has None, current must also be None (to ensure reset happened)
977        let auth_session_match = policy.auth_session_expiry == current.auth_session_expiry;
978
979        let cred_type_match = policy.credential_type_minimum == current.credential_type_minimum;
980
981        let password_len_match = policy.password_minimum_length == current.password_minimum_length;
982
983        let privilege_match = policy.privilege_expiry == current.privilege_expiry;
984
985        let webauthn_match =
986            policy.webauthn_attestation_ca_list == current.webauthn_attestation_ca_list;
987
988        let primary_cred_match =
989            policy.allow_primary_cred_fallback == current.allow_primary_cred_fallback;
990
991        let max_results_match = policy.limit_search_max_results == current.limit_search_max_results;
992
993        let max_filter_match =
994            policy.limit_search_max_filter_test == current.limit_search_max_filter_test;
995
996        auth_session_match
997            && cred_type_match
998            && password_len_match
999            && privilege_match
1000            && webauthn_match
1001            && primary_cred_match
1002            && max_results_match
1003            && max_filter_match
1004    }
1005
1006    fn generate_status(&self, group: Option<Entry>) -> Result<KanidmGroupStatus> {
1007        let now = Timestamp::now();
1008        match group {
1009            Some(g) => {
1010                let exist_condition = Condition {
1011                    type_: TYPE_EXISTS.to_string(),
1012                    status: CONDITION_TRUE.to_string(),
1013                    reason: "Exists".to_string(),
1014                    message: "Group exists.".to_string(),
1015                    last_transition_time: Time(now),
1016                    observed_generation: self.metadata.generation,
1017                };
1018                let managed_by_condition = self.spec.entry_managed_by.as_ref().map(|managed_by| {
1019                    if Some(managed_by)
1020                        == get_first_cloned(&g, ATTR_ENTRY_MANAGED_BY)
1021                            .as_ref()
1022                            .map(|s| normalize_spn(s.as_str()))
1023                            .as_ref()
1024                    {
1025                        Condition {
1026                            type_: TYPE_MANAGED_UPDATED.to_string(),
1027                            status: CONDITION_TRUE.to_string(),
1028                            reason: REASON_ATTRIBUTE_MATCH.to_string(),
1029                            message: format!(
1030                                "Group exists with desired {ATTR_ENTRY_MANAGED_BY} attribute."
1031                            ),
1032                            last_transition_time: Time(now),
1033                            observed_generation: self.metadata.generation,
1034                        }
1035                    } else {
1036                        Condition {
1037                            type_: TYPE_MANAGED_UPDATED.to_string(),
1038                            status: CONDITION_FALSE.to_string(),
1039                            reason: REASON_ATTRIBUTE_NOT_MATCH.to_string(),
1040                            message: format!(
1041                                "Group exists with different {ATTR_ENTRY_MANAGED_BY} attribute."
1042                            ),
1043                            last_transition_time: Time(now),
1044                            observed_generation: self.metadata.generation,
1045                        }
1046                    }
1047                });
1048
1049                let mail_condition = self.spec.mail.as_ref().map(|mail| {
1050                    let empty_mail = Vec::new();
1051                    let current_mail = g.attrs.get(ATTR_MAIL).unwrap_or(&empty_mail);
1052                    if compare_mail(mail, current_mail) {
1053                        Condition {
1054                            type_: TYPE_MAIL_UPDATED.to_string(),
1055                            status: CONDITION_TRUE.to_string(),
1056                            reason: REASON_ATTRIBUTE_MATCH.to_string(),
1057                            message: format!("Group exists with desired {ATTR_MAIL} attribute."),
1058                            last_transition_time: Time(now),
1059                            observed_generation: self.metadata.generation,
1060                        }
1061                    } else {
1062                        Condition {
1063                            type_: TYPE_MAIL_UPDATED.to_string(),
1064                            status: CONDITION_FALSE.to_string(),
1065                            reason: REASON_ATTRIBUTE_NOT_MATCH.to_string(),
1066                            message: format!("Group exists with different {ATTR_MAIL} attribute."),
1067                            last_transition_time: Time(now),
1068                            observed_generation: self.metadata.generation,
1069                        }
1070                    }
1071                });
1072
1073                let members_condition = self.spec.members.as_ref().map(|members| {
1074                    if compare_names(members, g.attrs.get(ATTR_MEMBER).unwrap_or(&Vec::new())) {
1075                        Condition {
1076                            type_: TYPE_MEMBERS_UPDATED.to_string(),
1077                            status: CONDITION_TRUE.to_string(),
1078                            reason: REASON_ATTRIBUTES_MATCH.to_string(),
1079                            message: format!("Group exists with desired {ATTR_MEMBER} attributes."),
1080                            last_transition_time: Time(now),
1081                            observed_generation: self.metadata.generation,
1082                        }
1083                    } else {
1084                        Condition {
1085                            type_: TYPE_MEMBERS_UPDATED.to_string(),
1086                            status: CONDITION_FALSE.to_string(),
1087                            reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
1088                            message: format!(
1089                                "Group exists with different {ATTR_MEMBER} attributes."
1090                            ),
1091                            last_transition_time: Time(now),
1092                            observed_generation: self.metadata.generation,
1093                        }
1094                    }
1095                });
1096
1097                // Account policy conditions
1098                let current_account_policy = KanidmGroupAccountPolicyAttributes::from(&g);
1099                let account_policy_conditions =
1100                    self.generate_account_policy_conditions(&current_account_policy, now);
1101
1102                let current_group_posix = KanidmGroupPosixAttributes::from(g);
1103                let posix_initialized_condition = if current_group_posix.gidnumber.is_some() {
1104                    Condition {
1105                        type_: TYPE_POSIX_INITIALIZED.to_string(),
1106                        status: CONDITION_TRUE.to_string(),
1107                        reason: "PosixInitialized".to_string(),
1108                        message: "Group exists with POSIX attributes.".to_string(),
1109                        last_transition_time: Time(now),
1110                        observed_generation: self.metadata.generation,
1111                    }
1112                } else {
1113                    Condition {
1114                        type_: TYPE_POSIX_INITIALIZED.to_string(),
1115                        status: CONDITION_FALSE.to_string(),
1116                        reason: "PosixNotInitialized".to_string(),
1117                        message: "Group exists without POSIX attributes.".to_string(),
1118                        last_transition_time: Time(now),
1119                        observed_generation: self.metadata.generation,
1120                    }
1121                };
1122
1123                let posix_updated_condition = self.spec.posix_attributes.as_ref().map(|posix| {
1124                    if posix == &current_group_posix {
1125                        Condition {
1126                            type_: TYPE_POSIX_UPDATED.to_string(),
1127                            status: CONDITION_TRUE.to_string(),
1128                            reason: REASON_ATTRIBUTES_MATCH.to_string(),
1129                            message: "Group exists with desired POSIX attributes.".to_string(),
1130                            last_transition_time: Time(now),
1131                            observed_generation: self.metadata.generation,
1132                        }
1133                    } else {
1134                        Condition {
1135                            type_: TYPE_POSIX_UPDATED.to_string(),
1136                            status: CONDITION_FALSE.to_string(),
1137                            reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
1138                            message: "Group exists with different POSIX attributes.".to_string(),
1139                            last_transition_time: Time(now),
1140                            observed_generation: self.metadata.generation,
1141                        }
1142                    }
1143                });
1144                let conditions = vec![exist_condition, posix_initialized_condition]
1145                    .into_iter()
1146                    .chain(managed_by_condition)
1147                    .chain(mail_condition)
1148                    .chain(members_condition)
1149                    .chain(posix_updated_condition)
1150                    .chain(account_policy_conditions)
1151                    .collect::<Vec<_>>();
1152                let status = conditions
1153                    .iter()
1154                    .filter(|c| {
1155                        c.type_ != TYPE_POSIX_INITIALIZED && c.type_ != TYPE_ACCOUNT_POLICY_ENABLED
1156                    })
1157                    .all(|c| c.status == CONDITION_TRUE);
1158                Ok(KanidmGroupStatus {
1159                    conditions: Some(conditions),
1160                    ready: status,
1161                    gid: current_group_posix.gidnumber,
1162                    kanidm_ref: self.kanidm_ref(),
1163                })
1164            }
1165            None => {
1166                let conditions = vec![Condition {
1167                    type_: TYPE_EXISTS.to_string(),
1168                    status: CONDITION_FALSE.to_string(),
1169                    reason: "NotExists".to_string(),
1170                    message: "Group is not present.".to_string(),
1171                    last_transition_time: Time(now),
1172                    observed_generation: self.metadata.generation,
1173                }];
1174                Ok(KanidmGroupStatus {
1175                    conditions: Some(conditions),
1176                    ready: false,
1177                    gid: None,
1178                    kanidm_ref: self.kanidm_ref(),
1179                })
1180            }
1181        }
1182    }
1183}
1184
1185pub fn is_group(type_: &str, status: KanidmGroupStatus) -> bool {
1186    status
1187        .conditions
1188        .unwrap_or_default()
1189        .iter()
1190        .any(|c| c.type_ == type_ && c.status == CONDITION_TRUE)
1191}
1192
1193pub fn is_group_false(type_: &str, status: KanidmGroupStatus) -> bool {
1194    status
1195        .conditions
1196        .unwrap_or_default()
1197        .iter()
1198        .any(|c| c.type_ == type_ && c.status == CONDITION_FALSE)
1199}