Skip to main content

engenho_controllers/
crd_validator.rs

1//! CRD validation webhook — typed-shape validation of CR writes.
2//!
3//! Performs typed-shape validation on every Put / Patch:
4//!   * The kind must be registered (or be in the core "always-allowed"
5//!     set: Pod / Service / Endpoints / etc.)
6//!   * Scope match — Namespaced kinds must have a namespace; Cluster-scoped
7//!     kinds must NOT.
8//!   * Required fields exist (shallow check via the entry's
9//!     `schema.required`, when present).
10//!
11//! ## Status: DEFERRED + UNWIRED
12//!
13//! This webhook is NOT wired into the runtime admission chain today —
14//! structural-schema validation of CR instances is a DEFERRED surface (per
15//! the CRD-serving scope boundary: CR creates are accepted as opaque JSON
16//! via `kubectl apply --validate=false`; we never CLAIM validation, so
17//! there is no false-accept of a malformed object). Full JSON Schema Draft 7
18//! validation requires a schema-compiler crate; future R22b lands it as an
19//! optional cargo feature so the substrate stays light.
20//!
21//! It carries its own read-only [`ValidationRegistry`] snapshot rather than
22//! re-introducing a parallel routing surface — routing now lives ONLY in the
23//! apiserver's `RouterState` (driven by `CrdController` via
24//! [`crate::DynamicHandlerSink`]). When validation is wired, the source of
25//! the registered-kinds snapshot will be the controller's bookkeeping (or a
26//! read view of the router table), NOT a second authoritative registry.
27
28use std::collections::{BTreeMap, BTreeSet};
29use std::sync::Arc;
30
31use serde_json::Value;
32
33use async_trait::async_trait;
34
35use crate::admission::{
36    AdmissionAction, AdmissionDecision, AdmissionError, AdmissionRequest, AdmissionWebhook,
37};
38use crate::crd::{CrdEntry, CrdScope};
39
40/// Read-only snapshot of registered CRD entries the validation webhook
41/// consults. Keyed by the canonical `{group}/{version}/{kind}` string.
42///
43/// Deliberately NOT a routing surface — it is a validation-only view. Built
44/// once from a `Vec<CrdEntry>` (e.g. the `CrdController`'s bookkeeping when
45/// validation is wired); not mutated concurrently with reads, so a plain
46/// `BTreeMap` (no lock) suffices.
47#[derive(Clone, Default, Debug)]
48pub struct ValidationRegistry {
49    by_key: BTreeMap<String, CrdEntry>,
50}
51
52impl ValidationRegistry {
53    /// Empty registry.
54    #[must_use]
55    pub fn new() -> Self {
56        Self::default()
57    }
58
59    /// Build from a snapshot of entries.
60    #[must_use]
61    pub fn from_entries(entries: Vec<CrdEntry>) -> Self {
62        let mut by_key = BTreeMap::new();
63        for e in entries {
64            by_key.insert(Self::key_of(&e), e);
65        }
66        Self { by_key }
67    }
68
69    /// Canonical `{group-or-v1}/{version}/{kind}` key.
70    fn key_of(e: &CrdEntry) -> String {
71        let g = if e.group.is_empty() {
72            "v1"
73        } else {
74            e.group.as_str()
75        };
76        let mut s = String::with_capacity(g.len() + e.version.len() + e.kind.len() + 2);
77        s.push_str(g);
78        s.push('/');
79        s.push_str(&e.version);
80        s.push('/');
81        s.push_str(&e.kind);
82        s
83    }
84
85    /// Look up an entry by canonical key.
86    #[must_use]
87    pub fn get(&self, key: &str) -> Option<&CrdEntry> {
88        self.by_key.get(key)
89    }
90}
91
92/// Core kinds the apiserver knows without an explicit CRD. Mirrors
93/// engenho-types's static catalog. Any kind not in this set must be
94/// registered in the [`ValidationRegistry`] before admission.
95fn core_kinds() -> BTreeSet<&'static str> {
96    [
97        "Pod",
98        "Service",
99        "Endpoints",
100        "ConfigMap",
101        "Secret",
102        "Namespace",
103        "Node",
104        "PersistentVolume",
105        "PersistentVolumeClaim",
106        "ReplicaSet",
107        "Deployment",
108        "StatefulSet",
109        "DaemonSet",
110        "Job",
111        "CronJob",
112        "Ingress",
113        "NetworkPolicy",
114        "HorizontalPodAutoscaler",
115        "PodDisruptionBudget",
116        "ServiceAccount",
117        "Role",
118        "RoleBinding",
119        "ClusterRole",
120        "ClusterRoleBinding",
121        "CustomResourceDefinition",
122    ]
123    .into_iter()
124    .collect()
125}
126
127/// Webhook that gates writes on kind registration + scope match.
128pub struct CrdValidationWebhook {
129    registry: ValidationRegistry,
130    core: BTreeSet<&'static str>,
131}
132
133impl CrdValidationWebhook {
134    /// New webhook backed by `registry`.
135    #[must_use]
136    pub fn new(registry: ValidationRegistry) -> Self {
137        Self {
138            registry,
139            core: core_kinds(),
140        }
141    }
142
143    /// True if `kind` is a substrate-known core kind.
144    #[must_use]
145    pub fn is_core_kind(&self, kind: &str) -> bool {
146        self.core.contains(kind)
147    }
148
149    /// Validate required fields exist on the value (shallow: only top-level
150    /// keys named in `schema.required` are checked). Returns the first
151    /// missing-required field name, or None.
152    #[must_use]
153    pub fn first_missing_required<'a>(schema: &'a Value, value: &Value) -> Option<&'a str> {
154        let required = schema.get("required")?.as_array()?;
155        for r in required {
156            let Some(name) = r.as_str() else { continue };
157            if value.get(name).is_none() {
158                return Some(name);
159            }
160        }
161        None
162    }
163}
164
165#[async_trait]
166impl AdmissionWebhook for CrdValidationWebhook {
167    fn name(&self) -> &'static str {
168        "crd-validation"
169    }
170
171    async fn review(
172        &self,
173        request: &AdmissionRequest,
174    ) -> Result<AdmissionDecision, AdmissionError> {
175        // Delete is allowed — we never block teardown for missing CRDs.
176        if request.action == AdmissionAction::Delete {
177            return Ok(AdmissionDecision::Allow);
178        }
179        // Core kinds bypass CRD lookup.
180        if self.is_core_kind(&request.key.kind) {
181            return Ok(AdmissionDecision::Allow);
182        }
183        // Compose the canonical registry key.
184        let g = if request.key.group.is_empty() {
185            "v1"
186        } else {
187            request.key.group.as_str()
188        };
189        let registry_key = format!("{g}/{}/{}", request.key.version, request.key.kind);
190        let entry = match self.registry.get(&registry_key) {
191            Some(e) => e,
192            None => {
193                return Ok(AdmissionDecision::Deny(format!(
194                    "kind {registry_key} is not registered"
195                )));
196            }
197        };
198        // Scope check.
199        match (entry.scope, request.key.namespace.as_deref()) {
200            (CrdScope::Cluster, Some(ns)) if !ns.is_empty() => {
201                return Ok(AdmissionDecision::Deny(format!(
202                    "kind {registry_key} is cluster-scoped; rejecting namespace={ns}"
203                )));
204            }
205            (CrdScope::Namespaced, None) => {
206                return Ok(AdmissionDecision::Deny(format!(
207                    "kind {registry_key} is namespaced; namespace required"
208                )));
209            }
210            _ => {}
211        }
212        // Shallow required-fields check (Put only — Patch can omit required
213        // fields as long as the merged result has them).
214        if request.action == AdmissionAction::Put
215            && let Some(value) = &request.value
216            && let Some(missing) = Self::first_missing_required(&entry.schema, value)
217        {
218            return Ok(AdmissionDecision::Deny(format!(
219                "required field {missing} missing on {registry_key}"
220            )));
221        }
222        Ok(AdmissionDecision::Allow)
223    }
224}
225
226/// Convenience constructor.
227#[must_use]
228pub fn crd_validation_webhook(registry: ValidationRegistry) -> Arc<dyn AdmissionWebhook> {
229    Arc::new(CrdValidationWebhook::new(registry))
230}
231
232#[cfg(test)]
233mod tests {
234    use super::*;
235    use engenho_store::resource::ResourceKey;
236    use serde_json::json;
237
238    fn ns_request(
239        action: AdmissionAction,
240        kind: &str,
241        ns: Option<&str>,
242        value: Value,
243    ) -> AdmissionRequest {
244        let key = match ns {
245            Some(n) => ResourceKey::namespaced("engenho.io", "v1", kind, n, "x"),
246            None => ResourceKey::cluster_scoped("engenho.io", "v1", kind, "x"),
247        };
248        AdmissionRequest {
249            action,
250            key,
251            value: Some(value),
252            current: None,
253            user_info: engenho_types::auth::UserInfo::default(),
254        }
255    }
256
257    /// Build a `CrdEntry` for `kind` with the given scope + schema.
258    fn entry(kind: &str, scope: CrdScope, schema: Value) -> CrdEntry {
259        CrdEntry {
260            group: "engenho.io".into(),
261            version: "v1".into(),
262            kind: kind.into(),
263            list_kind: format!("{kind}List"),
264            plural: format!("{}s", kind.to_lowercase()),
265            singular: kind.to_lowercase(),
266            short_names: Vec::new(),
267            categories: Vec::new(),
268            scope,
269            // These fixtures exercise SCHEMA validation, not the
270            // subresource surface — false keeps them at the old behaviour.
271            serves_status: false,
272            schema,
273            printer_columns: Vec::new(),
274        }
275    }
276
277    fn webhook_with(entries: Vec<CrdEntry>) -> CrdValidationWebhook {
278        CrdValidationWebhook::new(ValidationRegistry::from_entries(entries))
279    }
280
281    #[tokio::test]
282    async fn delete_always_allowed() {
283        let w = webhook_with(vec![]);
284        let req = ns_request(
285            AdmissionAction::Delete,
286            "Unknown",
287            Some("default"),
288            json!({}),
289        );
290        assert_eq!(w.review(&req).await.unwrap(), AdmissionDecision::Allow);
291    }
292
293    #[tokio::test]
294    async fn core_kind_bypasses_registry() {
295        let w = webhook_with(vec![]);
296        let req = AdmissionRequest {
297            action: AdmissionAction::Put,
298            key: ResourceKey::namespaced("", "v1", "Pod", "default", "x"),
299            value: Some(json!({})),
300            current: None,
301            user_info: engenho_types::auth::UserInfo::default(),
302        };
303        assert_eq!(w.review(&req).await.unwrap(), AdmissionDecision::Allow);
304    }
305
306    #[tokio::test]
307    async fn unregistered_custom_kind_is_denied() {
308        let w = webhook_with(vec![]);
309        let req = ns_request(AdmissionAction::Put, "Widget", Some("default"), json!({}));
310        let r = w.review(&req).await.unwrap();
311        match r {
312            AdmissionDecision::Deny(reason) => {
313                assert!(reason.contains("Widget"));
314                assert!(reason.contains("not registered"));
315            }
316            other => panic!("expected Deny, got {other:?}"),
317        }
318    }
319
320    #[tokio::test]
321    async fn registered_namespaced_kind_allowed() {
322        let w = webhook_with(vec![entry("Widget", CrdScope::Namespaced, json!({}))]);
323        let req = ns_request(
324            AdmissionAction::Put,
325            "Widget",
326            Some("default"),
327            json!({"spec": {}}),
328        );
329        assert_eq!(w.review(&req).await.unwrap(), AdmissionDecision::Allow);
330    }
331
332    #[tokio::test]
333    async fn cluster_scoped_kind_with_namespace_denied() {
334        let w = webhook_with(vec![entry("ClusterWidget", CrdScope::Cluster, json!({}))]);
335        let req = ns_request(
336            AdmissionAction::Put,
337            "ClusterWidget",
338            Some("default"),
339            json!({}),
340        );
341        let r = w.review(&req).await.unwrap();
342        assert!(matches!(r, AdmissionDecision::Deny(reason) if reason.contains("cluster-scoped")));
343    }
344
345    #[tokio::test]
346    async fn namespaced_kind_without_namespace_denied() {
347        let w = webhook_with(vec![entry("Widget", CrdScope::Namespaced, json!({}))]);
348        let req = ns_request(AdmissionAction::Put, "Widget", None, json!({}));
349        let r = w.review(&req).await.unwrap();
350        assert!(
351            matches!(r, AdmissionDecision::Deny(reason) if reason.contains("namespace required"))
352        );
353    }
354
355    #[tokio::test]
356    async fn missing_required_field_denied() {
357        let w = webhook_with(vec![entry(
358            "Widget",
359            CrdScope::Namespaced,
360            json!({"required": ["spec"]}),
361        )]);
362        let req = ns_request(
363            AdmissionAction::Put,
364            "Widget",
365            Some("default"),
366            json!({"metadata": {"name": "x"}}), // spec missing
367        );
368        let r = w.review(&req).await.unwrap();
369        assert!(matches!(r, AdmissionDecision::Deny(reason) if reason.contains("spec")));
370    }
371
372    #[tokio::test]
373    async fn required_field_present_allowed() {
374        let w = webhook_with(vec![entry(
375            "Widget",
376            CrdScope::Namespaced,
377            json!({"required": ["spec"]}),
378        )]);
379        let req = ns_request(
380            AdmissionAction::Put,
381            "Widget",
382            Some("default"),
383            json!({"spec": {}}),
384        );
385        assert_eq!(w.review(&req).await.unwrap(), AdmissionDecision::Allow);
386    }
387
388    #[tokio::test]
389    async fn patch_doesnt_enforce_required_fields() {
390        let w = webhook_with(vec![entry(
391            "Widget",
392            CrdScope::Namespaced,
393            json!({"required": ["spec"]}),
394        )]);
395        let req = ns_request(
396            AdmissionAction::Patch,
397            "Widget",
398            Some("default"),
399            json!({"metadata": {"labels": {"app": "x"}}}), // partial update; no spec
400        );
401        assert_eq!(w.review(&req).await.unwrap(), AdmissionDecision::Allow);
402    }
403
404    #[test]
405    fn first_missing_required_finds_first() {
406        let schema = json!({"required": ["a", "b", "c"]});
407        let value = json!({"a": 1, "c": 3});
408        assert_eq!(
409            CrdValidationWebhook::first_missing_required(&schema, &value),
410            Some("b")
411        );
412    }
413
414    #[test]
415    fn first_missing_required_returns_none_when_schema_has_no_required() {
416        let schema = json!({});
417        let value = json!({});
418        assert_eq!(
419            CrdValidationWebhook::first_missing_required(&schema, &value),
420            None
421        );
422    }
423
424    #[tokio::test]
425    async fn webhook_name_is_stable() {
426        let w = webhook_with(vec![]);
427        assert_eq!(w.name(), "crd-validation");
428    }
429}