Skip to main content

engenho_controllers/
admission_webhook.rs

1//! Dynamic admission webhooks — the apiserver-side call-out to
2//! `MutatingWebhookConfiguration` (and the `ValidatingWebhookConfiguration`
3//! call path) registered under `admissionregistration.k8s.io/v1`.
4//!
5//! This is THE brick that lets a service mesh (tatara-mesh) run on engenho:
6//! the mesh's sidecar injector (`lareira-enxerto`) is a
7//! `MutatingWebhookConfiguration` that intercepts Pod creation and injects the
8//! `aresta` proxy sidecar + a SPIRE-agent init container as a base64
9//! RFC6902 `JSONPatch`. This module dispatches that call-out and applies the
10//! returned patch to the object BEFORE it is persisted — and the kubelet's
11//! init-container driver (commit a7810a6) then runs the injected init
12//! container. The loop closes.
13//!
14//! ## Shape (★★ TYPED-SPEC + INTERPRETER TRIPLET — Environment trait)
15//!
16//! The interpreter is [`MutatingWebhookPlugin`] (an [`AdmissionWebhook`]). Its
17//! two side effects are abstracted behind traits so the whole plugin is
18//! unit-testable with ZERO network + ZERO store:
19//!
20//!   1. [`WebhookConfigSource`] — "list the live
21//!      `MutatingWebhookConfiguration` objects" (production: read the store;
22//!      test: an in-memory list).
23//!   2. [`WebhookCaller`] — "POST this `AdmissionReview` JSON to a webhook
24//!      endpoint and return its response JSON" (production: HTTPS via reqwest,
25//!      lives in the apiserver crate; test: a canned-patch mock).
26//!
27//! The wire `AdmissionReview` request/response objects are built + read as
28//! typed `serde_json::Value` trees (NO `format!()` of JSON — ★★ TYPED
29//! EMISSION). The returned base64 `JSONPatch` is decoded + applied through
30//! [`engenho_store::patch_apply`]'s RFC6902 engine — the SAME engine the
31//! apiserver's `kubectl patch --type=json` path uses (solve-once: no second
32//! patch implementation).
33//!
34//! ## Honest scope (deferred surfaces are TYPED, never silent)
35//!
36//!   * `clientConfig.url` is supported. `clientConfig.service` is ALSO
37//!     supported now: the plugin resolves `{namespace, name, port, path}`
38//!     to the Service's allocated `ClusterIP` via the [`ServiceResolver`]
39//!     seam and synthesizes `https://<clusterIP>:<port><path>`, which the
40//!     [`WebhookCaller`] then calls (this is the brick the `ClusterIP`
41//!     allocator unblocks). A Service that has NO `ClusterIP` yet (headless,
42//!     or not-yet-allocated) yields a typed
43//!     [`WebhookError::ServiceUnresolvable`] the `failurePolicy` governs —
44//!     never a silent skip.
45//!   * `clientConfig.caBundle` TLS verification is DEFERRED to the production
46//!     [`WebhookCaller`] impl in the apiserver crate; this module records the
47//!     caBundle on the typed [`WebhookClientConfig`] + passes it to the caller.
48//!     The security control is surfaced, never dropped.
49//!   * `namespaceSelector` / `objectSelector` are matched best-effort against
50//!     the request object's own labels + namespace label set the caller may
51//!     thread in; an unparseable selector denies the match (conservative).
52
53use std::sync::Arc;
54
55use async_trait::async_trait;
56use base64::Engine as _;
57use serde_json::{Value, json};
58use thiserror::Error;
59use tokio::sync::Mutex;
60
61use engenho_store::patch_apply::{
62    Gvk, MockPatchEnv, PatchBody, PatchSchemaEnv, apply as apply_patch,
63};
64use engenho_types::patch::PatchType;
65
66use crate::admission::{
67    AdmissionAction, AdmissionDecision, AdmissionError, AdmissionRequest, AdmissionWebhook,
68};
69
70// ═══════════════════════════════════════════════════════════════════════════
71//  Typed border — the webhook-configuration shapes we read off the wire.
72// ═══════════════════════════════════════════════════════════════════════════
73
74/// A single `MutatingWebhook` entry within a `MutatingWebhookConfiguration`.
75///
76/// Parsed from the opaque-JSON config object the apiserver stores (the
77/// admissionregistration kinds are served as opaque JSON today). A field the
78/// config omits takes the K8s default.
79#[derive(Clone, Debug, PartialEq, Eq)]
80pub struct MutatingWebhook {
81    /// `webhooks[].name` — telemetry + ordering identity.
82    pub name: String,
83    /// Where to call (`clientConfig`).
84    pub client_config: WebhookClientConfig,
85    /// `webhooks[].rules` — which (group, version, resource, operation)
86    /// requests this webhook intercepts. Empty ⇒ matches nothing.
87    pub rules: Vec<RuleWithOperations>,
88    /// `webhooks[].failurePolicy` — `Fail` (default) ⇒ a call/parse error
89    /// rejects the request; `Ignore` ⇒ the request proceeds unmutated.
90    pub failure_policy: FailurePolicy,
91    /// `webhooks[].timeoutSeconds` — per-call deadline (default 10, max 30).
92    pub timeout_seconds: u32,
93    /// `webhooks[].reinvocationPolicy` — `Never` (default) ⇒ called once;
94    /// `IfNeeded` ⇒ may be reinvoked if a later webhook mutated the object.
95    pub reinvocation_policy: ReinvocationPolicy,
96    /// `webhooks[].namespaceSelector` — best-effort label match on the
97    /// request namespace's labels. `None` ⇒ matches all namespaces.
98    pub namespace_selector: Option<LabelSelector>,
99    /// `webhooks[].objectSelector` — best-effort label match on the request
100    /// object's own labels. `None` ⇒ matches all objects.
101    pub object_selector: Option<LabelSelector>,
102}
103
104/// `clientConfig` — how to reach the webhook server.
105#[derive(Clone, Debug, PartialEq, Eq)]
106pub struct WebhookClientConfig {
107    /// `clientConfig.url` — a fully-qualified `https://…/path` endpoint.
108    pub url: Option<String>,
109    /// `clientConfig.service` — an in-cluster Service ref. Resolved to the
110    /// Service's allocated `ClusterIP` via a [`ServiceResolver`] when one is
111    /// wired (→ `https://<clusterIP>:<port><path>`); a Service with no VIP
112    /// yields a typed [`WebhookError::ServiceUnresolvable`]. A `url`, when
113    /// also set, takes precedence.
114    pub service: Option<ServiceRef>,
115    /// `clientConfig.caBundle` — base64 PEM CA bundle for verifying the
116    /// webhook's serving cert. Threaded to the [`WebhookCaller`]; the actual
117    /// TLS verification is the caller's responsibility (DEFERRED in the
118    /// reqwest impl, surfaced never dropped).
119    pub ca_bundle: Option<String>,
120}
121
122/// `clientConfig.service` — `{namespace, name, path?, port?}`.
123#[derive(Clone, Debug, PartialEq, Eq)]
124pub struct ServiceRef {
125    /// Service namespace.
126    pub namespace: String,
127    /// Service name.
128    pub name: String,
129    /// URL path on the service (default `/`).
130    pub path: Option<String>,
131    /// Service port (default 443).
132    pub port: Option<u16>,
133}
134
135/// One `rules[]` entry — the (apiGroups, apiVersions, resources, operations)
136/// match set.
137#[derive(Clone, Debug, PartialEq, Eq)]
138pub struct RuleWithOperations {
139    /// `operations` — `CREATE` / `UPDATE` / `DELETE` / `*`.
140    pub operations: Vec<String>,
141    /// `apiGroups` — `""` (core) / a group / `*`.
142    pub api_groups: Vec<String>,
143    /// `apiVersions` — `v1` / `*`.
144    pub api_versions: Vec<String>,
145    /// `resources` — plural resource name (`pods`) / `*`.
146    pub resources: Vec<String>,
147}
148
149/// `failurePolicy` discriminant.
150#[derive(Clone, Copy, Debug, PartialEq, Eq)]
151pub enum FailurePolicy {
152    /// Reject the request when the webhook errors (K8s default).
153    Fail,
154    /// Proceed (unmutated by this webhook) when the webhook errors.
155    Ignore,
156}
157
158/// `reinvocationPolicy` discriminant.
159#[derive(Clone, Copy, Debug, PartialEq, Eq)]
160pub enum ReinvocationPolicy {
161    /// Call once (K8s default).
162    Never,
163    /// May reinvoke if a later webhook mutated the object.
164    IfNeeded,
165}
166
167/// A label selector — `matchLabels` only (the common shape; `matchExpressions`
168/// is a typed follow-up). `None`-equivalent (match-all) is modeled by an
169/// `Option<LabelSelector>` at the use site, not by an empty selector here.
170#[derive(Clone, Debug, PartialEq, Eq, Default)]
171pub struct LabelSelector {
172    /// `matchLabels` — every (k, v) must be present on the target.
173    pub match_labels: std::collections::BTreeMap<String, String>,
174}
175
176impl LabelSelector {
177    /// True iff every `matchLabels` pair is present in `labels`.
178    #[must_use]
179    pub fn matches(&self, labels: &std::collections::BTreeMap<String, String>) -> bool {
180        self.match_labels
181            .iter()
182            .all(|(k, v)| labels.get(k).is_some_and(|got| got == v))
183    }
184}
185
186// ═══════════════════════════════════════════════════════════════════════════
187//  Errors.
188// ═══════════════════════════════════════════════════════════════════════════
189
190/// A typed failure from the webhook plugin. NO silent wrong answers — every
191/// surface that can't honor a webhook returns one of these; the caller's
192/// `failurePolicy` then decides Fail vs Ignore.
193#[derive(Debug, Clone, Error, PartialEq, Eq)]
194pub enum WebhookError {
195    /// The [`WebhookCaller`] failed to reach / get a response from the
196    /// endpoint (network, TLS, timeout, non-2xx).
197    #[error("call to webhook {webhook:?} failed: {message}")]
198    CallFailed {
199        /// The webhook's `name`.
200        webhook: String,
201        /// Backend message.
202        message: String,
203    },
204    /// The webhook's `AdmissionReview` response was malformed (missing
205    /// `response`, bad `uid`, …).
206    #[error("webhook {webhook:?} returned a malformed AdmissionReview: {reason}")]
207    BadResponse {
208        /// The webhook's `name`.
209        webhook: String,
210        /// What was wrong.
211        reason: String,
212    },
213    /// The webhook returned a `patchType` other than `JSONPatch`.
214    #[error("webhook {webhook:?} returned unsupported patchType {got:?} (only JSONPatch)")]
215    UnsupportedPatchType {
216        /// The webhook's `name`.
217        webhook: String,
218        /// The unsupported value.
219        got: String,
220    },
221    /// The base64 `patch` payload failed to decode, or the decoded body was
222    /// not a valid RFC6902 op array, or applying it failed.
223    #[error("webhook {webhook:?} patch could not be applied: {reason}")]
224    PatchApply {
225        /// The webhook's `name`.
226        webhook: String,
227        /// What failed.
228        reason: String,
229    },
230    /// The `clientConfig.service` ref could not be resolved to a callable
231    /// `https://<clusterIP>:<port><path>` endpoint — the Service has no
232    /// allocated `ClusterIP` (it doesn't exist, is headless, or hasn't been
233    /// allocated yet). A typed deferral the `failurePolicy` governs — NOT a
234    /// silent skip.
235    #[error(
236        "webhook {webhook:?} clientConfig.service ({namespace}/{name}) is \
237         unresolvable: {reason}"
238    )]
239    ServiceUnresolvable {
240        /// The webhook's `name`.
241        webhook: String,
242        /// Service namespace.
243        namespace: String,
244        /// Service name.
245        name: String,
246        /// Why resolution failed.
247        reason: String,
248    },
249    /// The `clientConfig` declared neither `url` nor `service` — invalid.
250    #[error("webhook {webhook:?} clientConfig declares neither url nor service")]
251    NoEndpoint {
252        /// The webhook's `name`.
253        webhook: String,
254    },
255}
256
257// ═══════════════════════════════════════════════════════════════════════════
258//  The two Environment traits (the testability contract).
259// ═══════════════════════════════════════════════════════════════════════════
260
261/// Source of the live `MutatingWebhookConfiguration` objects. Production reads
262/// the store; tests pass a static list. Returns the raw opaque-JSON config
263/// objects (the plugin parses them into [`MutatingWebhook`]s) — so the source
264/// stays a thin "give me the configs" seam with no parsing logic to drift.
265#[async_trait]
266pub trait WebhookConfigSource: Send + Sync {
267    /// Every live `MutatingWebhookConfiguration` object, as stored JSON.
268    async fn mutating_configs(&self) -> Vec<Value>;
269
270    /// Every live `ValidatingWebhookConfiguration` object, as stored JSON.
271    ///
272    /// ★ WHY A SEPARATE ARM AND NOT A REUSE OF THE MUTATING ONE. The two
273    /// kinds are stored separately, called at different points in the
274    /// pipeline, and mean different things: a mutating webhook may REWRITE
275    /// the object, a validating one may only accept or reject it. Serving
276    /// validating configs from the mutating list would let a policy webhook
277    /// silently rewrite objects, which is precisely the privilege the split
278    /// exists to withhold.
279    ///
280    /// Defaulted to empty so every existing implementor keeps compiling and
281    /// behaves exactly as before — an implementor that has not yet been
282    /// taught about validating webhooks reports none, rather than
283    /// accidentally reporting the mutating ones.
284    async fn validating_configs(&self) -> Vec<Value> {
285        Vec::new()
286    }
287}
288
289/// The HTTP(S) call-out seam. Production POSTs the `AdmissionReview` request
290/// JSON over HTTPS (reqwest impl in the apiserver crate, honoring
291/// `ca_bundle` + `timeout`); tests return a canned response.
292#[async_trait]
293pub trait WebhookCaller: Send + Sync {
294    /// POST `review_request` (a v1 `AdmissionReview` JSON) to the endpoint and
295    /// return the response `AdmissionReview` JSON.
296    ///
297    /// `endpoint` is the resolved `clientConfig.url`. `ca_bundle` is the
298    /// base64 PEM bundle (caller verifies). `timeout_seconds` bounds the call.
299    ///
300    /// # Errors
301    /// A backend message string on any network/TLS/timeout/non-2xx failure —
302    /// the plugin wraps it into a typed [`WebhookError::CallFailed`].
303    async fn call(
304        &self,
305        endpoint: &str,
306        ca_bundle: Option<&str>,
307        timeout_seconds: u32,
308        review_request: &Value,
309    ) -> Result<Value, String>;
310}
311
312/// Resolves a `clientConfig.service` ref to the Service's allocated
313/// `ClusterIP`. Production reads the store (the `ClusterIP` allocator stamps
314/// `spec.clusterIP`); tests pass a static map. The seam keeps the plugin
315/// unit-testable with ZERO store: a Service ref resolves to a VIP through
316/// a mock.
317#[async_trait]
318pub trait ServiceResolver: Send + Sync {
319    /// The allocated `ClusterIP` (`spec.clusterIP`) for the Service
320    /// `namespace/name`, or `None` when it has no VIP (absent, headless,
321    /// or not-yet-allocated).
322    async fn cluster_ip(&self, namespace: &str, name: &str) -> Option<String>;
323}
324
325/// Production [`ServiceResolver`] — reads `spec.clusterIP` off the live
326/// Service object in the store. A `"None"` (headless) `ClusterIP` resolves
327/// to `None` (a headless Service has no VIP to call).
328pub struct StoreServiceResolver {
329    store: Arc<engenho_store::StoreMesh>,
330}
331
332impl StoreServiceResolver {
333    /// New resolver over `store`.
334    #[must_use]
335    pub fn new(store: Arc<engenho_store::StoreMesh>) -> Self {
336        Self { store }
337    }
338}
339
340#[async_trait]
341impl ServiceResolver for StoreServiceResolver {
342    async fn cluster_ip(&self, namespace: &str, name: &str) -> Option<String> {
343        let key =
344            engenho_store::resource::ResourceKey::namespaced("", "v1", "Service", namespace, name);
345        let svc = self.store.get(&key).await?;
346        let ip = svc
347            .get("spec")
348            .and_then(|s| s.get("clusterIP"))
349            .and_then(Value::as_str)?;
350        // Headless / empty has no callable VIP.
351        if ip == "None" || ip.is_empty() {
352            None
353        } else {
354            Some(ip.to_string())
355        }
356    }
357}
358
359/// Synthesize the `https://<clusterIP>:<port><path>` endpoint for a
360/// resolved Service ref. Pure — the typed pieces (`ip`, `port`, `path`)
361/// compose the canonical webhook URL (`clientConfig.service` defaults:
362/// port 443, path `/`). The `https://{ip}:{port}{path}` shape IS the
363/// value's render surface (★★ TYPED EMISSION — the URL builder).
364#[must_use]
365pub fn synthesize_service_endpoint(cluster_ip: &str, svc: &ServiceRef) -> String {
366    let port = svc.port.unwrap_or(443);
367    let path = svc.path.as_deref().unwrap_or("/");
368    // The path is expected to be absolute (`/mutate`); a missing leading
369    // slash is normalized so the URL is well-formed.
370    if path.starts_with('/') {
371        format!("https://{cluster_ip}:{port}{path}")
372    } else {
373        format!("https://{cluster_ip}:{port}/{path}")
374    }
375}
376
377// ═══════════════════════════════════════════════════════════════════════════
378//  Parsing — opaque config JSON → typed MutatingWebhook list.
379// ═══════════════════════════════════════════════════════════════════════════
380
381/// Parse a stored `MutatingWebhookConfiguration` object's `webhooks[]` into the
382/// typed list. Unparseable/absent fields take the K8s default; a webhook with
383/// no name is skipped (it can never be referenced/ordered).
384#[must_use]
385pub fn parse_mutating_config(config: &Value) -> Vec<MutatingWebhook> {
386    let Some(hooks) = config.get("webhooks").and_then(Value::as_array) else {
387        return Vec::new();
388    };
389    hooks.iter().filter_map(parse_one_webhook).collect()
390}
391
392fn parse_one_webhook(hook: &Value) -> Option<MutatingWebhook> {
393    let name = hook.get("name").and_then(Value::as_str)?.to_string();
394    let cc = hook.get("clientConfig").unwrap_or(&Value::Null);
395    let client_config = WebhookClientConfig {
396        url: cc.get("url").and_then(Value::as_str).map(str::to_string),
397        service: cc.get("service").and_then(parse_service_ref),
398        ca_bundle: cc
399            .get("caBundle")
400            .and_then(Value::as_str)
401            .map(str::to_string),
402    };
403    let rules = hook
404        .get("rules")
405        .and_then(Value::as_array)
406        .map(|rs| rs.iter().map(parse_rule).collect())
407        .unwrap_or_default();
408    let failure_policy = match hook.get("failurePolicy").and_then(Value::as_str) {
409        Some("Ignore") => FailurePolicy::Ignore,
410        // default + explicit "Fail"
411        _ => FailurePolicy::Fail,
412    };
413    let timeout_seconds = hook
414        .get("timeoutSeconds")
415        .and_then(Value::as_u64)
416        .map_or(10, |t| t.min(30) as u32);
417    let reinvocation_policy = match hook.get("reinvocationPolicy").and_then(Value::as_str) {
418        Some("IfNeeded") => ReinvocationPolicy::IfNeeded,
419        _ => ReinvocationPolicy::Never,
420    };
421    let namespace_selector = hook.get("namespaceSelector").and_then(parse_selector);
422    let object_selector = hook.get("objectSelector").and_then(parse_selector);
423    Some(MutatingWebhook {
424        name,
425        client_config,
426        rules,
427        failure_policy,
428        timeout_seconds,
429        reinvocation_policy,
430        namespace_selector,
431        object_selector,
432    })
433}
434
435fn parse_service_ref(svc: &Value) -> Option<ServiceRef> {
436    Some(ServiceRef {
437        namespace: svc.get("namespace").and_then(Value::as_str)?.to_string(),
438        name: svc.get("name").and_then(Value::as_str)?.to_string(),
439        path: svc.get("path").and_then(Value::as_str).map(str::to_string),
440        port: svc
441            .get("port")
442            .and_then(Value::as_u64)
443            .and_then(|p| u16::try_from(p).ok()),
444    })
445}
446
447fn parse_rule(rule: &Value) -> RuleWithOperations {
448    let strs = |key: &str| -> Vec<String> {
449        rule.get(key)
450            .and_then(Value::as_array)
451            .map(|a| {
452                a.iter()
453                    .filter_map(|v| v.as_str().map(str::to_string))
454                    .collect()
455            })
456            .unwrap_or_default()
457    };
458    RuleWithOperations {
459        operations: strs("operations"),
460        api_groups: strs("apiGroups"),
461        api_versions: strs("apiVersions"),
462        resources: strs("resources"),
463    }
464}
465
466fn parse_selector(sel: &Value) -> Option<LabelSelector> {
467    let ml = sel.get("matchLabels")?.as_object()?;
468    let match_labels = ml
469        .iter()
470        .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
471        .collect();
472    Some(LabelSelector { match_labels })
473}
474
475// ═══════════════════════════════════════════════════════════════════════════
476//  Rule matching.
477// ═══════════════════════════════════════════════════════════════════════════
478
479/// Map an [`AdmissionAction`] to its wire `operation` verb.
480#[must_use]
481pub fn operation_for(action: AdmissionAction) -> &'static str {
482    match action {
483        AdmissionAction::Put => "CREATE",
484        AdmissionAction::Patch => "UPDATE",
485        AdmissionAction::Delete => "DELETE",
486    }
487}
488
489/// A `*` wildcard matches anything; otherwise an exact membership check.
490fn rule_field_matches(patterns: &[String], value: &str) -> bool {
491    patterns.iter().any(|p| p == "*" || p == value)
492}
493
494/// Does `webhook`'s `rules` match `(group, version, resource, operation)`?
495/// A webhook matches if ANY of its rules matches on all four axes.
496#[must_use]
497pub fn rules_match(
498    webhook: &MutatingWebhook,
499    group: &str,
500    version: &str,
501    resource: &str,
502    operation: &str,
503) -> bool {
504    webhook.rules.iter().any(|r| {
505        rule_field_matches(&r.operations, operation)
506            && rule_field_matches(&r.api_groups, group)
507            && rule_field_matches(&r.api_versions, version)
508            && rule_field_matches(&r.resources, resource)
509    })
510}
511
512// ═══════════════════════════════════════════════════════════════════════════
513//  AdmissionReview request build + response read (typed serde_json — no format!)
514// ═══════════════════════════════════════════════════════════════════════════
515
516/// Build a v1 `AdmissionReview` request object for `request` targeting
517/// `resource` (the plural). `uid` is the per-call correlation id.
518#[must_use]
519pub fn build_admission_review(request: &AdmissionRequest, resource: &str, uid: &str) -> Value {
520    let key = &request.key;
521    let user = &request.user_info;
522    json!({
523        "apiVersion": "admission.k8s.io/v1",
524        "kind": "AdmissionReview",
525        "request": {
526            "uid": uid,
527            "kind": {
528                "group": key.group,
529                "version": key.version,
530                "kind": key.kind,
531            },
532            "resource": {
533                "group": key.group,
534                "version": key.version,
535                "resource": resource,
536            },
537            "name": key.name,
538            "namespace": key.namespace.clone().unwrap_or_default(),
539            "operation": operation_for(request.action),
540            "userInfo": {
541                "username": user.username,
542                "uid": user.uid,
543                "groups": user.groups,
544                "extra": user.extra,
545            },
546            "object": request.value.clone().unwrap_or(Value::Null),
547            "oldObject": request.current.clone().unwrap_or(Value::Null),
548            "dryRun": false,
549        }
550    })
551}
552
553/// The parsed `response` half of a webhook's `AdmissionReview`.
554#[derive(Clone, Debug, PartialEq, Eq)]
555pub struct WebhookResponse {
556    /// `response.uid` (should echo the request uid).
557    pub uid: String,
558    /// `response.allowed`.
559    pub allowed: bool,
560    /// `response.status.message` when denied.
561    pub message: Option<String>,
562    /// `response.patch` decoded + base64-decoded → RFC6902 op array, IF the
563    /// webhook returned a `JSONPatch`. `None` if no patch.
564    pub patch: Option<Value>,
565}
566
567/// Read the `response` half of a webhook's `AdmissionReview`, decoding +
568/// base64-decoding any `JSONPatch`.
569///
570/// # Errors
571/// [`WebhookError::BadResponse`] for a missing/malformed response;
572/// [`WebhookError::UnsupportedPatchType`] for a non-JSONPatch patchType;
573/// [`WebhookError::PatchApply`] for a base64/JSON decode failure on the patch.
574pub fn read_admission_review(
575    webhook_name: &str,
576    review: &Value,
577) -> Result<WebhookResponse, WebhookError> {
578    let resp = review
579        .get("response")
580        .ok_or_else(|| WebhookError::BadResponse {
581            webhook: webhook_name.to_string(),
582            reason: "missing `response`".into(),
583        })?;
584    let uid = resp
585        .get("uid")
586        .and_then(Value::as_str)
587        .unwrap_or_default()
588        .to_string();
589    let allowed = resp
590        .get("allowed")
591        .and_then(Value::as_bool)
592        .ok_or_else(|| WebhookError::BadResponse {
593            webhook: webhook_name.to_string(),
594            reason: "missing/non-bool `response.allowed`".into(),
595        })?;
596    let message = resp
597        .get("status")
598        .and_then(|s| s.get("message"))
599        .and_then(Value::as_str)
600        .map(str::to_string);
601
602    // A patch is present only when `patch` is set; its type MUST be JSONPatch.
603    let patch = match resp.get("patch").and_then(Value::as_str) {
604        None | Some("") => None,
605        Some(b64) => {
606            let patch_type = resp
607                .get("patchType")
608                .and_then(Value::as_str)
609                .unwrap_or("JSONPatch");
610            if patch_type != "JSONPatch" {
611                return Err(WebhookError::UnsupportedPatchType {
612                    webhook: webhook_name.to_string(),
613                    got: patch_type.to_string(),
614                });
615            }
616            let decoded = base64::engine::general_purpose::STANDARD
617                .decode(b64)
618                .map_err(|e| WebhookError::PatchApply {
619                    webhook: webhook_name.to_string(),
620                    reason: format!("base64 decode: {e}"),
621                })?;
622            let ops: Value =
623                serde_json::from_slice(&decoded).map_err(|e| WebhookError::PatchApply {
624                    webhook: webhook_name.to_string(),
625                    reason: format!("patch JSON parse: {e}"),
626                })?;
627            Some(ops)
628        }
629    };
630
631    Ok(WebhookResponse {
632        uid,
633        allowed,
634        message,
635        patch,
636    })
637}
638
639/// Apply a webhook's RFC6902 op array (already decoded) to `object`, returning
640/// the mutated object. Reuses the apiserver's canonical json-patch engine.
641///
642/// # Errors
643/// [`WebhookError::PatchApply`] when the ops don't form a valid RFC6902 array
644/// or applying them fails.
645pub fn apply_webhook_patch(
646    webhook_name: &str,
647    object: &Value,
648    ops: &Value,
649    gvk: &Gvk,
650) -> Result<Value, WebhookError> {
651    let body = PatchBody::from_raw(PatchType::Json, ops.clone()).map_err(|e| {
652        WebhookError::PatchApply {
653            webhook: webhook_name.to_string(),
654            reason: e.to_string(),
655        }
656    })?;
657    // json-patch is pure (touches no schema env) — the mock env is never
658    // consulted; pass one to satisfy the signature.
659    let env: &dyn PatchSchemaEnv = &MockPatchEnv::new();
660    apply_patch(PatchType::Json, object, &body, env, gvk).map_err(|e| WebhookError::PatchApply {
661        webhook: webhook_name.to_string(),
662        reason: e.to_string(),
663    })
664}
665
666// ═══════════════════════════════════════════════════════════════════════════
667//  The plugin — an AdmissionWebhook composing the two seams.
668// ═══════════════════════════════════════════════════════════════════════════
669
670/// A `(group, version, kind) -> plural` resolver. Boxed so the plugin stays
671/// object-safe; production wires the generated-catalog pluralizer, tests pass a
672/// closure.
673pub type Pluralizer = Box<dyn Fn(&str, &str, &str) -> Option<String> + Send + Sync>;
674
675/// The mutating-admission-webhook dispatch plugin.
676///
677/// On every Put/Patch (CREATE/UPDATE) it lists the live
678/// `MutatingWebhookConfiguration`s, finds the webhooks whose `rules` match the
679/// request, builds an `AdmissionReview`, calls each in config+webhook order,
680/// and applies each returned `JSONPatch` to the object — feeding the mutated
681/// object forward to the next webhook. A `Deny` (`allowed: false`) short
682/// circuits with [`AdmissionDecision::Deny`]. Errors are governed per-webhook
683/// by `failurePolicy` (`Fail` ⇒ deny; `Ignore` ⇒ skip that webhook).
684pub struct MutatingWebhookPlugin {
685    source: Arc<dyn WebhookConfigSource>,
686    caller: Arc<dyn WebhookCaller>,
687    /// Resolves a `clientConfig.service` ref to the Service's `ClusterIP`.
688    /// `None` ⇒ no resolver wired: a service ref yields a typed
689    /// [`WebhookError::ServiceUnresolvable`] (preserving the typed-deferral
690    /// for plugins constructed without store access).
691    resolver: Option<Arc<dyn ServiceResolver>>,
692    /// Maps a kind to its plural resource for rule matching + the
693    /// `AdmissionReview.request.resource`. Production wires the catalog
694    /// pluralizer; tests pass a closure.
695    pluralize: Pluralizer,
696}
697
698impl MutatingWebhookPlugin {
699    /// New plugin from the two seams + a pluralizer
700    /// `(group, version, kind) -> plural`. No [`ServiceResolver`] — a
701    /// `clientConfig.service` ref is a typed
702    /// [`WebhookError::ServiceUnresolvable`]. Use [`Self::with_resolver`] to
703    /// enable service-ref resolution against the allocated `ClusterIPs`.
704    #[must_use]
705    pub fn new(
706        source: Arc<dyn WebhookConfigSource>,
707        caller: Arc<dyn WebhookCaller>,
708        pluralize: Pluralizer,
709    ) -> Self {
710        Self {
711            source,
712            caller,
713            resolver: None,
714            pluralize,
715        }
716    }
717
718    /// Builder: attach a [`ServiceResolver`] so `clientConfig.service` refs
719    /// resolve to `https://<clusterIP>:<port><path>`.
720    #[must_use]
721    pub fn with_resolver(mut self, resolver: Arc<dyn ServiceResolver>) -> Self {
722        self.resolver = Some(resolver);
723        self
724    }
725
726    /// The full dispatch over the request's (possibly already-mutated) value.
727    /// Returns the [`AdmissionDecision`] for the chain.
728    async fn dispatch(&self, request: &AdmissionRequest) -> AdmissionDecision {
729        let key = &request.key;
730        let Some(resource) = (self.pluralize)(&key.group, &key.version, &key.kind) else {
731            // Unknown kind → no plural → cannot rule-match; admit unchanged.
732            return AdmissionDecision::Allow;
733        };
734        let operation = operation_for(request.action);
735        let configs = self.source.mutating_configs().await;
736
737        // The object that flows through the webhook chain. CREATE/UPDATE carry
738        // a value; without one there's nothing to mutate → admit.
739        let Some(mut object) = request.value.clone() else {
740            return AdmissionDecision::Allow;
741        };
742        let gvk = Gvk::from(key);
743        let mut mutated = false;
744        let mut uid_counter = 0u64;
745
746        for config in &configs {
747            for webhook in parse_mutating_config(config) {
748                if !rules_match(&webhook, &key.group, &key.version, &resource, operation) {
749                    continue;
750                }
751                if !self.selectors_match(&webhook, request, &object) {
752                    continue;
753                }
754                uid_counter += 1;
755                let uid = format!("{}-{}", request.key.label(), uid_counter);
756                // Build the review against the CURRENT (possibly mutated)
757                // object so a later webhook sees earlier injections.
758                let mut req_for_review = request.clone();
759                req_for_review.value = Some(object.clone());
760                let review_req = build_admission_review(&req_for_review, &resource, &uid);
761
762                match self.call_one(&webhook, &review_req).await {
763                    Ok(resp) => {
764                        if !resp.allowed {
765                            let reason = resp
766                                .message
767                                .unwrap_or_else(|| "request denied by webhook".to_string());
768                            return AdmissionDecision::Deny(format!("{}: {reason}", webhook.name));
769                        }
770                        if let Some(ops) = resp.patch {
771                            match apply_webhook_patch(&webhook.name, &object, &ops, &gvk) {
772                                Ok(new) => {
773                                    object = new;
774                                    mutated = true;
775                                }
776                                Err(e) => {
777                                    if let Some(d) = Self::govern_failure(&webhook, &e.to_string())
778                                    {
779                                        return d;
780                                    }
781                                }
782                            }
783                        }
784                    }
785                    Err(e) => {
786                        if let Some(d) = Self::govern_failure(&webhook, &e.to_string()) {
787                            return d;
788                        }
789                    }
790                }
791            }
792        }
793
794        // ── VALIDATING PASS ───────────────────────────────────────────
795        //
796        // ★ AFTER every mutation, and that ORDER is the whole point. A
797        // validating webhook exists to judge the object the cluster will
798        // actually store; running it first would let a later mutating
799        // webhook rewrite the object into something the policy would have
800        // rejected — which is exactly the hole a policy engine is deployed
801        // to close.
802        //
803        // ★ A VALIDATING WEBHOOK MAY NOT MUTATE. Any patch in its response
804        // is IGNORED rather than applied. Upstream ignores it too, and
805        // honouring it would hand a policy webhook a privilege the object
806        // kind it was registered under explicitly withholds.
807        let validating = self.source.validating_configs().await;
808        for config in &validating {
809            for webhook in parse_mutating_config(config) {
810                if !rules_match(&webhook, &key.group, &key.version, &resource, operation) {
811                    continue;
812                }
813                if !self.selectors_match(&webhook, request, &object) {
814                    continue;
815                }
816                uid_counter += 1;
817                let uid = format!("{}-{}", request.key.label(), uid_counter);
818                let mut req_for_review = request.clone();
819                req_for_review.value = Some(object.clone());
820                let review_req = build_admission_review(&req_for_review, &resource, &uid);
821
822                match self.call_one(&webhook, &review_req).await {
823                    Ok(resp) => {
824                        if !resp.allowed {
825                            let reason = resp
826                                .message
827                                .unwrap_or_else(|| "request denied by webhook".to_string());
828                            return AdmissionDecision::Deny(format!("{}: {reason}", webhook.name));
829                        }
830                        // resp.patch deliberately unread — see above.
831                    }
832                    Err(e) => {
833                        if let Some(d) = Self::govern_failure(&webhook, &e.to_string()) {
834                            return d;
835                        }
836                    }
837                }
838            }
839        }
840
841        if mutated {
842            AdmissionDecision::Mutate(object)
843        } else {
844            AdmissionDecision::Allow
845        }
846    }
847
848    /// Resolve the endpoint + invoke the [`WebhookCaller`], parsing the
849    /// response. A `url` wins over a `service` ref; a `service` ref alone is
850    /// resolved through the [`ServiceResolver`]; neither is
851    /// [`WebhookError::NoEndpoint`]. The `caBundle` goes to the caller with
852    /// every call.
853    async fn call_one(
854        &self,
855        webhook: &MutatingWebhook,
856        review_req: &Value,
857    ) -> Result<WebhookResponse, WebhookError> {
858        // Bound by name with no `..`: a `clientConfig` field added to
859        // WebhookClientConfig does not compile here (E0027) until the call
860        // path consumes it, so a parsed security control cannot be dropped
861        // on the way to the caller.
862        let WebhookClientConfig {
863            url,
864            service,
865            ca_bundle,
866        } = &webhook.client_config;
867        let endpoint = match (url, service) {
868            (Some(url), _) => url.clone(),
869            (None, Some(svc)) => self.resolve_service_endpoint(&webhook.name, svc).await?,
870            (None, None) => {
871                return Err(WebhookError::NoEndpoint {
872                    webhook: webhook.name.clone(),
873                });
874            }
875        };
876        let raw = self
877            .caller
878            .call(
879                &endpoint,
880                ca_bundle.as_deref(),
881                webhook.timeout_seconds,
882                review_req,
883            )
884            .await
885            .map_err(|message| WebhookError::CallFailed {
886                webhook: webhook.name.clone(),
887                message,
888            })?;
889        read_admission_review(&webhook.name, &raw)
890    }
891
892    /// Resolve a `clientConfig.service` ref to a callable
893    /// `https://<clusterIP>:<port><path>` endpoint. Requires a wired
894    /// [`ServiceResolver`]; without one (or when the Service has no
895    /// allocated `ClusterIP`) returns a typed
896    /// [`WebhookError::ServiceUnresolvable`] the `failurePolicy` governs.
897    async fn resolve_service_endpoint(
898        &self,
899        webhook_name: &str,
900        svc: &ServiceRef,
901    ) -> Result<String, WebhookError> {
902        let Some(resolver) = &self.resolver else {
903            return Err(WebhookError::ServiceUnresolvable {
904                webhook: webhook_name.to_string(),
905                namespace: svc.namespace.clone(),
906                name: svc.name.clone(),
907                reason: "no service resolver wired (supply clientConfig.url instead)".to_string(),
908            });
909        };
910        match resolver.cluster_ip(&svc.namespace, &svc.name).await {
911            Some(ip) => Ok(synthesize_service_endpoint(&ip, svc)),
912            None => Err(WebhookError::ServiceUnresolvable {
913                webhook: webhook_name.to_string(),
914                namespace: svc.namespace.clone(),
915                name: svc.name.clone(),
916                reason:
917                    "Service has no allocated ClusterIP (absent, headless, or not yet allocated)"
918                        .to_string(),
919            }),
920        }
921    }
922
923    /// Best-effort `namespaceSelector` / `objectSelector` matching. An
924    /// `objectSelector` matches against the request object's own
925    /// `metadata.labels`. A `namespaceSelector` matches against any namespace
926    /// labels the request threads through `user_info.extra["namespaceLabels"]`
927    /// (the apiserver may populate this); absent ⇒ an empty label set ⇒ a
928    /// non-empty selector does NOT match (conservative). `None` selectors
929    /// match all.
930    fn selectors_match(
931        &self,
932        webhook: &MutatingWebhook,
933        request: &AdmissionRequest,
934        object: &Value,
935    ) -> bool {
936        if let Some(sel) = &webhook.object_selector {
937            let labels = object_labels(object);
938            if !sel.matches(&labels) {
939                return false;
940            }
941        }
942        if let Some(sel) = &webhook.namespace_selector {
943            let labels = namespace_labels(request);
944            if !sel.matches(&labels) {
945                return false;
946            }
947        }
948        true
949    }
950
951    /// Per-webhook `failurePolicy`: `Fail` ⇒ `Some(Deny(...))`; `Ignore` ⇒
952    /// `None` (skip this webhook, keep going).
953    fn govern_failure(webhook: &MutatingWebhook, message: &str) -> Option<AdmissionDecision> {
954        match webhook.failure_policy {
955            FailurePolicy::Fail => Some(AdmissionDecision::Deny(format!(
956                "{}: {message} (failurePolicy=Fail)",
957                webhook.name
958            ))),
959            FailurePolicy::Ignore => None,
960        }
961    }
962}
963
964/// Read `metadata.labels` off an object as a string map.
965fn object_labels(object: &Value) -> std::collections::BTreeMap<String, String> {
966    object
967        .get("metadata")
968        .and_then(|m| m.get("labels"))
969        .and_then(Value::as_object)
970        .map(|m| {
971            m.iter()
972                .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
973                .collect()
974        })
975        .unwrap_or_default()
976}
977
978/// Read namespace labels threaded via `user_info.extra["namespaceLabels"]`
979/// (each `"k=v"`), if the apiserver populated them.
980fn namespace_labels(request: &AdmissionRequest) -> std::collections::BTreeMap<String, String> {
981    request
982        .user_info
983        .extra
984        .get("namespaceLabels")
985        .map(|pairs| {
986            pairs
987                .iter()
988                .filter_map(|kv| {
989                    kv.split_once('=')
990                        .map(|(k, v)| (k.to_string(), v.to_string()))
991                })
992                .collect()
993        })
994        .unwrap_or_default()
995}
996
997#[async_trait]
998impl AdmissionWebhook for MutatingWebhookPlugin {
999    fn name(&self) -> &'static str {
1000        "mutating-admission-webhooks"
1001    }
1002
1003    async fn review(
1004        &self,
1005        request: &AdmissionRequest,
1006    ) -> Result<AdmissionDecision, AdmissionError> {
1007        // Only CREATE/UPDATE carry an object to mutate; DELETE is admit-through
1008        // for the mutating plugin (validating webhooks for delete are a typed
1009        // follow-up — this plugin is the MUTATING path).
1010        match request.action {
1011            AdmissionAction::Put | AdmissionAction::Patch => Ok(self.dispatch(request).await),
1012            AdmissionAction::Delete => Ok(AdmissionDecision::Allow),
1013        }
1014    }
1015}
1016
1017// ═══════════════════════════════════════════════════════════════════════════
1018//  Mock seams for tests.
1019// ═══════════════════════════════════════════════════════════════════════════
1020
1021/// A [`WebhookConfigSource`] holding static lists of config objects.
1022#[derive(Clone, Default)]
1023pub struct StaticConfigSource {
1024    configs: Arc<Vec<Value>>,
1025    validating: Arc<Vec<Value>>,
1026}
1027
1028impl StaticConfigSource {
1029    /// New source from a list of `MutatingWebhookConfiguration` objects.
1030    #[must_use]
1031    pub fn new(configs: Vec<Value>) -> Self {
1032        Self {
1033            configs: Arc::new(configs),
1034            validating: Arc::new(Vec::new()),
1035        }
1036    }
1037
1038    /// New source carrying `ValidatingWebhookConfiguration` objects too.
1039    ///
1040    /// Separate constructor rather than a second argument on `new` so every
1041    /// existing caller keeps its meaning: a test that registered mutating
1042    /// configs must not silently acquire validating ones.
1043    #[must_use]
1044    pub fn with_validating(mutating: Vec<Value>, validating: Vec<Value>) -> Self {
1045        Self {
1046            configs: Arc::new(mutating),
1047            validating: Arc::new(validating),
1048        }
1049    }
1050}
1051
1052#[async_trait]
1053impl WebhookConfigSource for StaticConfigSource {
1054    async fn mutating_configs(&self) -> Vec<Value> {
1055        (*self.configs).clone()
1056    }
1057
1058    async fn validating_configs(&self) -> Vec<Value> {
1059        (*self.validating).clone()
1060    }
1061}
1062
1063/// A [`WebhookCaller`] that returns a canned `AdmissionReview` keyed by
1064/// endpoint, and records every call. Lets a test inject a `JSONPatch` (or a
1065/// deny, or a backend error) WITHOUT a real webhook server.
1066#[derive(Clone, Default)]
1067pub struct MockWebhookCaller {
1068    inner: Arc<Mutex<MockCallerState>>,
1069}
1070
1071#[derive(Default)]
1072struct MockCallerState {
1073    /// endpoint → canned response review.
1074    responses: std::collections::BTreeMap<String, Value>,
1075    /// endpoint → backend error message (takes precedence over a response).
1076    errors: std::collections::BTreeMap<String, String>,
1077    /// (endpoint, timeout, request) call log.
1078    calls: Vec<(String, u32, Value)>,
1079    /// The `caBundle` each call carried, in call order.
1080    ca_bundles: Vec<Option<String>>,
1081}
1082
1083impl MockWebhookCaller {
1084    /// New empty caller — every endpoint errors with "no canned response".
1085    #[must_use]
1086    pub fn new() -> Self {
1087        Self::default()
1088    }
1089
1090    /// Pin a canned response review for `endpoint`.
1091    pub async fn set_response(&self, endpoint: &str, review: Value) {
1092        self.inner
1093            .lock()
1094            .await
1095            .responses
1096            .insert(endpoint.to_string(), review);
1097    }
1098
1099    /// Pin a backend error for `endpoint`.
1100    pub async fn set_error(&self, endpoint: &str, message: impl Into<String>) {
1101        self.inner
1102            .lock()
1103            .await
1104            .errors
1105            .insert(endpoint.to_string(), message.into());
1106    }
1107
1108    /// The recorded calls `(endpoint, timeout_seconds, request)`.
1109    pub async fn calls(&self) -> Vec<(String, u32, Value)> {
1110        self.inner.lock().await.calls.clone()
1111    }
1112
1113    /// The `caBundle` each recorded call carried, in call order.
1114    pub async fn ca_bundles(&self) -> Vec<Option<String>> {
1115        self.inner.lock().await.ca_bundles.clone()
1116    }
1117
1118    /// Convenience: a `JSONPatch` `AdmissionReview` response from RFC6902 ops.
1119    #[must_use]
1120    pub fn json_patch_review(uid: &str, ops: &Value) -> Value {
1121        let b64 = base64::engine::general_purpose::STANDARD
1122            .encode(serde_json::to_vec(ops).expect("ops serialize"));
1123        json!({
1124            "apiVersion": "admission.k8s.io/v1",
1125            "kind": "AdmissionReview",
1126            "response": {
1127                "uid": uid,
1128                "allowed": true,
1129                "patchType": "JSONPatch",
1130                "patch": b64,
1131            }
1132        })
1133    }
1134
1135    /// Convenience: an allow-with-no-patch response.
1136    #[must_use]
1137    pub fn allow_review(uid: &str) -> Value {
1138        json!({
1139            "apiVersion": "admission.k8s.io/v1",
1140            "kind": "AdmissionReview",
1141            "response": { "uid": uid, "allowed": true }
1142        })
1143    }
1144
1145    /// Convenience: a deny response carrying `message`.
1146    #[must_use]
1147    pub fn deny_review(uid: &str, message: &str) -> Value {
1148        json!({
1149            "apiVersion": "admission.k8s.io/v1",
1150            "kind": "AdmissionReview",
1151            "response": {
1152                "uid": uid,
1153                "allowed": false,
1154                "status": { "code": 403, "message": message }
1155            }
1156        })
1157    }
1158}
1159
1160/// A [`ServiceResolver`] backed by a static `namespace/name → clusterIP`
1161/// map. Lets a test prove service-ref resolution WITHOUT a real store.
1162#[derive(Clone, Default)]
1163pub struct MockServiceResolver {
1164    map: std::collections::BTreeMap<String, String>,
1165}
1166
1167impl MockServiceResolver {
1168    /// New empty resolver (every ref resolves to `None`).
1169    #[must_use]
1170    pub fn new() -> Self {
1171        Self::default()
1172    }
1173
1174    /// Pin `namespace/name → clusterIP`.
1175    #[must_use]
1176    pub fn with(mut self, namespace: &str, name: &str, cluster_ip: &str) -> Self {
1177        self.map
1178            .insert(format!("{namespace}/{name}"), cluster_ip.to_string());
1179        self
1180    }
1181}
1182
1183#[async_trait]
1184impl ServiceResolver for MockServiceResolver {
1185    async fn cluster_ip(&self, namespace: &str, name: &str) -> Option<String> {
1186        self.map.get(&format!("{namespace}/{name}")).cloned()
1187    }
1188}
1189
1190#[async_trait]
1191impl WebhookCaller for MockWebhookCaller {
1192    async fn call(
1193        &self,
1194        endpoint: &str,
1195        ca_bundle: Option<&str>,
1196        timeout_seconds: u32,
1197        review_request: &Value,
1198    ) -> Result<Value, String> {
1199        let mut state = self.inner.lock().await;
1200        state.calls.push((
1201            endpoint.to_string(),
1202            timeout_seconds,
1203            review_request.clone(),
1204        ));
1205        state.ca_bundles.push(ca_bundle.map(str::to_string));
1206        if let Some(msg) = state.errors.get(endpoint) {
1207            return Err(msg.clone());
1208        }
1209        state
1210            .responses
1211            .get(endpoint)
1212            .cloned()
1213            .ok_or_else(|| format!("no canned response for endpoint {endpoint:?}"))
1214    }
1215}
1216
1217#[cfg(test)]
1218mod tests {
1219    use super::*;
1220    use engenho_store::resource::ResourceKey;
1221    use serde_json::json;
1222
1223    fn pluralizer() -> Pluralizer {
1224        Box::new(|_g, _v, kind| {
1225            Some(
1226                match kind {
1227                    "Pod" => "pods",
1228                    "Deployment" => "deployments",
1229                    other => return Some(format!("{}s", other.to_lowercase())),
1230                }
1231                .to_string(),
1232            )
1233        })
1234    }
1235
1236    fn pod_request() -> AdmissionRequest {
1237        AdmissionRequest {
1238            action: AdmissionAction::Put,
1239            key: ResourceKey::namespaced("", "v1", "Pod", "default", "podinfo"),
1240            value: Some(json!({
1241                "apiVersion": "v1",
1242                "kind": "Pod",
1243                "metadata": { "name": "podinfo" },
1244                "spec": { "containers": [{"name": "app", "image": "podinfo:6"}] }
1245            })),
1246            current: None,
1247            user_info: engenho_types::auth::UserInfo::default(),
1248        }
1249    }
1250
1251    /// A config whose webhook injects a sidecar container via a `JSONPatch` and
1252    /// matches Pod CREATE.
1253    /// A `ValidatingWebhookConfiguration` over the same rule shape.
1254    ///
1255    /// Same webhook body as the mutating one on purpose: the tests below
1256    /// must show that the DIFFERENCE in behaviour comes from WHICH LIST the
1257    /// config was read from, not from anything in the object.
1258    fn validating_config(endpoint: &str, name: &str) -> Value {
1259        json!({
1260            "apiVersion": "admissionregistration.k8s.io/v1",
1261            "kind": "ValidatingWebhookConfiguration",
1262            "metadata": { "name": name },
1263            "webhooks": [{
1264                "name": "policy.tatara-mesh.io",
1265                "clientConfig": { "url": endpoint },
1266                "rules": [{
1267                    "operations": ["CREATE"],
1268                    "apiGroups": [""],
1269                    "apiVersions": ["v1"],
1270                    "resources": ["pods"]
1271                }],
1272                "failurePolicy": "Fail",
1273                "timeoutSeconds": 5
1274            }]
1275        })
1276    }
1277
1278    fn sidecar_inject_config(endpoint: &str) -> Value {
1279        json!({
1280            "apiVersion": "admissionregistration.k8s.io/v1",
1281            "kind": "MutatingWebhookConfiguration",
1282            "metadata": { "name": "lareira-enxerto" },
1283            "webhooks": [{
1284                "name": "inject.tatara-mesh.io",
1285                "clientConfig": { "url": endpoint },
1286                "rules": [{
1287                    "operations": ["CREATE"],
1288                    "apiGroups": [""],
1289                    "apiVersions": ["v1"],
1290                    "resources": ["pods"]
1291                }],
1292                "failurePolicy": "Fail",
1293                "timeoutSeconds": 5
1294            }]
1295        })
1296    }
1297
1298    /// The RFC6902 ops the sidecar injector returns: append the aresta proxy
1299    /// container + a SPIRE-agent init container.
1300    fn sidecar_ops() -> Value {
1301        json!([
1302            {"op": "add", "path": "/spec/containers/-",
1303             "value": {"name": "aresta-proxy", "image": "aresta:1.0"}},
1304            {"op": "add", "path": "/spec/initContainers",
1305             "value": [{"name": "spire-agent-init", "image": "spire-agent:1.0"}]}
1306        ])
1307    }
1308
1309    #[tokio::test]
1310    async fn sidecar_is_injected_into_the_object() {
1311        let endpoint = "https://inject.tatara-mesh.svc/mutate";
1312        let source = Arc::new(StaticConfigSource::new(vec![sidecar_inject_config(
1313            endpoint,
1314        )]));
1315        let caller = Arc::new(MockWebhookCaller::new());
1316        caller
1317            .set_response(
1318                endpoint,
1319                MockWebhookCaller::json_patch_review("u", &sidecar_ops()),
1320            )
1321            .await;
1322        let plugin = MutatingWebhookPlugin::new(source, caller.clone(), pluralizer());
1323
1324        let decision = plugin.review(&pod_request()).await.unwrap();
1325        let mutated = match decision {
1326            AdmissionDecision::Mutate(v) => v,
1327            other => panic!("expected Mutate, got {other:?}"),
1328        };
1329        // The proxy sidecar landed.
1330        let containers = mutated["spec"]["containers"].as_array().unwrap();
1331        assert_eq!(containers.len(), 2, "aresta proxy appended");
1332        assert!(containers.iter().any(|c| c["name"] == "aresta-proxy"));
1333        // The SPIRE init container landed (closes the loop with the kubelet
1334        // init-container driver).
1335        let inits = mutated["spec"]["initContainers"].as_array().unwrap();
1336        assert_eq!(inits.len(), 1);
1337        assert_eq!(inits[0]["name"], "spire-agent-init");
1338        // The webhook was actually called with a CREATE AdmissionReview.
1339        let calls = caller.calls().await;
1340        assert_eq!(calls.len(), 1);
1341        assert_eq!(calls[0].0, endpoint);
1342        assert_eq!(calls[0].2["request"]["operation"], "CREATE");
1343        assert_eq!(calls[0].2["request"]["resource"]["resource"], "pods");
1344    }
1345
1346    #[tokio::test]
1347    async fn non_matching_rule_is_not_called() {
1348        // A webhook matching Deployments only must NOT be called for a Pod.
1349        let endpoint = "https://deploy-only.svc/mutate";
1350        let config = json!({
1351            "kind": "MutatingWebhookConfiguration",
1352            "webhooks": [{
1353                "name": "deploy.only.io",
1354                "clientConfig": { "url": endpoint },
1355                "rules": [{
1356                    "operations": ["CREATE"],
1357                    "apiGroups": ["apps"],
1358                    "apiVersions": ["v1"],
1359                    "resources": ["deployments"]
1360                }]
1361            }]
1362        });
1363        let source = Arc::new(StaticConfigSource::new(vec![config]));
1364        let caller = Arc::new(MockWebhookCaller::new());
1365        let plugin = MutatingWebhookPlugin::new(source, caller.clone(), pluralizer());
1366
1367        let decision = plugin.review(&pod_request()).await.unwrap();
1368        assert!(
1369            matches!(decision, AdmissionDecision::Allow),
1370            "no rule match → admit unchanged"
1371        );
1372        assert_eq!(caller.calls().await.len(), 0, "webhook NOT called");
1373    }
1374
1375    #[tokio::test]
1376    async fn failure_policy_fail_rejects_on_call_error() {
1377        let endpoint = "https://flaky.svc/mutate";
1378        let source = Arc::new(StaticConfigSource::new(vec![sidecar_inject_config(
1379            endpoint,
1380        )]));
1381        let caller = Arc::new(MockWebhookCaller::new());
1382        caller.set_error(endpoint, "connection refused").await;
1383        let plugin = MutatingWebhookPlugin::new(source, caller, pluralizer());
1384
1385        let decision = plugin.review(&pod_request()).await.unwrap();
1386        match decision {
1387            AdmissionDecision::Deny(reason) => {
1388                assert!(reason.contains("inject.tatara-mesh.io"));
1389                assert!(reason.contains("failurePolicy=Fail"));
1390                assert!(reason.contains("connection refused"));
1391            }
1392            other => panic!("expected Deny, got {other:?}"),
1393        }
1394    }
1395
1396    #[tokio::test]
1397    async fn failure_policy_ignore_proceeds_on_call_error() {
1398        let endpoint = "https://flaky.svc/mutate";
1399        let mut config = sidecar_inject_config(endpoint);
1400        config["webhooks"][0]["failurePolicy"] = json!("Ignore");
1401        let source = Arc::new(StaticConfigSource::new(vec![config]));
1402        let caller = Arc::new(MockWebhookCaller::new());
1403        caller.set_error(endpoint, "connection refused").await;
1404        let plugin = MutatingWebhookPlugin::new(source, caller, pluralizer());
1405
1406        let decision = plugin.review(&pod_request()).await.unwrap();
1407        // The webhook errored but failurePolicy=Ignore → request proceeds
1408        // unmutated by this webhook → Allow (no mutation happened).
1409        assert!(
1410            matches!(decision, AdmissionDecision::Allow),
1411            "failurePolicy=Ignore on error → admit unchanged"
1412        );
1413    }
1414
1415    #[tokio::test]
1416    async fn webhook_deny_short_circuits() {
1417        let endpoint = "https://policy.svc/mutate";
1418        let source = Arc::new(StaticConfigSource::new(vec![sidecar_inject_config(
1419            endpoint,
1420        )]));
1421        let caller = Arc::new(MockWebhookCaller::new());
1422        caller
1423            .set_response(
1424                endpoint,
1425                MockWebhookCaller::deny_review("u", "pods must carry a mesh label"),
1426            )
1427            .await;
1428        let plugin = MutatingWebhookPlugin::new(source, caller, pluralizer());
1429
1430        let decision = plugin.review(&pod_request()).await.unwrap();
1431        match decision {
1432            AdmissionDecision::Deny(reason) => {
1433                assert!(reason.contains("inject.tatara-mesh.io"));
1434                assert!(reason.contains("mesh label"));
1435            }
1436            other => panic!("expected Deny, got {other:?}"),
1437        }
1438    }
1439
1440    /// A service-ref config matching Pod CREATE with the given
1441    /// `{namespace, name, port, path}`.
1442    fn service_ref_config(namespace: &str, name: &str, port: u64, path: &str) -> Value {
1443        json!({
1444            "kind": "MutatingWebhookConfiguration",
1445            "webhooks": [{
1446                "name": "svc.mesh.io",
1447                "clientConfig": { "service": {
1448                    "namespace": namespace, "name": name, "port": port, "path": path
1449                } },
1450                "rules": [{
1451                    "operations": ["CREATE"], "apiGroups": [""],
1452                    "apiVersions": ["v1"], "resources": ["pods"]
1453                }],
1454                "failurePolicy": "Fail"
1455            }]
1456        })
1457    }
1458
1459    #[tokio::test]
1460    async fn service_ref_without_resolver_is_typed_deferral() {
1461        // No ServiceResolver wired → a service ref is a typed deferral,
1462        // governed by failurePolicy=Fail → Deny (NOT a silent skip).
1463        let config = json!({
1464            "kind": "MutatingWebhookConfiguration",
1465            "webhooks": [{
1466                "name": "svc.only.io",
1467                "clientConfig": { "service": { "namespace": "mesh", "name": "injector" } },
1468                "rules": [{
1469                    "operations": ["CREATE"], "apiGroups": [""],
1470                    "apiVersions": ["v1"], "resources": ["pods"]
1471                }],
1472                "failurePolicy": "Fail"
1473            }]
1474        });
1475        let source = Arc::new(StaticConfigSource::new(vec![config]));
1476        let caller = Arc::new(MockWebhookCaller::new());
1477        let plugin = MutatingWebhookPlugin::new(source, caller.clone(), pluralizer());
1478
1479        match plugin.review(&pod_request()).await.unwrap() {
1480            AdmissionDecision::Deny(reason) => {
1481                assert!(reason.contains("unresolvable"));
1482                assert!(reason.contains("mesh/injector"));
1483            }
1484            other => panic!("expected Deny, got {other:?}"),
1485        }
1486        assert_eq!(
1487            caller.calls().await.len(),
1488            0,
1489            "no HTTP call for an unresolved service ref"
1490        );
1491    }
1492
1493    // ── validating webhooks (Phase 5.9) ───────────────────────────────
1494
1495    #[tokio::test]
1496    async fn a_validating_webhook_can_deny() {
1497        // ValidatingWebhookConfiguration has always been in the catalog and
1498        // therefore storable. Nothing read it, so a cluster could hold a
1499        // policy configuration that was never consulted and reported no
1500        // error — a policy engine that silently does nothing.
1501        let ep = "https://policy.example/validate";
1502        let source = Arc::new(StaticConfigSource::with_validating(
1503            vec![],
1504            vec![validating_config(ep, "policy")],
1505        ));
1506        let caller = Arc::new(MockWebhookCaller::new());
1507        caller
1508            .set_response(
1509                ep,
1510                MockWebhookCaller::deny_review("u", "no privileged pods"),
1511            )
1512            .await;
1513        let plugin = MutatingWebhookPlugin::new(source, caller.clone(), pluralizer());
1514
1515        match plugin.review(&pod_request()).await.unwrap() {
1516            AdmissionDecision::Deny(reason) => {
1517                assert!(reason.contains("no privileged pods"), "got: {reason}");
1518            }
1519            other => panic!("expected Deny, got {other:?}"),
1520        }
1521        assert_eq!(caller.calls().await.len(), 1, "the webhook must be called");
1522    }
1523
1524    #[tokio::test]
1525    async fn a_validating_webhook_may_not_mutate() {
1526        // The identical config body that MUTATES when registered as a
1527        // MutatingWebhookConfiguration must NOT mutate when registered as a
1528        // validating one. Honouring its patch would hand a policy webhook a
1529        // privilege the kind it registered under explicitly withholds.
1530        let ep = "https://policy.example/validate";
1531        let source = Arc::new(StaticConfigSource::with_validating(
1532            vec![],
1533            vec![validating_config(ep, "policy")],
1534        ));
1535        let caller = Arc::new(MockWebhookCaller::new());
1536        caller
1537            .set_response(
1538                ep,
1539                MockWebhookCaller::json_patch_review("u", &sidecar_ops()),
1540            )
1541            .await;
1542        let plugin = MutatingWebhookPlugin::new(source, caller, pluralizer());
1543
1544        match plugin.review(&pod_request()).await.unwrap() {
1545            AdmissionDecision::Allow => {}
1546            other => panic!("a validating webhook's patch must be ignored, got {other:?}"),
1547        }
1548    }
1549
1550    #[tokio::test]
1551    async fn validation_runs_after_mutation_so_it_judges_what_will_be_stored() {
1552        // THE ordering property. Running validation first would let a later
1553        // mutating webhook rewrite the object into something the policy
1554        // would have rejected — exactly the hole a policy engine closes.
1555        let mutate_ep = "https://inject.example/mutate";
1556        let validate_ep = "https://policy.example/validate";
1557        let source = Arc::new(StaticConfigSource::with_validating(
1558            vec![sidecar_inject_config(mutate_ep)],
1559            vec![validating_config(validate_ep, "policy")],
1560        ));
1561        let caller = Arc::new(MockWebhookCaller::new());
1562        caller
1563            .set_response(
1564                mutate_ep,
1565                MockWebhookCaller::json_patch_review("u", &sidecar_ops()),
1566            )
1567            .await;
1568        caller
1569            .set_response(validate_ep, MockWebhookCaller::allow_review("u"))
1570            .await;
1571        let plugin = MutatingWebhookPlugin::new(source, caller.clone(), pluralizer());
1572
1573        // The mutation still lands.
1574        match plugin.review(&pod_request()).await.unwrap() {
1575            AdmissionDecision::Mutate(_) => {}
1576            other => panic!("expected Mutate, got {other:?}"),
1577        }
1578        // And the validating webhook was called SECOND.
1579        let calls = caller.calls().await;
1580        assert_eq!(calls.len(), 2, "both webhooks must run");
1581        assert!(
1582            calls[0].0.contains("inject") && calls[1].0.contains("policy"),
1583            "validation must run after mutation, got {:?}",
1584            calls.iter().map(|c| c.0.clone()).collect::<Vec<_>>()
1585        );
1586    }
1587
1588    #[tokio::test]
1589    async fn a_source_that_reports_no_validating_configs_behaves_exactly_as_before() {
1590        // The defaulted trait method must not accidentally serve the
1591        // MUTATING list — that would let a policy webhook rewrite objects.
1592        let ep = "https://inject.example/mutate";
1593        let source = Arc::new(StaticConfigSource::new(vec![sidecar_inject_config(ep)]));
1594        assert!(
1595            source.validating_configs().await.is_empty(),
1596            "mutating configs must never surface as validating ones"
1597        );
1598    }
1599
1600    #[tokio::test]
1601    async fn service_ref_resolves_to_clusterip_url_and_calls() {
1602        // The injector Service has an allocated ClusterIP; the plugin
1603        // synthesizes https://<vip>:<port><path> + calls it.
1604        let cfg = service_ref_config("mesh", "injector", 8443, "/mutate");
1605        let source = Arc::new(StaticConfigSource::new(vec![cfg]));
1606        let caller = Arc::new(MockWebhookCaller::new());
1607        let resolved_endpoint = "https://10.96.0.5:8443/mutate";
1608        caller
1609            .set_response(
1610                resolved_endpoint,
1611                MockWebhookCaller::json_patch_review("u", &sidecar_ops()),
1612            )
1613            .await;
1614        let resolver = Arc::new(MockServiceResolver::new().with("mesh", "injector", "10.96.0.5"));
1615        let plugin = MutatingWebhookPlugin::new(source, caller.clone(), pluralizer())
1616            .with_resolver(resolver);
1617
1618        let decision = plugin.review(&pod_request()).await.unwrap();
1619        // The injection landed (the service ref resolved + the webhook ran).
1620        let mutated = match decision {
1621            AdmissionDecision::Mutate(v) => v,
1622            other => panic!("expected Mutate, got {other:?}"),
1623        };
1624        assert!(
1625            mutated["spec"]["containers"]
1626                .as_array()
1627                .unwrap()
1628                .iter()
1629                .any(|c| c["name"] == "aresta-proxy")
1630        );
1631        // The call went to the SYNTHESIZED ClusterIP URL.
1632        let calls = caller.calls().await;
1633        assert_eq!(calls.len(), 1);
1634        assert_eq!(calls[0].0, resolved_endpoint);
1635    }
1636
1637    #[tokio::test]
1638    async fn service_ref_defaults_port_443_and_path_root() {
1639        // No port/path on the ref → defaults: :443 and /.
1640        let cfg = json!({
1641            "kind": "MutatingWebhookConfiguration",
1642            "webhooks": [{
1643                "name": "svc.mesh.io",
1644                "clientConfig": { "service": { "namespace": "mesh", "name": "injector" } },
1645                "rules": [{
1646                    "operations": ["CREATE"], "apiGroups": [""],
1647                    "apiVersions": ["v1"], "resources": ["pods"]
1648                }]
1649            }]
1650        });
1651        let source = Arc::new(StaticConfigSource::new(vec![cfg]));
1652        let caller = Arc::new(MockWebhookCaller::new());
1653        let resolved_endpoint = "https://10.96.0.9:443/";
1654        caller
1655            .set_response(resolved_endpoint, MockWebhookCaller::allow_review("u"))
1656            .await;
1657        let resolver = Arc::new(MockServiceResolver::new().with("mesh", "injector", "10.96.0.9"));
1658        let plugin = MutatingWebhookPlugin::new(source, caller.clone(), pluralizer())
1659            .with_resolver(resolver);
1660
1661        let _ = plugin.review(&pod_request()).await.unwrap();
1662        assert_eq!(caller.calls().await[0].0, resolved_endpoint);
1663    }
1664
1665    #[tokio::test]
1666    async fn service_ref_with_no_clusterip_is_typed_deferral() {
1667        // A resolver that has no VIP for the ref (headless / absent) →
1668        // typed ServiceUnresolvable → governed by failurePolicy=Fail → Deny.
1669        let cfg = service_ref_config("mesh", "injector", 8443, "/mutate");
1670        let source = Arc::new(StaticConfigSource::new(vec![cfg]));
1671        let caller = Arc::new(MockWebhookCaller::new());
1672        let resolver = Arc::new(MockServiceResolver::new()); // empty
1673        let plugin = MutatingWebhookPlugin::new(source, caller.clone(), pluralizer())
1674            .with_resolver(resolver);
1675
1676        match plugin.review(&pod_request()).await.unwrap() {
1677            AdmissionDecision::Deny(reason) => {
1678                assert!(reason.contains("unresolvable"));
1679                assert!(reason.contains("no allocated ClusterIP"));
1680            }
1681            other => panic!("expected Deny, got {other:?}"),
1682        }
1683        assert_eq!(caller.calls().await.len(), 0);
1684    }
1685
1686    // ── The `clientConfig` doc claims, bound (I20) ──────────────────────
1687    //
1688    // WebhookClientConfig's docs say a `url` wins over a `service` ref and
1689    // that the `caBundle` is "threaded to the caller, surfaced never
1690    // dropped". Nothing checked either: the mock caller discarded the
1691    // bundle, so a call path that passed `None` stayed green.
1692
1693    /// A `clientConfig` carrying both a `url` and a `service` ref.
1694    fn url_and_service_config(url: &str, ca_bundle: Option<&str>) -> Value {
1695        let mut client = json!({
1696            "url": url,
1697            "service": { "namespace": "mesh", "name": "injector", "port": 8443 }
1698        });
1699        if let Some(bundle) = ca_bundle {
1700            client["caBundle"] = json!(bundle);
1701        }
1702        json!({
1703            "kind": "MutatingWebhookConfiguration",
1704            "webhooks": [{
1705                "name": "both.mesh.io",
1706                "clientConfig": client,
1707                "rules": [{
1708                    "operations": ["CREATE"], "apiGroups": [""],
1709                    "apiVersions": ["v1"], "resources": ["pods"]
1710                }],
1711                "failurePolicy": "Fail"
1712            }]
1713        })
1714    }
1715
1716    #[tokio::test]
1717    async fn a_url_wins_over_a_service_ref() {
1718        let url = "https://inject.example/mutate";
1719        let source = Arc::new(StaticConfigSource::new(vec![url_and_service_config(
1720            url, None,
1721        )]));
1722        let caller = Arc::new(MockWebhookCaller::new());
1723        caller
1724            .set_response(url, MockWebhookCaller::allow_review("u"))
1725            .await;
1726        // The service ref WOULD resolve, so only precedence keeps it unused.
1727        let resolver = Arc::new(MockServiceResolver::new().with("mesh", "injector", "10.96.0.5"));
1728        let plugin = MutatingWebhookPlugin::new(source, caller.clone(), pluralizer())
1729            .with_resolver(resolver);
1730
1731        let decision = plugin.review(&pod_request()).await.unwrap();
1732
1733        assert!(
1734            matches!(decision, AdmissionDecision::Allow),
1735            "expected Allow, got {decision:?}"
1736        );
1737        let endpoints: Vec<String> = caller.calls().await.into_iter().map(|c| c.0).collect();
1738        assert_eq!(
1739            endpoints,
1740            vec![url.to_string()],
1741            "the url must win over the service ref"
1742        );
1743    }
1744
1745    #[tokio::test]
1746    async fn the_ca_bundle_reaches_the_caller_on_both_endpoint_paths() {
1747        let bundle = "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0t";
1748        // Path 1: a url.
1749        let url = "https://inject.example/mutate";
1750        let source = Arc::new(StaticConfigSource::new(vec![url_and_service_config(
1751            url,
1752            Some(bundle),
1753        )]));
1754        let caller = Arc::new(MockWebhookCaller::new());
1755        caller
1756            .set_response(url, MockWebhookCaller::allow_review("u"))
1757            .await;
1758        let plugin = MutatingWebhookPlugin::new(source, caller.clone(), pluralizer());
1759        let _ = plugin.review(&pod_request()).await.unwrap();
1760        assert_eq!(
1761            caller.ca_bundles().await,
1762            vec![Some(bundle.to_string())],
1763            "the caBundle was dropped on the url path"
1764        );
1765
1766        // Path 2: a service ref resolved to its ClusterIP.
1767        let mut cfg = service_ref_config("mesh", "injector", 8443, "/mutate");
1768        cfg["webhooks"][0]["clientConfig"]["caBundle"] = json!(bundle);
1769        let source = Arc::new(StaticConfigSource::new(vec![cfg]));
1770        let caller = Arc::new(MockWebhookCaller::new());
1771        caller
1772            .set_response(
1773                "https://10.96.0.5:8443/mutate",
1774                MockWebhookCaller::allow_review("u"),
1775            )
1776            .await;
1777        let resolver = Arc::new(MockServiceResolver::new().with("mesh", "injector", "10.96.0.5"));
1778        let plugin = MutatingWebhookPlugin::new(source, caller.clone(), pluralizer())
1779            .with_resolver(resolver);
1780        let _ = plugin.review(&pod_request()).await.unwrap();
1781        assert_eq!(
1782            caller.ca_bundles().await,
1783            vec![Some(bundle.to_string())],
1784            "the caBundle was dropped on the service-ref path"
1785        );
1786    }
1787
1788    #[test]
1789    fn synthesize_endpoint_builds_https_url() {
1790        let svc = ServiceRef {
1791            namespace: "mesh".into(),
1792            name: "injector".into(),
1793            path: Some("/mutate".into()),
1794            port: Some(8443),
1795        };
1796        assert_eq!(
1797            synthesize_service_endpoint("10.96.0.5", &svc),
1798            "https://10.96.0.5:8443/mutate"
1799        );
1800        // Defaults.
1801        let bare = ServiceRef {
1802            namespace: "mesh".into(),
1803            name: "injector".into(),
1804            path: None,
1805            port: None,
1806        };
1807        assert_eq!(
1808            synthesize_service_endpoint("10.96.0.9", &bare),
1809            "https://10.96.0.9:443/"
1810        );
1811        // Path missing a leading slash is normalized.
1812        let noslash = ServiceRef {
1813            namespace: "m".into(),
1814            name: "i".into(),
1815            path: Some("mutate".into()),
1816            port: Some(443),
1817        };
1818        assert_eq!(
1819            synthesize_service_endpoint("10.0.0.1", &noslash),
1820            "https://10.0.0.1:443/mutate"
1821        );
1822    }
1823
1824    #[tokio::test]
1825    async fn two_webhooks_chain_mutations_forward() {
1826        // Webhook A appends a label; webhook B (a later config) sees it and
1827        // appends a container — proving the object flows forward.
1828        let ep_a = "https://a.svc/mutate";
1829        let ep_b = "https://b.svc/mutate";
1830        let cfg_a = json!({
1831            "kind": "MutatingWebhookConfiguration",
1832            "webhooks": [{
1833                "name": "a.io", "clientConfig": { "url": ep_a },
1834                "rules": [{"operations": ["CREATE"], "apiGroups": [""],
1835                           "apiVersions": ["v1"], "resources": ["pods"]}]
1836            }]
1837        });
1838        let cfg_b = json!({
1839            "kind": "MutatingWebhookConfiguration",
1840            "webhooks": [{
1841                "name": "b.io", "clientConfig": { "url": ep_b },
1842                "rules": [{"operations": ["CREATE"], "apiGroups": [""],
1843                           "apiVersions": ["v1"], "resources": ["pods"]}]
1844            }]
1845        });
1846        let source = Arc::new(StaticConfigSource::new(vec![cfg_a, cfg_b]));
1847        let caller = Arc::new(MockWebhookCaller::new());
1848        caller
1849            .set_response(
1850                ep_a,
1851                MockWebhookCaller::json_patch_review(
1852                    "ua",
1853                    &json!([{"op": "add", "path": "/metadata/labels",
1854                             "value": {"mutated-by-a": "yes"}}]),
1855                ),
1856            )
1857            .await;
1858        caller
1859            .set_response(
1860                ep_b,
1861                MockWebhookCaller::json_patch_review(
1862                    "ub",
1863                    &json!([{"op": "add", "path": "/spec/containers/-",
1864                             "value": {"name": "from-b", "image": "b:1"}}]),
1865                ),
1866            )
1867            .await;
1868        let plugin = MutatingWebhookPlugin::new(source, caller.clone(), pluralizer());
1869
1870        let mutated = match plugin.review(&pod_request()).await.unwrap() {
1871            AdmissionDecision::Mutate(v) => v,
1872            other => panic!("expected Mutate, got {other:?}"),
1873        };
1874        assert_eq!(mutated["metadata"]["labels"]["mutated-by-a"], "yes");
1875        let containers = mutated["spec"]["containers"].as_array().unwrap();
1876        assert!(containers.iter().any(|c| c["name"] == "from-b"));
1877        // B was called with the object A already mutated.
1878        let calls = caller.calls().await;
1879        let b_call = calls.iter().find(|(e, _, _)| e == ep_b).unwrap();
1880        assert_eq!(
1881            b_call.2["request"]["object"]["metadata"]["labels"]["mutated-by-a"],
1882            "yes"
1883        );
1884    }
1885
1886    #[tokio::test]
1887    async fn object_selector_filters() {
1888        // A webhook with objectSelector matchLabels{mesh=on} must skip a Pod
1889        // lacking that label.
1890        let endpoint = "https://sel.svc/mutate";
1891        let mut config = sidecar_inject_config(endpoint);
1892        config["webhooks"][0]["objectSelector"] = json!({"matchLabels": {"mesh": "on"}});
1893        let source = Arc::new(StaticConfigSource::new(vec![config]));
1894        let caller = Arc::new(MockWebhookCaller::new());
1895        caller
1896            .set_response(
1897                endpoint,
1898                MockWebhookCaller::json_patch_review("u", &sidecar_ops()),
1899            )
1900            .await;
1901        let plugin = MutatingWebhookPlugin::new(source, caller.clone(), pluralizer());
1902
1903        // Pod without the label → not selected → not called → admit unchanged.
1904        let decision = plugin.review(&pod_request()).await.unwrap();
1905        assert!(matches!(decision, AdmissionDecision::Allow));
1906        assert_eq!(caller.calls().await.len(), 0);
1907
1908        // Pod WITH the label → selected → injected.
1909        let mut req = pod_request();
1910        req.value.as_mut().unwrap()["metadata"]["labels"] = json!({"mesh": "on"});
1911        let decision = plugin.review(&req).await.unwrap();
1912        assert!(matches!(decision, AdmissionDecision::Mutate(_)));
1913        assert_eq!(caller.calls().await.len(), 1);
1914    }
1915
1916    #[tokio::test]
1917    async fn unsupported_patch_type_is_governed_by_failure_policy() {
1918        let endpoint = "https://badtype.svc/mutate";
1919        let source = Arc::new(StaticConfigSource::new(vec![sidecar_inject_config(
1920            endpoint,
1921        )]));
1922        let caller = Arc::new(MockWebhookCaller::new());
1923        // Response declares a patchType engenho doesn't support.
1924        caller
1925            .set_response(
1926                endpoint,
1927                json!({
1928                    "response": { "uid": "u", "allowed": true,
1929                                  "patchType": "SomeFuturePatch", "patch": "e30=" }
1930                }),
1931            )
1932            .await;
1933        let plugin = MutatingWebhookPlugin::new(source, caller, pluralizer());
1934
1935        // failurePolicy=Fail → the unsupported patchType denies (not silent).
1936        match plugin.review(&pod_request()).await.unwrap() {
1937            AdmissionDecision::Deny(reason) => {
1938                assert!(reason.contains("SomeFuturePatch") || reason.contains("unsupported"));
1939            }
1940            other => panic!("expected Deny, got {other:?}"),
1941        }
1942    }
1943
1944    #[tokio::test]
1945    async fn delete_is_admit_through() {
1946        let endpoint = "https://x.svc/mutate";
1947        let source = Arc::new(StaticConfigSource::new(vec![sidecar_inject_config(
1948            endpoint,
1949        )]));
1950        let caller = Arc::new(MockWebhookCaller::new());
1951        let plugin = MutatingWebhookPlugin::new(source, caller.clone(), pluralizer());
1952
1953        let mut req = pod_request();
1954        req.action = AdmissionAction::Delete;
1955        req.value = None;
1956        let decision = plugin.review(&req).await.unwrap();
1957        assert!(matches!(decision, AdmissionDecision::Allow));
1958        assert_eq!(
1959            caller.calls().await.len(),
1960            0,
1961            "mutating plugin doesn't call on delete"
1962        );
1963    }
1964
1965    #[test]
1966    fn rules_match_wildcards() {
1967        let wh = MutatingWebhook {
1968            name: "w".into(),
1969            client_config: WebhookClientConfig {
1970                url: Some("u".into()),
1971                service: None,
1972                ca_bundle: None,
1973            },
1974            rules: vec![RuleWithOperations {
1975                operations: vec!["*".into()],
1976                api_groups: vec!["*".into()],
1977                api_versions: vec!["*".into()],
1978                resources: vec!["*".into()],
1979            }],
1980            failure_policy: FailurePolicy::Fail,
1981            timeout_seconds: 10,
1982            reinvocation_policy: ReinvocationPolicy::Never,
1983            namespace_selector: None,
1984            object_selector: None,
1985        };
1986        assert!(rules_match(&wh, "apps", "v1", "deployments", "CREATE"));
1987        assert!(rules_match(&wh, "", "v1", "pods", "DELETE"));
1988    }
1989
1990    #[test]
1991    fn parse_defaults_are_k8s_defaults() {
1992        let cfg = json!({
1993            "webhooks": [{ "name": "w", "clientConfig": { "url": "u" } }]
1994        });
1995        let hooks = parse_mutating_config(&cfg);
1996        assert_eq!(hooks.len(), 1);
1997        assert_eq!(hooks[0].failure_policy, FailurePolicy::Fail);
1998        assert_eq!(hooks[0].timeout_seconds, 10);
1999        assert_eq!(hooks[0].reinvocation_policy, ReinvocationPolicy::Never);
2000    }
2001}