1mod secret;
2mod status;
3
4use self::secret::SecretExt;
5use self::status::{
6 CONDITION_FALSE, CONDITION_TRUE, StatusExt, TYPE_ALLOW_LOCALHOST_REDIRECT_UPDATED,
7 TYPE_CLAIMS_MAP_UPDATED, TYPE_DISABLE_CONSENT_PROMPT_UPDATED, TYPE_DISABLE_PKCE_UPDATED,
8 TYPE_EXISTS, TYPE_IMAGE_UPDATED, TYPE_LEGACY_CRYPTO_UPDATED, TYPE_PREFER_SHORT_NAME_UPDATED,
9 TYPE_REDIRECT_URL_UPDATED, TYPE_SCOPE_MAP_UPDATED, TYPE_SECRET_INITIALIZED,
10 TYPE_SECRET_ROTATED, TYPE_SECRET_TEMPLATE_SYNCED, TYPE_STRICT_REDIRECT_URL_UPDATED,
11 TYPE_SUP_SCOPE_MAP_UPDATED, TYPE_UPDATED,
12};
13use kaniop_k8s_util::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_CONSENT_PROMPT_ENABLE, ATTR_OAUTH2_JWT_LEGACY_CRYPTO_ENABLE,
43 ATTR_OAUTH2_PREFER_SHORT_USERNAME, ATTR_OAUTH2_RS_CLAIM_MAP, ATTR_OAUTH2_RS_ORIGIN,
44 ATTR_OAUTH2_RS_SCOPE_MAP, 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 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 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(), ¶ms, &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 self.rotate_secret(&kanidm_client, name, ctx.clone())
285 .await?;
286 require_status_update = true;
287 }
288
289 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 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_DISABLE_CONSENT_PROMPT_UPDATED, status.clone()) {
415 self.update_consent_prompt(&kanidm_client, name).await?;
416 require_status_update = true;
417 }
418
419 if is_oauth2_false(TYPE_IMAGE_UPDATED, status.clone()) {
420 self.update_image(&kanidm_client, name, &status, ctx.clone())
421 .await?;
422 require_status_update = true;
423 }
424
425 if require_status_update {
426 trace!(msg = "status update required, requeueing in 500ms");
427 Ok(Action::requeue(Duration::from_millis(500)))
428 } else {
429 Ok(Action::requeue(idm_reconcile_interval()))
430 }
431 }
432
433 async fn create(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
434 debug!(msg = "create");
435 if self.spec.public {
436 debug!(msg = "create public client");
437 kanidm_client
438 .idm_oauth2_rs_public_create(name, &self.spec.displayname, &self.spec.origin)
439 .await
440 .map_err(|e| {
441 Error::KanidmClientError(
442 format!(
443 "failed to create {name} from {namespace}/{kanidm}",
444 namespace = self.kanidm_namespace(),
445 kanidm = self.kanidm_name(),
446 ),
447 Box::new(e),
448 )
449 })?;
450 } else {
451 kanidm_client
452 .idm_oauth2_rs_basic_create(name, &self.spec.displayname, &self.spec.origin)
453 .await
454 .map_err(|e| {
455 Error::KanidmClientError(
456 format!(
457 "failed to create {name} from {namespace}/{kanidm}",
458 namespace = self.kanidm_namespace(),
459 kanidm = self.kanidm_name(),
460 ),
461 Box::new(e),
462 )
463 })?;
464 }
465 Ok(())
466 }
467
468 async fn update(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
469 debug!(msg = "update");
470 kanidm_client
471 .idm_oauth2_rs_update(
472 name,
473 None,
474 Some(&self.spec.displayname),
475 Some(&self.spec.origin),
476 false,
477 )
478 .await
479 .map_err(|e| {
480 Error::KanidmClientError(
481 format!(
482 "failed to create {name} from {namespace}/{kanidm}",
483 namespace = self.kanidm_namespace(),
484 kanidm = self.kanidm_name(),
485 ),
486 Box::new(e),
487 )
488 })?;
489 Ok(())
490 }
491
492 async fn rotate_secret(
493 &self,
494 kanidm_client: &KanidmClient,
495 name: &str,
496 ctx: Arc<Context>,
497 ) -> Result<()> {
498 info!(msg = "rotating OAuth2 client secret");
499 kanidm_client
501 .idm_oauth2_rs_update(name, None, None, None, true)
502 .await
503 .map_err(|e| {
504 Error::KanidmClientError(
505 format!(
506 "failed to rotate secret for {name} from {namespace}/{kanidm}",
507 namespace = self.kanidm_namespace(),
508 kanidm = self.kanidm_name(),
509 ),
510 Box::new(e),
511 )
512 })?;
513
514 let secret = self
516 .generate_secret(kanidm_client, self.spec.secret_rotation.as_ref())
517 .await?;
518 self.patch(&ctx, secret).await?;
519 Ok(())
520 }
521
522 async fn update_redirect_url(
523 &self,
524 kanidm_client: &KanidmClient,
525 name: &str,
526 status: &KanidmOAuth2ClientStatus,
527 ) -> Result<()> {
528 debug!(msg = format!("update {ATTR_OAUTH2_RS_ORIGIN} attribute"));
529
530 let current_urls: BTreeSet<_> = status
531 .origin
532 .as_ref()
533 .map(|o| o.iter().filter_map(|u| url::Url::parse(u).ok()).collect())
534 .unwrap_or_default();
535
536 let redirect_url = self
537 .spec
538 .redirect_url
539 .iter()
540 .map(|u| {
541 url::Url::parse(u).map_err(|e| {
542 Error::UrlParseError(
543 format!(
544 "failed to parse redirect URL {u} for {name} from {namespace}/{kanidm}",
545 namespace = self.kanidm_namespace(),
546 kanidm = self.kanidm_name(),
547 ),
548 e,
549 )
550 })
551 })
552 .collect::<Result<BTreeSet<_>>>()?;
553
554 let delete_futures = current_urls
555 .difference(&redirect_url)
556 .map(|url| kanidm_client.idm_oauth2_client_remove_origin(name, url))
557 .collect::<TryJoinAll<_>>();
558
559 let add_futures = redirect_url
560 .difference(¤t_urls)
561 .map(|url| kanidm_client.idm_oauth2_client_add_origin(name, url))
562 .collect::<TryJoinAll<_>>();
563
564 futures::try_join!(delete_futures, add_futures).map_err(|e| {
565 Error::KanidmClientError(
566 format!(
567 "failed to modify {ATTR_OAUTH2_RS_ORIGIN} for {name} from {namespace}/{kanidm}",
568 namespace = self.kanidm_namespace(),
569 kanidm = self.kanidm_name(),
570 ),
571 Box::new(e),
572 )
573 })?;
574
575 Ok(())
576 }
577
578 async fn update_scope_map(
579 &self,
580 kanidm_client: &KanidmClient,
581 name: &str,
582 status: &KanidmOAuth2ClientStatus,
583 ) -> Result<()> {
584 debug!(msg = format!("update {ATTR_OAUTH2_RS_SCOPE_MAP} attribute"));
585
586 let current_scope_map: BTreeSet<_> = status
587 .scope_map
588 .as_ref()
589 .map(|v| v.iter().filter_map(|v| KanidmScopeMap::from(v)).collect())
590 .unwrap_or_default();
591
592 let scope_map: BTreeSet<KanidmScopeMap> = self
593 .spec
594 .scope_map
595 .clone()
596 .unwrap_or_default()
597 .clone()
598 .into_iter()
599 .collect();
600
601 let delete_futures = current_scope_map
602 .difference(&scope_map)
603 .map(|s| kanidm_client.idm_oauth2_rs_delete_scope_map(name, &s.group))
604 .collect::<TryJoinAll<_>>();
605
606 let add_futures = scope_map
607 .difference(¤t_scope_map)
608 .map(|s| {
609 kanidm_client.idm_oauth2_rs_update_scope_map(
610 name,
611 &s.group,
612 s.scopes.iter().map(|s| s.as_str()).collect(),
613 )
614 })
615 .collect::<TryJoinAll<_>>();
616
617 try_join!(delete_futures, add_futures).map_err(|e| {
618 Error::KanidmClientError(
619 format!(
620 "failed to modify {ATTR_OAUTH2_RS_SCOPE_MAP} for {name} from {namespace}/{kanidm}",
621 namespace = self.kanidm_namespace(),
622 kanidm = self.kanidm_name(),
623 ),
624 Box::new(e),
625 )
626 })?;
627 Ok(())
628 }
629
630 async fn update_sup_scope_map(
631 &self,
632 kanidm_client: &KanidmClient,
633 name: &str,
634 status: &KanidmOAuth2ClientStatus,
635 ) -> Result<()> {
636 debug!(msg = format!("update {ATTR_OAUTH2_RS_SUP_SCOPE_MAP} attribute"));
637
638 let current_sup_scope_map: BTreeSet<_> = status
639 .sup_scope_map
640 .as_ref()
641 .map(|v| v.iter().filter_map(|v| KanidmScopeMap::from(v)).collect())
642 .unwrap_or_default();
643
644 let sup_scope_map: BTreeSet<KanidmScopeMap> = self
645 .spec
646 .sup_scope_map
647 .clone()
648 .unwrap_or_default()
649 .clone()
650 .into_iter()
651 .collect();
652
653 let delete_futures = current_sup_scope_map
654 .difference(&sup_scope_map)
655 .map(|s| kanidm_client.idm_oauth2_rs_delete_sup_scope_map(name, &s.group))
656 .collect::<TryJoinAll<_>>();
657
658 let add_futures = sup_scope_map
659 .difference(¤t_sup_scope_map)
660 .map(|s| {
661 kanidm_client.idm_oauth2_rs_update_sup_scope_map(
662 name,
663 &s.group,
664 s.scopes.iter().map(|s| s.as_str()).collect(),
665 )
666 })
667 .collect::<TryJoinAll<_>>();
668
669 try_join!(delete_futures, add_futures).map_err(|e| {
670 Error::KanidmClientError(
671 format!(
672 "failed to modify {ATTR_OAUTH2_RS_SUP_SCOPE_MAP} for {name} from {namespace}/{kanidm}",
673 namespace = self.kanidm_namespace(),
674 kanidm = self.kanidm_name(),
675 ),
676 Box::new(e),
677 )
678 })?;
679 Ok(())
680 }
681
682 async fn update_claims_map(
683 &self,
684 kanidm_client: &KanidmClient,
685 name: &str,
686 status: &KanidmOAuth2ClientStatus,
687 ) -> Result<()> {
688 debug!(msg = format!("update {ATTR_OAUTH2_RS_CLAIM_MAP} attribute"));
689
690 let current_claims_map: BTreeSet<_> = status
691 .claims_map
692 .as_ref()
693 .map(|v| {
694 KanidmClaimMap::group(
695 &v.iter()
696 .filter_map(|c| KanidmClaimMap::from(c))
697 .collect::<Vec<_>>(),
698 )
699 })
700 .unwrap_or_default();
701
702 let claims_map: BTreeSet<KanidmClaimMap> = self
703 .spec
704 .claim_map
705 .clone()
706 .unwrap_or_default()
707 .clone()
708 .into_iter()
709 .collect();
710
711 let delete_futures = current_claims_map
712 .difference(&claims_map)
713 .flat_map(|c| {
714 c.values_map
715 .iter()
716 .map(|v| kanidm_client.idm_oauth2_rs_delete_claim_map(name, &c.name, &v.group))
717 })
718 .collect::<TryJoinAll<_>>();
719
720 let claims_to_add = claims_map.difference(¤t_claims_map);
721 let add_futures = claims_to_add
722 .clone()
723 .flat_map(|c| {
724 c.values_map.iter().map(|v| {
725 kanidm_client.idm_oauth2_rs_update_claim_map(name, &c.name, &v.group, &v.values)
726 })
727 })
728 .collect::<TryJoinAll<_>>();
729
730 let join_strategy_futures = claims_to_add
731 .map(|c| {
732 kanidm_client.idm_oauth2_rs_update_claim_map_join(
733 name,
734 &c.name,
735 c.join_strategy.to_oauth2_claim_map_join(),
736 )
737 })
738 .collect::<TryJoinAll<_>>();
739
740 try_join!(delete_futures, add_futures, join_strategy_futures).map_err(|e| {
741 Error::KanidmClientError(
742 format!(
743 "failed to modify {ATTR_OAUTH2_RS_CLAIM_MAP} for {name} from {namespace}/{kanidm}",
744 namespace = self.kanidm_namespace(),
745 kanidm = self.kanidm_name(),
746 ),
747 Box::new(e),
748 )
749 })?;
750 Ok(())
751 }
752
753 async fn update_strict_redirect_url(
754 &self,
755 kanidm_client: &KanidmClient,
756 name: &str,
757 ) -> Result<()> {
758 debug!(msg = format!("update {ATTR_OAUTH2_STRICT_REDIRECT_URI} attribute"));
759 if let Some(strict_redirect_url_enabled) = self.spec.strict_redirect_url {
760 if strict_redirect_url_enabled {
761 kanidm_client
762 .idm_oauth2_rs_enable_strict_redirect_uri(
763 name,
764 )
765 .await
766 .map_err(|e| {
767 Error::KanidmClientError(
768 format!(
769 "failed to update {ATTR_OAUTH2_STRICT_REDIRECT_URI} for {name} from {namespace}/{kanidm}",
770 namespace = self.kanidm_namespace(),
771 kanidm = self.kanidm_name(),
772 ),
773 Box::new(e),
774 )
775 })?;
776 } else {
777 kanidm_client
778 .idm_oauth2_rs_disable_strict_redirect_uri(
779 name,
780 )
781 .await
782 .map_err(|e| {
783 Error::KanidmClientError(
784 format!(
785 "failed to update {ATTR_OAUTH2_STRICT_REDIRECT_URI} for {name} from {namespace}/{kanidm}",
786 namespace = self.kanidm_namespace(),
787 kanidm = self.kanidm_name(),
788 ),
789 Box::new(e),
790 )
791 })?;
792 }
793 };
794 Ok(())
795 }
796
797 async fn update_disable_pkce(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
798 debug!(msg = format!("update {ATTR_OAUTH2_ALLOW_INSECURE_CLIENT_DISABLE_PKCE} attribute"));
799 if let Some(disable_pkce) = self.spec.allow_insecure_client_disable_pkce {
800 if disable_pkce {
801 kanidm_client
802 .idm_oauth2_rs_disable_pkce(
803 name,
804 )
805 .await
806 .map_err(|e| {
807 Error::KanidmClientError(
808 format!(
809 "failed to update {ATTR_OAUTH2_ALLOW_INSECURE_CLIENT_DISABLE_PKCE} for {name} from {namespace}/{kanidm}",
810 namespace = self.kanidm_namespace(),
811 kanidm = self.kanidm_name(),
812 ),
813 Box::new(e),
814 )
815 })?;
816 } else {
817 kanidm_client
818 .idm_oauth2_rs_enable_pkce(
819 name,
820 )
821 .await
822 .map_err(|e| {
823 Error::KanidmClientError(
824 format!(
825 "failed to update {ATTR_OAUTH2_ALLOW_INSECURE_CLIENT_DISABLE_PKCE} for {name} from {namespace}/{kanidm}",
826 namespace = self.kanidm_namespace(),
827 kanidm = self.kanidm_name(),
828 ),
829 Box::new(e),
830 )
831 })?;
832 }
833 };
834 Ok(())
835 }
836
837 async fn update_prefer_short_name(
838 &self,
839 kanidm_client: &KanidmClient,
840 name: &str,
841 ) -> Result<()> {
842 debug!(msg = format!("update {ATTR_OAUTH2_PREFER_SHORT_USERNAME} attribute"));
843 if let Some(prefer_short_username) = self.spec.prefer_short_username {
844 if prefer_short_username {
845 kanidm_client
846 .idm_oauth2_rs_prefer_short_username(
847 name,
848 )
849 .await
850 .map_err(|e| {
851 Error::KanidmClientError(
852 format!(
853 "failed to update {ATTR_OAUTH2_PREFER_SHORT_USERNAME} for {name} from {namespace}/{kanidm}",
854 namespace = self.kanidm_namespace(),
855 kanidm = self.kanidm_name(),
856 ),
857 Box::new(e),
858 )
859 })?;
860 } else {
861 kanidm_client
862 .idm_oauth2_rs_prefer_spn_username(
863 name,
864 )
865 .await
866 .map_err(|e| {
867 Error::KanidmClientError(
868 format!(
869 "failed to update {ATTR_OAUTH2_PREFER_SHORT_USERNAME} for {name} from {namespace}/{kanidm}",
870 namespace = self.kanidm_namespace(),
871 kanidm = self.kanidm_name(),
872 ),
873 Box::new(e),
874 )
875 })?;
876 }
877 };
878 Ok(())
879 }
880
881 async fn update_allow_localhost_redirect(
882 &self,
883 kanidm_client: &KanidmClient,
884 name: &str,
885 ) -> Result<()> {
886 debug!(msg = format!("update {ATTR_OAUTH2_ALLOW_LOCALHOST_REDIRECT} attribute"));
887 if let Some(allow_localhost_redirect) = self.spec.allow_localhost_redirect {
888 if allow_localhost_redirect {
889 kanidm_client
890 .idm_oauth2_rs_enable_public_localhost_redirect(
891 name,
892 )
893 .await
894 .map_err(|e| {
895 Error::KanidmClientError(
896 format!(
897 "failed to update {ATTR_OAUTH2_ALLOW_LOCALHOST_REDIRECT} for {name} from {namespace}/{kanidm}",
898 namespace = self.kanidm_namespace(),
899 kanidm = self.kanidm_name(),
900 ),
901 Box::new(e),
902 )
903 })?;
904 } else {
905 kanidm_client
906 .idm_oauth2_rs_disable_public_localhost_redirect(
907 name,
908 )
909 .await
910 .map_err(|e| {
911 Error::KanidmClientError(
912 format!(
913 "failed to update {ATTR_OAUTH2_ALLOW_LOCALHOST_REDIRECT} for {name} from {namespace}/{kanidm}",
914 namespace = self.kanidm_namespace(),
915 kanidm = self.kanidm_name(),
916 ),
917 Box::new(e),
918 )
919 })?;
920 }
921 };
922 Ok(())
923 }
924
925 async fn update_legacy_crypto(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
926 debug!(msg = format!("update {ATTR_OAUTH2_JWT_LEGACY_CRYPTO_ENABLE} attribute"));
927 if let Some(legacy_crypto) = self.spec.jwt_legacy_crypto_enable {
928 if legacy_crypto {
929 kanidm_client
930 .idm_oauth2_rs_enable_legacy_crypto(
931 name,
932 )
933 .await
934 .map_err(|e| {
935 Error::KanidmClientError(
936 format!(
937 "failed to update {ATTR_OAUTH2_JWT_LEGACY_CRYPTO_ENABLE} for {name} from {namespace}/{kanidm}",
938 namespace = self.kanidm_namespace(),
939 kanidm = self.kanidm_name(),
940 ),
941 Box::new(e),
942 )
943 })?;
944 } else {
945 kanidm_client
946 .idm_oauth2_rs_disable_legacy_crypto(
947 name,
948 )
949 .await
950 .map_err(|e| {
951 Error::KanidmClientError(
952 format!(
953 "failed to update {ATTR_OAUTH2_JWT_LEGACY_CRYPTO_ENABLE} for {name} from {namespace}/{kanidm}",
954 namespace = self.kanidm_namespace(),
955 kanidm = self.kanidm_name(),
956 ),
957 Box::new(e),
958 )
959 })?;
960 }
961 };
962 Ok(())
963 }
964
965 async fn update_consent_prompt(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
966 debug!(msg = format!("update {ATTR_OAUTH2_CONSENT_PROMPT_ENABLE} attribute"));
967 if let Some(disable_consent_prompt) = self.spec.disable_consent_prompt {
968 if disable_consent_prompt {
969 kanidm_client
970 .idm_oauth2_rs_disable_consent_prompt(name)
971 .await
972 .map_err(|e| {
973 Error::KanidmClientError(
974 format!(
975 "failed to update {ATTR_OAUTH2_CONSENT_PROMPT_ENABLE} for {name} from {namespace}/{kanidm}",
976 namespace = self.kanidm_namespace(),
977 kanidm = self.kanidm_name(),
978 ),
979 Box::new(e),
980 )
981 })?;
982 } else {
983 kanidm_client
984 .idm_oauth2_rs_enable_consent_prompt(name)
985 .await
986 .map_err(|e| {
987 Error::KanidmClientError(
988 format!(
989 "failed to update {ATTR_OAUTH2_CONSENT_PROMPT_ENABLE} for {name} from {namespace}/{kanidm}",
990 namespace = self.kanidm_namespace(),
991 kanidm = self.kanidm_name(),
992 ),
993 Box::new(e),
994 )
995 })?;
996 }
997 };
998 Ok(())
999 }
1000
1001 async fn update_image(
1002 &self,
1003 kanidm_client: &KanidmClient,
1004 name: &str,
1005 status: &KanidmOAuth2ClientStatus,
1006 ctx: Arc<Context>,
1007 ) -> Result<()> {
1008 match &self.spec.image {
1009 None => {
1010 debug!(msg = "deleting image from OAuth2 client");
1011 kanidm_client
1012 .idm_oauth2_rs_delete_image(name)
1013 .await
1014 .map_err(|e| {
1015 Error::KanidmClientError(
1016 format!(
1017 "failed to delete image for {name} from {namespace}/{kanidm}",
1018 namespace = self.kanidm_namespace(),
1019 kanidm = self.kanidm_name(),
1020 ),
1021 Box::new(e),
1022 )
1023 })?;
1024 }
1025 Some(image_spec) => {
1026 let url = &image_spec.url;
1027 debug!(msg = format!("updating image for OAuth2 client from {url}"));
1028
1029 let current_headers = match fetch_headers(url).await {
1030 Ok(h) => h,
1031 Err(e) => {
1032 let msg = format!(
1033 "failed to fetch image headers for {name} from {namespace}/{kanidm}: {e:?}",
1034 namespace = self.kanidm_namespace(),
1035 kanidm = self.kanidm_name(),
1036 );
1037 let _ = ctx
1038 .kaniop_ctx
1039 .recorder
1040 .publish(
1041 &Event {
1042 type_: EventType::Warning,
1043 reason: "ImageFetchError".to_string(),
1044 note: Some(msg.clone()),
1045 action: "ImageUpdate".to_string(),
1046 secondary: None,
1047 },
1048 &self.object_ref(&()),
1049 )
1050 .await
1051 .map_err(|e| {
1052 warn!(msg = "failed to publish ImageFetchError event", %e);
1053 });
1054 return Err(e);
1055 }
1056 };
1057
1058 let should_download = match &status.image {
1059 None => true,
1060 Some(cached) => cached.url != *url || headers_changed(¤t_headers, cached),
1061 };
1062
1063 if should_download {
1064 info!(msg = format!("downloading image from {url}"));
1065 let downloaded = match download_image(url).await {
1066 Ok(d) => d,
1067 Err(e) => {
1068 let msg = format!(
1069 "failed to download image for {name} from {namespace}/{kanidm}: {e:?}",
1070 namespace = self.kanidm_namespace(),
1071 kanidm = self.kanidm_name(),
1072 );
1073 let _ = ctx
1074 .kaniop_ctx
1075 .recorder
1076 .publish(
1077 &Event {
1078 type_: EventType::Warning,
1079 reason: "ImageDownloadError".to_string(),
1080 note: Some(msg.clone()),
1081 action: "ImageUpdate".to_string(),
1082 secondary: None,
1083 },
1084 &self.object_ref(&()),
1085 )
1086 .await
1087 .map_err(|e| {
1088 warn!(msg = "failed to publish ImageDownloadError event", %e);
1089 });
1090 return Err(e);
1091 }
1092 };
1093
1094 kanidm_client
1095 .idm_oauth2_rs_update_image(name, downloaded.image_value)
1096 .await
1097 .map_err(|e| {
1098 Error::KanidmClientError(
1099 format!(
1100 "failed to update image for {name} from {namespace}/{kanidm}",
1101 namespace = self.kanidm_namespace(),
1102 kanidm = self.kanidm_name(),
1103 ),
1104 Box::new(e),
1105 )
1106 })?;
1107
1108 let new_image_status = OAuth2ClientImageStatus {
1109 url: url.clone(),
1110 etag: downloaded.headers.etag,
1111 last_modified: downloaded.headers.last_modified,
1112 content_length: downloaded.headers.content_length,
1113 content_hash: Some(downloaded.content_hash),
1114 };
1115
1116 let namespace = self.namespace().unwrap();
1117 let name = self.name_any();
1118 let oauth2_api = Api::<KanidmOAuth2Client>::namespaced(
1119 ctx.kaniop_ctx.client.clone(),
1120 &namespace,
1121 );
1122 let status_patch = Patch::Apply(KanidmOAuth2Client {
1123 status: Some(KanidmOAuth2ClientStatus {
1124 image: Some(new_image_status),
1125 ..status.clone()
1126 }),
1127 ..KanidmOAuth2Client::default()
1128 });
1129 oauth2_api
1130 .patch_status(
1131 &name,
1132 &PatchParams::apply(OAUTH2_OPERATOR_NAME),
1133 &status_patch,
1134 )
1135 .await
1136 .map_err(|e| {
1137 Error::KubeError(
1138 format!(
1139 "failed to patch KanidmOAuth2Client/status {namespace}/{name}"
1140 ),
1141 Box::new(e),
1142 )
1143 })?;
1144 }
1145 }
1146 };
1147 Ok(())
1148 }
1149
1150 async fn cleanup(
1151 &self,
1152 kanidm_client: Arc<KanidmClient>,
1153 status: KanidmOAuth2ClientStatus,
1154 ) -> Result<Action> {
1155 let name = &self.kanidm_entity_name();
1156 if is_oauth2(TYPE_EXISTS, status.clone()) {
1157 debug!(msg = "delete");
1158 kanidm_client
1159 .idm_oauth2_rs_delete(name)
1160 .await
1161 .map_err(|e| {
1162 Error::KanidmClientError(
1163 format!(
1164 "failed to delete {name} from {namespace}/{kanidm}",
1165 namespace = self.kanidm_namespace(),
1166 kanidm = self.kanidm_name(),
1167 ),
1168 Box::new(e),
1169 )
1170 })?;
1171 }
1172 Ok(Action::requeue(idm_reconcile_interval()))
1173 }
1174}
1175
1176pub fn is_oauth2(type_: &str, status: KanidmOAuth2ClientStatus) -> bool {
1177 status
1178 .conditions
1179 .unwrap_or_default()
1180 .iter()
1181 .any(|c| c.type_ == type_ && c.status == CONDITION_TRUE)
1182}
1183
1184pub fn is_oauth2_false(type_: &str, status: KanidmOAuth2ClientStatus) -> bool {
1185 status
1186 .conditions
1187 .unwrap_or_default()
1188 .iter()
1189 .any(|c| c.type_ == type_ && c.status == CONDITION_FALSE)
1190}