Skip to main content

kaniop_operator/controller/
kanidm.rs

1use crate::{
2    crd::KanidmRef,
3    kanidm::{
4        crd::Kanidm,
5        reconcile::secret::{
6            ADMIN_PASSWORD_KEY, ADMIN_USER, IDM_ADMIN_PASSWORD_KEY, IDM_ADMIN_USER,
7        },
8    },
9};
10
11use kanidm_client::{KanidmClient, KanidmClientBuilder};
12use kaniop_k8s_util::error::{Error, Result};
13
14use std::collections::HashMap;
15use std::fmt::Debug;
16use std::io::Write;
17use std::sync::Arc;
18
19use k8s_openapi::api::core::v1::{Namespace, Secret};
20use k8s_openapi::apimachinery::pkg::apis::meta::v1::LabelSelector;
21use kube::ResourceExt;
22use kube::api::Api;
23use kube::client::Client;
24use kube::core::{Selector, SelectorExt};
25use kube::runtime::reflector::Store;
26use openssl::x509::X509;
27use serde::Serialize;
28use tempfile::NamedTempFile;
29use tracing::{debug, trace};
30
31pub trait KanidmResource: ResourceExt {
32    /// Returns the KanidmRef from the resource's spec
33    fn kanidm_ref_spec(&self) -> &KanidmRef;
34
35    /// Returns the namespace selector field for this resource type from the Kanidm spec
36    fn get_namespace_selector(kanidm: &Kanidm) -> &Option<LabelSelector>;
37
38    /// Returns the optional Kanidm entity name override from the spec
39    fn kanidm_name_override(&self) -> Option<&str>;
40
41    /// Returns the name of the referenced Kanidm resource
42    fn kanidm_name(&self) -> String {
43        self.kanidm_ref_spec().name.clone()
44    }
45
46    /// Returns the namespace of the referenced Kanidm resource
47    /// Uses the explicitly specified namespace in kanidm_ref, or falls back to the resource's own namespace
48    fn kanidm_namespace(&self) -> String {
49        self.kanidm_ref_spec()
50            .namespace
51            .clone()
52            // safe unwrap: all resources implementing this trait are namespaced scoped
53            .unwrap_or_else(|| self.namespace().unwrap())
54    }
55
56    /// Returns a string representation of the Kanidm reference in "namespace/name" format
57    fn kanidm_ref(&self) -> String {
58        format!("{}/{}", self.kanidm_namespace(), self.kanidm_name())
59    }
60
61    /// Returns the entity name to use in Kanidm.
62    /// If `kanidmName` is specified in the spec, uses that; otherwise uses the K8s resource name.
63    fn kanidm_entity_name(&self) -> String {
64        self.kanidm_name_override()
65            .map(|s| s.to_string())
66            .unwrap_or_else(|| self.name_any())
67    }
68}
69
70/// Check if a LabelSelector matches all namespaces (empty selector with no constraints)
71fn selector_matches_all(selector: &LabelSelector) -> bool {
72    selector.match_labels.is_none() || selector.match_labels.as_ref().is_some_and(|l| l.is_empty())
73}
74
75/// Generic function to check if a resource is watched based on namespace selectors
76///
77/// This function implements the common logic for checking whether a resource should be
78/// reconciled based on the namespace selector configuration in the referenced Kanidm resource.
79pub async fn is_resource_watched<T>(
80    resource: &T,
81    kanidm: &Kanidm,
82    namespace_store: &Store<Namespace>,
83    k8s_client: &Client,
84) -> bool
85where
86    T: KanidmResource,
87{
88    let namespace = resource.namespace().unwrap();
89    trace!(%namespace, "check if resource is watched");
90
91    let namespace_selector = if let Some(selector) = T::get_namespace_selector(kanidm) {
92        selector
93    } else {
94        trace!("no namespace selector found, defaulting to current namespace");
95        return kanidm.namespace().unwrap() == namespace;
96    };
97
98    if selector_matches_all(namespace_selector) {
99        trace!("namespace selector matches all namespaces, fast-track accepted");
100        return true;
101    }
102
103    let selector: Selector = if let Ok(s) = namespace_selector.clone().try_into() {
104        s
105    } else {
106        trace!("failed to parse namespace selector, defaulting to current namespace");
107        return kanidm.namespace().unwrap() == namespace;
108    };
109
110    trace!(?selector, "namespace selector");
111
112    let found_in_store = namespace_store
113        .state()
114        .iter()
115        .filter(|n| selector.matches(n.metadata.labels.as_ref().unwrap_or(&Default::default())))
116        .any(|n| n.name_any() == namespace);
117
118    if found_in_store {
119        return true;
120    }
121
122    trace!(%namespace, "namespace not found in store, fetching from K8s API");
123    let namespace_api: Api<Namespace> = Api::all(k8s_client.clone());
124    match namespace_api.get(&namespace).await {
125        Ok(ns) => {
126            let matches =
127                selector.matches(ns.metadata.labels.as_ref().unwrap_or(&Default::default()));
128            trace!(%namespace, matches, "namespace fetched from API");
129            matches
130        }
131        Err(e) => {
132            trace!(%namespace, ?e, "failed to fetch namespace from API, treating as not watched");
133            false
134        }
135    }
136}
137
138#[derive(Serialize, Clone, Debug, PartialEq, Eq, Hash)]
139pub enum KanidmUser {
140    IdmAdmin,
141    Admin,
142}
143
144const TLS_CERT_KEY: &str = "tls.crt";
145const CA_CERT_KEY: &str = "ca.crt";
146
147fn certificate_trust_anchor(
148    certificate_bundle: &[u8],
149    key: &str,
150    namespace: &str,
151    secret_name: &str,
152) -> Result<Vec<u8>> {
153    let certificates = X509::stack_from_pem(certificate_bundle).map_err(|e| {
154        Error::ParseError(format!(
155            "failed to parse {key} from TLS secret {namespace}/{secret_name}: {e}"
156        ))
157    })?;
158    let trust_anchor = certificates.last().ok_or_else(|| {
159        Error::MissingData(format!(
160            "no certificates found in {key} from TLS secret {namespace}/{secret_name}"
161        ))
162    })?;
163    trust_anchor.to_pem().map_err(|e| {
164        Error::ParseError(format!(
165            "failed to encode trust anchor from TLS secret {namespace}/{secret_name}: {e}"
166        ))
167    })
168}
169
170fn tls_trust_anchor(secret: &Secret, namespace: &str, secret_name: &str) -> Result<Vec<u8>> {
171    let data = secret.data.as_ref().ok_or_else(|| {
172        Error::MissingData(format!(
173            "failed to get data in TLS secret: {namespace}/{secret_name}"
174        ))
175    })?;
176
177    // cert-manager intentionally keeps the issuing CA separate from tls.crt when it knows the
178    // issuer. Prefer ca.crt so private/self-signed PKIs can be used without requiring the root CA
179    // to be appended to the served certificate chain.
180    if let Some(certificate_bundle) = data.get(CA_CERT_KEY) {
181        return certificate_trust_anchor(
182            &certificate_bundle.0,
183            CA_CERT_KEY,
184            namespace,
185            secret_name,
186        );
187    }
188
189    // Keep the existing behavior for Secrets that only provide tls.crt. The final certificate in
190    // that bundle is treated as the trust anchor, which supports the common leaf+intermediate
191    // layout and preserves compatibility with operator-managed certificates.
192    let certificate_bundle = data.get(TLS_CERT_KEY).ok_or_else(|| {
193        Error::MissingData(format!(
194            "missing {TLS_CERT_KEY} in TLS secret: {namespace}/{secret_name}"
195        ))
196    })?;
197    certificate_trust_anchor(&certificate_bundle.0, TLS_CERT_KEY, namespace, secret_name)
198}
199
200#[derive(Default)]
201pub struct KanidmClients(HashMap<KanidmKey, Arc<KanidmClient>>);
202
203impl KanidmClients {
204    pub fn get(&self, key: &KanidmKey) -> Option<&Arc<KanidmClient>> {
205        self.0.get(key)
206    }
207
208    pub fn insert(
209        &mut self,
210        key: KanidmKey,
211        client: Arc<KanidmClient>,
212    ) -> Option<Arc<KanidmClient>> {
213        self.0.insert(key, client)
214    }
215
216    pub fn remove(&mut self, key: &KanidmKey) -> Option<Arc<KanidmClient>> {
217        let client = self.0.remove(key);
218        self.0.shrink_to_fit();
219        client
220    }
221
222    pub async fn create_client(
223        namespace: &str,
224        name: &str,
225        user: KanidmUser,
226        k_client: Client,
227    ) -> Result<Arc<KanidmClient>> {
228        debug!(namespace, name, "create Kanidm client");
229
230        let secret_api = Api::<Secret>::namespaced(k_client.clone(), namespace);
231        let kanidm_api = Api::<Kanidm>::namespaced(k_client.clone(), namespace);
232        let kanidm = kanidm_api.get(name).await.map_err(|e| {
233            Error::KubeError(
234                format!("failed to get Kanidm: {namespace}/{name}"),
235                Box::new(e),
236            )
237        })?;
238        let tls_secret_name = kanidm.effective_tls_secret_name();
239        let tls_secret = secret_api.get(&tls_secret_name).await.map_err(|e| {
240            Error::KubeError(
241                format!("failed to get TLS secret: {namespace}/{tls_secret_name}"),
242                Box::new(e),
243            )
244        })?;
245        let trust_anchor = tls_trust_anchor(&tls_secret, namespace, &tls_secret_name)?;
246        let mut trust_anchor_file = NamedTempFile::new_in("/tmp").map_err(|e| {
247            Error::ParseError(format!(
248                "failed to create temporary Kanidm trust anchor: {e}"
249            ))
250        })?;
251        trust_anchor_file.write_all(&trust_anchor).map_err(|e| {
252            Error::ParseError(format!(
253                "failed to write temporary Kanidm trust anchor: {e}"
254            ))
255        })?;
256        let trust_anchor_path = trust_anchor_file.path().to_str().ok_or_else(|| {
257            Error::ParseError("temporary Kanidm trust anchor path is not valid UTF-8".to_string())
258        })?;
259
260        let client = KanidmClientBuilder::new()
261            // The operator connects to the Kubernetes Service DNS name while Kanidm's certificate
262            // represents its configured public domain. Verify the certificate chain against the
263            // exact TLS Secret, but do not pretend the Service DNS name is present in the SAN.
264            .enable_native_ca_roots(false)
265            .danger_accept_invalid_hostnames(true)
266            .add_root_certificate_filepath(trust_anchor_path)
267            .map_err(|e| {
268                Error::KanidmClientError(
269                    "failed to configure Kanidm TLS trust".to_string(),
270                    Box::new(e),
271                )
272            })?
273            .address(format!("https://{name}.{namespace}.svc:8443"))
274            .connect_timeout(5)
275            .build()
276            .map_err(|e| {
277                Error::KanidmClientError("failed to build Kanidm client".to_string(), Box::new(e))
278            })?;
279        drop(trust_anchor_file);
280
281        let secret_name = format!("{name}-admin-passwords");
282        let admin_secret = secret_api.get(&secret_name).await.map_err(|e| {
283            Error::KubeError(
284                format!("failed to get secret: {namespace}/{secret_name}"),
285                Box::new(e),
286            )
287        })?;
288        let secret_data = admin_secret.data.ok_or_else(|| {
289            Error::MissingData(format!(
290                "failed to get data in secret: {namespace}/{secret_name}"
291            ))
292        })?;
293
294        let (username, password_key) = match user {
295            KanidmUser::Admin => (ADMIN_USER, ADMIN_PASSWORD_KEY),
296            KanidmUser::IdmAdmin => (IDM_ADMIN_USER, IDM_ADMIN_PASSWORD_KEY),
297        };
298        trace!(
299            namespace,
300            name, secret_name, "fetch Kanidm {username} password"
301        );
302        let password_bytes = secret_data.get(password_key).ok_or_else(|| {
303            Error::MissingData(format!(
304                "missing password for {username} in secret: {namespace}/{secret_name}"
305            ))
306        })?;
307
308        let password = std::str::from_utf8(&password_bytes.0)
309            .map_err(|e| Error::Utf8Error("failed to convert password to string".to_string(), e))?;
310        trace!(
311            namespace,
312            name, "authenticating with new client and user {username}"
313        );
314        client
315            .auth_simple_password(username, password)
316            .await
317            .map_err(|e| {
318                Error::KanidmClientError("client failed to authenticate".to_string(), Box::new(e))
319            })?;
320        Ok(Arc::new(client))
321    }
322}
323
324#[derive(Clone, PartialEq, Hash, Eq)]
325pub struct KanidmKey {
326    pub namespace: String,
327    pub name: String,
328}
329
330#[derive(Clone, PartialEq, Hash, Eq, Debug)]
331pub struct ClientLockKey {
332    pub namespace: String,
333    pub name: String,
334    pub user: KanidmUser,
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340
341    use std::collections::BTreeMap;
342
343    use k8s_openapi::ByteString;
344
345    const LEAF_CERT: &[u8] = b"-----BEGIN CERTIFICATE-----\nMIICGjCCAb+gAwIBAgIUHpT08nqX951u//GR+v8XT79r9SUwCgYIKoZIzj0EAwIw\nRDELMAkGA1UEBhMCQVUxDDAKBgNVBAgMA1FMRDEPMA0GA1UECgwGS2FuaWRtMRYw\nFAYDVQQDDA1LYW5pb3AgRTJFIENBMB4XDTI2MDgwODA2MTkxOVoXDTM2MDgwNTA2\nMTkxOVowRjELMAkGA1UEBhMCQVUxDDAKBgNVBAgMA1FMRDEPMA0GA1UECgwGS2Fu\naWRtMRgwFgYDVQQDDA9pZG0uZXhhbXBsZS5jb20wWTATBgcqhkjOPQIBBggqhkjO\nPQMBBwNCAAQvppDjypVndfeojNUQ4o1r0v/+ry6an9tRRgdaqpAWycCsHHwqzxRG\nvQmGifZQ5dsBle7+3df8YBfXmikDRTEeo4GMMIGJMAkGA1UdEwQCMAAwCwYDVR0P\nBAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMBoGA1UdEQQTMBGCD2lkbS5leGFt\ncGxlLmNvbTAdBgNVHQ4EFgQU08vzk3TPxjTZYSarIJ/X8483q5MwHwYDVR0jBBgw\nFoAU/oFjdY0iaHDwDEsG9K2kLqnKaCswCgYIKoZIzj0EAwIDSQAwRgIhAOAaimcS\nz/IUkI03CYbicyGIQDmXBruN584Uk0wLmOxBAiEA1T6y7HbX3F1oyftd5wABZPDB\nCpREB0kqGwMUURezf4w=\n-----END CERTIFICATE-----\n";
346    const CA_CERT: &[u8] = b"-----BEGIN CERTIFICATE-----\nMIIB3DCCAYOgAwIBAgIUfsv6cZIgDmqN1h4xCuD9CjVRLkgwCgYIKoZIzj0EAwIw\nRDELMAkGA1UEBhMCQVUxDDAKBgNVBAgMA1FMRDEPMA0GA1UECgwGS2FuaWRtMRYw\nFAYDVQQDDA1LYW5pb3AgRTJFIENBMB4XDTI2MDgwODA2MTkxOVoXDTM2MDgwNTA2\nMTkxOVowRDELMAkGA1UEBhMCQVUxDDAKBgNVBAgMA1FMRDEPMA0GA1UECgwGS2Fu\naWRtMRYwFAYDVQQDDA1LYW5pb3AgRTJFIENBMFkwEwYHKoZIzj0CAQYIKoZIzj0D\nAQcDQgAEy84lnsJddCODwnayK4yoqLf6jVGTWIT0mpUh01Ghoq8GrXSrvYGIjxZ0\nYFPEwstiso8GJP15JKXzoGJTUs4a6aNTMFEwHQYDVR0OBBYEFP6BY3WNImhw8AxL\nBvStpC6pymgrMB8GA1UdIwQYMBaAFP6BY3WNImhw8AxLBvStpC6pymgrMA8GA1Ud\nEwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDRwAwRAIgLqbXmVvrEP9zjuMcU0j+R79Z\nFzsMIBS59ZhCJVTa3NACIG2rT7suWcwoc2Wkv7y0AWdpRoZcpLwL0kGNzN5yidHS\n-----END CERTIFICATE-----\n";
347
348    fn tls_secret(entries: &[(&str, &[u8])]) -> Secret {
349        let data: BTreeMap<String, ByteString> = entries
350            .iter()
351            .map(|(key, value)| ((*key).to_string(), ByteString(value.to_vec())))
352            .collect();
353        Secret {
354            data: Some(data),
355            ..Default::default()
356        }
357    }
358
359    #[test]
360    fn tls_trust_anchor_prefers_ca_crt() -> Result<()> {
361        let secret = tls_secret(&[(TLS_CERT_KEY, LEAF_CERT), (CA_CERT_KEY, CA_CERT)]);
362
363        let trust_anchor = tls_trust_anchor(&secret, "default", "kanidm-certificate")?;
364
365        assert_eq!(trust_anchor, CA_CERT);
366        Ok(())
367    }
368
369    #[test]
370    fn tls_trust_anchor_falls_back_to_last_tls_crt_certificate() -> Result<()> {
371        let mut tls_bundle = LEAF_CERT.to_vec();
372        tls_bundle.extend_from_slice(CA_CERT);
373        let secret = tls_secret(&[(TLS_CERT_KEY, &tls_bundle)]);
374
375        let trust_anchor = tls_trust_anchor(&secret, "default", "kanidm-certificate")?;
376
377        assert_eq!(trust_anchor, CA_CERT);
378        Ok(())
379    }
380}