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