Skip to main content

kaniop_oauth2/reconcile/
secret.rs

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