Skip to main content

kaniop_oauth2/reconcile/
mod.rs

1mod secret;
2mod status;
3
4use self::secret::SecretExt;
5use self::status::{
6    CONDITION_FALSE, CONDITION_TRUE, StatusExt, TYPE_ALLOW_LOCALHOST_REDIRECT_UPDATED,
7    TYPE_CLAIMS_MAP_UPDATED, TYPE_DISABLE_CONSENT_PROMPT_UPDATED, TYPE_DISABLE_PKCE_UPDATED,
8    TYPE_EXISTS, TYPE_IMAGE_UPDATED, TYPE_LEGACY_CRYPTO_UPDATED, TYPE_PREFER_SHORT_NAME_UPDATED,
9    TYPE_REDIRECT_URL_UPDATED, TYPE_SCOPE_MAP_UPDATED, TYPE_SECRET_INITIALIZED,
10    TYPE_SECRET_KEY_ALIASES_SYNCED, TYPE_SECRET_ROTATED, TYPE_SECRET_TEMPLATE_SYNCED,
11    TYPE_STRICT_REDIRECT_URL_UPDATED, TYPE_SUP_SCOPE_MAP_UPDATED, TYPE_UPDATED,
12};
13use kaniop_k8s_util::image::{ImageOperation, publish_image_error_event, update_image_if_needed};
14
15use crate::{
16    controller::Context,
17    crd::{
18        KanidmClaimMap, KanidmOAuth2Client, KanidmOAuth2ClientStatus, KanidmScopeMap,
19        OAuth2ClientImageStatus,
20    },
21};
22
23use kanidm_proto::internal::OperationError;
24use kaniop_k8s_util::error::{Error, Result};
25use kaniop_operator::controller::context::{IdmClientContext, KubeOperations};
26use kaniop_operator::controller::idm_reconcile_interval;
27use kaniop_operator::controller::kanidm::{KanidmResource, is_resource_watched};
28use kaniop_operator::object_meta_template::ObjectMetaTemplateExt;
29use kaniop_operator::telemetry;
30
31use std::collections::BTreeSet;
32use std::sync::Arc;
33use std::time::Duration;
34
35use futures::future::TryJoinAll;
36use futures::try_join;
37
38use k8s_openapi::NamespaceResourceScope;
39use k8s_openapi::api::core::v1::Secret;
40use kanidm_client::{ClientError, KanidmClient, StatusCode};
41use kanidm_proto::constants::{
42    ATTR_OAUTH2_ALLOW_INSECURE_CLIENT_DISABLE_PKCE, ATTR_OAUTH2_ALLOW_LOCALHOST_REDIRECT,
43    ATTR_OAUTH2_CONSENT_PROMPT_ENABLE, ATTR_OAUTH2_JWT_LEGACY_CRYPTO_ENABLE,
44    ATTR_OAUTH2_PREFER_SHORT_USERNAME, ATTR_OAUTH2_RS_CLAIM_MAP, ATTR_OAUTH2_RS_ORIGIN,
45    ATTR_OAUTH2_RS_SCOPE_MAP, ATTR_OAUTH2_RS_SUP_SCOPE_MAP, ATTR_OAUTH2_STRICT_REDIRECT_URI,
46};
47use kube::api::{Api, Patch, PatchParams};
48use kube::runtime::controller::Action;
49use kube::runtime::events::{Event, EventType};
50use kube::runtime::finalizer::{Event as Finalizer, finalizer};
51use kube::{Resource, ResourceExt};
52use serde::{Deserialize, Serialize};
53use serde_json::json;
54
55use tracing::{Span, debug, field, info, instrument, trace, warn};
56
57static OAUTH2_OPERATOR_NAME: &str = "kanidmoauth2clients.kaniop.rs";
58static OAUTH2_FINALIZER: &str = "kanidmoauth2clients.kaniop.rs/finalizer";
59pub const FORCE_SECRET_ROTATION_ANNOTATION: &str = "kaniop.rs/force-secret-rotation";
60pub const SECRET_KEY_ALIASES_GENERATION_ANNOTATION: &str =
61    "kaniop.rs/secret-key-aliases-generation";
62
63pub async fn watched_resource(oauth2: &KanidmOAuth2Client, ctx: Arc<Context>) -> bool {
64    let kanidm = if let Some(k) = ctx.kaniop_ctx.get_kanidm(oauth2) {
65        k
66    } else {
67        trace!(msg = "no kanidm found");
68        return false;
69    };
70
71    is_resource_watched(
72        oauth2,
73        &kanidm,
74        &ctx.kaniop_ctx.namespace_store,
75        &ctx.kaniop_ctx.client,
76    )
77    .await
78}
79
80#[instrument(skip(ctx, oauth2))]
81pub async fn reconcile_oauth2(
82    oauth2: Arc<KanidmOAuth2Client>,
83    ctx: Arc<Context>,
84) -> Result<Action> {
85    let trace_id = telemetry::get_trace_id();
86    Span::current().record("trace_id", field::display(&trace_id));
87    let _timer = ctx
88        .kaniop_ctx
89        .metrics
90        .reconcile_count_and_measure(&trace_id);
91    let kanidm_client = ctx.get_idm_client(&oauth2).await?;
92
93    if !watched_resource(&oauth2, ctx.clone()).await {
94        debug!(msg = "resource not watched, skipping reconcile");
95        ctx.kaniop_ctx.recorder
96        .publish(
97            &Event {
98                type_: EventType::Warning,
99                reason: "ResourceNotWatched".to_string(),
100                note: Some("configure `oauth2ClientNamespaceSelector` on Kanidm resource to watch this namespace".to_string()),
101                action: "Reconcile".to_string(),
102                secondary: None,
103            },
104            &oauth2.object_ref(&()),
105        )
106        .await
107        .map_err(|e| {
108            warn!(msg = "failed to publish KanidmError event", %e);
109            Error::kube_error("publish", "event", oauth2.get_namespace(), oauth2.name_any(), e)
110        })?;
111        return Ok(Action::requeue(idm_reconcile_interval()));
112    }
113
114    info!(msg = "reconciling oauth2 client");
115    let namespace = oauth2.get_namespace();
116    let status = oauth2
117        .update_status(kanidm_client.clone(), ctx.clone())
118        .await
119        .map_err(|e| {
120            debug!(msg = "failed to reconcile status", %e);
121            ctx.kaniop_ctx.metrics.status_update_errors_inc();
122            e
123        })?;
124    let persons_api: Api<KanidmOAuth2Client> =
125        Api::namespaced(ctx.kaniop_ctx.client.clone(), &namespace);
126    finalizer(&persons_api, OAUTH2_FINALIZER, oauth2, |event| async {
127        match event {
128            Finalizer::Apply(p) => p.reconcile(kanidm_client, status, ctx).await,
129            Finalizer::Cleanup(p) => p.cleanup(kanidm_client, status).await,
130        }
131    })
132    .await
133    .map_err(|e| {
134        Error::FinalizerError("failed on oauth2 client finalizer".to_string(), Box::new(e))
135    })
136}
137
138impl KanidmOAuth2Client {
139    // Method kube_patch are provided by KubeOperations trait
140    pub async fn patch<K>(&self, ctx: &Context, resource: K) -> Result<K>
141    where
142        K: Resource<Scope = NamespaceResourceScope>
143            + Serialize
144            + Clone
145            + std::fmt::Debug
146            + for<'de> Deserialize<'de>,
147        <K as kube::Resource>::DynamicType: Default,
148        <K as Resource>::Scope: std::marker::Sized,
149    {
150        self.kube_patch(
151            ctx.kaniop_ctx.client.clone(),
152            &ctx.kaniop_ctx.metrics,
153            resource,
154            OAUTH2_OPERATOR_NAME,
155        )
156        .await
157    }
158
159    async fn apply_secret(&self, ctx: &Context, secret: Secret) -> Result<Secret> {
160        self.patch(ctx, secret).await
161    }
162
163    #[inline]
164    fn get_namespace(&self) -> String {
165        // safe unwrap: oauth2 is namespaced scoped
166        self.namespace().unwrap()
167    }
168
169    #[inline]
170    fn force_secret_rotation_requested(&self) -> bool {
171        self.annotations()
172            .get(FORCE_SECRET_ROTATION_ANNOTATION)
173            .is_some()
174    }
175
176    async fn clear_force_secret_rotation_annotation(&self, ctx: Arc<Context>) -> Result<()> {
177        let namespace = self.get_namespace();
178        let patch = Patch::Merge(json!({
179            "metadata": {
180                "annotations": {
181                    FORCE_SECRET_ROTATION_ANNOTATION: null
182                }
183            }
184        }));
185        let params = PatchParams::default();
186        let oauth2_api =
187            Api::<KanidmOAuth2Client>::namespaced(ctx.kaniop_ctx.client.clone(), &namespace);
188        oauth2_api
189            .patch(&self.name_any(), &params, &patch)
190            .await
191            .map_err(|e| {
192                Error::KubeError(
193                    format!(
194                        "failed to clear annotation {FORCE_SECRET_ROTATION_ANNOTATION} on {namespace}/{}",
195                        self.name_any()
196                    ),
197                    Box::new(e),
198                )
199            })?;
200        Ok(())
201    }
202
203    async fn patch_alias_generation_annotation(
204        &self,
205        ctx: Arc<Context>,
206        generation: i64,
207    ) -> Result<()> {
208        let namespace = self.get_namespace();
209        let patch = Patch::Merge(json!({
210            "metadata": {
211                "annotations": {
212                    SECRET_KEY_ALIASES_GENERATION_ANNOTATION: generation.to_string()
213                }
214            }
215        }));
216        let params = PatchParams::default();
217        let oauth2_api =
218            Api::<KanidmOAuth2Client>::namespaced(ctx.kaniop_ctx.client.clone(), &namespace);
219        oauth2_api
220            .patch(&self.name_any(), &params, &patch)
221            .await
222            .map_err(|e| {
223                Error::KubeError(
224                    format!(
225                        "failed to set annotation {SECRET_KEY_ALIASES_GENERATION_ANNOTATION} on {namespace}/{}",
226                        self.name_any()
227                    ),
228                    Box::new(e),
229                )
230            })?;
231        Ok(())
232    }
233
234    #[inline]
235    async fn reconcile(
236        &self,
237        kanidm_client: Arc<KanidmClient>,
238        status: KanidmOAuth2ClientStatus,
239        ctx: Arc<Context>,
240    ) -> Result<Action> {
241        match self
242            .internal_reconcile(kanidm_client, status, ctx.clone())
243            .await
244        {
245            Ok(action) => Ok(action),
246            Err(e) => match &e {
247                Error::KanidmClientError(msg, client_err) => {
248                    let event_note = match client_err.as_ref() {
249                        ClientError::Http(
250                            StatusCode::NOT_FOUND,
251                            Some(OperationError::NoMatchingEntries),
252                            kopid,
253                        ) => {
254                            format!("group not found: {msg}. KOpId: {kopid}")
255                        }
256                        _ => {
257                            format!("{msg}: KanidmClientError: {client_err:?}")
258                        }
259                    };
260                    ctx.kaniop_ctx
261                        .recorder
262                        .publish(
263                            &Event {
264                                type_: EventType::Warning,
265                                reason: "KanidmError".to_string(),
266                                note: Some(event_note),
267                                action: "KanidmRequest".to_string(),
268                                secondary: None,
269                            },
270                            &self.object_ref(&()),
271                        )
272                        .await
273                        .map_err(|e| {
274                            warn!(msg = "failed to publish KanidmError event", %e);
275                            Error::kube_error(
276                                "publish",
277                                "event",
278                                self.get_namespace(),
279                                self.name_any(),
280                                e,
281                            )
282                        })?;
283                    Err(e)
284                }
285                _ => Err(e),
286            },
287        }
288    }
289
290    #[inline]
291    async fn internal_reconcile(
292        &self,
293        kanidm_client: Arc<KanidmClient>,
294        status: KanidmOAuth2ClientStatus,
295        ctx: Arc<Context>,
296    ) -> Result<Action> {
297        let name = &self.kanidm_entity_name();
298        let namespace = self.get_namespace();
299        let mut require_status_update = false;
300        let force_secret_rotation_requested = self.force_secret_rotation_requested();
301
302        if is_oauth2_false(TYPE_EXISTS, status.clone()) {
303            self.create(&kanidm_client, name).await?;
304            require_status_update = true;
305        }
306
307        if is_oauth2_false(TYPE_SECRET_INITIALIZED, status.clone()) {
308            let secret = self
309                .generate_secret(
310                    &kanidm_client,
311                    self.spec.secret_rotation.as_ref(),
312                    self.spec.secret_key_aliases.as_ref(),
313                )
314                .await?;
315            self.apply_secret(&ctx, secret).await?;
316            return Ok(Action::requeue(Duration::from_millis(500)));
317        }
318
319        // Handle secret key aliases sync - regenerate secret if aliases are not synced.
320        // Skip this if force rotation is requested, as rotation will regenerate the secret.
321        // We regenerate when TYPE_SECRET_KEY_ALIASES_SYNCED is False, regardless of annotation.
322        // This ensures we keep regenerating until the secret actually has the correct keys.
323        // The annotation is updated only when TYPE is True (confirmed synced).
324        if is_oauth2_false(TYPE_SECRET_KEY_ALIASES_SYNCED, status.clone())
325            && !force_secret_rotation_requested
326        {
327            info!(msg = "regenerating secret due to secretKeyAliases not synced");
328            let secret = self
329                .generate_secret(
330                    &kanidm_client,
331                    self.spec.secret_rotation.as_ref(),
332                    self.spec.secret_key_aliases.as_ref(),
333                )
334                .await?;
335            self.apply_secret(&ctx, secret).await?;
336            return Ok(Action::requeue(Duration::from_millis(500)));
337        }
338
339        // Update annotation when aliases are confirmed synced but annotation is outdated.
340        // Do this only after TYPE is True to avoid race conditions.
341        let current_generation = self.metadata.generation.unwrap_or(0);
342        let annotation_generation = self
343            .annotations()
344            .get(SECRET_KEY_ALIASES_GENERATION_ANNOTATION)
345            .and_then(|v| v.parse::<i64>().ok())
346            .unwrap_or(0);
347        if is_oauth2(TYPE_SECRET_KEY_ALIASES_SYNCED, status.clone())
348            && current_generation > annotation_generation
349        {
350            self.patch_alias_generation_annotation(ctx.clone(), current_generation)
351                .await?;
352            require_status_update = true;
353        }
354
355        if force_secret_rotation_requested {
356            if self.spec.public {
357                info!(msg = "skipping forced secret rotation annotation for public OAuth2 client");
358            } else {
359                info!(msg = "rotating OAuth2 client secret due to force annotation");
360                self.rotate_secret(&kanidm_client, name, ctx.clone())
361                    .await?;
362            }
363            self.clear_force_secret_rotation_annotation(ctx.clone())
364                .await?;
365            require_status_update = true;
366        } else if is_oauth2_false(TYPE_SECRET_ROTATED, status.clone()) {
367            // Handle scheduled secret rotation for confidential clients
368            self.rotate_secret(&kanidm_client, name, ctx.clone())
369                .await?;
370            require_status_update = true;
371        }
372
373        // Note: when the Secret is created in this same reconcile cycle,
374        // TYPE_SECRET_TEMPLATE_SYNCED is absent (not False) in `status` because the Secret
375        // didn't exist when `update_status` ran. The template apply is therefore deferred to
376        // the next reconcile after the watch delivers the new Secret to the store.
377        if is_oauth2_false(TYPE_SECRET_TEMPLATE_SYNCED, status.clone()) {
378            match ctx.secret_store.find(|s| {
379                s.name_any() == self.secret_name() && s.namespace().as_ref() == Some(&namespace)
380            }) {
381                None => debug!(msg = "secret not yet in store, deferring secretTemplate apply"),
382                Some(secret_meta) => {
383                    // Re-evaluate here rather than reusing the status result: the store may
384                    // have been updated between update_status and now, and we need the
385                    // FilteredMetadata value (including has_discards) which is not carried
386                    // through the status conditions.
387                    if let Some(filtered) = self.needs_meta_template_apply(&secret_meta) {
388                        if filtered.has_discards() {
389                            warn!(
390                                msg = "secretTemplate contains keys already owned by the operator; they will be ignored",
391                                discarded_labels = ?filtered.discarded_labels,
392                                discarded_annotations = ?filtered.discarded_annotations,
393                            );
394                            ctx.kaniop_ctx
395                                .recorder
396                                .publish(
397                                    &Event {
398                                        type_: EventType::Warning,
399                                        reason: "SecretTemplateConflict".to_string(),
400                                        note: Some(format!(
401                                            "secretTemplate contains keys already owned by the \
402                                             operator and will be ignored. Labels: [{}]. \
403                                             Annotations: [{}].",
404                                            filtered
405                                                .discarded_labels
406                                                .iter()
407                                                .cloned()
408                                                .collect::<Vec<_>>()
409                                                .join(", "),
410                                            filtered
411                                                .discarded_annotations
412                                                .iter()
413                                                .cloned()
414                                                .collect::<Vec<_>>()
415                                                .join(", "),
416                                        )),
417                                        action: "ApplySecretTemplate".to_string(),
418                                        secondary: None,
419                                    },
420                                    &self.object_ref(&()),
421                                )
422                                .await
423                                .map_err(|e| {
424                                    warn!(msg = "failed to publish SecretTemplateConflict event", %e);
425Error::kube_error("publish", "event", self.get_namespace(), self.name_any(), e)
426                                })?;
427                        }
428                        self.apply_meta_template(
429                            ctx.kaniop_ctx.client.clone(),
430                            &ctx.kaniop_ctx.metrics,
431                            filtered,
432                        )
433                        .await?;
434                        require_status_update = true;
435                    }
436                }
437            }
438        }
439
440        if is_oauth2_false(TYPE_UPDATED, status.clone()) {
441            self.update(&kanidm_client, name).await?;
442            require_status_update = true;
443        }
444
445        if is_oauth2_false(TYPE_REDIRECT_URL_UPDATED, status.clone()) {
446            self.update_redirect_url(&kanidm_client, name, &status)
447                .await?;
448            require_status_update = true;
449        }
450
451        if is_oauth2_false(TYPE_SCOPE_MAP_UPDATED, status.clone()) {
452            self.update_scope_map(&kanidm_client, name, &status).await?;
453            require_status_update = true;
454        }
455
456        if is_oauth2_false(TYPE_SUP_SCOPE_MAP_UPDATED, status.clone()) {
457            self.update_sup_scope_map(&kanidm_client, name, &status)
458                .await?;
459            require_status_update = true;
460        }
461
462        if is_oauth2_false(TYPE_CLAIMS_MAP_UPDATED, status.clone()) {
463            self.update_claims_map(&kanidm_client, name, &status)
464                .await?;
465            require_status_update = true;
466        }
467
468        if is_oauth2_false(TYPE_STRICT_REDIRECT_URL_UPDATED, status.clone()) {
469            self.update_strict_redirect_url(&kanidm_client, name)
470                .await?;
471            require_status_update = true;
472        }
473
474        if is_oauth2_false(TYPE_DISABLE_PKCE_UPDATED, status.clone()) {
475            self.update_disable_pkce(&kanidm_client, name).await?;
476            require_status_update = true;
477        }
478
479        if is_oauth2_false(TYPE_PREFER_SHORT_NAME_UPDATED, status.clone()) {
480            self.update_prefer_short_name(&kanidm_client, name).await?;
481            require_status_update = true;
482        }
483
484        if is_oauth2_false(TYPE_ALLOW_LOCALHOST_REDIRECT_UPDATED, status.clone()) {
485            self.update_allow_localhost_redirect(&kanidm_client, name)
486                .await?;
487            require_status_update = true;
488        }
489
490        if is_oauth2_false(TYPE_LEGACY_CRYPTO_UPDATED, status.clone()) {
491            self.update_legacy_crypto(&kanidm_client, name).await?;
492            require_status_update = true;
493        }
494
495        if is_oauth2_false(TYPE_DISABLE_CONSENT_PROMPT_UPDATED, status.clone()) {
496            self.update_consent_prompt(&kanidm_client, name).await?;
497            require_status_update = true;
498        }
499
500        if is_oauth2_false(TYPE_IMAGE_UPDATED, status.clone()) {
501            self.update_image(&kanidm_client, name, &status, ctx.clone())
502                .await?;
503            require_status_update = true;
504        }
505
506        if require_status_update {
507            trace!(msg = "status update required, requeueing in 500ms");
508            Ok(Action::requeue(Duration::from_millis(500)))
509        } else {
510            Ok(Action::requeue(idm_reconcile_interval()))
511        }
512    }
513
514    async fn create(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
515        debug!(msg = "create");
516        if self.spec.public {
517            debug!(msg = "create public client");
518            kanidm_client
519                .idm_oauth2_rs_public_create(name, &self.spec.displayname, &self.spec.origin)
520                .await
521                .map_err(|e| {
522                    Error::kanidm_client_error(
523                        "create",
524                        name,
525                        self.kanidm_namespace(),
526                        self.kanidm_name(),
527                        e,
528                    )
529                })?;
530        } else {
531            kanidm_client
532                .idm_oauth2_rs_basic_create(name, &self.spec.displayname, &self.spec.origin)
533                .await
534                .map_err(|e| {
535                    Error::kanidm_client_error(
536                        "create",
537                        name,
538                        self.kanidm_namespace(),
539                        self.kanidm_name(),
540                        e,
541                    )
542                })?;
543        }
544        Ok(())
545    }
546
547    async fn update(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
548        debug!(msg = "update");
549        kanidm_client
550            .idm_oauth2_rs_update(
551                name,
552                None,
553                Some(&self.spec.displayname),
554                Some(&self.spec.origin),
555                false,
556            )
557            .await
558            .map_err(|e| {
559                Error::kanidm_client_error(
560                    "update",
561                    name,
562                    self.kanidm_namespace(),
563                    self.kanidm_name(),
564                    e,
565                )
566            })?;
567        Ok(())
568    }
569
570    async fn rotate_secret(
571        &self,
572        kanidm_client: &KanidmClient,
573        name: &str,
574        ctx: Arc<Context>,
575    ) -> Result<()> {
576        info!(msg = "rotating OAuth2 client secret");
577        // Reset the secret in Kanidm using idm_oauth2_rs_update with reset_secret=true
578        kanidm_client
579            .idm_oauth2_rs_update(name, None, None, None, true)
580            .await
581            .map_err(|e| {
582                Error::kanidm_client_error_attr(
583                    "rotate",
584                    "secret",
585                    name,
586                    self.kanidm_namespace(),
587                    self.kanidm_name(),
588                    e,
589                )
590            })?;
591
592        // Regenerate and patch the Kubernetes secret with the new client secret
593        let secret = self
594            .generate_secret(
595                kanidm_client,
596                self.spec.secret_rotation.as_ref(),
597                self.spec.secret_key_aliases.as_ref(),
598            )
599            .await?;
600        self.apply_secret(&ctx, secret).await?;
601        Ok(())
602    }
603
604    async fn update_redirect_url(
605        &self,
606        kanidm_client: &KanidmClient,
607        name: &str,
608        status: &KanidmOAuth2ClientStatus,
609    ) -> Result<()> {
610        debug!(msg = format!("update {ATTR_OAUTH2_RS_ORIGIN} attribute"));
611
612        let current_urls: BTreeSet<_> = status
613            .origin
614            .as_ref()
615            .map(|o| o.iter().filter_map(|u| url::Url::parse(u).ok()).collect())
616            .unwrap_or_default();
617
618        let redirect_url = self
619            .spec
620            .redirect_url
621            .iter()
622            .map(|u| {
623                url::Url::parse(u).map_err(|e| {
624                    Error::UrlParseError(
625                        format!(
626                            "failed to parse redirect URL {u} for {name} from {namespace}/{kanidm}",
627                            namespace = self.kanidm_namespace(),
628                            kanidm = self.kanidm_name(),
629                        ),
630                        e,
631                    )
632                })
633            })
634            .collect::<Result<BTreeSet<_>>>()?;
635
636        let delete_futures = current_urls
637            .difference(&redirect_url)
638            .map(|url| kanidm_client.idm_oauth2_client_remove_origin(name, url))
639            .collect::<TryJoinAll<_>>();
640
641        let add_futures = redirect_url
642            .difference(&current_urls)
643            .map(|url| kanidm_client.idm_oauth2_client_add_origin(name, url))
644            .collect::<TryJoinAll<_>>();
645
646        futures::try_join!(delete_futures, add_futures).map_err(|e| {
647            Error::kanidm_client_error_attr(
648                "modify",
649                ATTR_OAUTH2_RS_ORIGIN,
650                name,
651                self.kanidm_namespace(),
652                self.kanidm_name(),
653                e,
654            )
655        })?;
656
657        Ok(())
658    }
659
660    async fn update_scope_map(
661        &self,
662        kanidm_client: &KanidmClient,
663        name: &str,
664        status: &KanidmOAuth2ClientStatus,
665    ) -> Result<()> {
666        debug!(msg = format!("update {ATTR_OAUTH2_RS_SCOPE_MAP} attribute"));
667
668        let current_scope_map: BTreeSet<_> = status
669            .scope_map
670            .as_ref()
671            .map(|v| v.iter().filter_map(|v| KanidmScopeMap::from(v)).collect())
672            .unwrap_or_default();
673
674        let scope_map: BTreeSet<KanidmScopeMap> = self
675            .spec
676            .scope_map
677            .clone()
678            .unwrap_or_default()
679            .clone()
680            .into_iter()
681            .collect();
682
683        let delete_futures = current_scope_map
684            .difference(&scope_map)
685            .map(|s| kanidm_client.idm_oauth2_rs_delete_scope_map(name, &s.group))
686            .collect::<TryJoinAll<_>>();
687
688        let add_futures = scope_map
689            .difference(&current_scope_map)
690            .map(|s| {
691                kanidm_client.idm_oauth2_rs_update_scope_map(
692                    name,
693                    &s.group,
694                    s.scopes.iter().map(|s| s.as_str()).collect(),
695                )
696            })
697            .collect::<TryJoinAll<_>>();
698
699        try_join!(delete_futures, add_futures).map_err(|e| {
700            Error::kanidm_client_error_attr(
701                "modify",
702                ATTR_OAUTH2_RS_SCOPE_MAP,
703                name,
704                self.kanidm_namespace(),
705                self.kanidm_name(),
706                e,
707            )
708        })?;
709        Ok(())
710    }
711
712    async fn update_sup_scope_map(
713        &self,
714        kanidm_client: &KanidmClient,
715        name: &str,
716        status: &KanidmOAuth2ClientStatus,
717    ) -> Result<()> {
718        debug!(msg = format!("update {ATTR_OAUTH2_RS_SUP_SCOPE_MAP} attribute"));
719
720        let current_sup_scope_map: BTreeSet<_> = status
721            .sup_scope_map
722            .as_ref()
723            .map(|v| v.iter().filter_map(|v| KanidmScopeMap::from(v)).collect())
724            .unwrap_or_default();
725
726        let sup_scope_map: BTreeSet<KanidmScopeMap> = self
727            .spec
728            .sup_scope_map
729            .clone()
730            .unwrap_or_default()
731            .clone()
732            .into_iter()
733            .collect();
734
735        let delete_futures = current_sup_scope_map
736            .difference(&sup_scope_map)
737            .map(|s| kanidm_client.idm_oauth2_rs_delete_sup_scope_map(name, &s.group))
738            .collect::<TryJoinAll<_>>();
739
740        let add_futures = sup_scope_map
741            .difference(&current_sup_scope_map)
742            .map(|s| {
743                kanidm_client.idm_oauth2_rs_update_sup_scope_map(
744                    name,
745                    &s.group,
746                    s.scopes.iter().map(|s| s.as_str()).collect(),
747                )
748            })
749            .collect::<TryJoinAll<_>>();
750
751        try_join!(delete_futures, add_futures).map_err(|e| {
752            Error::kanidm_client_error_attr(
753                "modify",
754                ATTR_OAUTH2_RS_SUP_SCOPE_MAP,
755                name,
756                self.kanidm_namespace(),
757                self.kanidm_name(),
758                e,
759            )
760        })?;
761        Ok(())
762    }
763
764    async fn update_claims_map(
765        &self,
766        kanidm_client: &KanidmClient,
767        name: &str,
768        status: &KanidmOAuth2ClientStatus,
769    ) -> Result<()> {
770        debug!(msg = format!("update {ATTR_OAUTH2_RS_CLAIM_MAP} attribute"));
771
772        let current_claims_map: BTreeSet<_> = status
773            .claims_map
774            .as_ref()
775            .map(|v| {
776                KanidmClaimMap::group(
777                    &v.iter()
778                        .filter_map(|c| KanidmClaimMap::from(c))
779                        .collect::<Vec<_>>(),
780                )
781            })
782            .unwrap_or_default();
783
784        let claims_map: BTreeSet<KanidmClaimMap> = self
785            .spec
786            .claim_map
787            .clone()
788            .unwrap_or_default()
789            .clone()
790            .into_iter()
791            .collect();
792
793        let delete_futures = current_claims_map
794            .difference(&claims_map)
795            .flat_map(|c| {
796                c.values_map
797                    .iter()
798                    .map(|v| kanidm_client.idm_oauth2_rs_delete_claim_map(name, &c.name, &v.group))
799            })
800            .collect::<TryJoinAll<_>>();
801
802        let claims_to_add = claims_map.difference(&current_claims_map);
803        let add_futures = claims_to_add
804            .clone()
805            .flat_map(|c| {
806                c.values_map.iter().map(|v| {
807                    kanidm_client.idm_oauth2_rs_update_claim_map(name, &c.name, &v.group, &v.values)
808                })
809            })
810            .collect::<TryJoinAll<_>>();
811
812        let join_strategy_futures = claims_to_add
813            .map(|c| {
814                kanidm_client.idm_oauth2_rs_update_claim_map_join(
815                    name,
816                    &c.name,
817                    c.join_strategy.to_oauth2_claim_map_join(),
818                )
819            })
820            .collect::<TryJoinAll<_>>();
821
822        try_join!(delete_futures, add_futures, join_strategy_futures).map_err(|e| {
823            Error::kanidm_client_error_attr(
824                "modify",
825                ATTR_OAUTH2_RS_CLAIM_MAP,
826                name,
827                self.kanidm_namespace(),
828                self.kanidm_name(),
829                e,
830            )
831        })?;
832        Ok(())
833    }
834
835    async fn update_strict_redirect_url(
836        &self,
837        kanidm_client: &KanidmClient,
838        name: &str,
839    ) -> Result<()> {
840        debug!(msg = format!("update {ATTR_OAUTH2_STRICT_REDIRECT_URI} attribute"));
841        if let Some(strict_redirect_url_enabled) = self.spec.strict_redirect_url {
842            if strict_redirect_url_enabled {
843                kanidm_client
844                    .idm_oauth2_rs_enable_strict_redirect_uri(name)
845                    .await
846                    .map_err(|e| {
847                        Error::kanidm_client_error_attr(
848                            "update",
849                            ATTR_OAUTH2_STRICT_REDIRECT_URI,
850                            name,
851                            self.kanidm_namespace(),
852                            self.kanidm_name(),
853                            e,
854                        )
855                    })?;
856            } else {
857                kanidm_client
858                    .idm_oauth2_rs_disable_strict_redirect_uri(name)
859                    .await
860                    .map_err(|e| {
861                        Error::kanidm_client_error_attr(
862                            "update",
863                            ATTR_OAUTH2_STRICT_REDIRECT_URI,
864                            name,
865                            self.kanidm_namespace(),
866                            self.kanidm_name(),
867                            e,
868                        )
869                    })?;
870            }
871        };
872        Ok(())
873    }
874
875    async fn update_disable_pkce(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
876        debug!(msg = format!("update {ATTR_OAUTH2_ALLOW_INSECURE_CLIENT_DISABLE_PKCE} attribute"));
877        if let Some(disable_pkce) = self.spec.allow_insecure_client_disable_pkce {
878            if disable_pkce {
879                kanidm_client
880                    .idm_oauth2_rs_disable_pkce(name)
881                    .await
882                    .map_err(|e| {
883                        Error::kanidm_client_error_attr(
884                            "update",
885                            ATTR_OAUTH2_ALLOW_INSECURE_CLIENT_DISABLE_PKCE,
886                            name,
887                            self.kanidm_namespace(),
888                            self.kanidm_name(),
889                            e,
890                        )
891                    })?;
892            } else {
893                kanidm_client
894                    .idm_oauth2_rs_enable_pkce(name)
895                    .await
896                    .map_err(|e| {
897                        Error::kanidm_client_error_attr(
898                            "update",
899                            ATTR_OAUTH2_ALLOW_INSECURE_CLIENT_DISABLE_PKCE,
900                            name,
901                            self.kanidm_namespace(),
902                            self.kanidm_name(),
903                            e,
904                        )
905                    })?;
906            }
907        };
908        Ok(())
909    }
910
911    async fn update_prefer_short_name(
912        &self,
913        kanidm_client: &KanidmClient,
914        name: &str,
915    ) -> Result<()> {
916        debug!(msg = format!("update {ATTR_OAUTH2_PREFER_SHORT_USERNAME} attribute"));
917        if let Some(prefer_short_username) = self.spec.prefer_short_username {
918            if prefer_short_username {
919                kanidm_client
920                    .idm_oauth2_rs_prefer_short_username(name)
921                    .await
922                    .map_err(|e| {
923                        Error::kanidm_client_error_attr(
924                            "update",
925                            ATTR_OAUTH2_PREFER_SHORT_USERNAME,
926                            name,
927                            self.kanidm_namespace(),
928                            self.kanidm_name(),
929                            e,
930                        )
931                    })?;
932            } else {
933                kanidm_client
934                    .idm_oauth2_rs_prefer_spn_username(name)
935                    .await
936                    .map_err(|e| {
937                        Error::kanidm_client_error_attr(
938                            "update",
939                            ATTR_OAUTH2_PREFER_SHORT_USERNAME,
940                            name,
941                            self.kanidm_namespace(),
942                            self.kanidm_name(),
943                            e,
944                        )
945                    })?;
946            }
947        };
948        Ok(())
949    }
950
951    async fn update_allow_localhost_redirect(
952        &self,
953        kanidm_client: &KanidmClient,
954        name: &str,
955    ) -> Result<()> {
956        debug!(msg = format!("update {ATTR_OAUTH2_ALLOW_LOCALHOST_REDIRECT} attribute"));
957        if let Some(allow_localhost_redirect) = self.spec.allow_localhost_redirect {
958            if allow_localhost_redirect {
959                kanidm_client
960                    .idm_oauth2_rs_enable_public_localhost_redirect(name)
961                    .await
962                    .map_err(|e| {
963                        Error::kanidm_client_error_attr(
964                            "update",
965                            ATTR_OAUTH2_ALLOW_LOCALHOST_REDIRECT,
966                            name,
967                            self.kanidm_namespace(),
968                            self.kanidm_name(),
969                            e,
970                        )
971                    })?;
972            } else {
973                kanidm_client
974                    .idm_oauth2_rs_disable_public_localhost_redirect(name)
975                    .await
976                    .map_err(|e| {
977                        Error::kanidm_client_error_attr(
978                            "update",
979                            ATTR_OAUTH2_ALLOW_LOCALHOST_REDIRECT,
980                            name,
981                            self.kanidm_namespace(),
982                            self.kanidm_name(),
983                            e,
984                        )
985                    })?;
986            }
987        };
988        Ok(())
989    }
990
991    async fn update_legacy_crypto(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
992        debug!(msg = format!("update {ATTR_OAUTH2_JWT_LEGACY_CRYPTO_ENABLE} attribute"));
993        if let Some(legacy_crypto) = self.spec.jwt_legacy_crypto_enable {
994            if legacy_crypto {
995                kanidm_client
996                    .idm_oauth2_rs_enable_legacy_crypto(name)
997                    .await
998                    .map_err(|e| {
999                        Error::kanidm_client_error_attr(
1000                            "update",
1001                            ATTR_OAUTH2_JWT_LEGACY_CRYPTO_ENABLE,
1002                            name,
1003                            self.kanidm_namespace(),
1004                            self.kanidm_name(),
1005                            e,
1006                        )
1007                    })?;
1008            } else {
1009                kanidm_client
1010                    .idm_oauth2_rs_disable_legacy_crypto(name)
1011                    .await
1012                    .map_err(|e| {
1013                        Error::kanidm_client_error_attr(
1014                            "update",
1015                            ATTR_OAUTH2_JWT_LEGACY_CRYPTO_ENABLE,
1016                            name,
1017                            self.kanidm_namespace(),
1018                            self.kanidm_name(),
1019                            e,
1020                        )
1021                    })?;
1022            }
1023        };
1024        Ok(())
1025    }
1026
1027    async fn update_consent_prompt(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
1028        debug!(msg = format!("update {ATTR_OAUTH2_CONSENT_PROMPT_ENABLE} attribute"));
1029        if let Some(disable_consent_prompt) = self.spec.disable_consent_prompt {
1030            if disable_consent_prompt {
1031                kanidm_client
1032                    .idm_oauth2_rs_disable_consent_prompt(name)
1033                    .await
1034                    .map_err(|e| {
1035                        Error::kanidm_client_error_attr(
1036                            "update",
1037                            ATTR_OAUTH2_CONSENT_PROMPT_ENABLE,
1038                            name,
1039                            self.kanidm_namespace(),
1040                            self.kanidm_name(),
1041                            e,
1042                        )
1043                    })?;
1044            } else {
1045                kanidm_client
1046                    .idm_oauth2_rs_enable_consent_prompt(name)
1047                    .await
1048                    .map_err(|e| {
1049                        Error::kanidm_client_error_attr(
1050                            "update",
1051                            ATTR_OAUTH2_CONSENT_PROMPT_ENABLE,
1052                            name,
1053                            self.kanidm_namespace(),
1054                            self.kanidm_name(),
1055                            e,
1056                        )
1057                    })?;
1058            }
1059        };
1060        Ok(())
1061    }
1062
1063    async fn update_image(
1064        &self,
1065        kanidm_client: &KanidmClient,
1066        name: &str,
1067        status: &KanidmOAuth2ClientStatus,
1068        ctx: Arc<Context>,
1069    ) -> Result<()> {
1070        match &self.spec.image {
1071            None => {
1072                debug!(msg = "deleting image from OAuth2 client");
1073                kanidm_client
1074                    .idm_oauth2_rs_delete_image(name)
1075                    .await
1076                    .map_err(|e| {
1077                        Error::kanidm_client_error_attr(
1078                            "delete",
1079                            "image",
1080                            name,
1081                            self.kanidm_namespace(),
1082                            self.kanidm_name(),
1083                            e,
1084                        )
1085                    })?;
1086            }
1087            Some(image_spec) => {
1088                let url = &image_spec.url;
1089                debug!(msg = format!("updating image for OAuth2 client from {url}"));
1090
1091                let namespace = self.kanidm_namespace();
1092                let kanidm = self.kanidm_name();
1093
1094                let update_result =
1095                    update_image_if_needed(url, status.image.as_ref(), |image_value| async {
1096                        kanidm_client
1097                            .idm_oauth2_rs_update_image(name, image_value)
1098                            .await
1099                            .map_err(|e| {
1100                                Error::kanidm_client_error_attr(
1101                                    "update",
1102                                    "image",
1103                                    name,
1104                                    namespace.clone(),
1105                                    kanidm.clone(),
1106                                    e,
1107                                )
1108                            })
1109                    })
1110                    .await;
1111
1112                match update_result {
1113                    Ok(Some(updated)) => {
1114                        let new_image_status = OAuth2ClientImageStatus {
1115                            url: updated.image_status.url,
1116                            etag: updated.image_status.etag,
1117                            last_modified: updated.image_status.last_modified,
1118                            content_length: updated.image_status.content_length,
1119                            content_hash: Some(updated.image_status.content_hash),
1120                        };
1121
1122                        let namespace = self.namespace().unwrap();
1123                        let name = self.name_any();
1124                        let oauth2_api = Api::<KanidmOAuth2Client>::namespaced(
1125                            ctx.kaniop_ctx.client.clone(),
1126                            &namespace,
1127                        );
1128                        let status_patch = Patch::Apply(KanidmOAuth2Client {
1129                            status: Some(KanidmOAuth2ClientStatus {
1130                                image: Some(new_image_status),
1131                                ..status.clone()
1132                            }),
1133                            ..KanidmOAuth2Client::default()
1134                        });
1135                        oauth2_api
1136                            .patch_status(
1137                                &name,
1138                                &PatchParams::apply(OAUTH2_OPERATOR_NAME),
1139                                &status_patch,
1140                            )
1141                            .await
1142                            .map_err(|e| {
1143                                Error::kube_status_error("KanidmOAuth2Client", &namespace, &name, e)
1144                            })?;
1145                    }
1146                    Ok(None) => {}
1147                    Err(e) => {
1148                        let operation = if matches!(e, Error::HttpError(_, _)) {
1149                            ImageOperation::Fetch
1150                        } else {
1151                            ImageOperation::Download
1152                        };
1153                        return Err(publish_image_error_event(
1154                            e,
1155                            operation,
1156                            name,
1157                            &namespace,
1158                            &kanidm,
1159                            &ctx.kaniop_ctx.recorder,
1160                            self,
1161                        )
1162                        .await);
1163                    }
1164                }
1165            }
1166        };
1167        Ok(())
1168    }
1169
1170    async fn cleanup(
1171        &self,
1172        kanidm_client: Arc<KanidmClient>,
1173        status: KanidmOAuth2ClientStatus,
1174    ) -> Result<Action> {
1175        let name = &self.kanidm_entity_name();
1176        if is_oauth2(TYPE_EXISTS, status.clone()) {
1177            debug!(msg = "delete");
1178            kanidm_client
1179                .idm_oauth2_rs_delete(name)
1180                .await
1181                .map_err(|e| {
1182                    Error::kanidm_client_error(
1183                        "delete",
1184                        name,
1185                        self.kanidm_namespace(),
1186                        self.kanidm_name(),
1187                        e,
1188                    )
1189                })?;
1190        }
1191        Ok(Action::requeue(idm_reconcile_interval()))
1192    }
1193}
1194
1195pub fn is_oauth2(type_: &str, status: KanidmOAuth2ClientStatus) -> bool {
1196    status
1197        .conditions
1198        .unwrap_or_default()
1199        .iter()
1200        .any(|c| c.type_ == type_ && c.status == CONDITION_TRUE)
1201}
1202
1203pub fn is_oauth2_false(type_: &str, status: KanidmOAuth2ClientStatus) -> bool {
1204    status
1205        .conditions
1206        .unwrap_or_default()
1207        .iter()
1208        .any(|c| c.type_ == type_ && c.status == CONDITION_FALSE)
1209}