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