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