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::{ImageOperation, publish_image_error_event, update_image_if_needed};
14
15use crate::{
16 controller::Context,
17 crd::{
18 KanidmClaimMap, KanidmOAuth2Client, KanidmOAuth2ClientStatus, KanidmScopeMap,
19 OAuth2ClientImageStatus,
20 },
21};
22
23use kanidm_proto::internal::OperationError;
24use kaniop_k8s_util::error::{Error, Result};
25use kaniop_operator::controller::context::{IdmClientContext, KubeOperations};
26use kaniop_operator::controller::idm_reconcile_interval;
27use kaniop_operator::controller::kanidm::{KanidmResource, is_resource_watched};
28use kaniop_operator::object_meta_template::ObjectMetaTemplateExt;
29use kaniop_operator::telemetry;
30
31use std::collections::BTreeSet;
32use std::sync::Arc;
33use std::time::Duration;
34
35use futures::future::TryJoinAll;
36use futures::try_join;
37
38use k8s_openapi::NamespaceResourceScope;
39use 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::kube_error("publish", "event", oauth2.get_namespace(), oauth2.name_any(), 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::kube_error(
238 "publish",
239 "event",
240 self.get_namespace(),
241 self.name_any(),
242 e,
243 )
244 })?;
245 Err(e)
246 }
247 _ => Err(e),
248 },
249 }
250 }
251
252 #[inline]
253 async fn internal_reconcile(
254 &self,
255 kanidm_client: Arc<KanidmClient>,
256 status: KanidmOAuth2ClientStatus,
257 ctx: Arc<Context>,
258 ) -> Result<Action> {
259 let name = &self.kanidm_entity_name();
260 let namespace = self.get_namespace();
261 let mut require_status_update = false;
262 let force_secret_rotation_requested = self.force_secret_rotation_requested();
263
264 if is_oauth2_false(TYPE_EXISTS, status.clone()) {
265 self.create(&kanidm_client, name).await?;
266 require_status_update = true;
267 }
268
269 if is_oauth2_false(TYPE_SECRET_INITIALIZED, status.clone()) {
270 let secret = self
271 .generate_secret(&kanidm_client, self.spec.secret_rotation.as_ref())
272 .await?;
273 self.patch(&ctx, secret).await?;
274 require_status_update = true;
275 }
276
277 if force_secret_rotation_requested {
278 if self.spec.public {
279 info!(msg = "skipping forced secret rotation annotation for public OAuth2 client");
280 } else {
281 info!(msg = "rotating OAuth2 client secret due to force annotation");
282 self.rotate_secret(&kanidm_client, name, ctx.clone())
283 .await?;
284 }
285 self.clear_force_secret_rotation_annotation(ctx.clone())
286 .await?;
287 require_status_update = true;
288 } else if is_oauth2_false(TYPE_SECRET_ROTATED, status.clone()) {
289 self.rotate_secret(&kanidm_client, name, ctx.clone())
291 .await?;
292 require_status_update = true;
293 }
294
295 if is_oauth2_false(TYPE_SECRET_TEMPLATE_SYNCED, status.clone()) {
300 match ctx.secret_store.find(|s| {
301 s.name_any() == self.secret_name() && s.namespace().as_ref() == Some(&namespace)
302 }) {
303 None => debug!(msg = "secret not yet in store, deferring secretTemplate apply"),
304 Some(secret_meta) => {
305 if let Some(filtered) = self.needs_meta_template_apply(&secret_meta) {
310 if filtered.has_discards() {
311 warn!(
312 msg = "secretTemplate contains keys already owned by the operator; they will be ignored",
313 discarded_labels = ?filtered.discarded_labels,
314 discarded_annotations = ?filtered.discarded_annotations,
315 );
316 ctx.kaniop_ctx
317 .recorder
318 .publish(
319 &Event {
320 type_: EventType::Warning,
321 reason: "SecretTemplateConflict".to_string(),
322 note: Some(format!(
323 "secretTemplate contains keys already owned by the \
324 operator and will be ignored. Labels: [{}]. \
325 Annotations: [{}].",
326 filtered
327 .discarded_labels
328 .iter()
329 .cloned()
330 .collect::<Vec<_>>()
331 .join(", "),
332 filtered
333 .discarded_annotations
334 .iter()
335 .cloned()
336 .collect::<Vec<_>>()
337 .join(", "),
338 )),
339 action: "ApplySecretTemplate".to_string(),
340 secondary: None,
341 },
342 &self.object_ref(&()),
343 )
344 .await
345 .map_err(|e| {
346 warn!(msg = "failed to publish SecretTemplateConflict event", %e);
347Error::kube_error("publish", "event", self.get_namespace(), self.name_any(), e)
348 })?;
349 }
350 self.apply_meta_template(
351 ctx.kaniop_ctx.client.clone(),
352 &ctx.kaniop_ctx.metrics,
353 filtered,
354 )
355 .await?;
356 require_status_update = true;
357 }
358 }
359 }
360 }
361
362 if is_oauth2_false(TYPE_UPDATED, status.clone()) {
363 self.update(&kanidm_client, name).await?;
364 require_status_update = true;
365 }
366
367 if is_oauth2_false(TYPE_REDIRECT_URL_UPDATED, status.clone()) {
368 self.update_redirect_url(&kanidm_client, name, &status)
369 .await?;
370 require_status_update = true;
371 }
372
373 if is_oauth2_false(TYPE_SCOPE_MAP_UPDATED, status.clone()) {
374 self.update_scope_map(&kanidm_client, name, &status).await?;
375 require_status_update = true;
376 }
377
378 if is_oauth2_false(TYPE_SUP_SCOPE_MAP_UPDATED, status.clone()) {
379 self.update_sup_scope_map(&kanidm_client, name, &status)
380 .await?;
381 require_status_update = true;
382 }
383
384 if is_oauth2_false(TYPE_CLAIMS_MAP_UPDATED, status.clone()) {
385 self.update_claims_map(&kanidm_client, name, &status)
386 .await?;
387 require_status_update = true;
388 }
389
390 if is_oauth2_false(TYPE_STRICT_REDIRECT_URL_UPDATED, status.clone()) {
391 self.update_strict_redirect_url(&kanidm_client, name)
392 .await?;
393 require_status_update = true;
394 }
395
396 if is_oauth2_false(TYPE_DISABLE_PKCE_UPDATED, status.clone()) {
397 self.update_disable_pkce(&kanidm_client, name).await?;
398 require_status_update = true;
399 }
400
401 if is_oauth2_false(TYPE_PREFER_SHORT_NAME_UPDATED, status.clone()) {
402 self.update_prefer_short_name(&kanidm_client, name).await?;
403 require_status_update = true;
404 }
405
406 if is_oauth2_false(TYPE_ALLOW_LOCALHOST_REDIRECT_UPDATED, status.clone()) {
407 self.update_allow_localhost_redirect(&kanidm_client, name)
408 .await?;
409 require_status_update = true;
410 }
411
412 if is_oauth2_false(TYPE_LEGACY_CRYPTO_UPDATED, status.clone()) {
413 self.update_legacy_crypto(&kanidm_client, name).await?;
414 require_status_update = true;
415 }
416
417 if is_oauth2_false(TYPE_DISABLE_CONSENT_PROMPT_UPDATED, status.clone()) {
418 self.update_consent_prompt(&kanidm_client, name).await?;
419 require_status_update = true;
420 }
421
422 if is_oauth2_false(TYPE_IMAGE_UPDATED, status.clone()) {
423 self.update_image(&kanidm_client, name, &status, ctx.clone())
424 .await?;
425 require_status_update = true;
426 }
427
428 if require_status_update {
429 trace!(msg = "status update required, requeueing in 500ms");
430 Ok(Action::requeue(Duration::from_millis(500)))
431 } else {
432 Ok(Action::requeue(idm_reconcile_interval()))
433 }
434 }
435
436 async fn create(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
437 debug!(msg = "create");
438 if self.spec.public {
439 debug!(msg = "create public client");
440 kanidm_client
441 .idm_oauth2_rs_public_create(name, &self.spec.displayname, &self.spec.origin)
442 .await
443 .map_err(|e| {
444 Error::kanidm_client_error(
445 "create",
446 name,
447 self.kanidm_namespace(),
448 self.kanidm_name(),
449 e,
450 )
451 })?;
452 } else {
453 kanidm_client
454 .idm_oauth2_rs_basic_create(name, &self.spec.displayname, &self.spec.origin)
455 .await
456 .map_err(|e| {
457 Error::kanidm_client_error(
458 "create",
459 name,
460 self.kanidm_namespace(),
461 self.kanidm_name(),
462 e,
463 )
464 })?;
465 }
466 Ok(())
467 }
468
469 async fn update(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
470 debug!(msg = "update");
471 kanidm_client
472 .idm_oauth2_rs_update(
473 name,
474 None,
475 Some(&self.spec.displayname),
476 Some(&self.spec.origin),
477 false,
478 )
479 .await
480 .map_err(|e| {
481 Error::kanidm_client_error(
482 "update",
483 name,
484 self.kanidm_namespace(),
485 self.kanidm_name(),
486 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::kanidm_client_error_attr(
505 "rotate",
506 "secret",
507 name,
508 self.kanidm_namespace(),
509 self.kanidm_name(),
510 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::kanidm_client_error_attr(
566 "modify",
567 ATTR_OAUTH2_RS_ORIGIN,
568 name,
569 self.kanidm_namespace(),
570 self.kanidm_name(),
571 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::kanidm_client_error_attr(
619 "modify",
620 ATTR_OAUTH2_RS_SCOPE_MAP,
621 name,
622 self.kanidm_namespace(),
623 self.kanidm_name(),
624 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::kanidm_client_error_attr(
671 "modify",
672 ATTR_OAUTH2_RS_SUP_SCOPE_MAP,
673 name,
674 self.kanidm_namespace(),
675 self.kanidm_name(),
676 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::kanidm_client_error_attr(
742 "modify",
743 ATTR_OAUTH2_RS_CLAIM_MAP,
744 name,
745 self.kanidm_namespace(),
746 self.kanidm_name(),
747 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(name)
763 .await
764 .map_err(|e| {
765 Error::kanidm_client_error_attr(
766 "update",
767 ATTR_OAUTH2_STRICT_REDIRECT_URI,
768 name,
769 self.kanidm_namespace(),
770 self.kanidm_name(),
771 e,
772 )
773 })?;
774 } else {
775 kanidm_client
776 .idm_oauth2_rs_disable_strict_redirect_uri(name)
777 .await
778 .map_err(|e| {
779 Error::kanidm_client_error_attr(
780 "update",
781 ATTR_OAUTH2_STRICT_REDIRECT_URI,
782 name,
783 self.kanidm_namespace(),
784 self.kanidm_name(),
785 e,
786 )
787 })?;
788 }
789 };
790 Ok(())
791 }
792
793 async fn update_disable_pkce(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
794 debug!(msg = format!("update {ATTR_OAUTH2_ALLOW_INSECURE_CLIENT_DISABLE_PKCE} attribute"));
795 if let Some(disable_pkce) = self.spec.allow_insecure_client_disable_pkce {
796 if disable_pkce {
797 kanidm_client
798 .idm_oauth2_rs_disable_pkce(name)
799 .await
800 .map_err(|e| {
801 Error::kanidm_client_error_attr(
802 "update",
803 ATTR_OAUTH2_ALLOW_INSECURE_CLIENT_DISABLE_PKCE,
804 name,
805 self.kanidm_namespace(),
806 self.kanidm_name(),
807 e,
808 )
809 })?;
810 } else {
811 kanidm_client
812 .idm_oauth2_rs_enable_pkce(name)
813 .await
814 .map_err(|e| {
815 Error::kanidm_client_error_attr(
816 "update",
817 ATTR_OAUTH2_ALLOW_INSECURE_CLIENT_DISABLE_PKCE,
818 name,
819 self.kanidm_namespace(),
820 self.kanidm_name(),
821 e,
822 )
823 })?;
824 }
825 };
826 Ok(())
827 }
828
829 async fn update_prefer_short_name(
830 &self,
831 kanidm_client: &KanidmClient,
832 name: &str,
833 ) -> Result<()> {
834 debug!(msg = format!("update {ATTR_OAUTH2_PREFER_SHORT_USERNAME} attribute"));
835 if let Some(prefer_short_username) = self.spec.prefer_short_username {
836 if prefer_short_username {
837 kanidm_client
838 .idm_oauth2_rs_prefer_short_username(name)
839 .await
840 .map_err(|e| {
841 Error::kanidm_client_error_attr(
842 "update",
843 ATTR_OAUTH2_PREFER_SHORT_USERNAME,
844 name,
845 self.kanidm_namespace(),
846 self.kanidm_name(),
847 e,
848 )
849 })?;
850 } else {
851 kanidm_client
852 .idm_oauth2_rs_prefer_spn_username(name)
853 .await
854 .map_err(|e| {
855 Error::kanidm_client_error_attr(
856 "update",
857 ATTR_OAUTH2_PREFER_SHORT_USERNAME,
858 name,
859 self.kanidm_namespace(),
860 self.kanidm_name(),
861 e,
862 )
863 })?;
864 }
865 };
866 Ok(())
867 }
868
869 async fn update_allow_localhost_redirect(
870 &self,
871 kanidm_client: &KanidmClient,
872 name: &str,
873 ) -> Result<()> {
874 debug!(msg = format!("update {ATTR_OAUTH2_ALLOW_LOCALHOST_REDIRECT} attribute"));
875 if let Some(allow_localhost_redirect) = self.spec.allow_localhost_redirect {
876 if allow_localhost_redirect {
877 kanidm_client
878 .idm_oauth2_rs_enable_public_localhost_redirect(name)
879 .await
880 .map_err(|e| {
881 Error::kanidm_client_error_attr(
882 "update",
883 ATTR_OAUTH2_ALLOW_LOCALHOST_REDIRECT,
884 name,
885 self.kanidm_namespace(),
886 self.kanidm_name(),
887 e,
888 )
889 })?;
890 } else {
891 kanidm_client
892 .idm_oauth2_rs_disable_public_localhost_redirect(name)
893 .await
894 .map_err(|e| {
895 Error::kanidm_client_error_attr(
896 "update",
897 ATTR_OAUTH2_ALLOW_LOCALHOST_REDIRECT,
898 name,
899 self.kanidm_namespace(),
900 self.kanidm_name(),
901 e,
902 )
903 })?;
904 }
905 };
906 Ok(())
907 }
908
909 async fn update_legacy_crypto(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
910 debug!(msg = format!("update {ATTR_OAUTH2_JWT_LEGACY_CRYPTO_ENABLE} attribute"));
911 if let Some(legacy_crypto) = self.spec.jwt_legacy_crypto_enable {
912 if legacy_crypto {
913 kanidm_client
914 .idm_oauth2_rs_enable_legacy_crypto(name)
915 .await
916 .map_err(|e| {
917 Error::kanidm_client_error_attr(
918 "update",
919 ATTR_OAUTH2_JWT_LEGACY_CRYPTO_ENABLE,
920 name,
921 self.kanidm_namespace(),
922 self.kanidm_name(),
923 e,
924 )
925 })?;
926 } else {
927 kanidm_client
928 .idm_oauth2_rs_disable_legacy_crypto(name)
929 .await
930 .map_err(|e| {
931 Error::kanidm_client_error_attr(
932 "update",
933 ATTR_OAUTH2_JWT_LEGACY_CRYPTO_ENABLE,
934 name,
935 self.kanidm_namespace(),
936 self.kanidm_name(),
937 e,
938 )
939 })?;
940 }
941 };
942 Ok(())
943 }
944
945 async fn update_consent_prompt(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
946 debug!(msg = format!("update {ATTR_OAUTH2_CONSENT_PROMPT_ENABLE} attribute"));
947 if let Some(disable_consent_prompt) = self.spec.disable_consent_prompt {
948 if disable_consent_prompt {
949 kanidm_client
950 .idm_oauth2_rs_disable_consent_prompt(name)
951 .await
952 .map_err(|e| {
953 Error::kanidm_client_error_attr(
954 "update",
955 ATTR_OAUTH2_CONSENT_PROMPT_ENABLE,
956 name,
957 self.kanidm_namespace(),
958 self.kanidm_name(),
959 e,
960 )
961 })?;
962 } else {
963 kanidm_client
964 .idm_oauth2_rs_enable_consent_prompt(name)
965 .await
966 .map_err(|e| {
967 Error::kanidm_client_error_attr(
968 "update",
969 ATTR_OAUTH2_CONSENT_PROMPT_ENABLE,
970 name,
971 self.kanidm_namespace(),
972 self.kanidm_name(),
973 e,
974 )
975 })?;
976 }
977 };
978 Ok(())
979 }
980
981 async fn update_image(
982 &self,
983 kanidm_client: &KanidmClient,
984 name: &str,
985 status: &KanidmOAuth2ClientStatus,
986 ctx: Arc<Context>,
987 ) -> Result<()> {
988 match &self.spec.image {
989 None => {
990 debug!(msg = "deleting image from OAuth2 client");
991 kanidm_client
992 .idm_oauth2_rs_delete_image(name)
993 .await
994 .map_err(|e| {
995 Error::kanidm_client_error_attr(
996 "delete",
997 "image",
998 name,
999 self.kanidm_namespace(),
1000 self.kanidm_name(),
1001 e,
1002 )
1003 })?;
1004 }
1005 Some(image_spec) => {
1006 let url = &image_spec.url;
1007 debug!(msg = format!("updating image for OAuth2 client from {url}"));
1008
1009 let namespace = self.kanidm_namespace();
1010 let kanidm = self.kanidm_name();
1011
1012 let update_result =
1013 update_image_if_needed(url, status.image.as_ref(), |image_value| async {
1014 kanidm_client
1015 .idm_oauth2_rs_update_image(name, image_value)
1016 .await
1017 .map_err(|e| {
1018 Error::kanidm_client_error_attr(
1019 "update",
1020 "image",
1021 name,
1022 namespace.clone(),
1023 kanidm.clone(),
1024 e,
1025 )
1026 })
1027 })
1028 .await;
1029
1030 match update_result {
1031 Ok(Some(updated)) => {
1032 let new_image_status = OAuth2ClientImageStatus {
1033 url: updated.image_status.url,
1034 etag: updated.image_status.etag,
1035 last_modified: updated.image_status.last_modified,
1036 content_length: updated.image_status.content_length,
1037 content_hash: Some(updated.image_status.content_hash),
1038 };
1039
1040 let namespace = self.namespace().unwrap();
1041 let name = self.name_any();
1042 let oauth2_api = Api::<KanidmOAuth2Client>::namespaced(
1043 ctx.kaniop_ctx.client.clone(),
1044 &namespace,
1045 );
1046 let status_patch = Patch::Apply(KanidmOAuth2Client {
1047 status: Some(KanidmOAuth2ClientStatus {
1048 image: Some(new_image_status),
1049 ..status.clone()
1050 }),
1051 ..KanidmOAuth2Client::default()
1052 });
1053 oauth2_api
1054 .patch_status(
1055 &name,
1056 &PatchParams::apply(OAUTH2_OPERATOR_NAME),
1057 &status_patch,
1058 )
1059 .await
1060 .map_err(|e| {
1061 Error::kube_status_error("KanidmOAuth2Client", &namespace, &name, e)
1062 })?;
1063 }
1064 Ok(None) => {}
1065 Err(e) => {
1066 let operation = if matches!(e, Error::HttpError(_, _)) {
1067 ImageOperation::Fetch
1068 } else {
1069 ImageOperation::Download
1070 };
1071 return Err(publish_image_error_event(
1072 e,
1073 operation,
1074 name,
1075 &namespace,
1076 &kanidm,
1077 &ctx.kaniop_ctx.recorder,
1078 self,
1079 )
1080 .await);
1081 }
1082 }
1083 }
1084 };
1085 Ok(())
1086 }
1087
1088 async fn cleanup(
1089 &self,
1090 kanidm_client: Arc<KanidmClient>,
1091 status: KanidmOAuth2ClientStatus,
1092 ) -> Result<Action> {
1093 let name = &self.kanidm_entity_name();
1094 if is_oauth2(TYPE_EXISTS, status.clone()) {
1095 debug!(msg = "delete");
1096 kanidm_client
1097 .idm_oauth2_rs_delete(name)
1098 .await
1099 .map_err(|e| {
1100 Error::kanidm_client_error(
1101 "delete",
1102 name,
1103 self.kanidm_namespace(),
1104 self.kanidm_name(),
1105 e,
1106 )
1107 })?;
1108 }
1109 Ok(Action::requeue(idm_reconcile_interval()))
1110 }
1111}
1112
1113pub fn is_oauth2(type_: &str, status: KanidmOAuth2ClientStatus) -> bool {
1114 status
1115 .conditions
1116 .unwrap_or_default()
1117 .iter()
1118 .any(|c| c.type_ == type_ && c.status == CONDITION_TRUE)
1119}
1120
1121pub fn is_oauth2_false(type_: &str, status: KanidmOAuth2ClientStatus) -> bool {
1122 status
1123 .conditions
1124 .unwrap_or_default()
1125 .iter()
1126 .any(|c| c.type_ == type_ && c.status == CONDITION_FALSE)
1127}