1use 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#[derive(Clone, Debug, PartialEq, Eq)]
80pub struct MutatingWebhook {
81 pub name: String,
83 pub client_config: WebhookClientConfig,
85 pub rules: Vec<RuleWithOperations>,
88 pub failure_policy: FailurePolicy,
91 pub timeout_seconds: u32,
93 pub reinvocation_policy: ReinvocationPolicy,
96 pub namespace_selector: Option<LabelSelector>,
99 pub object_selector: Option<LabelSelector>,
102}
103
104#[derive(Clone, Debug, PartialEq, Eq)]
106pub struct WebhookClientConfig {
107 pub url: Option<String>,
109 pub service: Option<ServiceRef>,
115 pub ca_bundle: Option<String>,
120}
121
122#[derive(Clone, Debug, PartialEq, Eq)]
124pub struct ServiceRef {
125 pub namespace: String,
127 pub name: String,
129 pub path: Option<String>,
131 pub port: Option<u16>,
133}
134
135#[derive(Clone, Debug, PartialEq, Eq)]
138pub struct RuleWithOperations {
139 pub operations: Vec<String>,
141 pub api_groups: Vec<String>,
143 pub api_versions: Vec<String>,
145 pub resources: Vec<String>,
147}
148
149#[derive(Clone, Copy, Debug, PartialEq, Eq)]
151pub enum FailurePolicy {
152 Fail,
154 Ignore,
156}
157
158#[derive(Clone, Copy, Debug, PartialEq, Eq)]
160pub enum ReinvocationPolicy {
161 Never,
163 IfNeeded,
165}
166
167#[derive(Clone, Debug, PartialEq, Eq, Default)]
171pub struct LabelSelector {
172 pub match_labels: std::collections::BTreeMap<String, String>,
174}
175
176impl LabelSelector {
177 #[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#[derive(Debug, Clone, Error, PartialEq, Eq)]
194pub enum WebhookError {
195 #[error("call to webhook {webhook:?} failed: {message}")]
198 CallFailed {
199 webhook: String,
201 message: String,
203 },
204 #[error("webhook {webhook:?} returned a malformed AdmissionReview: {reason}")]
207 BadResponse {
208 webhook: String,
210 reason: String,
212 },
213 #[error("webhook {webhook:?} returned unsupported patchType {got:?} (only JSONPatch)")]
215 UnsupportedPatchType {
216 webhook: String,
218 got: String,
220 },
221 #[error("webhook {webhook:?} patch could not be applied: {reason}")]
224 PatchApply {
225 webhook: String,
227 reason: String,
229 },
230 #[error(
236 "webhook {webhook:?} clientConfig.service ({namespace}/{name}) is \
237 unresolvable: {reason}"
238 )]
239 ServiceUnresolvable {
240 webhook: String,
242 namespace: String,
244 name: String,
246 reason: String,
248 },
249 #[error("webhook {webhook:?} clientConfig declares neither url nor service")]
251 NoEndpoint {
252 webhook: String,
254 },
255}
256
257#[async_trait]
266pub trait WebhookConfigSource: Send + Sync {
267 async fn mutating_configs(&self) -> Vec<Value>;
269
270 async fn validating_configs(&self) -> Vec<Value> {
285 Vec::new()
286 }
287}
288
289#[async_trait]
293pub trait WebhookCaller: Send + Sync {
294 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#[async_trait]
318pub trait ServiceResolver: Send + Sync {
319 async fn cluster_ip(&self, namespace: &str, name: &str) -> Option<String>;
323}
324
325pub struct StoreServiceResolver {
329 store: Arc<engenho_store::StoreMesh>,
330}
331
332impl StoreServiceResolver {
333 #[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 if ip == "None" || ip.is_empty() {
352 None
353 } else {
354 Some(ip.to_string())
355 }
356 }
357}
358
359#[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 if path.starts_with('/') {
371 format!("https://{cluster_ip}:{port}{path}")
372 } else {
373 format!("https://{cluster_ip}:{port}/{path}")
374 }
375}
376
377#[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 _ => 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#[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
489fn rule_field_matches(patterns: &[String], value: &str) -> bool {
491 patterns.iter().any(|p| p == "*" || p == value)
492}
493
494#[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#[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#[derive(Clone, Debug, PartialEq, Eq)]
555pub struct WebhookResponse {
556 pub uid: String,
558 pub allowed: bool,
560 pub message: Option<String>,
562 pub patch: Option<Value>,
565}
566
567pub 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 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
639pub 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 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
666pub type Pluralizer = Box<dyn Fn(&str, &str, &str) -> Option<String> + Send + Sync>;
674
675pub struct MutatingWebhookPlugin {
685 source: Arc<dyn WebhookConfigSource>,
686 caller: Arc<dyn WebhookCaller>,
687 resolver: Option<Arc<dyn ServiceResolver>>,
692 pluralize: Pluralizer,
696}
697
698impl MutatingWebhookPlugin {
699 #[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 #[must_use]
721 pub fn with_resolver(mut self, resolver: Arc<dyn ServiceResolver>) -> Self {
722 self.resolver = Some(resolver);
723 self
724 }
725
726 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 return AdmissionDecision::Allow;
733 };
734 let operation = operation_for(request.action);
735 let configs = self.source.mutating_configs().await;
736
737 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 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 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 }
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 async fn call_one(
854 &self,
855 webhook: &MutatingWebhook,
856 review_req: &Value,
857 ) -> Result<WebhookResponse, WebhookError> {
858 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 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 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 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
964fn 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
978fn 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 match request.action {
1011 AdmissionAction::Put | AdmissionAction::Patch => Ok(self.dispatch(request).await),
1012 AdmissionAction::Delete => Ok(AdmissionDecision::Allow),
1013 }
1014 }
1015}
1016
1017#[derive(Clone, Default)]
1023pub struct StaticConfigSource {
1024 configs: Arc<Vec<Value>>,
1025 validating: Arc<Vec<Value>>,
1026}
1027
1028impl StaticConfigSource {
1029 #[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 #[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#[derive(Clone, Default)]
1067pub struct MockWebhookCaller {
1068 inner: Arc<Mutex<MockCallerState>>,
1069}
1070
1071#[derive(Default)]
1072struct MockCallerState {
1073 responses: std::collections::BTreeMap<String, Value>,
1075 errors: std::collections::BTreeMap<String, String>,
1077 calls: Vec<(String, u32, Value)>,
1079 ca_bundles: Vec<Option<String>>,
1081}
1082
1083impl MockWebhookCaller {
1084 #[must_use]
1086 pub fn new() -> Self {
1087 Self::default()
1088 }
1089
1090 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 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 pub async fn calls(&self) -> Vec<(String, u32, Value)> {
1110 self.inner.lock().await.calls.clone()
1111 }
1112
1113 pub async fn ca_bundles(&self) -> Vec<Option<String>> {
1115 self.inner.lock().await.ca_bundles.clone()
1116 }
1117
1118 #[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 #[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 #[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#[derive(Clone, Default)]
1163pub struct MockServiceResolver {
1164 map: std::collections::BTreeMap<String, String>,
1165}
1166
1167impl MockServiceResolver {
1168 #[must_use]
1170 pub fn new() -> Self {
1171 Self::default()
1172 }
1173
1174 #[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 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 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 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 let inits = mutated["spec"]["initContainers"].as_array().unwrap();
1336 assert_eq!(inits.len(), 1);
1337 assert_eq!(inits[0]["name"], "spire-agent-init");
1338 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 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 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 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 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 #[tokio::test]
1496 async fn a_validating_webhook_can_deny() {
1497 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 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 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 match plugin.review(&pod_request()).await.unwrap() {
1575 AdmissionDecision::Mutate(_) => {}
1576 other => panic!("expected Mutate, got {other:?}"),
1577 }
1578 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 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 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 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 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 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 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()); 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 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 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 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 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 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 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 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 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 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 let decision = plugin.review(&pod_request()).await.unwrap();
1905 assert!(matches!(decision, AdmissionDecision::Allow));
1906 assert_eq!(caller.calls().await.len(), 0);
1907
1908 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 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 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}