Skip to main content

engenho_controllers/
admission.rs

1//! R20 — Admission webhook trait.
2//!
3//! Lets the apiserver call out to a pluggable validator before
4//! committing any `ResourceCommand`. Backends can:
5//!   * Inspect the proposed value (validation)
6//!   * Mutate the proposed value (mutating webhook)
7//!   * Reject the request with a typed reason
8//!
9//! ## Use-cases
10//!
11//! * Defaulting (mutating) — set missing `replicas`, inject sidecars
12//! * Validation — reject Pods without resource requests, enforce
13//!   network-policy labels, gate compliance overlays
14//! * Policy — enforce admission rules from a Cilium/OPA/Kyverno
15//!   compatibility layer
16//! * Tameshi attestation — verify image signatures before admission
17//!
18//! ## Decision shape
19//!
20//! Each webhook returns an [`AdmissionDecision`]:
21//!   * `Allow` — accept the request as-is
22//!   * `Mutate(new_value)` — accept with a transformed value
23//!   * `Deny(reason)` — reject; reason surfaces to the operator
24//!
25//! Multiple webhooks compose: the apiserver feeds the (possibly
26//! mutated) value through every registered webhook in order. First
27//! `Deny` short-circuits.
28
29use std::collections::BTreeMap;
30use std::sync::Arc;
31
32use async_trait::async_trait;
33use engenho_store::resource::ResourceKey;
34use serde_json::Value;
35use thiserror::Error;
36use tokio::sync::Mutex;
37
38/// What an admission webhook says about a request.
39#[derive(Clone, Debug, PartialEq, Eq)]
40pub enum AdmissionDecision {
41    /// Accept the request, optionally with a mutated value.
42    Allow,
43    /// Accept the request with the value replaced by `new`.
44    Mutate(Value),
45    /// Reject the request with a human-readable reason.
46    Deny(String),
47}
48
49/// What action the request is performing (mirrors `ResourceCommand`'s
50/// variants but as a flat enum the webhook can pattern-match on).
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum AdmissionAction {
53    /// `Put` of a new or existing resource.
54    Put,
55    /// `Patch` — partial update.
56    Patch,
57    /// `Delete` of an existing resource.
58    Delete,
59}
60
61/// The complete admission request handed to a webhook.
62#[derive(Clone, Debug)]
63pub struct AdmissionRequest {
64    /// What's being done.
65    pub action: AdmissionAction,
66    /// The target resource.
67    pub key: ResourceKey,
68    /// The proposed value (for Put / Patch). None for Delete.
69    pub value: Option<Value>,
70    /// The current stored value, if the resource already exists.
71    pub current: Option<Value>,
72    /// The AUTHENTICATED identity behind the request — populated by the
73    /// apiserver from the request's `Extension<UserInfo>` (the authenticator
74    /// chain's output). `UserInfo: Default` so existing test constructors that
75    /// build the brace-literal directly can use `UserInfo::default()` (the
76    /// empty identity) without a behavior change; the production `admit()` path
77    /// threads the real authenticated identity in. Mirrors upstream
78    /// `AdmissionReview.request.userInfo`.
79    pub user_info: engenho_types::auth::UserInfo,
80}
81
82/// Admission errors.
83#[derive(Debug, Clone, Error)]
84pub enum AdmissionError {
85    /// Webhook backend (HTTP / OPA / Kyverno) failed.
86    #[error("backend: {0}")]
87    Backend(String),
88}
89
90engenho_substrate::impl_error_kind! {
91    AdmissionError {
92        (Backend(_)) => "backend",
93    }
94}
95
96/// Pluggable admission webhook trait.
97#[async_trait]
98pub trait AdmissionWebhook: Send + Sync {
99    /// Webhook identifier for telemetry.
100    fn name(&self) -> &'static str;
101
102    /// Inspect / mutate / reject `request`.
103    ///
104    /// # Errors
105    /// [`AdmissionError::Backend`] on backend failure (caller
106    /// decides whether to fail-open or fail-closed via the
107    /// [`AdmissionChain`] mode).
108    async fn review(&self, request: &AdmissionRequest)
109    -> Result<AdmissionDecision, AdmissionError>;
110}
111
112// =================================================================
113// AdmissionChain — runs N webhooks in order, fan-out + short-circuit
114// =================================================================
115
116/// Composition policy when a webhook returns an error.
117#[derive(Clone, Copy, Debug, PartialEq, Eq)]
118pub enum AdmissionMode {
119    /// Treat backend errors as `Allow` (fail-open). Production
120    /// default for non-critical webhooks (e.g. metrics injectors).
121    FailOpen,
122    /// Treat backend errors as `Deny` (fail-closed). Production
123    /// default for compliance/security webhooks.
124    FailClosed,
125}
126
127/// Chain of webhooks evaluated in order. Each webhook's mutation is
128/// fed forward to the next; first Deny short-circuits.
129pub struct AdmissionChain {
130    hooks: Vec<Arc<dyn AdmissionWebhook>>,
131    mode: AdmissionMode,
132}
133
134impl AdmissionChain {
135    /// New chain with the given mode.
136    #[must_use]
137    pub fn new(hooks: Vec<Arc<dyn AdmissionWebhook>>, mode: AdmissionMode) -> Self {
138        Self { hooks, mode }
139    }
140
141    /// Evaluate the chain. Returns the final value (possibly
142    /// mutated) on Allow; the Deny reason on rejection.
143    pub async fn review(&self, mut request: AdmissionRequest) -> AdmissionDecision {
144        for hook in &self.hooks {
145            let decision = match hook.review(&request).await {
146                Ok(d) => d,
147                Err(_) => match self.mode {
148                    AdmissionMode::FailOpen => AdmissionDecision::Allow,
149                    AdmissionMode::FailClosed => {
150                        return AdmissionDecision::Deny(format!(
151                            "{}: backend failure (fail-closed)",
152                            hook.name()
153                        ));
154                    }
155                },
156            };
157            match decision {
158                AdmissionDecision::Allow => continue,
159                AdmissionDecision::Mutate(new) => {
160                    request.value = Some(new);
161                }
162                AdmissionDecision::Deny(reason) => {
163                    return AdmissionDecision::Deny(format!("{}: {reason}", hook.name()));
164                }
165            }
166        }
167        // Either the value is unchanged (Allow) or it was mutated
168        // through the chain — both surface as Allow/Mutate.
169        match request.value {
170            Some(v) => AdmissionDecision::Mutate(v),
171            None => AdmissionDecision::Allow,
172        }
173    }
174
175    /// Count of hooks in the chain.
176    #[must_use]
177    pub fn len(&self) -> usize {
178        self.hooks.len()
179    }
180
181    /// True if no hooks are registered.
182    #[must_use]
183    pub fn is_empty(&self) -> bool {
184        self.hooks.is_empty()
185    }
186}
187
188// =================================================================
189// FakeAdmissionWebhook — deterministic for tests
190// =================================================================
191
192/// Test webhook with explicit decisions per-key. Records review calls.
193#[derive(Clone, Default)]
194pub struct FakeAdmissionWebhook {
195    inner: Arc<Mutex<FakeAdmissionState>>,
196    backend_name: &'static str,
197}
198
199#[derive(Default)]
200struct FakeAdmissionState {
201    decisions: BTreeMap<String, AdmissionDecision>,
202    fail_with: Option<String>,
203    call_log: Vec<(AdmissionAction, String)>,
204    /// The `user_info` observed on the MOST RECENT review — lets a test prove
205    /// the apiserver threaded the authenticated identity into
206    /// `AdmissionRequest.user_info` (not the empty default).
207    last_user_info: Option<engenho_types::auth::UserInfo>,
208}
209
210impl FakeAdmissionWebhook {
211    /// New webhook with the given telemetry name.
212    #[must_use]
213    pub fn new(name: &'static str) -> Self {
214        Self {
215            inner: Arc::new(Mutex::new(FakeAdmissionState::default())),
216            backend_name: name,
217        }
218    }
219
220    /// Pin a decision for a specific resource (by `key.label()`).
221    pub async fn set_decision(&self, key: &str, d: AdmissionDecision) {
222        self.inner.lock().await.decisions.insert(key.to_string(), d);
223    }
224
225    /// Make `review` return `AdmissionError::Backend` for the next call.
226    pub async fn fail_next(&self, msg: impl Into<String>) {
227        self.inner.lock().await.fail_with = Some(msg.into());
228    }
229
230    /// Snapshot of the call log.
231    pub async fn calls(&self) -> Vec<(AdmissionAction, String)> {
232        self.inner.lock().await.call_log.clone()
233    }
234
235    /// The `user_info` the webhook observed on the most recent review. `None`
236    /// until at least one review has run. Lets an integration test assert the
237    /// apiserver threaded the AUTHENTICATED identity into the admission request.
238    pub async fn last_user_info(&self) -> Option<engenho_types::auth::UserInfo> {
239        self.inner.lock().await.last_user_info.clone()
240    }
241}
242
243#[async_trait]
244impl AdmissionWebhook for FakeAdmissionWebhook {
245    fn name(&self) -> &'static str {
246        self.backend_name
247    }
248
249    async fn review(
250        &self,
251        request: &AdmissionRequest,
252    ) -> Result<AdmissionDecision, AdmissionError> {
253        let mut state = self.inner.lock().await;
254        state.call_log.push((request.action, request.key.label()));
255        state.last_user_info = Some(request.user_info.clone());
256        if let Some(msg) = state.fail_with.take() {
257            return Err(AdmissionError::Backend(msg));
258        }
259        Ok(state
260            .decisions
261            .get(&request.key.label())
262            .cloned()
263            .unwrap_or(AdmissionDecision::Allow))
264    }
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270    use serde_json::json;
271
272    fn req(action: AdmissionAction, name: &str, value: Value) -> AdmissionRequest {
273        AdmissionRequest {
274            action,
275            key: ResourceKey::namespaced("", "v1", "Pod", "default", name),
276            value: Some(value),
277            current: None,
278            user_info: engenho_types::auth::UserInfo::default(),
279        }
280    }
281
282    fn label_for(name: &str) -> String {
283        ResourceKey::namespaced("", "v1", "Pod", "default", name).label()
284    }
285
286    #[tokio::test]
287    async fn allow_passes_through_unchanged() {
288        let hook = Arc::new(FakeAdmissionWebhook::new("test"));
289        let chain = AdmissionChain::new(vec![hook], AdmissionMode::FailClosed);
290        let r = chain
291            .review(req(AdmissionAction::Put, "x", json!({"spec": {}})))
292            .await;
293        // value was set → returns Mutate of unchanged value
294        assert!(matches!(r, AdmissionDecision::Mutate(_)));
295    }
296
297    #[tokio::test]
298    async fn deny_short_circuits_chain() {
299        let h1 = Arc::new(FakeAdmissionWebhook::new("h1"));
300        let h2 = Arc::new(FakeAdmissionWebhook::new("h2"));
301        h1.set_decision(&label_for("x"), AdmissionDecision::Deny("no".into()))
302            .await;
303        let chain = AdmissionChain::new(vec![h1.clone(), h2.clone()], AdmissionMode::FailClosed);
304        let r = chain
305            .review(req(AdmissionAction::Put, "x", json!({})))
306            .await;
307        assert!(
308            matches!(r, AdmissionDecision::Deny(reason) if reason.contains("h1") && reason.contains("no"))
309        );
310        // h2 should NOT have been called.
311        assert_eq!(h2.calls().await.len(), 0);
312    }
313
314    #[tokio::test]
315    async fn mutate_feeds_forward() {
316        let h1 = Arc::new(FakeAdmissionWebhook::new("defaulter"));
317        let h2 = Arc::new(FakeAdmissionWebhook::new("validator"));
318        h1.set_decision(
319            &label_for("x"),
320            AdmissionDecision::Mutate(json!({"spec": {"replicas": 3}})),
321        )
322        .await;
323        // h2 sees the mutated value: read the call log
324        let chain = AdmissionChain::new(vec![h1.clone(), h2.clone()], AdmissionMode::FailClosed);
325        let r = chain
326            .review(req(AdmissionAction::Put, "x", json!({"spec": {}})))
327            .await;
328        match r {
329            AdmissionDecision::Mutate(v) => {
330                assert_eq!(v.get("spec").unwrap().get("replicas").unwrap(), 3);
331            }
332            other => panic!("expected Mutate, got {other:?}"),
333        }
334        assert_eq!(h2.calls().await.len(), 1);
335    }
336
337    #[tokio::test]
338    async fn fail_open_treats_error_as_allow() {
339        let h1 = Arc::new(FakeAdmissionWebhook::new("h1"));
340        h1.fail_next("oops").await;
341        let chain = AdmissionChain::new(vec![h1], AdmissionMode::FailOpen);
342        let r = chain
343            .review(req(AdmissionAction::Put, "x", json!({})))
344            .await;
345        // Failure swallowed; value still flows through as Mutate(unchanged).
346        assert!(matches!(r, AdmissionDecision::Mutate(_)));
347    }
348
349    #[tokio::test]
350    async fn fail_closed_treats_error_as_deny() {
351        let h1 = Arc::new(FakeAdmissionWebhook::new("compliance"));
352        h1.fail_next("oops").await;
353        let chain = AdmissionChain::new(vec![h1], AdmissionMode::FailClosed);
354        let r = chain
355            .review(req(AdmissionAction::Put, "x", json!({})))
356            .await;
357        match r {
358            AdmissionDecision::Deny(reason) => {
359                assert!(reason.contains("compliance"));
360                assert!(reason.contains("fail-closed"));
361            }
362            other => panic!("expected Deny, got {other:?}"),
363        }
364    }
365
366    #[tokio::test]
367    async fn empty_chain_allows_anything() {
368        let chain = AdmissionChain::new(vec![], AdmissionMode::FailClosed);
369        let r = chain
370            .review(req(AdmissionAction::Put, "x", json!({})))
371            .await;
372        assert!(matches!(r, AdmissionDecision::Mutate(_)));
373    }
374
375    #[tokio::test]
376    async fn chain_metadata_helpers() {
377        let h1 = Arc::new(FakeAdmissionWebhook::new("a"));
378        let h2 = Arc::new(FakeAdmissionWebhook::new("b"));
379        let chain = AdmissionChain::new(vec![h1, h2], AdmissionMode::FailOpen);
380        assert_eq!(chain.len(), 2);
381        assert!(!chain.is_empty());
382        let empty = AdmissionChain::new(vec![], AdmissionMode::FailOpen);
383        assert!(empty.is_empty());
384    }
385
386    #[test]
387    fn admission_error_kind_is_stable() {
388        assert_eq!(AdmissionError::Backend("x".into()).kind(), "backend");
389    }
390
391    #[tokio::test]
392    async fn webhook_observes_threaded_user_info() {
393        // A webhook records the `user_info` on the AdmissionRequest it reviews —
394        // the apiserver-side threading is proven end-to-end in the
395        // m0_authn.rs integration test; here we prove the webhook surface sees a
396        // non-default identity (the brace-literal default would be empty).
397        let hook = Arc::new(FakeAdmissionWebhook::new("observer"));
398        let chain = AdmissionChain::new(vec![hook.clone()], AdmissionMode::FailClosed);
399        let mut request = req(AdmissionAction::Put, "x", json!({}));
400        request.user_info = engenho_types::auth::UserInfo::admin();
401        let _ = chain.review(request).await;
402        let observed = hook.last_user_info().await.expect("a review ran");
403        assert_eq!(observed.username, "engenho-admin");
404        assert!(observed.groups.iter().any(|g| g == "system:masters"));
405    }
406
407    #[tokio::test]
408    async fn default_request_carries_empty_user_info() {
409        // The legacy brace-literal path (user_info: UserInfo::default()) is the
410        // empty identity — the existing test constructors are unchanged.
411        let hook = Arc::new(FakeAdmissionWebhook::new("observer"));
412        let chain = AdmissionChain::new(vec![hook.clone()], AdmissionMode::FailClosed);
413        let _ = chain
414            .review(req(AdmissionAction::Put, "x", json!({})))
415            .await;
416        let observed = hook.last_user_info().await.expect("a review ran");
417        assert_eq!(observed, engenho_types::auth::UserInfo::default());
418    }
419}