1use std::collections::BTreeMap;
8
9use std::fmt::Debug;
10
11use k8s_openapi::api::core::v1::{ConfigMap, Secret};
12use kaniop_k8s_util::error::Error;
13use kube::{Api, Client, Resource, ResourceExt};
14use openssl::x509::X509;
15use serde::de::DeserializeOwned;
16use sha2::{Digest, Sha256};
17use thiserror::Error;
18
19use crate::crd::{KanidmRadiusServer, KanidmRadiusServerSpec, RadiusCaKind};
20use crate::reconcile::config::{
21 KANIDM_CA_PATH, RADIUS_CA_PATH, RadiusClient, RadiusConfig, RadiusConfigError, RadiusGroup,
22};
23use crate::reconcile::tls::{RadiusTlsError, validate_eap_tls_material};
24
25#[derive(Debug, Error, PartialEq, Eq)]
26pub enum RadiusPreflightError {
27 #[error("RADIUS resource has no namespace")]
28 MissingNamespace,
29 #[error("RADIUS CR has invalid replicas, service, rotation, or Secret references")]
30 InvalidSpec,
31 #[error("cannot read a referenced RADIUS NAS Secret")]
32 NasSecretUnavailable,
33 #[error("RADIUS NAS Secret key is absent or not valid UTF-8")]
34 NasSecretKeyUnavailable,
35 #[error("cannot read a referenced EAP TLS Secret")]
36 TlsSecretUnavailable,
37 #[error("RADIUS EAP TLS Secret is missing required key material")]
38 TlsKeyUnavailable,
39 #[error("cannot read the referenced Kanidm CA Secret or ConfigMap")]
40 KanidmCaUnavailable,
41 #[error("Kanidm CA input contains no valid certificates")]
42 InvalidKanidmCa,
43 #[error(transparent)]
44 Config(#[from] RadiusConfigError),
45 #[error(transparent)]
46 Tls(#[from] RadiusTlsError),
47}
48
49impl RadiusPreflightError {
50 pub fn reason(&self) -> &'static str {
52 match self {
53 Self::MissingNamespace | Self::InvalidSpec => "InvalidSpec",
54 Self::NasSecretUnavailable => "NasSecretNotFound",
55 Self::NasSecretKeyUnavailable => "NasSecretKeyInvalid",
56 Self::TlsSecretUnavailable => "TlsSecretNotFound",
57 Self::TlsKeyUnavailable => "TlsSecretKeyMissing",
58 Self::KanidmCaUnavailable => "KanidmCaNotFound",
59 Self::InvalidKanidmCa => "KanidmCaInvalid",
60 Self::Config(_) => "InvalidConfiguration",
61 Self::Tls(_) => "InvalidTlsMaterial",
62 }
63 }
64}
65
66#[derive(Debug, Error)]
69pub enum InputsError {
70 #[error(transparent)]
71 Invalid(#[from] RadiusPreflightError),
72 #[error(transparent)]
73 Api(Error),
74}
75
76pub struct PreparedRadiusInputs {
80 uri: String,
81 clients: Vec<RadiusClient>,
82 required_groups: Vec<String>,
83 default_vlan: u16,
84 group_vlans: Vec<RadiusGroup>,
85 has_kanidm_ca: bool,
86 has_eap_ca: bool,
87 inputs_digest: String,
88}
89
90pub fn inputs_digest(eap_cert: &[u8], eap_ca: Option<&[u8]>, kanidm_ca: Option<&[u8]>) -> String {
100 let mut hasher = Sha256::new();
101 let fields: [(&[u8], Option<&[u8]>); 3] = [
102 (b"eap-cert", Some(eap_cert)),
103 (b"eap-ca", eap_ca),
104 (b"kanidm-ca", kanidm_ca),
105 ];
106 for (tag, bytes) in fields {
107 hasher.update((tag.len() as u64).to_be_bytes());
108 hasher.update(tag);
109 match bytes {
110 Some(bytes) => {
111 hasher.update([1u8]);
112 hasher.update((bytes.len() as u64).to_be_bytes());
113 hasher.update(bytes);
114 }
115 None => hasher.update([0u8]),
116 }
117 }
118 hex::encode(hasher.finalize())
119}
120
121impl PreparedRadiusInputs {
122 pub fn inputs_digest(&self) -> &str {
124 &self.inputs_digest
125 }
126
127 pub fn config_with_token(&self, token: String) -> Result<RadiusConfig, RadiusConfigError> {
130 let config = RadiusConfig {
131 uri: self.uri.clone(),
132 auth_token: token,
133 ca_path: self.has_kanidm_ca.then(|| KANIDM_CA_PATH.into()),
134 radius_required_groups: self.required_groups.clone(),
135 radius_default_vlan: self.default_vlan,
136 radius_groups: self.group_vlans.clone(),
137 radius_clients: self.clients.clone(),
138 radius_ca_path: self.has_eap_ca.then(|| RADIUS_CA_PATH.into()),
139 };
140 config.validate()?;
141 Ok(config)
142 }
143}
144
145fn validate_spec(spec: &KanidmRadiusServerSpec) -> Result<(), RadiusPreflightError> {
148 if !(1..=100).contains(&spec.replicas)
149 || !(1..=65535).contains(&spec.service.port)
150 || !(1..=365).contains(&spec.token_rotation.period_days)
151 || !matches!(
152 spec.service.type_.as_str(),
153 "ClusterIP" | "NodePort" | "LoadBalancer"
154 )
155 || !matches!(
156 spec.service.external_traffic_policy.as_deref(),
157 None | Some("Cluster") | Some("Local")
158 )
159 || (spec.service.type_ == "ClusterIP" && spec.service.external_traffic_policy.is_some())
160 || spec.radius_tls.secret_ref.name.is_empty()
161 || spec.radius_tls.cert_key.is_empty()
162 || spec.radius_tls.private_key_key.is_empty()
163 || spec.clients.is_empty()
164 || spec.clients.len() > 100
165 || spec.authorization.required_groups.is_empty()
166 || spec.authorization.required_groups.len() > 100
167 || spec
168 .clients
169 .iter()
170 .any(|c| c.shared_secret_ref.name.is_empty() || c.shared_secret_ref.key.is_empty())
171 {
172 return Err(RadiusPreflightError::InvalidSpec);
173 }
174 Ok(())
175}
176
177fn data_key<'a>(secret: &'a Secret, key: &str) -> Result<&'a [u8], RadiusPreflightError> {
178 secret
179 .data
180 .as_ref()
181 .and_then(|data| data.get(key))
182 .map(|data| data.0.as_slice())
183 .ok_or(RadiusPreflightError::TlsKeyUnavailable)
184}
185
186async fn get_input<K>(
189 api: &Api<K>,
190 namespace: &str,
191 name: &str,
192 missing: RadiusPreflightError,
193) -> Result<K, InputsError>
194where
195 K: Resource<DynamicType = ()> + Clone + DeserializeOwned + Debug,
196{
197 match api.get(name).await {
198 Ok(object) => Ok(object),
199 Err(kube::Error::Api(status)) if status.code == 404 => Err(missing.into()),
200 Err(error) => Err(InputsError::Api(Error::kube_error(
201 "get",
202 K::kind(&()),
203 namespace,
204 name,
205 error,
206 ))),
207 }
208}
209
210async fn resolve_nas_clients(
211 api: &Api<Secret>,
212 namespace: &str,
213 spec: &KanidmRadiusServerSpec,
214) -> Result<Vec<RadiusClient>, InputsError> {
215 let mut cache = BTreeMap::<String, Secret>::new();
217 let mut clients = Vec::with_capacity(spec.clients.len());
218 for client in &spec.clients {
219 let secret_ref = &client.shared_secret_ref;
220 if !cache.contains_key(&secret_ref.name) {
221 let secret = get_input(
222 api,
223 namespace,
224 &secret_ref.name,
225 RadiusPreflightError::NasSecretUnavailable,
226 )
227 .await?;
228 cache.insert(secret_ref.name.clone(), secret);
229 }
230 let secret = cache
231 .get(&secret_ref.name)
232 .ok_or(RadiusPreflightError::NasSecretUnavailable)?;
233 let value = secret
234 .data
235 .as_ref()
236 .and_then(|map| map.get(&secret_ref.key))
237 .ok_or(RadiusPreflightError::NasSecretKeyUnavailable)?;
238 let value = String::from_utf8(value.0.clone())
239 .map_err(|_| RadiusPreflightError::NasSecretKeyUnavailable)?;
240 clients.push(RadiusClient {
241 name: client.name.clone(),
242 ipaddr: client.ipaddr.clone(),
243 secret: value,
244 });
245 }
246 Ok(clients)
247}
248
249pub async fn prepare_radius_inputs(
253 client: Client,
254 radius: &KanidmRadiusServer,
255 kanidm_uri: &str,
256) -> Result<PreparedRadiusInputs, InputsError> {
257 validate_spec(&radius.spec)?;
258 let namespace = radius
259 .namespace()
260 .ok_or(RadiusPreflightError::MissingNamespace)?;
261 let secrets: Api<Secret> = Api::namespaced(client.clone(), &namespace);
262
263 let clients = resolve_nas_clients(&secrets, &namespace, &radius.spec).await?;
264 let tls = &radius.spec.radius_tls;
265 let eap = get_input(
266 &secrets,
267 &namespace,
268 &tls.secret_ref.name,
269 RadiusPreflightError::TlsSecretUnavailable,
270 )
271 .await?;
272 let cert = data_key(&eap, &tls.cert_key)?;
273 let key = data_key(&eap, &tls.private_key_key)?;
274 let ca = tls
275 .ca_key
276 .as_deref()
277 .map(|name| data_key(&eap, name))
278 .transpose()?;
279 validate_eap_tls_material(cert, key, ca).map_err(RadiusPreflightError::from)?;
280
281 let mut kanidm_ca_pem: Option<Vec<u8>> = None;
282 let has_kanidm_ca = if let Some(ca_ref) = radius
283 .spec
284 .kanidm_tls
285 .as_ref()
286 .and_then(|tls| tls.ca_bundle_ref.as_ref())
287 {
288 if ca_ref.name.is_empty() || ca_ref.key.is_empty() {
289 return Err(RadiusPreflightError::InvalidSpec.into());
290 }
291 let pem = match ca_ref.kind {
292 RadiusCaKind::ConfigMap => {
293 let api: Api<ConfigMap> = Api::namespaced(client.clone(), &namespace);
294 let config_map = get_input(
295 &api,
296 &namespace,
297 &ca_ref.name,
298 RadiusPreflightError::KanidmCaUnavailable,
299 )
300 .await?;
301 config_map
302 .data
303 .as_ref()
304 .and_then(|data| data.get(&ca_ref.key))
305 .map(|value| value.as_bytes().to_vec())
306 .ok_or(RadiusPreflightError::InvalidKanidmCa)?
307 }
308 RadiusCaKind::Secret => {
309 let secret = get_input(
310 &secrets,
311 &namespace,
312 &ca_ref.name,
313 RadiusPreflightError::KanidmCaUnavailable,
314 )
315 .await?;
316 secret
317 .data
318 .as_ref()
319 .and_then(|data| data.get(&ca_ref.key))
320 .map(|value| value.0.clone())
321 .ok_or(RadiusPreflightError::InvalidKanidmCa)?
322 }
323 };
324 let certificates =
325 X509::stack_from_pem(&pem).map_err(|_| RadiusPreflightError::InvalidKanidmCa)?;
326 if certificates.is_empty() {
327 return Err(RadiusPreflightError::InvalidKanidmCa.into());
328 }
329 kanidm_ca_pem = Some(pem);
330 true
331 } else {
332 false
333 };
334
335 let default_vlan = u16::try_from(radius.spec.authorization.default_vlan)
336 .map_err(|_| RadiusPreflightError::Config(RadiusConfigError::InvalidVlan))?;
337 let group_vlans: Vec<RadiusGroup> = radius
338 .spec
339 .authorization
340 .group_vlans
341 .iter()
342 .map(|group| {
343 u16::try_from(group.vlan)
344 .map(|vlan| RadiusGroup {
345 spn: group.group.clone(),
346 vlan,
347 })
348 .map_err(|_| RadiusPreflightError::Config(RadiusConfigError::InvalidVlan))
349 })
350 .collect::<Result<_, _>>()?;
351
352 let prepared = PreparedRadiusInputs {
353 uri: kanidm_uri.into(),
354 clients,
355 required_groups: radius.spec.authorization.required_groups.clone(),
356 default_vlan,
357 group_vlans,
358 has_kanidm_ca,
359 has_eap_ca: ca.is_some(),
360 inputs_digest: inputs_digest(cert, ca, kanidm_ca_pem.as_deref()),
361 };
362 prepared
365 .config_with_token("preflight-only".into())
366 .map_err(RadiusPreflightError::from)?;
367 Ok(prepared)
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373 use crate::crd::KanidmRadiusServerSpec;
374
375 fn spec() -> KanidmRadiusServerSpec {
376 serde_json::from_value(serde_json::json!({
377 "kanidmRef": {"name": "idm"},
378 "authorization": {"requiredGroups": ["radius_access_allowed@idm.example.com"]},
379 "clients": [
380 {"name": "nas1", "ipaddr": "192.0.2.1", "sharedSecretRef": {"name": "nas-secret", "key": "nas1"}}
381 ],
382 "radiusTls": {"secretRef": {"name": "eap-tls"}}
383 })).unwrap()
384 }
385
386 #[test]
387 fn rejects_invalid_spec_before_reading_any_secrets() {
388 let mut spec = spec();
389 assert_eq!(spec.token_rotation.period_days, 90);
390 assert_eq!(validate_spec(&spec), Ok(()));
391 spec.radius_tls.secret_ref.name.clear();
392 assert_eq!(validate_spec(&spec), Err(RadiusPreflightError::InvalidSpec));
393 spec.radius_tls.secret_ref.name = "eap-tls".into();
394 spec.service.type_ = "LoadBalancer".into();
395 spec.service.external_traffic_policy = Some("Local".into());
396 assert_eq!(validate_spec(&spec), Ok(()));
397 spec.service.type_ = "ClusterIP".into();
398 assert_eq!(validate_spec(&spec), Err(RadiusPreflightError::InvalidSpec));
399 }
400
401 #[test]
402 fn token_rotation_period_must_be_1_to_365_days() {
403 let mut spec = spec();
404 spec.token_rotation.enabled = true;
405 for days in [1, 90, 365] {
406 spec.token_rotation.period_days = days;
407 assert_eq!(validate_spec(&spec), Ok(()), "{days}");
408 }
409 for days in [0, 366, u32::MAX] {
412 spec.token_rotation.period_days = days;
413 assert_eq!(
414 validate_spec(&spec),
415 Err(RadiusPreflightError::InvalidSpec),
416 "{days}"
417 );
418 }
419 }
420
421 #[test]
422 fn missing_tls_key_is_not_reported_with_data() {
423 let secret = Secret::default();
424 assert_eq!(
425 data_key(&secret, "tls.key"),
426 Err(RadiusPreflightError::TlsKeyUnavailable)
427 );
428 }
429
430 #[test]
431 fn inputs_digest_follows_public_material_only() {
432 let base = inputs_digest(b"cert", Some(b"eap-ca"), Some(b"kanidm-ca"));
433 assert_eq!(
434 base,
435 inputs_digest(b"cert", Some(b"eap-ca"), Some(b"kanidm-ca"))
436 );
437 assert_ne!(
439 base,
440 inputs_digest(b"cert2", Some(b"eap-ca"), Some(b"kanidm-ca"))
441 );
442 assert_ne!(
443 base,
444 inputs_digest(b"cert\n", Some(b"eap-ca"), Some(b"kanidm-ca"))
445 );
446 assert_ne!(
447 base,
448 inputs_digest(b"cert", Some(b"eap-ca2"), Some(b"kanidm-ca"))
449 );
450 assert_ne!(
451 base,
452 inputs_digest(b"cert", Some(b"eap-ca"), Some(b"kanidm-ca2"))
453 );
454 }
455
456 #[test]
457 fn inputs_digest_distinguishes_absent_empty_and_swapped_inputs() {
458 let none = inputs_digest(b"cert", None, None);
459 assert_ne!(none, inputs_digest(b"cert", Some(b""), None));
460 assert_ne!(
461 inputs_digest(b"cert", Some(b"a"), None),
462 inputs_digest(b"cert", None, Some(b"a"))
463 );
464 assert_ne!(
465 inputs_digest(b"ab", Some(b"c"), None),
466 inputs_digest(b"a", Some(b"bc"), None)
467 );
468 assert_eq!(none.len(), 64);
469 }
470}