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";
145
146fn tls_trust_anchor(secret: &Secret, namespace: &str, secret_name: &str) -> Result<Vec<u8>> {
147    let data = secret.data.as_ref().ok_or_else(|| {
148        Error::MissingData(format!(
149            "failed to get data in TLS secret: {namespace}/{secret_name}"
150        ))
151    })?;
152    let certificate_bundle = data.get(TLS_CERT_KEY).ok_or_else(|| {
153        Error::MissingData(format!(
154            "missing {TLS_CERT_KEY} in TLS secret: {namespace}/{secret_name}"
155        ))
156    })?;
157    let certificates = X509::stack_from_pem(&certificate_bundle.0).map_err(|e| {
158        Error::ParseError(format!(
159            "failed to parse {TLS_CERT_KEY} from TLS secret {namespace}/{secret_name}: {e}"
160        ))
161    })?;
162    let trust_anchor = certificates.last().ok_or_else(|| {
163        Error::MissingData(format!(
164            "no certificates found in {TLS_CERT_KEY} from TLS secret {namespace}/{secret_name}"
165        ))
166    })?;
167    trust_anchor.to_pem().map_err(|e| {
168        Error::ParseError(format!(
169            "failed to encode trust anchor from TLS secret {namespace}/{secret_name}: {e}"
170        ))
171    })
172}
173
174#[derive(Default)]
175pub struct KanidmClients(HashMap<KanidmKey, Arc<KanidmClient>>);
176
177impl KanidmClients {
178    pub fn get(&self, key: &KanidmKey) -> Option<&Arc<KanidmClient>> {
179        self.0.get(key)
180    }
181
182    pub fn insert(
183        &mut self,
184        key: KanidmKey,
185        client: Arc<KanidmClient>,
186    ) -> Option<Arc<KanidmClient>> {
187        self.0.insert(key, client)
188    }
189
190    pub fn remove(&mut self, key: &KanidmKey) -> Option<Arc<KanidmClient>> {
191        let client = self.0.remove(key);
192        self.0.shrink_to_fit();
193        client
194    }
195
196    pub async fn create_client(
197        namespace: &str,
198        name: &str,
199        user: KanidmUser,
200        k_client: Client,
201    ) -> Result<Arc<KanidmClient>> {
202        debug!(namespace, name, "create Kanidm client");
203
204        let secret_api = Api::<Secret>::namespaced(k_client.clone(), namespace);
205        let kanidm_api = Api::<Kanidm>::namespaced(k_client.clone(), namespace);
206        let kanidm = kanidm_api.get(name).await.map_err(|e| {
207            Error::KubeError(
208                format!("failed to get Kanidm: {namespace}/{name}"),
209                Box::new(e),
210            )
211        })?;
212        let tls_secret_name = kanidm.effective_tls_secret_name();
213        let tls_secret = secret_api.get(&tls_secret_name).await.map_err(|e| {
214            Error::KubeError(
215                format!("failed to get TLS secret: {namespace}/{tls_secret_name}"),
216                Box::new(e),
217            )
218        })?;
219        let trust_anchor = tls_trust_anchor(&tls_secret, namespace, &tls_secret_name)?;
220        let mut trust_anchor_file = NamedTempFile::new_in("/tmp").map_err(|e| {
221            Error::ParseError(format!(
222                "failed to create temporary Kanidm trust anchor: {e}"
223            ))
224        })?;
225        trust_anchor_file.write_all(&trust_anchor).map_err(|e| {
226            Error::ParseError(format!(
227                "failed to write temporary Kanidm trust anchor: {e}"
228            ))
229        })?;
230        let trust_anchor_path = trust_anchor_file.path().to_str().ok_or_else(|| {
231            Error::ParseError("temporary Kanidm trust anchor path is not valid UTF-8".to_string())
232        })?;
233
234        let client = KanidmClientBuilder::new()
235            // The operator connects to the Kubernetes Service DNS name while Kanidm's certificate
236            // represents its configured public domain. Verify the certificate chain against the
237            // exact TLS Secret, but do not pretend the Service DNS name is present in the SAN.
238            .enable_native_ca_roots(false)
239            .danger_accept_invalid_hostnames(true)
240            .add_root_certificate_filepath(trust_anchor_path)
241            .map_err(|e| {
242                Error::KanidmClientError(
243                    "failed to configure Kanidm TLS trust".to_string(),
244                    Box::new(e),
245                )
246            })?
247            .address(format!("https://{name}.{namespace}.svc:8443"))
248            .connect_timeout(5)
249            .build()
250            .map_err(|e| {
251                Error::KanidmClientError("failed to build Kanidm client".to_string(), Box::new(e))
252            })?;
253        drop(trust_anchor_file);
254
255        let secret_name = format!("{name}-admin-passwords");
256        let admin_secret = secret_api.get(&secret_name).await.map_err(|e| {
257            Error::KubeError(
258                format!("failed to get secret: {namespace}/{secret_name}"),
259                Box::new(e),
260            )
261        })?;
262        let secret_data = admin_secret.data.ok_or_else(|| {
263            Error::MissingData(format!(
264                "failed to get data in secret: {namespace}/{secret_name}"
265            ))
266        })?;
267
268        let (username, password_key) = match user {
269            KanidmUser::Admin => (ADMIN_USER, ADMIN_PASSWORD_KEY),
270            KanidmUser::IdmAdmin => (IDM_ADMIN_USER, IDM_ADMIN_PASSWORD_KEY),
271        };
272        trace!(
273            namespace,
274            name, secret_name, "fetch Kanidm {username} password"
275        );
276        let password_bytes = secret_data.get(password_key).ok_or_else(|| {
277            Error::MissingData(format!(
278                "missing password for {username} in secret: {namespace}/{secret_name}"
279            ))
280        })?;
281
282        let password = std::str::from_utf8(&password_bytes.0)
283            .map_err(|e| Error::Utf8Error("failed to convert password to string".to_string(), e))?;
284        trace!(
285            namespace,
286            name, "authenticating with new client and user {username}"
287        );
288        client
289            .auth_simple_password(username, password)
290            .await
291            .map_err(|e| {
292                Error::KanidmClientError("client failed to authenticate".to_string(), Box::new(e))
293            })?;
294        Ok(Arc::new(client))
295    }
296}
297
298#[derive(Clone, PartialEq, Hash, Eq)]
299pub struct KanidmKey {
300    pub namespace: String,
301    pub name: String,
302}
303
304#[derive(Clone, PartialEq, Hash, Eq, Debug)]
305pub struct ClientLockKey {
306    pub namespace: String,
307    pub name: String,
308    pub user: KanidmUser,
309}