Skip to main content

kaniop_radius/
crd.rs

1//! Proposed public API for independently managed Kanidm RADIUS endpoints.
2//!
3//! This is the *source* of the CRD. Generated Kubernetes CRD YAML and example
4//! manifests must be produced by the repository's Rust generators, never
5//! hand-edited. Runtime reconciliation and registration are separate gates.
6
7use std::collections::BTreeMap;
8
9use k8s_openapi::api::core::v1::{
10    Affinity, ResourceRequirements, Toleration, TopologySpreadConstraint,
11};
12use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, LabelSelector, Time};
13use kube::CustomResource;
14#[cfg(feature = "schemars")]
15use schemars::JsonSchema;
16use kaniop_operator::controller::kanidm::KanidmResource;
17use kaniop_operator::crd::{KanidmRef, SecretRotation};
18use kaniop_operator::kanidm::crd::Kanidm;
19use serde::{Deserialize, Serialize};
20
21/// An independently deployed Kanidm-backed RADIUS authentication endpoint.
22///
23/// RADIUS user credentials are managed inside Kanidm by each account, not in
24/// this resource. The operator creates one dedicated read-only service account,
25/// config Secret, Deployment and UDP Service per resource.
26#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
27#[cfg_attr(feature = "schemars", derive(JsonSchema))]
28#[kube(
29    category = "kaniop",
30    group = "kaniop.rs",
31    version = "v1beta1",
32    kind = "KanidmRadiusServer",
33    plural = "kanidmradiusservers",
34    singular = "kanidmradiusserver",
35    shortname = "krs",
36    namespaced,
37    status = "KanidmRadiusServerStatus",
38    printcolumn = r#"{"name":"Kanidm","type":"string","jsonPath":".spec.kanidmRef.name"}"#,
39    printcolumn = r#"{"name":"Ready","type":"boolean","jsonPath":".status.ready"}"#,
40    printcolumn = r#"{"name":"Endpoint","type":"string","jsonPath":".status.endpoint"}"#,
41    printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#,
42    validation = Rule::new("size(self.metadata.name) <= 52")
43        .message("RADIUS server name must be at most 52 characters"),
44    derive = "Default"
45)]
46#[serde(rename_all = "camelCase")]
47pub struct KanidmRadiusServerSpec {
48    /// Target Kanidm cluster. Cross-namespace access is subject to the
49    /// referenced Kanidm namespace selector. Immutable after creation.
50    pub kanidm_ref: KanidmRef,
51
52    /// Optional RADIUS component image override, independent from the Kanidm
53    /// server image. Required if the Kanidm image uses a digest or an unknown
54    /// registry. Do not inherit the server image digest.
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub image: Option<String>,
57
58    /// Number of RADIUS replicas, at least one. Defaults to two.
59    #[serde(default = "default_replicas")]
60    #[schemars(extend("x-kubernetes-validations" = [{"message": "RADIUS replicas must be between 1 and 100", "rule": "self >= 1 && self <= 100"}]))]
61    pub replicas: i32,
62
63    /// Authorization groups and VLAN mapping. At least one required group must
64    /// be present to avoid inadvertently permitting all Kanidm users.
65    pub authorization: RadiusAuthorizationSpec,
66
67    /// Allowed NAS clients. Never put the RADIUS shared secret in the CRD:
68    /// only references to same-namespace Kubernetes Secret keys are accepted.
69    #[schemars(extend("x-kubernetes-validations" = [{"message": "At least one RADIUS NAS client is required", "rule": "self.size() > 0 && self.size() <= 100"}]))]
70    // max is defined so the API server can estimate CEL expression costs; it matches the rule.
71    #[schemars(length(max = 100))]
72    pub clients: Vec<RadiusClientSpec>,
73
74    /// User-managed EAP certificate and key. Required by upstream bootstrap.
75    pub radius_tls: RadiusTlsSpec,
76
77    /// Optional CA bundle for outbound Kanidm HTTPS certificate verification.
78    /// Verification of TLS hostnames and certificates always remains enabled.
79    #[serde(skip_serializing_if = "Option::is_none")]
80    pub kanidm_tls: Option<KanidmTlsSpec>,
81
82    /// UDP Service endpoint; defaults to ClusterIP:1812.
83    #[serde(default)]
84    pub service: RadiusServiceSpec,
85
86    /// Periodic API token rotation (disabled unless explicitly enabled). When
87    /// enabled, the token is replaced after `periodDays` (default 90, accepted
88    /// range 1 to 365) and new tokens expire after twice that period.
89    #[serde(default)]
90    pub token_rotation: SecretRotation,
91
92    /// Resource requests and limits for the official RADIUS container.
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub resources: Option<ResourceRequirements>,
95
96    /// Optional scheduling controls.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub node_selector: Option<BTreeMap<String, String>>,
99
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub affinity: Option<Affinity>,
102
103    #[serde(skip_serializing_if = "Option::is_none")]
104    pub tolerations: Option<Vec<Toleration>>,
105
106    #[serde(skip_serializing_if = "Option::is_none")]
107    pub topology_spread_constraints: Option<Vec<TopologySpreadConstraint>>,
108}
109
110fn default_replicas() -> i32 {
111    2
112}
113
114impl KanidmResource for KanidmRadiusServer {
115    fn kanidm_ref_spec(&self) -> &KanidmRef {
116        &self.spec.kanidm_ref
117    }
118
119    fn get_namespace_selector(kanidm: &Kanidm) -> &Option<LabelSelector> {
120        &kanidm.spec.radius_server_namespace_selector
121    }
122
123    fn kanidm_name_override(&self) -> Option<&str> {
124        None
125    }
126}
127
128#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
129#[cfg_attr(feature = "schemars", derive(JsonSchema))]
130#[serde(rename_all = "camelCase")]
131pub struct RadiusAuthorizationSpec {
132    /// Users must belong to at least one of these Kanidm groups.
133    #[schemars(extend("x-kubernetes-validations" = [{"message": "At least one RADIUS authorization group is required", "rule": "self.size() > 0 && self.size() <= 100"}]))]
134    // max is defined so the API server can estimate CEL expression costs; it matches the rule.
135    // Items are Kanidm group SPNs (name@domain), bounded by the DNS name limit.
136    #[schemars(length(max = 100), inner(length(max = 253)))]
137    pub required_groups: Vec<String>,
138
139    /// Fallback VLAN for permitted users. Valid production VLAN range: 1..4094.
140    #[serde(default = "default_vlan")]
141    #[schemars(extend("x-kubernetes-validations" = [{"message": "RADIUS default VLAN must be in 1..4094", "rule": "self >= 1 && self <= 4094"}]))]
142    pub default_vlan: i32,
143
144    /// Optional per-group VLAN mappings, independent of authorization groups.
145    // max is defined so the API server can estimate CEL expression costs of item rules.
146    #[schemars(length(max = 100))]
147    #[serde(default, skip_serializing_if = "Vec::is_empty")]
148    pub group_vlans: Vec<RadiusGroupVlan>,
149}
150
151fn default_vlan() -> i32 {
152    1
153}
154
155#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
156#[cfg_attr(feature = "schemars", derive(JsonSchema))]
157#[serde(rename_all = "camelCase")]
158pub struct RadiusGroupVlan {
159    /// Kanidm group SPN to map to a VLAN.
160    #[schemars(length(max = 253))]
161    pub group: String,
162    #[schemars(extend("x-kubernetes-validations" = [{"message": "RADIUS VLAN must be in 1..4094", "rule": "self >= 1 && self <= 4094"}]))]
163    pub vlan: i32,
164}
165
166#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
167#[cfg_attr(feature = "schemars", derive(JsonSchema))]
168#[serde(rename_all = "camelCase", deny_unknown_fields)]
169pub struct RadiusClientSpec {
170    /// FreeRADIUS client name; safe ASCII letters, numbers, dash, underscore.
171    // max matches the 63 character limit in the rule below, bounding its estimated cost.
172    #[schemars(length(max = 63))]
173    #[schemars(extend("x-kubernetes-validations" = [{"message": "RADIUS NAS client name must be a safe FreeRADIUS identifier", "rule": "self.matches(r'^[A-Za-z0-9_-]{1,63}$')"}]))]
174    pub name: String,
175
176    /// IPv4/IPv6 address or nonzero CIDR identifying the connecting NAS.
177    pub ipaddr: String,
178
179    /// Reference to a same-namespace Secret key. Values are validated again
180    /// after reading to prevent injection into FreeRADIUS clients.conf.
181    pub shared_secret_ref: RadiusSecretKeyRef,
182}
183
184#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
185#[cfg_attr(feature = "schemars", derive(JsonSchema))]
186#[serde(rename_all = "camelCase", deny_unknown_fields)]
187pub struct RadiusSecretKeyRef {
188    pub name: String,
189    pub key: String,
190}
191
192/// Which Kubernetes object contains the trusted Kanidm HTTPS CA bundle.
193/// Only these two kinds are allowed; no implicit use of arbitrary references.
194#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
195#[cfg_attr(feature = "schemars", derive(JsonSchema))]
196#[serde(rename_all = "PascalCase")]
197pub enum RadiusCaKind {
198    #[default]
199    ConfigMap,
200    Secret,
201}
202
203/// Same-namespace reference to a PEM CA bundle. ConfigMap is the default
204/// for non-secret trust anchors; Secret supports privately managed CA chains.
205#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
206#[cfg_attr(feature = "schemars", derive(JsonSchema))]
207#[serde(rename_all = "camelCase", deny_unknown_fields)]
208pub struct RadiusCaBundleRef {
209    /// Source type: ConfigMap (default) or Secret.
210    #[serde(default)]
211    pub kind: RadiusCaKind,
212    /// Name of the ConfigMap or Secret containing the CA bundle.
213    pub name: String,
214    /// Key containing the PEM-encoded CA certificates.
215    pub key: String,
216}
217
218#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
219#[cfg_attr(feature = "schemars", derive(JsonSchema))]
220#[serde(rename_all = "camelCase")]
221pub struct KanidmTlsSpec {
222    /// Reference to a CA bundle for the Kanidm HTTPS endpoint. The operator
223    /// never disables hostname or certificate validation.
224    #[serde(skip_serializing_if = "Option::is_none")]
225    pub ca_bundle_ref: Option<RadiusCaBundleRef>,
226}
227
228#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
229#[cfg_attr(feature = "schemars", derive(JsonSchema))]
230#[serde(rename_all = "camelCase")]
231pub struct RadiusSecretRef {
232    pub name: String,
233}
234
235#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
236#[cfg_attr(feature = "schemars", derive(JsonSchema))]
237#[serde(rename_all = "camelCase")]
238pub struct RadiusTlsSpec {
239    /// Same-namespace Secret with EAP server certificate and private key.
240    pub secret_ref: RadiusSecretRef,
241
242    /// Key containing the PEM certificate chain, defaults to tls.crt.
243    #[serde(default = "default_cert_key")]
244    pub cert_key: String,
245
246    /// Key containing the matching PEM private key, defaults to tls.key.
247    #[serde(default = "default_private_key")]
248    pub private_key_key: String,
249
250    /// Optional key in the same Secret containing the trusted EAP CA.
251    #[serde(skip_serializing_if = "Option::is_none")]
252    pub ca_key: Option<String>,
253}
254
255fn default_cert_key() -> String {
256    "tls.crt".into()
257}
258
259fn default_private_key() -> String {
260    "tls.key".into()
261}
262
263#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
264#[cfg_attr(feature = "schemars", derive(JsonSchema))]
265#[serde(rename_all = "camelCase")]
266#[cfg_attr(feature = "schemars", schemars(extend("x-kubernetes-validations" = [{"message": "RADIUS externalTrafficPolicy is only allowed for NodePort and LoadBalancer Services", "rule": "(has(self.type) ? self.type : 'ClusterIP') != 'ClusterIP' || !has(self.externalTrafficPolicy)"}])))]
267pub struct RadiusServiceSpec {
268    /// ClusterIP, NodePort or LoadBalancer. Defaults to ClusterIP.
269    #[serde(rename = "type", default = "default_service_type")]
270    #[schemars(extend("x-kubernetes-validations" = [{"message": "RADIUS Service must be ClusterIP, NodePort or LoadBalancer", "rule": "self in ['ClusterIP','NodePort','LoadBalancer']"}]))]
271    pub type_: String,
272
273    /// Exposed UDP Service port, defaults to 1812.
274    #[serde(default = "default_service_port")]
275    #[schemars(extend("x-kubernetes-validations" = [{"message": "RADIUS UDP port must be 1..65535", "rule": "self >= 1 && self <= 65535"}]))]
276    pub port: i32,
277
278    /// Cluster or Local. Only allowed for NodePort and LoadBalancer Services:
279    /// the CRD rejects it on a ClusterIP Service, as Kubernetes does.
280    #[serde(skip_serializing_if = "Option::is_none")]
281    #[schemars(extend("x-kubernetes-validations" = [{"message": "RADIUS externalTrafficPolicy must be Cluster or Local", "rule": "self in ['Cluster','Local']"}]))]
282    pub external_traffic_policy: Option<String>,
283
284    /// Annotations to place on the Service (for cloud load balancers).
285    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
286    pub annotations: BTreeMap<String, String>,
287}
288
289impl Default for RadiusServiceSpec {
290    fn default() -> Self {
291        Self {
292            type_: default_service_type(),
293            port: default_service_port(),
294            external_traffic_policy: None,
295            annotations: BTreeMap::new(),
296        }
297    }
298}
299
300fn default_service_type() -> String {
301    "ClusterIP".into()
302}
303
304fn default_service_port() -> i32 {
305    1812
306}
307
308/// Observed state, recomputed from Kanidm and Kubernetes on every reconcile.
309///
310/// Status is a report and cache only: the controller never reads it to decide
311/// what to do, so losing it changes nothing. It carries token **ids** only,
312/// never token values or NAS secrets.
313#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
314#[cfg_attr(feature = "schemars", derive(JsonSchema))]
315#[serde(rename_all = "camelCase")]
316pub struct KanidmRadiusServerStatus {
317    /// `IdentityReady`, `ConfigurationReady`, `Available`, `Exposed` and
318    /// `Rotating`; all five are always present.
319    #[serde(default, skip_serializing_if = "Option::is_none")]
320    #[cfg_attr(
321        feature = "schemars",
322        schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
323    )]
324    pub conditions: Option<Vec<Condition>>,
325
326    /// True when the identity and configuration are ready, the rollout is
327    /// complete and available, and the Service is exposed.
328    #[serde(default)]
329    pub ready: bool,
330
331    #[serde(skip_serializing_if = "Option::is_none")]
332    pub observed_generation: Option<i64>,
333
334    /// Address clients should use, `host:port` of the Service (shown as the
335    /// `Endpoint` print column): the cluster IP for `ClusterIP`, `*:<nodePort>`
336    /// (any node address) for `NodePort`, and the load balancer address for
337    /// `LoadBalancer`. Absent until an address is assigned.
338    #[serde(skip_serializing_if = "Option::is_none")]
339    pub endpoint: Option<String>,
340
341    /// Id of the Kanidm API token the Deployment template runs with.
342    #[serde(skip_serializing_if = "Option::is_none")]
343    pub token_id: Option<String>,
344
345    /// When Kanidm issued the current token.
346    #[serde(skip_serializing_if = "Option::is_none")]
347    pub token_issued_at: Option<Time>,
348
349    /// Immutable config Secret the Deployment template mounts.
350    #[serde(skip_serializing_if = "Option::is_none")]
351    pub config_secret_name: Option<String>,
352
353    #[serde(skip_serializing_if = "Option::is_none")]
354    pub deployment_name: Option<String>,
355
356    #[serde(skip_serializing_if = "Option::is_none")]
357    pub service_name: Option<String>,
358
359    /// Desired replicas of the Deployment.
360    #[serde(skip_serializing_if = "Option::is_none")]
361    pub replicas: Option<i32>,
362
363    #[serde(skip_serializing_if = "Option::is_none")]
364    pub ready_replicas: Option<i32>,
365
366    /// Tokens still on the account but no longer current; revoked once no
367    /// pod, ReplicaSet or template uses them. Informational only.
368    #[serde(default, skip_serializing_if = "Vec::is_empty")]
369    pub retiring_token_ids: Vec<String>,
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375
376    #[test]
377    fn defaults_are_explicit_and_are_not_permissive() {
378        assert_eq!(RadiusServiceSpec::default().type_, "ClusterIP");
379        assert_eq!(RadiusServiceSpec::default().port, 1812);
380        assert!(!SecretRotation::default().enabled);
381        assert_eq!(SecretRotation::default().period_days, 90);
382        let spec: KanidmRadiusServerSpec = serde_json::from_value(serde_json::json!({
383            "kanidmRef": {"name": "idm"},
384            "authorization": {"requiredGroups": ["allowed@idm.example.com"]},
385            "clients": [{"name": "nas", "ipaddr": "192.0.2.1", "sharedSecretRef": {"name": "nas-secret", "key": "nas"}}],
386            "radiusTls": {"secretRef": {"name": "eap-tls"}}
387        })).unwrap();
388        assert_eq!(spec.token_rotation.period_days, 90);
389        assert_eq!(default_replicas(), 2);
390    }
391
392    #[test]
393    fn nas_secrets_are_references_only() {
394        let value: RadiusClientSpec = serde_json::from_value(serde_json::json!({
395            "name": "mikrotik",
396            "ipaddr": "192.0.2.10",
397            "sharedSecretRef": {"name": "nas-credentials", "key": "mikrotik"}
398        }))
399        .unwrap();
400        assert_eq!(value.shared_secret_ref.name, "nas-credentials");
401        let serialized = serde_json::to_string(&value).unwrap();
402        assert!(!serialized.contains("sharedSecret\""));
403        assert!(serialized.contains("sharedSecretRef"));
404        let raw_secret = serde_json::json!({
405            "name": "mikrotik",
406            "ipaddr": "192.0.2.10",
407            "sharedSecret": "do-not-store-this",
408            "sharedSecretRef": {"name": "nas-credentials", "key": "mikrotik"}
409        });
410        assert!(serde_json::from_value::<RadiusClientSpec>(raw_secret).is_err());
411    }
412
413    #[test]
414    fn kanidm_ca_ref_kind_defaults_to_config_map_and_supports_secret() {
415        let implicit: RadiusCaBundleRef = serde_json::from_value(serde_json::json!({
416            "name": "kanidm-ca", "key": "ca.crt"
417        }))
418        .unwrap();
419        assert_eq!(implicit.kind, RadiusCaKind::ConfigMap);
420        // Explicitly serializing the default makes generated examples show
421        // the CA source kind without changing deserialization compatibility.
422        let serialized = serde_json::to_value(&implicit).unwrap();
423        assert_eq!(serialized["kind"], "ConfigMap");
424
425        let explicit: RadiusCaBundleRef = serde_json::from_value(serde_json::json!({
426            "kind": "Secret", "name": "private-ca", "key": "ca.crt"
427        }))
428        .unwrap();
429        assert_eq!(explicit.kind, RadiusCaKind::Secret);
430        assert_eq!(serde_json::to_value(&explicit).unwrap()["kind"], "Secret");
431        assert!(
432            serde_json::from_value::<RadiusCaBundleRef>(serde_json::json!({
433                "kind": "Pod", "name": "bad", "key": "ca.crt"
434            }))
435            .is_err()
436        );
437    }
438
439    #[test]
440    fn status_reports_token_ids_and_round_trips() {
441        let status = KanidmRadiusServerStatus {
442            token_id: Some("9ad74e68-147f-49e8-96db-dc21c920ff3b".into()),
443            config_secret_name: Some("campus-0123456789".into()),
444            retiring_token_ids: vec!["31b30b65-037a-418f-b7ca-0c376da2db28".into()],
445            ..Default::default()
446        };
447        let value = serde_json::to_value(&status).unwrap();
448        assert_eq!(value["tokenId"], "9ad74e68-147f-49e8-96db-dc21c920ff3b");
449        assert_eq!(value["configSecretName"], "campus-0123456789");
450        // An empty retiring list is omitted.
451        let empty = serde_json::to_value(KanidmRadiusServerStatus::default()).unwrap();
452        assert!(empty.get("retiringTokenIds").is_none());
453        let restored: KanidmRadiusServerStatus = serde_json::from_value(value).unwrap();
454        assert_eq!(restored, status);
455    }
456
457    #[cfg(feature = "schemars")]
458    #[test]
459    fn conditions_have_map_list_schema_and_refs_are_immutable() {
460        use kube::CustomResourceExt;
461
462        let crd = KanidmRadiusServer::crd();
463        // Catch a schema default that violates its own CEL validation before
464        // Helm/Kind installation (e.g. an accidental derived Rust Default=0).
465        let schema = serde_json::to_value(&crd).unwrap();
466        assert_eq!(
467            schema.pointer("/spec/versions/0/schema/openAPIV3Schema/properties/spec/properties/tokenRotation/default/periodDays"),
468            Some(&serde_json::json!(90))
469        );
470        let json = serde_json::to_string(&crd).unwrap();
471        assert!(json.contains("x-kubernetes-list-type"));
472        assert!(json.contains("x-kubernetes-list-map-keys"));
473        assert!(json.contains("Value is immutable"));
474        assert!(json.contains("At least one RADIUS NAS client is required"));
475        assert!(json.contains("At least one RADIUS authorization group is required"));
476        assert!(json.contains("RADIUS default VLAN must be in 1..4094"));
477        assert!(json.contains("RADIUS NAS client name must be a safe FreeRADIUS identifier"));
478    }
479
480    #[cfg(feature = "schemars")]
481    #[test]
482    fn cel_validated_lists_and_strings_are_bounded() {
483        use kube::CustomResourceExt;
484
485        // Unbounded lists/strings make the API server reject the CRD because the
486        // estimated CEL rule cost exceeds its budget.
487        let schema = serde_json::to_value(KanidmRadiusServer::crd()).unwrap();
488        let spec = "/spec/versions/0/schema/openAPIV3Schema/properties/spec/properties";
489        let at = |path: &str| schema.pointer(&format!("{spec}/{path}")).cloned();
490
491        for list in [
492            "clients",
493            "authorization/properties/requiredGroups",
494            "authorization/properties/groupVlans",
495        ] {
496            assert_eq!(
497                at(&format!("{list}/maxItems")),
498                Some(serde_json::json!(100)),
499                "{list} must define maxItems"
500            );
501        }
502        assert_eq!(
503            at("clients/items/properties/name/maxLength"),
504            Some(serde_json::json!(63))
505        );
506        assert_eq!(
507            at("authorization/properties/requiredGroups/items/maxLength"),
508            Some(serde_json::json!(253))
509        );
510        assert_eq!(
511            at("authorization/properties/groupVlans/items/properties/group/maxLength"),
512            Some(serde_json::json!(253))
513        );
514    }
515
516    #[cfg(feature = "schemars")]
517    #[test]
518    fn name_length_rule_matches_the_generated_name_limit() {
519        use kube::CustomResourceExt;
520
521        let value = serde_json::to_value(KanidmRadiusServer::crd()).unwrap();
522        let rules = value
523            .pointer("/spec/versions/0/schema/openAPIV3Schema/x-kubernetes-validations")
524            .and_then(|rules| rules.as_array())
525            .expect("root x-kubernetes-validations");
526        let max = crate::reconcile::workload::MAX_RADIUS_NAME_LEN;
527        assert!(
528            rules
529                .iter()
530                .any(|rule| rule["rule"] == format!("size(self.metadata.name) <= {max}")),
531            "{rules:?}"
532        );
533    }
534
535    #[cfg(feature = "schemars")]
536    #[test]
537    fn service_rule_rejects_external_traffic_policy_on_cluster_ip() {
538        use kube::CustomResourceExt;
539
540        let value = serde_json::to_value(KanidmRadiusServer::crd()).unwrap();
541        let service = value
542            .pointer("/spec/versions/0/schema/openAPIV3Schema/properties/spec/properties/service")
543            .expect("service schema");
544        let rules = service["x-kubernetes-validations"]
545            .as_array()
546            .expect("service x-kubernetes-validations");
547        // `type` defaults to ClusterIP, so the rule must hold when it is absent.
548        assert!(
549            rules.iter().any(|rule| rule["rule"]
550                == "(has(self.type) ? self.type : 'ClusterIP') != 'ClusterIP' || !has(self.externalTrafficPolicy)"
551                && rule["message"]
552                    .as_str()
553                    .is_some_and(|m| m.contains("only allowed for NodePort and LoadBalancer"))),
554            "{rules:?}"
555        );
556        assert_eq!(service["properties"]["type"]["default"], "ClusterIP");
557    }
558
559    #[cfg(feature = "schemars")]
560    #[test]
561    fn print_columns_show_readiness_and_endpoint() {
562        use kube::CustomResourceExt;
563
564        let value = serde_json::to_value(KanidmRadiusServer::crd()).unwrap();
565        let columns = value
566            .pointer("/spec/versions/0/additionalPrinterColumns")
567            .and_then(|columns| columns.as_array())
568            .unwrap();
569        let names: Vec<_> = columns
570            .iter()
571            .map(|column| column["name"].as_str().unwrap())
572            .collect();
573        assert_eq!(names, ["Kanidm", "Ready", "Endpoint", "Age"]);
574        let status = KanidmRadiusServerStatus {
575            endpoint: Some("10.0.0.1:1812".into()),
576            ..Default::default()
577        };
578        assert_eq!(
579            serde_json::to_value(status).unwrap()["endpoint"],
580            "10.0.0.1:1812"
581        );
582    }
583}