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::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, PartialEq, Eq, Hash)]
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 fn remove(&mut self, key: &KanidmKey) -> Option<Arc<KanidmClient>> {
118        let client = self.0.remove(key);
119        self.0.shrink_to_fit();
120        client
121    }
122
123    pub async fn create_client(
124        namespace: &str,
125        name: &str,
126        user: KanidmUser,
127        k_client: Client,
128    ) -> Result<Arc<KanidmClient>> {
129        debug!(msg = "create Kanidm client", namespace, name);
130
131        let client = KanidmClientBuilder::new()
132            .danger_accept_invalid_certs(true)
133            // TODO: ensure that URL matches the service name and port programmatically
134            // using Kanidm object from cache is the unique way
135            .address(format!("https://{name}.{namespace}.svc:8443"))
136            .connect_timeout(5)
137            .build()
138            .map_err(|e| {
139                Error::KanidmClientError("failed to build Kanidm client".to_string(), Box::new(e))
140            })?;
141
142        let secret_api = Api::<Secret>::namespaced(k_client.clone(), namespace);
143        let secret_name = format!("{name}-admin-passwords");
144        let admin_secret = secret_api.get(&secret_name).await.map_err(|e| {
145            Error::KubeError(
146                format!("failed to get secret: {namespace}/{secret_name}"),
147                Box::new(e),
148            )
149        })?;
150        let secret_data = admin_secret.data.ok_or_else(|| {
151            Error::MissingData(format!(
152                "failed to get data in secret: {namespace}/{secret_name}"
153            ))
154        })?;
155
156        let (username, password_key) = match user {
157            KanidmUser::Admin => (ADMIN_USER, ADMIN_PASSWORD_KEY),
158            KanidmUser::IdmAdmin => (IDM_ADMIN_USER, IDM_ADMIN_PASSWORD_KEY),
159        };
160        trace!(
161            msg = format!("fetch Kanidm {username} password"),
162            namespace, name, secret_name
163        );
164        let password_bytes = secret_data.get(password_key).ok_or_else(|| {
165            Error::MissingData(format!(
166                "missing password for {username} in secret: {namespace}/{secret_name}"
167            ))
168        })?;
169
170        let password = std::str::from_utf8(&password_bytes.0)
171            .map_err(|e| Error::Utf8Error("failed to convert password to string".to_string(), e))?;
172        trace!(
173            msg = format!("authenticating with new client and user {username}"),
174            namespace, name
175        );
176        client
177            .auth_simple_password(username, password)
178            .await
179            .map_err(|e| {
180                Error::KanidmClientError("client failed to authenticate".to_string(), Box::new(e))
181            })?;
182        Ok(Arc::new(client))
183    }
184}
185
186#[derive(Clone, PartialEq, Hash, Eq)]
187pub struct KanidmKey {
188    pub namespace: String,
189    pub name: String,
190}
191
192#[derive(Clone, PartialEq, Hash, Eq, Debug)]
193pub struct ClientLockKey {
194    pub namespace: String,
195    pub name: String,
196    pub user: KanidmUser,
197}