kaniop_operator/controller/
kanidm.rs

1use crate::{
2    error::{Error, Result},
3    kanidm::reconcile::secret::{
4        ADMIN_PASSWORD_KEY, ADMIN_USER, IDM_ADMIN_PASSWORD_KEY, IDM_ADMIN_USER,
5    },
6};
7
8use kanidm_client::{KanidmClient, KanidmClientBuilder};
9
10use std::collections::HashMap;
11use std::fmt::Debug;
12use std::sync::Arc;
13
14use k8s_openapi::api::core::v1::Secret;
15use kube::api::Api;
16use kube::client::Client;
17use serde::Serialize;
18use tracing::{debug, trace};
19
20pub trait KanidmResource {
21    fn kanidm_name(&self) -> String;
22    fn kanidm_namespace(&self) -> String;
23    fn kanidm_ref(&self) -> String {
24        format!("{}/{}", self.kanidm_namespace(), self.kanidm_name())
25    }
26}
27
28#[derive(Serialize, Clone, Debug)]
29pub enum KanidmUser {
30    IdmAdmin,
31    Admin,
32}
33
34#[derive(Default)]
35pub struct KanidmClients(HashMap<KanidmKey, Arc<KanidmClient>>);
36
37impl KanidmClients {
38    pub fn get(&self, key: &KanidmKey) -> Option<&Arc<KanidmClient>> {
39        self.0.get(key)
40    }
41
42    pub fn insert(
43        &mut self,
44        key: KanidmKey,
45        client: Arc<KanidmClient>,
46    ) -> Option<Arc<KanidmClient>> {
47        self.0.insert(key, client)
48    }
49
50    pub async fn create_client(
51        namespace: &str,
52        name: &str,
53        user: KanidmUser,
54        k_client: Client,
55    ) -> Result<Arc<KanidmClient>> {
56        debug!(msg = "create Kanidm client", namespace, name);
57
58        let client = KanidmClientBuilder::new()
59            .danger_accept_invalid_certs(true)
60            // TODO: ensure that URL matches the service name and port programmatically
61            // using Kanidm object from cache is the unique way
62            .address(format!("https://{name}.{namespace}.svc:8443"))
63            .connect_timeout(5)
64            .build()
65            .map_err(|e| {
66                Error::KanidmClientError("failed to build Kanidm client".to_string(), Box::new(e))
67            })?;
68
69        let secret_api = Api::<Secret>::namespaced(k_client.clone(), namespace);
70        let secret_name = format!("{name}-admin-passwords");
71        let admin_secret = secret_api.get(&secret_name).await.map_err(|e| {
72            Error::KubeError(
73                format!("failed to get secret: {namespace}/{secret_name}"),
74                Box::new(e),
75            )
76        })?;
77        let secret_data = admin_secret.data.ok_or_else(|| {
78            Error::MissingData(format!(
79                "failed to get data in secret: {namespace}/{secret_name}"
80            ))
81        })?;
82
83        let (username, password_key) = match user {
84            KanidmUser::Admin => (ADMIN_USER, ADMIN_PASSWORD_KEY),
85            KanidmUser::IdmAdmin => (IDM_ADMIN_USER, IDM_ADMIN_PASSWORD_KEY),
86        };
87        trace!(
88            msg = format!("fetch Kanidm {username} password"),
89            namespace, name, secret_name
90        );
91        let password_bytes = secret_data.get(password_key).ok_or_else(|| {
92            Error::MissingData(format!(
93                "missing password for {username} in secret: {namespace}/{secret_name}"
94            ))
95        })?;
96
97        let password = std::str::from_utf8(&password_bytes.0)
98            .map_err(|e| Error::Utf8Error("failed to convert password to string".to_string(), e))?;
99        trace!(
100            msg = format!("authenticating with new client and user {username}"),
101            namespace, name
102        );
103        client
104            .auth_simple_password(username, password)
105            .await
106            .map_err(|e| {
107                Error::KanidmClientError("client failed to authenticate".to_string(), Box::new(e))
108            })?;
109        Ok(Arc::new(client))
110    }
111}
112
113#[derive(Clone, PartialEq, Hash, Eq)]
114pub struct KanidmKey {
115    pub namespace: String,
116    pub name: String,
117}