kaniop_operator/controller/
kanidm.rs

1use crate::{
2    crd::KanidmRef,
3    error::{Error, Result},
4    kanidm::{
5        crd::Kanidm,
6        reconcile::secret::{
7            ADMIN_PASSWORD_KEY, ADMIN_USER, IDM_ADMIN_PASSWORD_KEY, IDM_ADMIN_USER,
8        },
9    },
10};
11
12use kanidm_client::{KanidmClient, KanidmClientBuilder};
13
14use std::collections::HashMap;
15use std::fmt::Debug;
16use std::sync::Arc;
17
18use k8s_openapi::api::core::v1::{Namespace, Secret};
19use k8s_openapi::apimachinery::pkg::apis::meta::v1::LabelSelector;
20use kube::ResourceExt;
21use kube::api::Api;
22use kube::client::Client;
23use kube::core::{Selector, SelectorExt};
24use kube::runtime::reflector::Store;
25use serde::Serialize;
26use tracing::{debug, trace};
27
28pub trait KanidmResource: ResourceExt {
29    /// Returns the KanidmRef from the resource's spec
30    fn kanidm_ref_spec(&self) -> &KanidmRef;
31
32    /// Returns the namespace selector field for this resource type from the Kanidm spec
33    fn get_namespace_selector(kanidm: &Kanidm) -> &Option<LabelSelector>;
34
35    /// Returns the name of the referenced Kanidm resource
36    fn kanidm_name(&self) -> String {
37        self.kanidm_ref_spec().name.clone()
38    }
39
40    /// Returns the namespace of the referenced Kanidm resource
41    /// Uses the explicitly specified namespace in kanidm_ref, or falls back to the resource's own namespace
42    fn kanidm_namespace(&self) -> String {
43        self.kanidm_ref_spec()
44            .namespace
45            .clone()
46            // safe unwrap: all resources implementing this trait are namespaced scoped
47            .unwrap_or_else(|| self.namespace().unwrap())
48    }
49
50    /// Returns a string representation of the Kanidm reference in "namespace/name" format
51    fn kanidm_ref(&self) -> String {
52        format!("{}/{}", self.kanidm_namespace(), self.kanidm_name())
53    }
54}
55
56/// Generic function to check if a resource is watched based on namespace selectors
57///
58/// This function implements the common logic for checking whether a resource should be
59/// reconciled based on the namespace selector configuration in the referenced Kanidm resource.
60pub fn is_resource_watched<T>(
61    resource: &T,
62    kanidm: &Kanidm,
63    namespace_store: &Store<Namespace>,
64) -> bool
65where
66    T: KanidmResource,
67{
68    // safe unwrap: all resources are namespaced
69    let namespace = resource.namespace().unwrap();
70    trace!(msg = "check if resource is watched");
71
72    let namespace_selector = if let Some(selector) = T::get_namespace_selector(kanidm) {
73        selector
74    } else {
75        trace!(msg = "no namespace selector found, defaulting to current namespace");
76        // A null label selector (default value) matches the current namespace only
77        return kanidm.namespace().unwrap() == namespace;
78    };
79
80    let selector: Selector = if let Ok(s) = namespace_selector.clone().try_into() {
81        s
82    } else {
83        trace!(msg = "failed to parse namespace selector, defaulting to current namespace");
84        return kanidm.namespace().unwrap() == namespace;
85    };
86
87    trace!(msg = "namespace selector", ?selector);
88    namespace_store
89        .state()
90        .iter()
91        .filter(|n| selector.matches(n.metadata.labels.as_ref().unwrap_or(&Default::default())))
92        .any(|n| n.name_any() == namespace)
93}
94
95#[derive(Serialize, Clone, Debug)]
96pub enum KanidmUser {
97    IdmAdmin,
98    Admin,
99}
100
101#[derive(Default)]
102pub struct KanidmClients(HashMap<KanidmKey, Arc<KanidmClient>>);
103
104impl KanidmClients {
105    pub fn get(&self, key: &KanidmKey) -> Option<&Arc<KanidmClient>> {
106        self.0.get(key)
107    }
108
109    pub fn insert(
110        &mut self,
111        key: KanidmKey,
112        client: Arc<KanidmClient>,
113    ) -> Option<Arc<KanidmClient>> {
114        self.0.insert(key, client)
115    }
116
117    pub async fn create_client(
118        namespace: &str,
119        name: &str,
120        user: KanidmUser,
121        k_client: Client,
122    ) -> Result<Arc<KanidmClient>> {
123        debug!(msg = "create Kanidm client", namespace, name);
124
125        let client = KanidmClientBuilder::new()
126            .danger_accept_invalid_certs(true)
127            // TODO: ensure that URL matches the service name and port programmatically
128            // using Kanidm object from cache is the unique way
129            .address(format!("https://{name}.{namespace}.svc:8443"))
130            .connect_timeout(5)
131            .build()
132            .map_err(|e| {
133                Error::KanidmClientError("failed to build Kanidm client".to_string(), Box::new(e))
134            })?;
135
136        let secret_api = Api::<Secret>::namespaced(k_client.clone(), namespace);
137        let secret_name = format!("{name}-admin-passwords");
138        let admin_secret = secret_api.get(&secret_name).await.map_err(|e| {
139            Error::KubeError(
140                format!("failed to get secret: {namespace}/{secret_name}"),
141                Box::new(e),
142            )
143        })?;
144        let secret_data = admin_secret.data.ok_or_else(|| {
145            Error::MissingData(format!(
146                "failed to get data in secret: {namespace}/{secret_name}"
147            ))
148        })?;
149
150        let (username, password_key) = match user {
151            KanidmUser::Admin => (ADMIN_USER, ADMIN_PASSWORD_KEY),
152            KanidmUser::IdmAdmin => (IDM_ADMIN_USER, IDM_ADMIN_PASSWORD_KEY),
153        };
154        trace!(
155            msg = format!("fetch Kanidm {username} password"),
156            namespace, name, secret_name
157        );
158        let password_bytes = secret_data.get(password_key).ok_or_else(|| {
159            Error::MissingData(format!(
160                "missing password for {username} in secret: {namespace}/{secret_name}"
161            ))
162        })?;
163
164        let password = std::str::from_utf8(&password_bytes.0)
165            .map_err(|e| Error::Utf8Error("failed to convert password to string".to_string(), e))?;
166        trace!(
167            msg = format!("authenticating with new client and user {username}"),
168            namespace, name
169        );
170        client
171            .auth_simple_password(username, password)
172            .await
173            .map_err(|e| {
174                Error::KanidmClientError("client failed to authenticate".to_string(), Box::new(e))
175            })?;
176        Ok(Arc::new(client))
177    }
178}
179
180#[derive(Clone, PartialEq, Hash, Eq)]
181pub struct KanidmKey {
182    pub namespace: String,
183    pub name: String,
184}