kaniop_operator/controller/
kanidm.rs1use 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 fn kanidm_ref_spec(&self) -> &KanidmRef;
31
32 fn get_namespace_selector(kanidm: &Kanidm) -> &Option<LabelSelector>;
34
35 fn kanidm_name(&self) -> String {
37 self.kanidm_ref_spec().name.clone()
38 }
39
40 fn kanidm_namespace(&self) -> String {
43 self.kanidm_ref_spec()
44 .namespace
45 .clone()
46 .unwrap_or_else(|| self.namespace().unwrap())
48 }
49
50 fn kanidm_ref(&self) -> String {
52 format!("{}/{}", self.kanidm_namespace(), self.kanidm_name())
53 }
54}
55
56pub fn is_resource_watched<T>(
61 resource: &T,
62 kanidm: &Kanidm,
63 namespace_store: &Store<Namespace>,
64) -> bool
65where
66 T: KanidmResource,
67{
68 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 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 .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}