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