Skip to main content

kaniop_radius/reconcile/
workload.rs

1//! Kubernetes workload builders for an independent Kanidm RADIUS endpoint.
2//!
3//! Pure construction only: reconciliation must verify parent UID ownership,
4//! validate referenced inputs, and preserve last-good credentials before apply.
5//! This does not mint Kanidm tokens or adopt existing Kubernetes objects.
6
7use std::collections::BTreeMap;
8
9use k8s_openapi::ByteString;
10use k8s_openapi::api::apps::v1::{
11    Deployment, DeploymentSpec, DeploymentStrategy, RollingUpdateDeployment,
12};
13use k8s_openapi::api::core::v1::{
14    Affinity, Capabilities, ConfigMapProjection, Container, ContainerPort, ExecAction, KeyToPath,
15    Lifecycle, LifecycleHandler, PodSecurityContext, PodSpec, PodTemplateSpec, Probe,
16    ProjectedVolumeSource, ResourceRequirements, SeccompProfile, Secret, SecretProjection,
17    SecurityContext, Service, ServicePort, ServiceSpec, Toleration, TopologySpreadConstraint,
18    Volume, VolumeMount, VolumeProjection,
19};
20use k8s_openapi::apimachinery::pkg::apis::meta::v1::{LabelSelector, ObjectMeta, OwnerReference};
21use k8s_openapi::apimachinery::pkg::util::intstr::IntOrString;
22use kube::{Resource, ResourceExt};
23use sha2::{Digest, Sha256};
24use thiserror::Error;
25
26use crate::crd::{KanidmRadiusServer, RadiusCaKind};
27use crate::reconcile::config::{RadiusConfig, RadiusConfigError};
28use crate::reconcile::image::{RADIUS_GID, RADIUS_UID};
29use crate::reconcile::meta::{
30    ANNOTATION_INPUTS_DIGEST, ANNOTATION_ROTATION_REQUEST, ANNOTATION_TOKEN_ID, COMPONENT,
31    LABEL_MANAGED_BY, LABEL_NAME, LABEL_UID, MANAGED_BY, SECRET_KEY_CONFIG, SECRET_KEY_TOKEN,
32};
33
34/// Longest CR name that keeps `<name>-<hash>` a valid 63-character DNS label.
35pub const MAX_RADIUS_NAME_LEN: usize = 52;
36/// Hex characters of the config digest used in the config Secret name.
37pub const CONFIG_HASH_LEN: usize = 10;
38/// Old ReplicaSets kept for rollback. One is enough: rotation safety is
39/// computed from live pods and ReplicaSets, not from history.
40const REVISION_HISTORY_LIMIT: i32 = 1;
41/// Seconds a terminating pod keeps serving before radiusd gets SIGTERM.
42/// kube-proxy removes a pod from the Service a moment after it starts
43/// terminating; UDP requests sent in between would be silently lost, which a
44/// rollout with `maxUnavailable: 0` must not cause.
45pub const PRE_STOP_SLEEP_SECONDS: i32 = 10;
46
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub enum RadiusCaSource {
49    Secret { name: String, key: String },
50    ConfigMap { name: String, key: String },
51}
52
53#[derive(Clone, Debug, PartialEq, Eq)]
54pub enum RadiusServiceExposure {
55    ClusterIP,
56    NodePort {
57        external_traffic_policy: Option<String>,
58    },
59    LoadBalancer {
60        external_traffic_policy: Option<String>,
61    },
62}
63
64impl RadiusServiceExposure {
65    /// Parse the CR's Service type and traffic policy. The policy only applies
66    /// to NodePort and LoadBalancer and is ignored on ClusterIP; the CRD and
67    /// input validation already reject that combination.
68    pub fn from_spec(
69        service_type: &str,
70        external_traffic_policy: Option<String>,
71    ) -> Result<Self, RadiusWorkloadError> {
72        match service_type {
73            "ClusterIP" => Ok(Self::ClusterIP),
74            "NodePort" => Ok(Self::NodePort {
75                external_traffic_policy,
76            }),
77            "LoadBalancer" => Ok(Self::LoadBalancer {
78                external_traffic_policy,
79            }),
80            _ => Err(RadiusWorkloadError::InvalidServiceType),
81        }
82    }
83
84    /// The Kubernetes `Service.spec.type` string.
85    pub fn service_type(&self) -> &'static str {
86        match self {
87            Self::ClusterIP => "ClusterIP",
88            Self::NodePort { .. } => "NodePort",
89            Self::LoadBalancer { .. } => "LoadBalancer",
90        }
91    }
92
93    fn external_traffic_policy(&self) -> Option<&str> {
94        match self {
95            Self::ClusterIP => None,
96            Self::NodePort {
97                external_traffic_policy,
98            }
99            | Self::LoadBalancer {
100                external_traffic_policy,
101            } => external_traffic_policy.as_deref(),
102        }
103    }
104}
105
106#[derive(Clone, Debug)]
107pub struct RadiusWorkload {
108    pub name: String,
109    pub namespace: String,
110    /// The owner must be the RADIUS CR itself, not the referenced Kanidm CR.
111    pub owner: OwnerReference,
112    pub image: String,
113    pub replicas: i32,
114    pub configuration_secret: String,
115    /// Kanidm token id the config Secret was rendered with (an id, never the
116    /// bearer). Recorded on the pod template so observers can tell which
117    /// token each pod uses.
118    pub token_id: String,
119    /// Digest of the public certificate and CA bytes (see
120    /// `reconcile::inputs::inputs_digest`); changing it rolls the pods.
121    pub inputs_digest: String,
122    pub eap_tls_secret: String,
123    pub eap_certificate_key: String,
124    pub eap_private_key_key: String,
125    pub eap_ca_key: Option<String>,
126    pub kanidm_ca: Option<RadiusCaSource>,
127    pub exposure: RadiusServiceExposure,
128    pub service_port: i32,
129    pub service_annotations: BTreeMap<String, String>,
130    pub resources: Option<ResourceRequirements>,
131    pub node_selector: Option<BTreeMap<String, String>>,
132    pub affinity: Option<Affinity>,
133    pub tolerations: Option<Vec<Toleration>>,
134    pub topology_spread_constraints: Option<Vec<TopologySpreadConstraint>>,
135}
136
137#[derive(Debug, Error, PartialEq, Eq)]
138pub enum RadiusWorkloadError {
139    #[error(
140        "RADIUS resource name, namespace, owner UID, image, token id, inputs digest or config Secret is missing"
141    )]
142    MissingResourceIdentity,
143    #[error("RADIUS Service type must be ClusterIP, NodePort or LoadBalancer")]
144    InvalidServiceType,
145    #[error("RADIUS resource name must be at most 52 characters to derive generated names")]
146    ResourceNameTooLong,
147    #[error(transparent)]
148    InvalidConfiguration(#[from] RadiusConfigError),
149}
150
151/// Derive the entire desired workload from the CR, the immutable config
152/// Secret and the token id it was rendered with. Never derive owner identity
153/// from the reusable resource name.
154pub fn build_workload(
155    radius: &KanidmRadiusServer,
156    image: String,
157    config_secret: &str,
158    token_id: &str,
159    inputs_digest: &str,
160) -> Result<RadiusWorkload, RadiusWorkloadError> {
161    let namespace = radius
162        .namespace()
163        .ok_or(RadiusWorkloadError::MissingResourceIdentity)?;
164    let owner = radius
165        .controller_owner_ref(&())
166        .ok_or(RadiusWorkloadError::MissingResourceIdentity)?;
167    let kanidm_ca = radius
168        .spec
169        .kanidm_tls
170        .as_ref()
171        .and_then(|tls| tls.ca_bundle_ref.as_ref())
172        .map(|ca| match ca.kind {
173            RadiusCaKind::ConfigMap => RadiusCaSource::ConfigMap {
174                name: ca.name.clone(),
175                key: ca.key.clone(),
176            },
177            RadiusCaKind::Secret => RadiusCaSource::Secret {
178                name: ca.name.clone(),
179                key: ca.key.clone(),
180            },
181        });
182    let policy = radius.spec.service.external_traffic_policy.clone();
183    let exposure = RadiusServiceExposure::from_spec(&radius.spec.service.type_, policy)?;
184    let tls = &radius.spec.radius_tls;
185    let workload = RadiusWorkload {
186        name: radius.name_any(),
187        namespace,
188        owner,
189        image,
190        replicas: radius.spec.replicas,
191        configuration_secret: config_secret.to_string(),
192        token_id: token_id.to_string(),
193        inputs_digest: inputs_digest.to_string(),
194        eap_tls_secret: tls.secret_ref.name.clone(),
195        eap_certificate_key: tls.cert_key.clone(),
196        eap_private_key_key: tls.private_key_key.clone(),
197        eap_ca_key: tls.ca_key.clone(),
198        kanidm_ca,
199        exposure,
200        service_port: radius.spec.service.port,
201        service_annotations: radius.spec.service.annotations.clone(),
202        resources: radius.spec.resources.clone(),
203        node_selector: radius.spec.node_selector.clone(),
204        affinity: radius.spec.affinity.clone(),
205        tolerations: radius.spec.tolerations.clone(),
206        topology_spread_constraints: radius.spec.topology_spread_constraints.clone(),
207    };
208    workload.validate()?;
209    Ok(workload)
210}
211
212impl RadiusWorkload {
213    pub fn validate(&self) -> Result<(), RadiusWorkloadError> {
214        if self.name.is_empty()
215            || self.namespace.is_empty()
216            || self.owner.uid.is_empty()
217            || self.image.trim().is_empty()
218            || self.token_id.is_empty()
219            || self.inputs_digest.is_empty()
220            || self.configuration_secret.is_empty()
221        {
222            return Err(RadiusWorkloadError::MissingResourceIdentity);
223        }
224        Ok(())
225    }
226
227    fn labels(&self) -> BTreeMap<String, String> {
228        BTreeMap::from([
229            (LABEL_NAME.into(), COMPONENT.into()),
230            (LABEL_UID.into(), self.owner.uid.clone()),
231        ])
232    }
233
234    fn owner_metadata(&self) -> ObjectMeta {
235        // The managed-by label is metadata only: it must not enter the
236        // immutable Deployment selector.
237        let mut labels = self.labels();
238        labels.insert(LABEL_MANAGED_BY.into(), MANAGED_BY.into());
239        ObjectMeta {
240            name: Some(self.name.clone()),
241            namespace: Some(self.namespace.clone()),
242            labels: Some(labels),
243            owner_references: Some(vec![self.owner.clone()]),
244            ..Default::default()
245        }
246    }
247
248    /// Project all files into the single /data mount expected by the official
249    /// bootstrap. No subPath mounts: each input is a user-owned Secret/ConfigMap,
250    /// and the rendered configuration uses an immutable operator-owned Secret.
251    fn projections(&self) -> Vec<VolumeProjection> {
252        let mut projections = vec![
253            VolumeProjection {
254                secret: Some(SecretProjection {
255                    name: self.configuration_secret.clone(),
256                    items: Some(vec![KeyToPath {
257                        key: SECRET_KEY_CONFIG.into(),
258                        path: SECRET_KEY_CONFIG.into(),
259                        ..Default::default()
260                    }]),
261                    ..Default::default()
262                }),
263                ..Default::default()
264            },
265            VolumeProjection {
266                secret: Some(SecretProjection {
267                    name: self.eap_tls_secret.clone(),
268                    items: Some({
269                        let mut items = vec![
270                            KeyToPath {
271                                key: self.eap_certificate_key.clone(),
272                                path: "cert.pem".into(),
273                                ..Default::default()
274                            },
275                            KeyToPath {
276                                key: self.eap_private_key_key.clone(),
277                                path: "key.pem".into(),
278                                ..Default::default()
279                            },
280                        ];
281                        if let Some(key) = &self.eap_ca_key {
282                            items.push(KeyToPath {
283                                key: key.clone(),
284                                path: "ca.pem".into(),
285                                ..Default::default()
286                            });
287                        }
288                        items
289                    }),
290                    optional: Some(false),
291                }),
292                ..Default::default()
293            },
294        ];
295
296        if let Some(ca) = &self.kanidm_ca {
297            projections.push(match ca {
298                RadiusCaSource::Secret { name, key } => VolumeProjection {
299                    secret: Some(SecretProjection {
300                        name: name.clone(),
301                        items: Some(vec![KeyToPath {
302                            key: key.clone(),
303                            path: "kanidm-ca.pem".into(),
304                            ..Default::default()
305                        }]),
306                        ..Default::default()
307                    }),
308                    ..Default::default()
309                },
310                RadiusCaSource::ConfigMap { name, key } => VolumeProjection {
311                    config_map: Some(ConfigMapProjection {
312                        name: name.clone(),
313                        items: Some(vec![KeyToPath {
314                            key: key.clone(),
315                            path: "kanidm-ca.pem".into(),
316                            ..Default::default()
317                        }]),
318                        ..Default::default()
319                    }),
320                    ..Default::default()
321                },
322            });
323        }
324        projections
325    }
326
327    pub fn deployment(&self) -> Result<Deployment, RadiusWorkloadError> {
328        self.validate()?;
329        let labels = self.labels();
330        let container = Container {
331            name: COMPONENT.into(),
332            image: Some(self.image.clone()),
333            resources: self.resources.clone(),
334            // A static configuration check is better than a ready-but-dead
335            // UDP process. It does not validate live Kanidm authentication:
336            // token promotion/revocation requires a separate real login probe.
337            readiness_probe: Some(Probe {
338                exec: Some(ExecAction {
339                    command: Some(vec!["/usr/sbin/radiusd".into(), "-C".into()]),
340                }),
341                period_seconds: Some(10),
342                timeout_seconds: Some(5),
343                failure_threshold: Some(3),
344                ..Default::default()
345            }),
346            lifecycle: Some(Lifecycle {
347                pre_stop: Some(LifecycleHandler {
348                    exec: Some(ExecAction {
349                        command: Some(vec!["sleep".into(), PRE_STOP_SLEEP_SECONDS.to_string()]),
350                    }),
351                    ..Default::default()
352                }),
353                ..Default::default()
354            }),
355            ports: Some(vec![ContainerPort {
356                name: Some("radius-auth".into()),
357                container_port: 1812,
358                protocol: Some("UDP".into()),
359                ..Default::default()
360            }]),
361            security_context: Some(SecurityContext {
362                allow_privilege_escalation: Some(false),
363                capabilities: Some(Capabilities {
364                    drop: Some(vec!["ALL".into()]),
365                    ..Default::default()
366                }),
367                // Explicit numeric identity is necessary for Kubelet's
368                // runAsNonRoot validation when the image USER is named.
369                run_as_user: Some(RADIUS_UID),
370                run_as_group: Some(RADIUS_GID),
371                run_as_non_root: Some(true),
372                // readOnlyRootFilesystem is deliberately unset. The
373                // upstream bootstrap rewrites /etc/raddb/clients.conf and
374                // writes /etc/raddb/certs/{ca,server}.pem, so the whole of
375                // /etc/raddb must be writable. A read-only root works only if
376                // /etc/raddb is a writable copy of the image directory, and
377                // radiusd then refuses to start when that directory is
378                // world-writable, which is what an emptyDir mount point is
379                // (0777). Seeding it with correct permissions needs a root
380                // init container. Revisit if upstream moves the generated
381                // files.
382                read_only_root_filesystem: None,
383                ..Default::default()
384            }),
385            volume_mounts: Some(vec![VolumeMount {
386                name: "radius-data".into(),
387                mount_path: "/data".into(),
388                read_only: Some(true),
389                ..Default::default()
390            }]),
391            ..Default::default()
392        };
393        let pod = PodSpec {
394            containers: vec![container],
395            node_selector: self.node_selector.clone(),
396            affinity: self.affinity.clone(),
397            tolerations: self.tolerations.clone(),
398            topology_spread_constraints: self.topology_spread_constraints.clone(),
399            termination_grace_period_seconds: Some(30),
400            automount_service_account_token: Some(false),
401            enable_service_links: Some(false),
402            security_context: Some(PodSecurityContext {
403                run_as_user: Some(RADIUS_UID),
404                run_as_group: Some(RADIUS_GID),
405                run_as_non_root: Some(true),
406                fs_group: Some(RADIUS_GID),
407                seccomp_profile: Some(SeccompProfile {
408                    type_: "RuntimeDefault".into(),
409                    ..Default::default()
410                }),
411                ..Default::default()
412            }),
413            volumes: Some(vec![Volume {
414                name: "radius-data".into(),
415                projected: Some(ProjectedVolumeSource {
416                    sources: Some(self.projections()),
417                    // The non-root RADIUS process must be able to read its
418                    // certificate and private key from the projected volume.
419                    // The K8s Secret API and pod access must remain restricted.
420                    default_mode: Some(0o440),
421                }),
422                ..Default::default()
423            }]),
424            ..Default::default()
425        };
426        Ok(Deployment {
427            metadata: self.owner_metadata(),
428            spec: Some(DeploymentSpec {
429                replicas: Some(self.replicas),
430                revision_history_limit: Some(REVISION_HISTORY_LIMIT),
431                selector: LabelSelector {
432                    match_labels: Some(labels.clone()),
433                    ..Default::default()
434                },
435                template: PodTemplateSpec {
436                    metadata: Some(ObjectMeta {
437                        labels: Some(labels),
438                        annotations: Some(BTreeMap::from([
439                            (ANNOTATION_TOKEN_ID.to_string(), self.token_id.clone()),
440                            (
441                                ANNOTATION_INPUTS_DIGEST.to_string(),
442                                self.inputs_digest.clone(),
443                            ),
444                        ])),
445                        ..Default::default()
446                    }),
447                    spec: Some(pod),
448                },
449                strategy: Some(DeploymentStrategy {
450                    type_: Some("RollingUpdate".into()),
451                    rolling_update: Some(RollingUpdateDeployment {
452                        max_surge: Some(IntOrString::Int(1)),
453                        max_unavailable: Some(IntOrString::Int(0)),
454                    }),
455                }),
456                ..Default::default()
457            }),
458            ..Default::default()
459        })
460    }
461
462    pub fn service(&self) -> Result<Service, RadiusWorkloadError> {
463        self.validate()?;
464        let service_type = self.exposure.service_type();
465        let external_traffic_policy = self.exposure.external_traffic_policy().map(String::from);
466        let mut metadata = self.owner_metadata();
467        if !self.service_annotations.is_empty() {
468            metadata.annotations = Some(self.service_annotations.clone());
469        }
470        Ok(Service {
471            metadata,
472            spec: Some(ServiceSpec {
473                type_: Some(service_type.into()),
474                external_traffic_policy,
475                selector: Some(self.labels()),
476                ports: Some(vec![ServicePort {
477                    name: Some("radius-auth".into()),
478                    port: self.service_port,
479                    protocol: Some("UDP".into()),
480                    target_port: Some(IntOrString::Int(1812)),
481                    ..Default::default()
482                }]),
483                ..Default::default()
484            }),
485            ..Default::default()
486        })
487    }
488}
489
490/// Name of the immutable config Secret: `<cr>-<first 10 hex of sha256(toml)>`.
491///
492/// Content addressing makes a re-render with identical content idempotent and
493/// any change a new object, so pods mounting the old Secret are never mutated
494/// (same practice as kustomize `secretGenerator`). The hash is over the whole
495/// TOML, which embeds the bearer token and NAS secrets; 40 bits of a SHA-256
496/// over a high-entropy token reveal nothing usable.
497pub fn config_secret_name(cr_name: &str, radius_toml: &str) -> Result<String, RadiusWorkloadError> {
498    if cr_name.is_empty() || cr_name.len() > MAX_RADIUS_NAME_LEN {
499        return Err(RadiusWorkloadError::ResourceNameTooLong);
500    }
501    let digest = hex::encode(Sha256::digest(radius_toml.as_bytes()));
502    Ok(format!("{cr_name}-{}", &digest[..CONFIG_HASH_LEN]))
503}
504
505/// Build the immutable, content-addressed config Secret.
506///
507/// Credentials live only in `data`. Metadata carries the owner, UID label,
508/// the token id and the manual-rotation request value, none of which is
509/// secret. `rotation_request` is the CR's `kaniop.rs/radius-rotate-token`
510/// value at mint time.
511pub fn build_config_secret(
512    radius: &KanidmRadiusServer,
513    token_id: &str,
514    rotation_request: Option<&str>,
515    config: &RadiusConfig,
516) -> Result<Secret, RadiusWorkloadError> {
517    let namespace = radius
518        .namespace()
519        .ok_or(RadiusWorkloadError::MissingResourceIdentity)?;
520    let owner = radius
521        .controller_owner_ref(&())
522        .ok_or(RadiusWorkloadError::MissingResourceIdentity)?;
523    if owner.uid.is_empty() || token_id.is_empty() {
524        return Err(RadiusWorkloadError::MissingResourceIdentity);
525    }
526    let toml = config.render_toml()?;
527    let name = config_secret_name(&radius.name_any(), &toml)?;
528    let mut annotations = BTreeMap::from([(ANNOTATION_TOKEN_ID.to_string(), token_id.to_string())]);
529    if let Some(request) = rotation_request {
530        annotations.insert(ANNOTATION_ROTATION_REQUEST.to_string(), request.to_string());
531    }
532    Ok(Secret {
533        metadata: ObjectMeta {
534            name: Some(name),
535            namespace: Some(namespace),
536            labels: Some(BTreeMap::from([
537                (LABEL_NAME.into(), COMPONENT.into()),
538                (LABEL_MANAGED_BY.into(), MANAGED_BY.into()),
539                (LABEL_UID.into(), owner.uid.clone()),
540            ])),
541            annotations: Some(annotations),
542            owner_references: Some(vec![owner]),
543            ..Default::default()
544        },
545        data: Some(BTreeMap::from([
546            (SECRET_KEY_CONFIG.into(), ByteString(toml.into_bytes())),
547            (
548                SECRET_KEY_TOKEN.into(),
549                ByteString(config.auth_token.as_bytes().to_vec()),
550            ),
551        ])),
552        immutable: Some(true),
553        type_: Some("Opaque".into()),
554        ..Default::default()
555    })
556}
557
558#[cfg(test)]
559mod tests {
560    use super::*;
561
562    fn workload() -> RadiusWorkload {
563        RadiusWorkload {
564            name: "campus-radius".into(),
565            namespace: "network-auth".into(),
566            owner: OwnerReference {
567                api_version: "kaniop.rs/v1beta1".into(),
568                kind: "KanidmRadiusServer".into(),
569                name: "campus-radius".into(),
570                uid: "d10066c3-4599-4487-972d-26bb42587a32".into(),
571                controller: Some(true),
572                block_owner_deletion: Some(true),
573            },
574            image: "kanidm/radius:1.11.2".into(),
575            replicas: 2,
576            configuration_secret: "campus-radius-cfg-1".into(),
577            token_id: "token-a".into(),
578            inputs_digest: "digest-a".into(),
579            eap_tls_secret: "radius-tls".into(),
580            eap_certificate_key: "tls.crt".into(),
581            eap_private_key_key: "tls.key".into(),
582            eap_ca_key: Some("ca.crt".into()),
583            kanidm_ca: Some(RadiusCaSource::ConfigMap {
584                name: "kanidm-ca".into(),
585                key: "ca.crt".into(),
586            }),
587            exposure: RadiusServiceExposure::ClusterIP,
588            service_port: 1812,
589            service_annotations: BTreeMap::new(),
590            resources: None,
591            node_selector: None,
592            affinity: None,
593            tolerations: None,
594            topology_spread_constraints: None,
595        }
596    }
597
598    #[test]
599    fn derives_workload_from_uid_owned_cr_and_secret_ca() {
600        let radius: KanidmRadiusServer = serde_json::from_value(serde_json::json!({
601            "apiVersion": "kaniop.rs/v1beta1",
602            "kind": "KanidmRadiusServer",
603            "metadata": {
604                "name": "campus-radius",
605                "namespace": "network-auth",
606                "uid": "d10066c3-4599-4487-972d-26bb42587a32"
607            },
608            "spec": {
609                "kanidmRef": {"name": "idm"},
610                "authorization": {"requiredGroups": ["allowed@idm.example.com"]},
611                "clients": [{
612                    "name": "nas",
613                    "ipaddr": "192.0.2.1",
614                    "sharedSecretRef": {"name": "nas-secret", "key": "nas"}
615                }],
616                "radiusTls": {"secretRef": {"name": "eap-tls"}},
617                "kanidmTls": {
618                    "caBundleRef": {
619                        "kind": "Secret",
620                        "name": "private-ca",
621                        "key": "ca.crt"
622                    }
623                },
624                "service": {"type": "LoadBalancer", "externalTrafficPolicy": "Local"}
625            }
626        }))
627        .unwrap();
628        let workload = build_workload(
629            &radius,
630            "kanidm/radius:1.11.2".into(),
631            "immutable-config",
632            "token-id",
633            "digest-a",
634        )
635        .unwrap();
636        assert_eq!(workload.owner.uid, "d10066c3-4599-4487-972d-26bb42587a32");
637        assert_eq!(workload.configuration_secret, "immutable-config");
638        assert_eq!(workload.token_id, "token-id");
639        assert!(matches!(
640            workload.kanidm_ca,
641            Some(RadiusCaSource::Secret { ref name, ref key })
642                if name == "private-ca" && key == "ca.crt"
643        ));
644        assert!(matches!(
645            workload.exposure,
646            RadiusServiceExposure::LoadBalancer {
647                external_traffic_policy: Some(ref policy)
648            } if policy == "Local"
649        ));
650    }
651
652    #[test]
653    fn deployment_has_no_kubernetes_token_or_injected_services() {
654        let deployment = workload().deployment().unwrap();
655        let spec = deployment.spec.unwrap();
656        assert_eq!(spec.replicas, Some(2));
657        assert_eq!(
658            spec.strategy.unwrap().type_.as_deref(),
659            Some("RollingUpdate")
660        );
661        let pod = spec.template.spec.unwrap();
662        assert_eq!(pod.automount_service_account_token, Some(false));
663        assert_eq!(pod.enable_service_links, Some(false));
664        assert_eq!(pod.termination_grace_period_seconds, Some(30));
665        assert_eq!(
666            pod.containers[0]
667                .readiness_probe
668                .as_ref()
669                .unwrap()
670                .exec
671                .as_ref()
672                .unwrap()
673                .command,
674            Some(vec!["/usr/sbin/radiusd".into(), "-C".into()])
675        );
676        let security = pod.security_context.as_ref().unwrap();
677        assert_eq!(security.run_as_user, Some(497));
678        assert_eq!(security.run_as_non_root, Some(true));
679        assert_eq!(security.fs_group, Some(496));
680        assert_eq!(
681            security.seccomp_profile.as_ref().unwrap().type_,
682            "RuntimeDefault"
683        );
684
685        assert_eq!(
686            pod.containers[0].image.as_deref(),
687            Some("kanidm/radius:1.11.2")
688        );
689        assert_eq!(
690            pod.containers[0].ports.as_ref().unwrap()[0]
691                .protocol
692                .as_deref(),
693            Some("UDP")
694        );
695        assert_eq!(
696            pod.containers[0].volume_mounts.as_ref().unwrap()[0].mount_path,
697            "/data"
698        );
699        assert!(
700            pod.containers[0].volume_mounts.as_ref().unwrap()[0]
701                .read_only
702                .unwrap()
703        );
704        assert_eq!(
705            pod.volumes.unwrap()[0]
706                .projected
707                .as_ref()
708                .unwrap()
709                .sources
710                .as_ref()
711                .unwrap()
712                .len(),
713            3
714        );
715    }
716
717    #[test]
718    fn config_secret_change_updates_pod_template_without_touching_client_secrets() {
719        let a = workload().deployment().unwrap();
720        let mut updated = workload();
721        updated.configuration_secret = "campus-radius-cfg-2".into();
722        let b = updated.deployment().unwrap();
723        assert_ne!(
724            a.spec.as_ref().unwrap().template,
725            b.spec.as_ref().unwrap().template
726        );
727        let deps = b.spec.unwrap().template.spec.unwrap().volumes.unwrap();
728        let projected = deps[0]
729            .projected
730            .as_ref()
731            .unwrap()
732            .sources
733            .as_ref()
734            .unwrap();
735        assert_eq!(
736            projected[1].secret.as_ref().unwrap().name.as_str(),
737            "radius-tls"
738        );
739    }
740
741    #[test]
742    fn service_is_udp_only_and_uses_owner_uid_selector() {
743        let mut input = workload();
744        input.exposure = RadiusServiceExposure::LoadBalancer {
745            external_traffic_policy: Some("Local".into()),
746        };
747        let service = input.service().unwrap();
748        assert_eq!(
749            service.metadata.owner_references.as_ref().unwrap()[0].uid,
750            input.owner.uid
751        );
752        let spec = service.spec.unwrap();
753        assert_eq!(spec.type_.as_deref(), Some("LoadBalancer"));
754        assert_eq!(spec.external_traffic_policy.as_deref(), Some("Local"));
755        let port = &spec.ports.unwrap()[0];
756        assert_eq!(port.port, 1812);
757        assert_eq!(port.protocol.as_deref(), Some("UDP"));
758        assert_eq!(port.target_port, Some(IntOrString::Int(1812)));
759    }
760
761    #[test]
762    fn propagates_scheduling_resources_and_service_annotations() {
763        let mut input = workload();
764        input.resources = Some(ResourceRequirements::default());
765        input.node_selector = Some(BTreeMap::from([(
766            "kubernetes.io/arch".to_string(),
767            "amd64".to_string(),
768        )]));
769        input.affinity = Some(Affinity::default());
770        input.tolerations = Some(vec![Toleration::default()]);
771        input.topology_spread_constraints = Some(vec![]);
772        input.service_annotations.insert(
773            "service.beta.kubernetes.io/example".into(),
774            "radius-udp".into(),
775        );
776        let deployment = input.deployment().unwrap();
777        let pod = deployment.spec.unwrap().template.spec.unwrap();
778        assert!(pod.containers[0].resources.is_some());
779        assert_eq!(
780            pod.node_selector.unwrap().get("kubernetes.io/arch"),
781            Some(&"amd64".to_string())
782        );
783        assert!(pod.affinity.is_some());
784        assert_eq!(pod.tolerations.unwrap().len(), 1);
785        assert_eq!(pod.topology_spread_constraints, Some(vec![]));
786
787        let service = input.service().unwrap();
788        assert_eq!(
789            service
790                .metadata
791                .annotations
792                .as_ref()
793                .unwrap()
794                .get("service.beta.kubernetes.io/example"),
795            Some(&"radius-udp".to_string())
796        );
797        // Workload metadata does not inherit Service annotations.
798        assert!(input.deployment().unwrap().metadata.annotations.is_none());
799    }
800
801    fn radius_from_service_type(service_type: &str) -> KanidmRadiusServer {
802        serde_json::from_value(serde_json::json!({
803            "apiVersion": "kaniop.rs/v1beta1",
804            "kind": "KanidmRadiusServer",
805            "metadata": {
806                "name": "campus-radius",
807                "namespace": "network-auth",
808                "uid": "d10066c3-4599-4487-972d-26bb42587a32"
809            },
810            "spec": {
811                "kanidmRef": {"name": "idm"},
812                "authorization": {"requiredGroups": ["allowed@idm.example.com"]},
813                "clients": [{
814                    "name": "nas",
815                    "ipaddr": "192.0.2.1",
816                    "sharedSecretRef": {"name": "nas-secret", "key": "nas"}
817                }],
818                "radiusTls": {"secretRef": {"name": "eap-tls"}},
819                "service": {"type": service_type}
820            }
821        }))
822        .unwrap()
823    }
824
825    #[test]
826    fn unknown_service_type_reports_service_type_error() {
827        let radius = radius_from_service_type("ExternalName");
828        assert_eq!(
829            build_workload(
830                &radius,
831                "kanidm/radius:1.11.2".into(),
832                "immutable-config",
833                "token-id",
834                "digest-a"
835            )
836            .unwrap_err(),
837            RadiusWorkloadError::InvalidServiceType
838        );
839    }
840
841    fn radius_config() -> RadiusConfig {
842        RadiusConfig {
843            uri: "https://idm.example.com".into(),
844            auth_token: "bearer-do-not-log".into(),
845            ca_path: None,
846            radius_required_groups: vec!["allowed@idm.example.com".into()],
847            radius_default_vlan: 10,
848            radius_groups: vec![],
849            radius_clients: vec![crate::reconcile::config::RadiusClient {
850                name: "nas".into(),
851                ipaddr: "192.0.2.10".into(),
852                secret: "safeRandomSecret123".into(),
853            }],
854            radius_ca_path: None,
855        }
856    }
857
858    #[test]
859    fn config_secret_name_is_content_addressed() {
860        let a = config_secret_name("campus", "uri = \"a\"\n").unwrap();
861        assert_eq!(a, config_secret_name("campus", "uri = \"a\"\n").unwrap());
862        assert_ne!(a, config_secret_name("campus", "uri = \"b\"\n").unwrap());
863        assert_ne!(a, config_secret_name("other", "uri = \"a\"\n").unwrap());
864        let (prefix, hash) = a.rsplit_once('-').unwrap();
865        assert_eq!(prefix, "campus");
866        assert_eq!(hash.len(), 10);
867        assert!(hash.bytes().all(|b| b.is_ascii_hexdigit()));
868    }
869
870    #[test]
871    fn config_secret_name_fits_a_dns_label_for_the_longest_cr_name() {
872        let longest = "a".repeat(MAX_RADIUS_NAME_LEN);
873        assert_eq!(config_secret_name(&longest, "x").unwrap().len(), 63);
874        assert_eq!(
875            config_secret_name(&"a".repeat(MAX_RADIUS_NAME_LEN + 1), "x"),
876            Err(RadiusWorkloadError::ResourceNameTooLong)
877        );
878    }
879
880    #[test]
881    fn config_secret_is_immutable_and_keeps_credentials_out_of_metadata() {
882        let radius = radius_from_service_type("ClusterIP");
883        let config = radius_config();
884        let secret = build_config_secret(&radius, "token-a", Some("req-1"), &config).unwrap();
885        let toml = config.render_toml().unwrap();
886        assert_eq!(
887            secret.metadata.name.as_deref(),
888            Some(config_secret_name("campus-radius", &toml).unwrap().as_str())
889        );
890        assert_eq!(secret.immutable, Some(true));
891        assert_eq!(secret.type_.as_deref(), Some("Opaque"));
892        let data = secret.data.as_ref().unwrap();
893        assert_eq!(data[SECRET_KEY_CONFIG].0, toml.as_bytes());
894        assert_eq!(data[SECRET_KEY_TOKEN].0, b"bearer-do-not-log");
895
896        let annotations = secret.metadata.annotations.as_ref().unwrap();
897        assert_eq!(annotations[ANNOTATION_TOKEN_ID], "token-a");
898        assert_eq!(annotations[ANNOTATION_ROTATION_REQUEST], "req-1");
899        // Names, labels, annotations and owner references: no credential.
900        let metadata = serde_json::to_string(&secret.metadata).unwrap();
901        assert!(!metadata.contains("bearer-do-not-log"));
902        assert!(!metadata.contains("safeRandomSecret123"));
903        assert_eq!(
904            secret.metadata.owner_references.as_ref().unwrap()[0].uid,
905            "d10066c3-4599-4487-972d-26bb42587a32"
906        );
907    }
908
909    #[test]
910    fn config_secret_name_follows_the_rendered_config() {
911        let radius = radius_from_service_type("ClusterIP");
912        let mut config = radius_config();
913        let a = build_config_secret(&radius, "token-a", None, &config).unwrap();
914        let same = build_config_secret(&radius, "token-a", None, &config).unwrap();
915        assert_eq!(a.metadata.name, same.metadata.name);
916        assert!(
917            !a.metadata
918                .annotations
919                .as_ref()
920                .unwrap()
921                .contains_key(ANNOTATION_ROTATION_REQUEST)
922        );
923        config.radius_clients[0].secret = "anotherSafeSecret456".into();
924        let b = build_config_secret(&radius, "token-a", None, &config).unwrap();
925        assert_ne!(a.metadata.name, b.metadata.name);
926    }
927
928    #[test]
929    fn pod_template_carries_token_id_and_inputs_digest() {
930        let deployment = workload().deployment().unwrap();
931        let template = deployment.spec.unwrap().template;
932        let annotations = template.metadata.unwrap().annotations.unwrap();
933        assert_eq!(annotations[ANNOTATION_TOKEN_ID], "token-a");
934        assert_eq!(annotations[ANNOTATION_INPUTS_DIGEST], "digest-a");
935
936        let mut renewed = workload();
937        renewed.inputs_digest = "digest-b".into();
938        assert_ne!(
939            deployment_template(&workload()),
940            deployment_template(&renewed),
941            "TLS renewal must roll the pods"
942        );
943        let mut rotated = workload();
944        rotated.token_id = "token-b".into();
945        assert_ne!(
946            deployment_template(&workload()),
947            deployment_template(&rotated)
948        );
949    }
950
951    fn deployment_template(workload: &RadiusWorkload) -> PodTemplateSpec {
952        workload.deployment().unwrap().spec.unwrap().template
953    }
954
955    #[test]
956    fn workload_requires_token_id_and_inputs_digest() {
957        let mut input = workload();
958        input.token_id.clear();
959        assert_eq!(
960            input.deployment().unwrap_err(),
961            RadiusWorkloadError::MissingResourceIdentity
962        );
963        let mut input = workload();
964        input.inputs_digest.clear();
965        assert_eq!(
966            input.deployment().unwrap_err(),
967            RadiusWorkloadError::MissingResourceIdentity
968        );
969    }
970
971    #[test]
972    fn terminating_pods_keep_serving_while_endpoint_removal_propagates() {
973        let pod = deployment_template(&workload()).spec.unwrap();
974        let hook = pod.containers[0]
975            .lifecycle
976            .as_ref()
977            .and_then(|l| l.pre_stop.as_ref())
978            .and_then(|h| h.exec.as_ref())
979            .and_then(|e| e.command.clone());
980        assert_eq!(
981            hook,
982            Some(vec!["sleep".into(), PRE_STOP_SLEEP_SECONDS.to_string()])
983        );
984        // The grace period must outlast the hook, or radiusd is killed first.
985        assert!(pod.termination_grace_period_seconds.unwrap() > i64::from(PRE_STOP_SLEEP_SECONDS));
986    }
987
988    #[test]
989    fn generated_objects_are_labelled_but_the_selector_is_stable() {
990        let input = workload();
991        let deployment = input.deployment().unwrap();
992        let labels = deployment.metadata.labels.as_ref().unwrap();
993        assert_eq!(labels[LABEL_MANAGED_BY], "kaniop-radius-server");
994        assert_eq!(
995            input.service().unwrap().metadata.labels.as_ref().unwrap()[LABEL_MANAGED_BY],
996            "kaniop-radius-server"
997        );
998        let selector = deployment.spec.unwrap().selector.match_labels.unwrap();
999        assert_eq!(
1000            selector.keys().map(String::as_str).collect::<Vec<_>>(),
1001            [LABEL_NAME, LABEL_UID]
1002        );
1003    }
1004
1005    #[test]
1006    fn runtime_identity_uses_the_verified_numeric_ids() {
1007        assert_eq!((RADIUS_UID, RADIUS_GID), (497, 496));
1008        let pod = workload()
1009            .deployment()
1010            .unwrap()
1011            .spec
1012            .unwrap()
1013            .template
1014            .spec
1015            .unwrap();
1016        let container = pod.containers[0].security_context.as_ref().unwrap();
1017        assert_eq!(container.run_as_user, Some(RADIUS_UID));
1018        assert_eq!(container.run_as_group, Some(RADIUS_GID));
1019        let pod_security = pod.security_context.unwrap();
1020        assert_eq!(pod_security.run_as_user, Some(RADIUS_UID));
1021        assert_eq!(pod_security.fs_group, Some(RADIUS_GID));
1022    }
1023
1024    #[test]
1025    fn root_filesystem_stays_writable_because_upstream_bootstraps_into_etc_raddb() {
1026        // The image rewrites /etc/raddb/clients.conf and
1027        // writes /etc/raddb/certs/*.pem at startup, and radiusd refuses to run
1028        // from a world-writable /etc/raddb (an emptyDir mount point is 0777).
1029        // Re-evaluate this assertion only together with the image contract.
1030        let pod = workload()
1031            .deployment()
1032            .unwrap()
1033            .spec
1034            .unwrap()
1035            .template
1036            .spec
1037            .unwrap();
1038        let container = pod.containers[0].security_context.as_ref().unwrap();
1039        assert_eq!(container.read_only_root_filesystem, None);
1040    }
1041
1042    #[test]
1043    fn service_type_parses_every_supported_value_and_nothing_else() {
1044        for (value, expected) in [
1045            ("ClusterIP", "ClusterIP"),
1046            ("NodePort", "NodePort"),
1047            ("LoadBalancer", "LoadBalancer"),
1048        ] {
1049            let exposure = RadiusServiceExposure::from_spec(value, None).unwrap();
1050            assert_eq!(exposure.service_type(), expected);
1051        }
1052        assert_eq!(
1053            RadiusServiceExposure::from_spec("clusterip", None),
1054            Err(RadiusWorkloadError::InvalidServiceType)
1055        );
1056    }
1057
1058    #[test]
1059    fn external_traffic_policy_is_dropped_on_cluster_ip_and_kept_otherwise() {
1060        let exposure = RadiusServiceExposure::from_spec("ClusterIP", Some("Local".into()));
1061        assert_eq!(exposure, Ok(RadiusServiceExposure::ClusterIP));
1062        assert_eq!(exposure.unwrap().external_traffic_policy(), None);
1063        for value in ["NodePort", "LoadBalancer"] {
1064            let exposure = RadiusServiceExposure::from_spec(value, Some("Local".into())).unwrap();
1065            assert_eq!(exposure.external_traffic_policy(), Some("Local"));
1066        }
1067    }
1068}