Skip to main content

kaniop_operator/kanidm/reconcile/
secret.rs

1use crate::kanidm::controller::context::Context;
2use crate::kanidm::crd::Kanidm;
3use crate::kanidm::reconcile::statefulset::REPLICA_LABEL;
4
5use kaniop_k8s_util::error::{Error, Result};
6
7use std::sync::{Arc, LazyLock};
8
9use k8s_openapi::api::core::v1::Secret;
10use kube::ResourceExt;
11use kube::api::{ObjectMeta, Resource};
12use regex::Regex;
13use serde::Serialize;
14use tracing::info;
15
16pub const ADMIN_PASSWORD_KEY: &str = "ADMIN_PASSWORD";
17pub const ADMIN_USER: &str = "admin";
18pub const IDM_ADMIN_PASSWORD_KEY: &str = "IDM_ADMIN_PASSWORD";
19pub const IDM_ADMIN_USER: &str = "idm_admin";
20pub const SECRET_TYPE_LABEL: &str = "kaniop.rs/secret-type";
21// decode with `basenc --base64url -d | openssl x509 -noout -text -inform DER`
22pub const REPLICA_SECRET_KEY: &str = "tls.der.b64url";
23
24#[allow(async_fn_in_trait)]
25pub trait SecretExt {
26    fn admins_secret_name(&self) -> String;
27    fn replica_secret_name(&self, pod_name: &str) -> String;
28    async fn generate_admins_secret(&self, ctx: Arc<Context>) -> Result<Secret>;
29    async fn generate_replica_secret(&self, ctx: Arc<Context>, pod_name: &str) -> Result<Secret>;
30    async fn update_replica_secret(&self, ctx: Arc<Context>, pod_name: &str) -> Result<Secret>;
31}
32
33#[derive(Serialize, Debug)]
34#[serde(rename_all = "kebab-case")]
35pub enum SecretType {
36    AdminPasswords,
37    ReplicaCert,
38}
39
40impl SecretExt for Kanidm {
41    #[inline]
42    fn admins_secret_name(&self) -> String {
43        format!("{}-admin-passwords", self.name_any())
44    }
45
46    #[inline]
47    fn replica_secret_name(&self, pod_name: &str) -> String {
48        format!("{pod_name}-cert")
49    }
50
51    async fn generate_admins_secret(&self, ctx: Arc<Context>) -> Result<Secret> {
52        let admin_password = self.recover_password(ctx.clone(), ADMIN_USER).await?;
53        let idm_admin_password = self.recover_password(ctx.clone(), IDM_ADMIN_USER).await?;
54
55        let secret = Secret {
56            metadata: ObjectMeta {
57                name: Some(self.admins_secret_name()),
58                namespace: Some(self.namespace().unwrap()),
59                owner_references: self.controller_owner_ref(&()).map(|oref| vec![oref]),
60                annotations: self
61                    .spec
62                    .service
63                    .as_ref()
64                    .and_then(|s| s.annotations.clone()),
65                labels: Some(
66                    self.generate_resource_labels()
67                        .clone()
68                        .into_iter()
69                        .chain(std::iter::once((
70                            SECRET_TYPE_LABEL.to_string(),
71                            serde_plain::to_string(&SecretType::AdminPasswords).unwrap(),
72                        )))
73                        .collect(),
74                ),
75                ..ObjectMeta::default()
76            },
77            string_data: Some(
78                [
79                    ("ADMIN_USERNAME".to_string(), ADMIN_USER.to_string()),
80                    (ADMIN_PASSWORD_KEY.to_string(), admin_password),
81                    ("IDM_ADMIN_USERNAME".to_string(), IDM_ADMIN_USER.to_string()),
82                    (IDM_ADMIN_PASSWORD_KEY.to_string(), idm_admin_password),
83                ]
84                .iter()
85                .cloned()
86                .collect(),
87            ),
88            ..Secret::default()
89        };
90
91        Ok(secret)
92    }
93
94    async fn generate_replica_secret(&self, ctx: Arc<Context>, pod_name: &str) -> Result<Secret> {
95        let cert = self.get_replica_cert(ctx.clone(), pod_name).await?;
96        let secret = self.build_replica_secret(cert, pod_name);
97        Ok(secret)
98    }
99
100    async fn update_replica_secret(&self, ctx: Arc<Context>, pod_name: &str) -> Result<Secret> {
101        info!(msg = format!("renewing replica certificate for pod {pod_name}"));
102        let cert = self.update_replica_cert(ctx.clone(), pod_name).await?;
103        let secret = self.build_replica_secret(cert, pod_name);
104        Ok(secret)
105    }
106}
107
108impl Kanidm {
109    async fn recover_password(&self, ctx: Arc<Context>, user: &str) -> Result<String, Error> {
110        let recover_command = vec!["kanidmd", "recover-account"];
111        let password_output = self
112            .exec_any(
113                ctx.clone(),
114                recover_command.into_iter().chain(std::iter::once(user)),
115            )
116            .await
117            .map_err(|e| match e {
118                Error::KubeExecError(_) => {
119                    Error::ReceiveOutput(format!("failed to recover password for {user}"))
120                }
121                _ => e,
122            })?;
123        extract_password(password_output)
124    }
125
126    fn build_replica_secret(&self, cert: String, pod_name: &str) -> Secret {
127        Secret {
128            metadata: ObjectMeta {
129                name: Some(self.replica_secret_name(pod_name)),
130                namespace: Some(self.namespace().unwrap()),
131                owner_references: self.controller_owner_ref(&()).map(|oref| vec![oref]),
132                annotations: self
133                    .spec
134                    .service
135                    .as_ref()
136                    .and_then(|s| s.annotations.clone()),
137                labels: Some(
138                    self.generate_resource_labels()
139                        .clone()
140                        .into_iter()
141                        .chain([
142                            (REPLICA_LABEL.to_string(), pod_name.to_string()),
143                            (
144                                SECRET_TYPE_LABEL.to_string(),
145                                serde_plain::to_string(&SecretType::ReplicaCert).unwrap(),
146                            ),
147                        ])
148                        .collect(),
149                ),
150                ..ObjectMeta::default()
151            },
152            string_data: Some(
153                [(REPLICA_SECRET_KEY.to_string(), cert)]
154                    .iter()
155                    .cloned()
156                    .collect(),
157            ),
158            ..Secret::default()
159        }
160    }
161
162    async fn get_replica_cert(&self, ctx: Arc<Context>, pod_name: &str) -> Result<String, Error> {
163        let show_certificate_command = vec!["kanidmd", "show-replication-certificate"];
164        let cert_output = self
165            .exec(ctx.clone(), pod_name, show_certificate_command)
166            .await
167            .map_err(|e| match e {
168                Error::KubeExecError(_) => {
169                    Error::ReceiveOutput(format!("failed to get certificate for {pod_name}"))
170                }
171                _ => e,
172            })?;
173        extract_cert(cert_output)
174    }
175
176    async fn update_replica_cert(
177        &self,
178        ctx: Arc<Context>,
179        pod_name: &str,
180    ) -> Result<String, Error> {
181        let renew_command = vec!["kanidmd", "renew-replication-certificate"];
182        let cert_output = self
183            .exec(ctx.clone(), pod_name, renew_command)
184            .await
185            .map_err(|e| {
186                Error::ReceiveOutput(format!("failed to renew certificate for {pod_name}: {e}"))
187            })?;
188        extract_cert(cert_output)
189    }
190}
191
192static PASSWORD_REGEX: LazyLock<Regex> = LazyLock::new(|| {
193    Regex::new(r#"new_password:\s*"([^"]+)"#).expect("password regex must be valid")
194});
195
196static CERT_REGEX_V1_9: LazyLock<Regex> = LazyLock::new(|| {
197    Regex::new(r#"certificate:\s*"([^"]+)"#).expect("certificate regex (v1.9) must be valid")
198});
199
200static CERT_REGEX_V1_10: LazyLock<Regex> = LazyLock::new(|| {
201    Regex::new(r#"certificate=([A-Za-z0-9_+/=-]+)"#)
202        .expect("certificate regex (v1.10) must be valid")
203});
204
205fn extract_password(output: String) -> Result<String, Error> {
206    PASSWORD_REGEX
207        .captures(&output)
208        .and_then(|caps| caps.get(1))
209        .map(|m| m.as_str().to_string())
210        .ok_or_else(|| Error::ReceiveOutput("password was not found".to_string()))
211}
212
213fn extract_cert(output: String) -> Result<String, Error> {
214    if let Some(caps) = CERT_REGEX_V1_9.captures(&output) {
215        caps.get(1)
216            .map(|m| m.as_str().to_string())
217            .ok_or_else(|| Error::ReceiveOutput("certificate was not found (v1.9)".to_string()))
218    } else {
219        CERT_REGEX_V1_10
220            .captures(&output)
221            .and_then(|caps| caps.get(1))
222            .map(|m| m.as_str().to_string())
223            .ok_or_else(|| Error::ReceiveOutput("certificate was not found".to_string()))
224    }
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    #[test]
232    fn test_extract_password() {
233        let output = r#"
234        00000000-0000-0000-0000-000000000000 WARN     🚧 [warn]: This is running as uid == 0 (root) which may be a security risk.
235        00000000-0000-0000-0000-000000000000 WARN     🚧 [warn]: WARNING: DB folder /data has 'everyone' permission bits in the mode. This could be a security risk ...
236        00000000-0000-0000-0000-000000000000 INFO     i [info]: Running account recovery ...
237        00000000-0000-0000-0000-000000000000 INFO     i [info]:  | new_password: "ZJhV4PU18qrf7x2AJGTJvS1LyQbh7v9ZER8aZrFu9Evc9sqH""#.to_string();
238
239        let result = extract_password(output).unwrap();
240        assert_eq!(result, "ZJhV4PU18qrf7x2AJGTJvS1LyQbh7v9ZER8aZrFu9Evc9sqH");
241    }
242
243    #[test]
244    fn test_extract_password_with_otel_tracing() {
245        let output = r#"
246        2026-05-07T18:10:01.000000Z INFO kanidmd::recover_account: Running account recovery
247        trace_id=12345 span_id=67890
248        2026-05-07T18:10:01.000000Z INFO kanidmd::recover_account:new_password: "OTELTestPassword123456789ABCDEFG"
249        trace_id=12345 span_id=67890"#.to_string();
250
251        let result = extract_password(output).unwrap();
252        assert_eq!(result, "OTELTestPassword123456789ABCDEFG");
253    }
254
255    #[test]
256    fn test_extract_password_with_extra_whitespace() {
257        let output = r#"
258        Running account recovery ...
259         | new_password:     "WhitespaceTestPassword12345"  "#
260            .to_string();
261
262        let result = extract_password(output).unwrap();
263        assert_eq!(result, "WhitespaceTestPassword12345");
264    }
265
266    #[test]
267    fn test_extract_cert() {
268        let output = r#"
269        00000000-0000-0000-0000-000000000000 WARN     🚧 [warn]: This is running as uid == 0 (root) which may be a security risk.
270        00000000-0000-0000-0000-000000000000 WARN     🚧 [warn]: WARNING: DB folder /data has 'everyone' permission bits in the mode. This could be a security risk ...
271        00000000-0000-0000-0000-000000000000 INFO     i [info]: Running show replication certificate ...
272        00000000-0000-0000-0000-000000000000 INFO     i [info]:  | certificate: "MIIB_DCCAaGgAwIBAgIBATAKBggqhkjOPQQDAjBMMRswGQYDVQQKDBJLYW5pZG0gUmVwbGljYXRpb24xLTArBgNVBAMMJDJiYTgzMTZhLWViYWEtNGJjMS04NDkzLTVmODZmYWZhZTU5NDAeFw0yNDExMDYxOTEzMjdaFw0yODExMDYxOTEzMjdaMEwxGzAZBgNVBAoMEkthbmlkbSBSZXBsaWNhdGlvbjEtMCsGA1UEAwwkMmJhODMxNmEtZWJhYS00YmMxLTg0OTMtNWY4NmZhZmFlNTk0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuXp1hNNZerxDQbCh7rAGW6uM0CPECNd3IvbSh7qH34MkO_plwwDVKFbzcTG8HJE2ouIJlJYN8P4wf6qmrRQMAKN0MHIwDAYDVR0TAQH_BAIwADAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQWBBTaOaPuXmtLDTJVv--VYBiQr9gHCTAUBgNVHREEDTALgglsb2NhbGhvc3QwCgYIKoZIzj0EAwIDSQAwRgIhAIZD_J4LyR7D0kg41GRg_TcRxm5mEVhM6WL9BO3XmfUsAiEA7Wpbkvd0b1e-Sg8AS9jP-CpBpmTnC7oEChkyhUYKyFc=""#.to_string();
273
274        let result = extract_cert(output).unwrap();
275        assert_eq!(
276            result,
277            "MIIB_DCCAaGgAwIBAgIBATAKBggqhkjOPQQDAjBMMRswGQYDVQQKDBJLYW5pZG0gUmVwbGljYXRpb24xLTArBgNVBAMMJDJiYTgzMTZhLWViYWEtNGJjMS04NDkzLTVmODZmYWZhZTU5NDAeFw0yNDExMDYxOTEzMjdaFw0yODExMDYxOTEzMjdaMEwxGzAZBgNVBAoMEkthbmlkbSBSZXBsaWNhdGlvbjEtMCsGA1UEAwwkMmJhODMxNmEtZWJhYS00YmMxLTg0OTMtNWY4NmZhZmFlNTk0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuXp1hNNZerxDQbCh7rAGW6uM0CPECNd3IvbSh7qH34MkO_plwwDVKFbzcTG8HJE2ouIJlJYN8P4wf6qmrRQMAKN0MHIwDAYDVR0TAQH_BAIwADAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQWBBTaOaPuXmtLDTJVv--VYBiQr9gHCTAUBgNVHREEDTALgglsb2NhbGhvc3QwCgYIKoZIzj0EAwIDSQAwRgIhAIZD_J4LyR7D0kg41GRg_TcRxm5mEVhM6WL9BO3XmfUsAiEA7Wpbkvd0b1e-Sg8AS9jP-CpBpmTnC7oEChkyhUYKyFc="
278        );
279    }
280
281    #[test]
282    fn test_extract_cert_with_otel_tracing() {
283        let output = r#"
284        2026-05-07T18:10:01.000000Z INFO kanidmd::show_certificate: Running show replication certificate
285        trace_id=12345 span_id=67890
286        2026-05-07T18:10:01.000000Z INFO kanidmd::show_certificate:certificate: "MIIBTestCertificateForOTELTracing123456789"
287        trace_id=12345 span_id=67890"#.to_string();
288
289        let result = extract_cert(output).unwrap();
290        assert_eq!(result, "MIIBTestCertificateForOTELTracing123456789");
291    }
292
293    #[test]
294    fn test_extract_cert_with_extra_whitespace() {
295        let output = r#"
296        Running show replication certificate ...
297         | certificate:     "WhitespaceTestCert12345"  "#
298            .to_string();
299
300        let result = extract_cert(output).unwrap();
301        assert_eq!(result, "WhitespaceTestCert12345");
302    }
303
304    #[test]
305    fn test_extract_cert_v1_10_format() {
306        let output = r#"
307        2026-05-07T18:10:01.000000Z INFO kanidmd::show_certificate: Running show replication certificate
308        2026-05-07T18:10:01.000000Z INFO kanidmd::show_certificate:certificate=MIIB_DCCAaGgAwIBAgIBATAKBggqhkjOPQQDAjBMMRswGQYDVQQKDBJLYW5pZG0gUmVwbGljYXRpb24xLTArBgNVBAMMJDJiYTgzMTZhLWViYWEtNGJjMS04NDkzLTVmODZmYWZhZTU5NDAeFw0yNDExMDYxOTEzMjdaFw0yODExMDYxOTEzMjdaMEwxGzAZBgNVBAoMEkthbmlkbSBSZXBsaWNhdGlvbjEtMCsGA1UEAwwkMmJhODMxNmEtZWJhYS00YmMxLTg0OTMtNWY4NmZhZmFlNTk0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuXp1hNNZerxDQbCh7rAGW6uM0CPECNd3IvbSh7qH34MkO_plwwDVKFbzcTG8HJE2ouIJlJYN8P4wf6qmrRQMAKN0MHIwDAYDVR0TAQH_BAIwADAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQWBBTaOaPuXmtLDTJVv--VYBiQr9gHCTAUBgNVHREEDTALgglsb2NhbGhvc3QwCgYIKoZIzj0EAwIDSQAwRgIhAIZD_J4LyR7D0kg41GRg_TcRxm5mEVhM6WL9BO3XmfUsAiEA7Wpbkvd0b1e-Sg8AS9jP-CpBpmTnC7oEChkyhUYKyFc="#.to_string();
309
310        let result = extract_cert(output).unwrap();
311        assert_eq!(
312            result,
313            "MIIB_DCCAaGgAwIBAgIBATAKBggqhkjOPQQDAjBMMRswGQYDVQQKDBJLYW5pZG0gUmVwbGljYXRpb24xLTArBgNVBAMMJDJiYTgzMTZhLWViYWEtNGJjMS04NDkzLTVmODZmYWZhZTU5NDAeFw0yNDExMDYxOTEzMjdaFw0yODExMDYxOTEzMjdaMEwxGzAZBgNVBAoMEkthbmlkbSBSZXBsaWNhdGlvbjEtMCsGA1UEAwwkMmJhODMxNmEtZWJhYS00YmMxLTg0OTMtNWY4NmZhZmFlNTk0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuXp1hNNZerxDQbCh7rAGW6uM0CPECNd3IvbSh7qH34MkO_plwwDVKFbzcTG8HJE2ouIJlJYN8P4wf6qmrRQMAKN0MHIwDAYDVR0TAQH_BAIwADAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQWBBTaOaPuXmtLDTJVv--VYBiQr9gHCTAUBgNVHREEDTALgglsb2NhbGhvc3QwCgYIKoZIzj0EAwIDSQAwRgIhAIZD_J4LyR7D0kg41GRg_TcRxm5mEVhM6WL9BO3XmfUsAiEA7Wpbkvd0b1e-Sg8AS9jP-CpBpmTnC7oEChkyhUYKyFc="
314        );
315    }
316}