1use std::collections::BTreeMap;
45use std::sync::Arc;
46
47use async_trait::async_trait;
48use serde_json::Value;
49use tracing::warn;
50
51use engenho_store::command::{Reason as CommandReason, ResourceCommand};
52use engenho_store::{ResourceKey, StoreMesh};
53
54use crate::controller::{Controller, ReconcileOutcome};
55use crate::effect::Effect;
56use crate::error::ControllerError;
57use crate::event_recorder::{EventRecord, EventSink, InvolvedObject, NullEventSink, Reason};
58use crate::meta::{ShapeError, object_mut};
59use crate::network_policy::{
60 Direction, NetworkPolicyEnforcer, NetworkPolicyRule, PeerSelector, PolicyDatapath, PortSpec,
61};
62use crate::reads::{DeclaresReads, Reads, gvk};
63use crate::sweep::{ObjectOutcome, Sweep};
64
65pub const ENFORCEMENT_ANNOTATION: &str = "engenho.io/network-policy-enforcement";
69
70pub const ALLOW_ALL_CIDR: &str = "0.0.0.0/0";
73
74#[must_use]
86pub fn effective_policy_types(spec: &Value) -> (bool, bool) {
87 if let Some(types) = spec.get("policyTypes").and_then(Value::as_array) {
88 let has = |t: &str| types.iter().any(|v| v.as_str() == Some(t));
89 return (has("Ingress"), has("Egress"));
90 }
91 let has_egress = spec
92 .get("egress")
93 .and_then(Value::as_array)
94 .is_some_and(|a| !a.is_empty());
95 (true, has_egress)
96}
97
98fn match_labels_of(v: Option<&Value>) -> BTreeMap<String, String> {
99 let mut out = BTreeMap::new();
100 let Some(obj) = v
101 .and_then(|s| s.get("matchLabels"))
102 .and_then(Value::as_object)
103 else {
104 return out;
105 };
106 for (k, val) in obj {
107 if let Some(s) = val.as_str() {
108 out.insert(k.clone(), s.to_string());
109 }
110 }
111 out
112}
113
114fn peer_of(entry: &Value) -> Option<PeerSelector> {
120 if let Some(ip) = entry.get("ipBlock") {
121 let cidr = ip.get("cidr").and_then(Value::as_str)?.to_string();
122 let except = ip
123 .get("except")
124 .and_then(Value::as_array)
125 .map(|a| {
126 a.iter()
127 .filter_map(|v| v.as_str().map(ToString::to_string))
128 .collect()
129 })
130 .unwrap_or_default();
131 return Some(PeerSelector::IpBlock { cidr, except });
132 }
133 if entry.get("podSelector").is_some() {
140 return Some(PeerSelector::PodSelector {
141 match_labels: match_labels_of(entry.get("podSelector")),
142 });
143 }
144 if entry.get("namespaceSelector").is_some() {
145 return Some(PeerSelector::NamespaceSelector {
146 match_labels: match_labels_of(entry.get("namespaceSelector")),
147 });
148 }
149 None
150}
151
152fn ports_of(rule: &Value) -> Vec<PortSpec> {
153 let Some(ports) = rule.get("ports").and_then(Value::as_array) else {
154 return Vec::new();
155 };
156 ports
157 .iter()
158 .filter_map(|p| {
159 let port = u16::try_from(p.get("port").and_then(Value::as_u64)?).ok()?;
165 let end_port = p
166 .get("endPort")
167 .and_then(Value::as_u64)
168 .and_then(|v| u16::try_from(v).ok());
169 Some(PortSpec {
170 port,
171 end_port,
172 protocol: p
173 .get("protocol")
174 .and_then(Value::as_str)
175 .unwrap_or("TCP")
176 .to_string(),
177 })
178 })
179 .collect()
180}
181
182#[must_use]
188pub fn rule_id(namespace: &str, name: &str, direction: Direction, index: usize) -> String {
189 let d = match direction {
190 Direction::Ingress => "ingress",
191 Direction::Egress => "egress",
192 };
193 format!("{namespace}/{name}#{d}:{index}")
194}
195
196#[must_use]
198pub fn policy_prefix(namespace: &str, name: &str) -> String {
199 format!("{namespace}/{name}#")
200}
201
202#[must_use]
207pub fn translate(policy: &Value) -> Vec<NetworkPolicyRule> {
208 let meta = policy.get("metadata");
209 let namespace = meta
210 .and_then(|m| m.get("namespace"))
211 .and_then(Value::as_str)
212 .unwrap_or("default");
213 let name = meta
214 .and_then(|m| m.get("name"))
215 .and_then(Value::as_str)
216 .unwrap_or_default();
217 if name.is_empty() {
218 return Vec::new();
219 }
220 let Some(spec) = policy.get("spec").filter(|s| s.is_object()) else {
226 return Vec::new();
227 };
228
229 let pod_selector = match_labels_of(spec.get("podSelector"));
230 let (ingress, egress) = effective_policy_types(spec);
231 let mut out = Vec::new();
232
233 for (enabled, direction, field, peer_field) in [
234 (ingress, Direction::Ingress, "ingress", "from"),
235 (egress, Direction::Egress, "egress", "to"),
236 ] {
237 if !enabled {
238 continue;
239 }
240 let rules = spec.get(field).and_then(Value::as_array).map(Vec::as_slice);
241 match rules {
242 None | Some(&[]) => out.push(NetworkPolicyRule {
245 policy_id: rule_id(namespace, name, direction, 0),
246 pod_selector: pod_selector.clone(),
247 direction,
248 allowed_peers: Vec::new(),
249 allowed_ports: Vec::new(),
250 }),
251 Some(list) => {
252 for (i, r) in list.iter().enumerate() {
253 let peers = match r
254 .get(peer_field)
255 .and_then(Value::as_array)
256 .map(Vec::as_slice)
257 {
258 None | Some(&[]) => vec![PeerSelector::IpBlock {
261 cidr: ALLOW_ALL_CIDR.to_string(),
262 except: Vec::new(),
263 }],
264 Some(entries) => {
265 let peers: Vec<_> = entries.iter().filter_map(peer_of).collect();
266 if peers.is_empty() {
272 continue;
273 }
274 peers
275 }
276 };
277 out.push(NetworkPolicyRule {
278 policy_id: rule_id(namespace, name, direction, i),
279 pod_selector: pod_selector.clone(),
280 direction,
281 allowed_peers: peers,
282 allowed_ports: ports_of(r),
283 });
284 }
285 }
286 }
287 }
288 out
289}
290
291#[must_use]
297pub fn enforcement_value(datapath: PolicyDatapath) -> &'static str {
298 match datapath {
299 PolicyDatapath::Computed => "Computed",
300 PolicyDatapath::Installed => "Installed",
301 }
302}
303
304#[must_use]
310pub fn already_annotated(policy: &Value, datapath: PolicyDatapath) -> bool {
311 policy
312 .get("metadata")
313 .and_then(|m| m.get("annotations"))
314 .and_then(|a| a.get(ENFORCEMENT_ANNOTATION))
315 .and_then(Value::as_str)
316 == Some(enforcement_value(datapath))
317}
318
319const ANNOTATIONS: &[&str] = &["metadata", "annotations"];
321
322pub fn annotated(policy: &Value, datapath: PolicyDatapath) -> Result<Value, ShapeError> {
334 let mut out = policy.clone();
335 object_mut(&mut out, ANNOTATIONS)?.insert(
336 ENFORCEMENT_ANNOTATION.to_string(),
337 Value::from(enforcement_value(datapath)),
338 );
339 Ok(out)
340}
341
342#[must_use]
347pub fn not_enforced_message(backend: &str) -> String {
348 format!(
349 "NetworkPolicy accepted and its rules computed, but the '{backend}' backend installs no \
350 packet filter on this node: traffic this policy claims to restrict is NOT restricted"
351 )
352}
353
354pub struct NetworkPolicyController {
361 store: Arc<StoreMesh>,
362 enforcer: Arc<dyn NetworkPolicyEnforcer>,
363 events: Arc<dyn EventSink>,
364 sweep: Sweep,
367}
368
369const COMPONENT: &str = "network-policy-controller";
371
372impl NetworkPolicyController {
373 #[must_use]
375 pub fn new(store: Arc<StoreMesh>, enforcer: Arc<dyn NetworkPolicyEnforcer>) -> Self {
376 Self {
377 store,
378 enforcer,
379 events: Arc::new(NullEventSink),
380 sweep: Sweep::new(COMPONENT, Reason::FailedUpdate),
381 }
382 }
383
384 #[must_use]
387 pub fn with_event_sink(mut self, events: Arc<dyn EventSink>) -> Self {
388 self.sweep = self.sweep.with_event_sink(events.clone());
389 self.events = events;
390 self
391 }
392
393 async fn reconcile_policy(
400 &self,
401 key: &ResourceKey,
402 policy: &Value,
403 rules: &[NetworkPolicyRule],
404 datapath: PolicyDatapath,
405 now: &str,
406 ) -> Result<ObjectOutcome, ControllerError> {
407 let mut refused = false;
408 for rule in rules {
409 if self.enforcer.upsert(rule).await.is_err() {
410 refused = true;
411 }
412 }
413
414 if already_annotated(policy, datapath) {
415 return Ok(if refused {
416 ObjectOutcome::skipped_because("enforcer refused a rule")
417 } else {
418 ObjectOutcome::Unchanged
419 });
420 }
421 let desired = annotated(policy, datapath)?;
422 let Ok(applied) = self
423 .store
424 .propose(ResourceCommand::Put {
425 key: key.clone(),
426 value: desired,
427 expected: None,
428 reason: CommandReason::Controller,
429 })
430 .await
431 else {
432 return Ok(ObjectOutcome::SKIPPED);
433 };
434 let effect = Effect::of(applied.op);
435
436 if datapath == PolicyDatapath::Computed && effect.landed() {
442 let meta = policy.get("metadata");
443 self.events
444 .record(EventRecord {
445 involved: InvolvedObject {
446 api_version: "networking.k8s.io/v1".into(),
447 kind: "NetworkPolicy".into(),
448 namespace: meta
449 .and_then(|m| m.get("namespace"))
450 .and_then(Value::as_str)
451 .map(ToString::to_string),
452 name: meta
453 .and_then(|m| m.get("name"))
454 .and_then(Value::as_str)
455 .unwrap_or_default()
456 .to_string(),
457 uid: meta
458 .and_then(|m| m.get("uid"))
459 .and_then(Value::as_str)
460 .map(ToString::to_string),
461 },
462 reason: Reason::NetworkPolicyNotEnforced,
463 message: not_enforced_message(self.enforcer.name()),
464 component: COMPONENT.into(),
465 timestamp: now.to_string(),
466 })
467 .await;
468 }
469 Ok(ObjectOutcome::from(effect))
470 }
471}
472
473impl DeclaresReads for NetworkPolicyController {
475 fn reads(&self) -> Reads {
476 Reads::of(&[gvk("networking.k8s.io", "v1", "NetworkPolicy")])
477 }
478}
479
480#[async_trait]
481impl Controller for NetworkPolicyController {
482 fn name(&self) -> &'static str {
483 "network-policy"
484 }
485
486 async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
487 let datapath = self.enforcer.datapath();
488 let now = engenho_types::time::now_rfc3339_utc();
489
490 let policies = self
491 .store
492 .list("networking.k8s.io", "v1", "NetworkPolicy", None)
493 .await;
494
495 let rules: BTreeMap<&ResourceKey, Vec<NetworkPolicyRule>> = policies
501 .iter()
502 .map(|(key, policy)| (key, translate(policy)))
503 .collect();
504 let desired_ids: Vec<&str> = rules
505 .values()
506 .flatten()
507 .map(|rule| rule.policy_id.as_str())
508 .collect();
509
510 let rules = &rules;
515 let now = now.as_str();
516 let report = self
517 .sweep
518 .run(&policies, |key, policy| async move {
519 let policy_rules = rules.get(key).map_or(&[][..], Vec::as_slice);
520 ObjectOutcome::settle(
521 self.reconcile_policy(key, policy, policy_rules, datapath, now)
522 .await,
523 )
524 })
525 .await?;
526
527 let mut outcome = ReconcileOutcome::from(report);
530
531 if let Ok(installed) = self.enforcer.list().await {
536 for rule in installed {
537 if desired_ids.contains(&rule.policy_id.as_str()) {
538 continue;
539 }
540 match Effect::applied(self.enforcer.remove(&rule.policy_id).await) {
541 Ok(effect) => outcome.report.record(effect),
542 Err(error) => warn!(
543 policy_id = %rule.policy_id,
544 enforcer = self.enforcer.name(),
545 %error,
546 "a deleted policy's rule could not be removed; it is still enforced"
547 ),
548 }
549 }
550 }
551 Ok(outcome)
552 }
553}
554
555#[cfg(test)]
556mod translate_tests {
557 use super::*;
558 use serde_json::json;
559
560 fn policy(spec: Value) -> Value {
561 json!({
562 "apiVersion": "networking.k8s.io/v1",
563 "kind": "NetworkPolicy",
564 "metadata": { "name": "p", "namespace": "ns" },
565 "spec": spec,
566 })
567 }
568
569 #[test]
571 fn absent_policy_types_means_ingress_plus_egress_only_if_egress_rules_exist() {
572 assert_eq!(effective_policy_types(&json!({})), (true, false));
573 assert_eq!(
574 effective_policy_types(&json!({ "egress": [{ "to": [] }] })),
575 (true, true)
576 );
577 assert_eq!(
580 effective_policy_types(&json!({ "egress": [] })),
581 (true, false)
582 );
583 assert_eq!(
585 effective_policy_types(&json!({ "policyTypes": ["Egress"], "ingress": [{}] })),
586 (false, true)
587 );
588 }
589
590 #[test]
593 fn deny_all_and_allow_all_do_not_collapse_onto_each_other() {
594 let deny = translate(&policy(json!({ "podSelector": {} })));
596 assert_eq!(deny.len(), 1);
597 assert!(
598 deny[0].allowed_peers.is_empty(),
599 "empty peers is this model's deny-all"
600 );
601
602 let allow = translate(&policy(json!({ "ingress": [{}] })));
604 assert_eq!(allow.len(), 1);
605 assert_eq!(
606 allow[0].allowed_peers,
607 vec![PeerSelector::IpBlock {
608 cidr: ALLOW_ALL_CIDR.into(),
609 except: vec![]
610 }]
611 );
612 assert_ne!(deny[0].allowed_peers, allow[0].allowed_peers);
613 }
614
615 #[test]
617 fn an_explicitly_empty_from_is_allow_all_not_deny_all() {
618 let r = translate(&policy(json!({ "ingress": [{ "from": [] }] })));
619 assert_eq!(r.len(), 1);
620 assert!(!r[0].allowed_peers.is_empty(), "from: [] means allow all");
621 }
622
623 #[test]
626 fn rule_ids_are_unique_and_share_the_policy_prefix() {
627 let r = translate(&policy(json!({
628 "policyTypes": ["Ingress", "Egress"],
629 "ingress": [{ "from": [{ "ipBlock": { "cidr": "10.0.0.0/8" } }] },
630 { "from": [{ "ipBlock": { "cidr": "192.168.0.0/16" } }] }],
631 "egress": [{ "to": [{ "ipBlock": { "cidr": "0.0.0.0/0" } }] }],
632 })));
633 assert_eq!(r.len(), 3);
634 let ids: Vec<_> = r.iter().map(|x| x.policy_id.clone()).collect();
635 let mut uniq = ids.clone();
636 uniq.sort();
637 uniq.dedup();
638 assert_eq!(uniq.len(), ids.len(), "ids collide: {ids:?}");
639 let prefix = policy_prefix("ns", "p");
640 assert!(ids.iter().all(|i| i.starts_with(&prefix)), "{ids:?}");
641 }
642
643 #[test]
645 fn a_named_port_is_dropped_rather_than_defaulted_to_a_number() {
646 let r = translate(&policy(json!({
647 "ingress": [{ "from": [{ "ipBlock": { "cidr": "10.0.0.0/8" } }],
648 "ports": [{ "port": 80, "protocol": "TCP" },
649 { "port": "http", "protocol": "TCP" },
650 { "port": 8000, "endPort": 8100, "protocol": "UDP" }] }]
651 })));
652 assert_eq!(r[0].allowed_ports.len(), 2, "the named port is dropped");
653 assert_eq!(r[0].allowed_ports[0].port, 80);
654 assert_eq!(r[0].allowed_ports[1].end_port, Some(8100));
655 assert_eq!(r[0].allowed_ports[1].protocol, "UDP");
656 }
657
658 #[test]
660 fn protocol_defaults_to_tcp() {
661 let r = translate(&policy(json!({
662 "ingress": [{ "from": [{ "ipBlock": { "cidr": "10.0.0.0/8" } }],
663 "ports": [{ "port": 53 }] }]
664 })));
665 assert_eq!(r[0].allowed_ports[0].protocol, "TCP");
666 }
667
668 #[test]
672 fn a_rule_with_only_unrecognised_peers_is_skipped_not_turned_into_a_deny() {
673 let r = translate(&policy(json!({
674 "policyTypes": ["Ingress"],
675 "ingress": [{ "from": [{ "somethingFromTheFuture": {} }] }],
676 })));
677 assert!(r.is_empty(), "got {r:?}");
678 }
679
680 #[test]
683 fn malformed_policies_are_total() {
684 assert!(translate(&json!({})).is_empty());
685 assert!(translate(&json!({ "metadata": { "name": "p" } })).is_empty());
686 assert!(translate(&json!({ "spec": {} })).is_empty(), "no name");
687 assert!(translate(&json!(null)).is_empty());
688 assert!(translate(&json!({ "metadata": { "name": "p" }, "spec": null })).is_empty());
690 }
691
692 #[test]
695 fn the_pod_selector_is_carried_onto_every_rule() {
696 let r = translate(&policy(json!({
697 "podSelector": { "matchLabels": { "app": "db" } },
698 "policyTypes": ["Ingress", "Egress"],
699 })));
700 assert_eq!(r.len(), 2);
701 assert!(r.iter().all(|x| x.pod_selector["app"] == "db"));
702 }
703
704 #[test]
707 fn a_policy_without_a_namespace_lands_in_default() {
708 let r = translate(&json!({
709 "metadata": { "name": "p" },
710 "spec": { "policyTypes": ["Ingress"] },
711 }));
712 assert!(r[0].policy_id.starts_with("default/p#"));
713 }
714}
715
716#[cfg(test)]
717mod honesty_tests {
718 use super::*;
719 use serde_json::json;
720
721 #[test]
722 fn the_annotation_records_the_verdict_and_is_idempotent() {
723 let p = json!({ "metadata": { "name": "p" } });
724 assert!(!already_annotated(&p, PolicyDatapath::Computed));
725 let once = annotated(&p, PolicyDatapath::Computed).unwrap();
726 assert!(already_annotated(&once, PolicyDatapath::Computed));
727 assert_eq!(once, annotated(&once, PolicyDatapath::Computed).unwrap());
730 }
731
732 #[test]
733 fn a_computed_annotation_does_not_satisfy_an_installed_check() {
734 let p = annotated(&json!({}), PolicyDatapath::Computed).unwrap();
737 assert!(!already_annotated(&p, PolicyDatapath::Installed));
738 }
739
740 #[test]
741 fn annotating_preserves_existing_metadata_and_annotations() {
742 let p = json!({
743 "metadata": { "name": "p", "namespace": "ns",
744 "annotations": { "keep": "me" } }
745 });
746 let out = annotated(&p, PolicyDatapath::Installed).unwrap();
747 assert_eq!(out["metadata"]["name"], "p");
748 assert_eq!(out["metadata"]["namespace"], "ns");
749 assert_eq!(out["metadata"]["annotations"]["keep"], "me");
750 }
751
752 #[test]
756 fn null_annotations_or_metadata_are_annotated() {
757 for p in [
758 json!({ "metadata": { "name": "p", "annotations": null } }),
759 json!({ "metadata": null }),
760 ] {
761 let out = annotated(&p, PolicyDatapath::Installed).unwrap();
762 assert!(already_annotated(&out, PolicyDatapath::Installed), "{p}");
763 }
764 }
765
766 #[test]
768 fn a_wrong_shaped_annotations_field_is_an_error() {
769 let p = json!({ "metadata": { "name": "p", "annotations": ["x"] } });
770 assert_eq!(
771 annotated(&p, PolicyDatapath::Computed)
772 .unwrap_err()
773 .to_string(),
774 "metadata.annotations is an array, expected an object"
775 );
776 }
777
778 #[test]
779 fn the_message_names_what_is_not_restricted_not_merely_what_is_missing() {
780 let m = not_enforced_message("fake");
781 assert!(m.contains("NOT restricted"), "{m}");
782 assert!(m.contains("fake"), "{m}");
783 }
784
785 #[test]
786 fn a_new_backend_that_forgets_to_override_claims_enforcement() {
787 struct Forgetful;
791 #[async_trait]
792 impl NetworkPolicyEnforcer for Forgetful {
793 fn name(&self) -> &'static str {
794 "forgetful"
795 }
796 async fn upsert(
797 &self,
798 _r: &NetworkPolicyRule,
799 ) -> Result<(), crate::network_policy::NetworkPolicyError> {
800 Ok(())
801 }
802 async fn remove(
803 &self,
804 _id: &str,
805 ) -> Result<(), crate::network_policy::NetworkPolicyError> {
806 Ok(())
807 }
808 async fn list(
809 &self,
810 ) -> Result<Vec<NetworkPolicyRule>, crate::network_policy::NetworkPolicyError>
811 {
812 Ok(vec![])
813 }
814 }
815 assert_eq!(Forgetful.datapath(), PolicyDatapath::Installed);
816 assert_eq!(
818 crate::network_policy::FakeNetworkPolicyEnforcer::new().datapath(),
819 PolicyDatapath::Computed
820 );
821 }
822}