Skip to main content

kaniop_oauth2/reconcile/
secret.rs

1use crate::controller::CONTROLLER_ID;
2use crate::crd::KanidmOAuth2Client;
3use crate::reconcile::OAUTH2_OPERATOR_NAME;
4
5use kanidm_client::KanidmClient;
6use kaniop_k8s_util::error::{Error, Result};
7use kaniop_k8s_util::rotation::add_rotation_annotations as add_annotations;
8use kaniop_operator::controller::kanidm::KanidmResource;
9use kaniop_operator::controller::{INSTANCE_LABEL, MANAGED_BY_LABEL, NAME_LABEL};
10use kaniop_operator::crd::{MetadataTemplate, SecretRotation};
11use kaniop_operator::object_meta_template::ObjectMetaTemplateExt;
12
13use std::collections::BTreeMap;
14use std::sync::LazyLock;
15
16use k8s_openapi::api::core::v1::Secret;
17use kube::ResourceExt;
18use kube::api::{ObjectMeta, Resource};
19
20static LABELS: LazyLock<BTreeMap<String, String>> = LazyLock::new(|| {
21    BTreeMap::from([
22        (NAME_LABEL.to_string(), "kanidm".to_string()),
23        (
24            MANAGED_BY_LABEL.to_string(),
25            format!("kaniop-{CONTROLLER_ID}"),
26        ),
27    ])
28});
29
30/// Add rotation annotations based on a SecretRotation config.
31fn add_rotation_annotations(
32    annotations: &mut BTreeMap<String, String>,
33    rotation_config: Option<&SecretRotation>,
34) {
35    if let Some(config) = rotation_config {
36        add_annotations(annotations, config.enabled, config.period_days);
37    }
38}
39
40#[allow(async_fn_in_trait)]
41pub trait SecretExt {
42    fn secret_name(&self) -> String;
43    async fn generate_secret(
44        &self,
45        kanidm_client: &KanidmClient,
46        rotation_config: Option<&SecretRotation>,
47    ) -> Result<Secret>;
48}
49
50impl SecretExt for KanidmOAuth2Client {
51    #[inline]
52    fn secret_name(&self) -> String {
53        format!("{}-kanidm-oauth2-credentials", self.name_any())
54    }
55
56    async fn generate_secret(
57        &self,
58        kanidm_client: &KanidmClient,
59        rotation_config: Option<&SecretRotation>,
60    ) -> Result<Secret> {
61        let name = &self.name_any();
62        let client_secret = kanidm_client
63            .idm_oauth2_rs_get_basic_secret(name)
64            .await
65            .map_err(|e| {
66                Error::KanidmClientError(
67                    format!(
68                        "failed to get basic secret for {name} from {namespace}/{kanidm}",
69                        namespace = self.kanidm_namespace(),
70                        kanidm = self.kanidm_name(),
71                    ),
72                    Box::new(e),
73                )
74            })?
75            .ok_or_else(|| {
76                Error::MissingData(format!(
77                    "no basic secret for {name} in {namespace}/{kanidm}",
78                    namespace = self.kanidm_namespace(),
79                    kanidm = self.kanidm_name(),
80                ))
81            })?;
82        let labels = LABELS
83            .clone()
84            .into_iter()
85            .chain([(INSTANCE_LABEL.to_string(), name.clone())])
86            .collect();
87
88        let mut annotations = BTreeMap::new();
89        add_rotation_annotations(&mut annotations, rotation_config);
90
91        let secret = Secret {
92            metadata: ObjectMeta {
93                name: Some(self.secret_name()),
94                namespace: Some(self.namespace().unwrap()),
95                owner_references: self.controller_owner_ref(&()).map(|oref| vec![oref]),
96                labels: Some(labels),
97                annotations: if annotations.is_empty() {
98                    None
99                } else {
100                    Some(annotations)
101                },
102                ..ObjectMeta::default()
103            },
104            string_data: Some(
105                [
106                    ("CLIENT_ID".to_string(), name.clone()),
107                    ("CLIENT_SECRET".to_string(), client_secret),
108                ]
109                .iter()
110                .cloned()
111                .collect(),
112            ),
113            ..Secret::default()
114        };
115
116        Ok(secret)
117    }
118}
119
120impl ObjectMetaTemplateExt<Secret> for KanidmOAuth2Client {
121    const OPERATOR_NAME: &'static str = OAUTH2_OPERATOR_NAME;
122    fn managed_object_name(&self) -> String {
123        self.secret_name()
124    }
125    fn metadata_template(&self) -> Option<&MetadataTemplate> {
126        self.spec.secret_template.as_ref()
127    }
128}