Skip to main content

engenho_controllers/
network_policy.rs

1//! R17 — `NetworkPolicy` enforcement.
2//!
3//! Typed pluggable backend for installing L3/L4 firewall rules
4//! that implement K8s `NetworkPolicy` semantics. Backends:
5//!   * [`FakeNetworkPolicyEnforcer`] (tests; tracks rules in `BTreeMap`)
6//!   * [`ComputedNetworkPolicyEnforcer`] (computes and records the rules,
7//!     and says it installs nothing: for a host with no packet filter to
8//!     install into)
9//!   * [`CiliumNetworkPolicyAdapter`] (renders `CiliumNetworkPolicy` CRD YAML
10//!     into a directory, for a cilium-operator to pick up)
11//!
12//! No backend installs kernel rules itself; an iptables backend is not
13//! written.
14
15use std::collections::BTreeMap;
16use std::sync::Arc;
17
18use async_trait::async_trait;
19use serde::{Deserialize, Serialize};
20use thiserror::Error;
21use tokio::sync::Mutex;
22
23/// One `NetworkPolicy` rule — a flat representation of the K8s
24/// `NetworkPolicy` spec.
25#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
26pub struct NetworkPolicyRule {
27    /// `namespace/name` of the source `NetworkPolicy` object.
28    pub policy_id: String,
29    /// Pod selector (matchLabels) — pods this rule applies to.
30    pub pod_selector: BTreeMap<String, String>,
31    /// Direction: ingress (incoming) or egress (outgoing).
32    pub direction: Direction,
33    /// Allowed peers — empty = deny all in that direction.
34    pub allowed_peers: Vec<PeerSelector>,
35    /// Allowed ports — empty = any port.
36    pub allowed_ports: Vec<PortSpec>,
37}
38
39/// Direction of traffic.
40#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "PascalCase")]
42pub enum Direction {
43    /// Incoming traffic to selected pods.
44    Ingress,
45    /// Outgoing traffic from selected pods.
46    Egress,
47}
48
49/// One allowed peer (pod selector, namespace selector, or CIDR).
50#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "snake_case")]
52pub enum PeerSelector {
53    /// Match pods with these labels.
54    PodSelector {
55        /// Pod label match map.
56        match_labels: BTreeMap<String, String>,
57    },
58    /// Match all pods in namespaces with these labels.
59    NamespaceSelector {
60        /// Namespace label match map.
61        match_labels: BTreeMap<String, String>,
62    },
63    /// Match an IP range (e.g. "10.0.0.0/8").
64    IpBlock {
65        /// CIDR string.
66        cidr: String,
67        /// Optional exclusion CIDRs.
68        #[serde(default, skip_serializing_if = "Vec::is_empty")]
69        except: Vec<String>,
70    },
71}
72
73/// One allowed port range.
74#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
75pub struct PortSpec {
76    /// Port number (or start of range).
77    pub port: u16,
78    /// Optional end of port range; None = single port.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub end_port: Option<u16>,
81    /// Protocol: TCP / UDP / SCTP (default TCP).
82    pub protocol: String,
83}
84
85/// `NetworkPolicy` backend errors.
86#[derive(Debug, Clone, Error)]
87pub enum NetworkPolicyError {
88    /// Backend (Cilium, iptables, ebpf) returned an error.
89    #[error("backend: {0}")]
90    Backend(String),
91    /// Invalid policy (e.g. empty `policy_id`).
92    #[error("invalid policy: {0}")]
93    InvalidPolicy(String),
94}
95
96engenho_substrate::impl_error_kind! {
97    NetworkPolicyError {
98        (Backend(_)) => "backend",
99        (InvalidPolicy(_)) => "invalid_policy",
100    }
101}
102
103/// Whether a backend actually INSTALLS the policy datapath, or only
104/// computes it.
105///
106/// ★ THE SAME SPLIT `DatapathInstall` MAKES FOR kube-proxy, AND FOR THE
107/// SAME REASON. A `NetworkPolicy` that is parsed, selected and tracked but
108/// never installed in a kernel allows every packet it claims to deny. That
109/// is not a partial implementation, it is the opposite of the stated
110/// semantics — and it is the one failure shape where silence is a security
111/// claim rather than a missing feature. Making the distinction a value on
112/// the trait means a caller cannot hold an enforcer without being able to
113/// ask which of the two it got.
114#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
115pub enum PolicyDatapath {
116    /// Rules are computed, selected and observable, but NO packet filter
117    /// is installed anywhere. The fail-safe state on a topology that
118    /// cannot host the filter (engenho on darwin, pods inside a podman
119    /// VM). Traffic is UNRESTRICTED; the policy is a plan, not a control.
120    Computed,
121    /// The backend installed the filter (iptables / eBPF / a Cilium CRD a
122    /// running cilium-operator loads). Traffic is actually restricted.
123    Installed,
124}
125
126/// Pluggable network-policy backend trait.
127#[async_trait]
128pub trait NetworkPolicyEnforcer: Send + Sync {
129    /// Backend identifier for telemetry.
130    fn name(&self) -> &'static str;
131
132    /// Whether this backend installs the datapath or only computes it.
133    ///
134    /// Defaults to [`PolicyDatapath::Installed`] — the kernel backends —
135    /// so a NEW backend that forgets to override is claimed to enforce and
136    /// will be caught by the honesty test, rather than defaulting to the
137    /// permissive answer that nobody notices.
138    fn datapath(&self) -> PolicyDatapath {
139        PolicyDatapath::Installed
140    }
141
142    /// Install / refresh a rule. Idempotent.
143    ///
144    /// # Errors
145    /// [`NetworkPolicyError::Backend`] on backend failure.
146    async fn upsert(&self, rule: &NetworkPolicyRule) -> Result<(), NetworkPolicyError>;
147
148    /// Remove a rule by `policy_id`.
149    ///
150    /// # Errors
151    /// [`NetworkPolicyError::Backend`] on backend failure.
152    async fn remove(&self, policy_id: &str) -> Result<(), NetworkPolicyError>;
153
154    /// Currently-installed rules.
155    ///
156    /// # Errors
157    /// [`NetworkPolicyError::Backend`] on backend failure.
158    async fn list(&self) -> Result<Vec<NetworkPolicyRule>, NetworkPolicyError>;
159}
160
161// =================================================================
162// FakeNetworkPolicyEnforcer — deterministic backend for tests
163// =================================================================
164
165/// In-memory backend. Tracks rules in a `BTreeMap` + records events.
166#[derive(Default, Clone)]
167pub struct FakeNetworkPolicyEnforcer {
168    inner: Arc<Mutex<FakeNpState>>,
169}
170
171#[derive(Default)]
172struct FakeNpState {
173    rules: BTreeMap<String, NetworkPolicyRule>,
174    events: Vec<FakeNpEvent>,
175}
176
177/// Per-call event log.
178#[derive(Clone, Debug, PartialEq, Eq)]
179pub enum FakeNpEvent {
180    /// `upsert(policy_id)`.
181    Upsert(String),
182    /// `remove(policy_id)`.
183    Remove(String),
184}
185
186impl FakeNetworkPolicyEnforcer {
187    /// Fresh empty backend.
188    #[must_use]
189    pub fn new() -> Self {
190        Self::default()
191    }
192
193    /// Snapshot of events.
194    pub async fn events(&self) -> Vec<FakeNpEvent> {
195        self.inner.lock().await.events.clone()
196    }
197
198    /// Count of installed rules.
199    pub async fn rule_count(&self) -> usize {
200        self.inner.lock().await.rules.len()
201    }
202}
203
204#[async_trait]
205impl NetworkPolicyEnforcer for FakeNetworkPolicyEnforcer {
206    fn name(&self) -> &'static str {
207        "fake"
208    }
209
210    /// A test double installs nothing, and neither does the darwin
211    /// topology it stands in for.
212    fn datapath(&self) -> PolicyDatapath {
213        PolicyDatapath::Computed
214    }
215
216    async fn upsert(&self, rule: &NetworkPolicyRule) -> Result<(), NetworkPolicyError> {
217        if rule.policy_id.is_empty() {
218            return Err(NetworkPolicyError::InvalidPolicy("empty policy_id".into()));
219        }
220        let mut state = self.inner.lock().await;
221        state.rules.insert(rule.policy_id.clone(), rule.clone());
222        state
223            .events
224            .push(FakeNpEvent::Upsert(rule.policy_id.clone()));
225        Ok(())
226    }
227
228    async fn remove(&self, policy_id: &str) -> Result<(), NetworkPolicyError> {
229        let mut state = self.inner.lock().await;
230        state.rules.remove(policy_id);
231        state
232            .events
233            .push(FakeNpEvent::Remove(policy_id.to_string()));
234        Ok(())
235    }
236
237    async fn list(&self) -> Result<Vec<NetworkPolicyRule>, NetworkPolicyError> {
238        Ok(self.inner.lock().await.rules.values().cloned().collect())
239    }
240}
241
242// =================================================================
243// CiliumNetworkPolicyAdapter — renders Cilium CRD YAML
244// =================================================================
245
246/// Renders [`NetworkPolicyRule`] as `CiliumNetworkPolicy` CRD YAML +
247/// writes to a configured directory. Cilium operator watches the
248/// directory + hot-reloads.
249///
250/// No shell-out; pure Rust + `std::fs`.
251#[derive(Clone)]
252pub struct CiliumNetworkPolicyAdapter {
253    output_dir: std::path::PathBuf,
254    inner: Arc<Mutex<CiliumState>>,
255}
256
257#[derive(Default)]
258struct CiliumState {
259    rules: BTreeMap<String, NetworkPolicyRule>,
260}
261
262impl CiliumNetworkPolicyAdapter {
263    /// New adapter writing to `output_dir`.
264    #[must_use]
265    pub fn new(output_dir: impl Into<std::path::PathBuf>) -> Self {
266        Self {
267            output_dir: output_dir.into(),
268            inner: Arc::new(Mutex::new(CiliumState::default())),
269        }
270    }
271
272    /// Render the `CiliumNetworkPolicy` CRD YAML for one rule. Pure.
273    ///
274    /// Builds a typed [`engenho_types::egress::CiliumNetworkPolicy`]
275    /// + renders it through `serde_norway` (per the ★★ TYPED EMISSION
276    /// rule — no `format!()` of YAML syntax).
277    #[must_use]
278    pub fn render_crd(rule: &NetworkPolicyRule) -> String {
279        use engenho_types::egress::{CiliumDirection, CiliumNetworkPolicy};
280        let name = rule.policy_id.replace('/', "-");
281        let direction = match rule.direction {
282            Direction::Ingress => CiliumDirection::Ingress,
283            Direction::Egress => CiliumDirection::Egress,
284        };
285        CiliumNetworkPolicy::new(name, rule.pod_selector.clone(), direction).to_yaml()
286    }
287
288    fn rule_filename(rule: &NetworkPolicyRule) -> String {
289        format!("{}.yaml", rule.policy_id.replace('/', "-"))
290    }
291}
292
293#[async_trait]
294impl NetworkPolicyEnforcer for CiliumNetworkPolicyAdapter {
295    fn name(&self) -> &'static str {
296        "cilium"
297    }
298
299    async fn upsert(&self, rule: &NetworkPolicyRule) -> Result<(), NetworkPolicyError> {
300        if rule.policy_id.is_empty() {
301            return Err(NetworkPolicyError::InvalidPolicy("empty policy_id".into()));
302        }
303        let yaml = Self::render_crd(rule);
304        let file = self.output_dir.join(Self::rule_filename(rule));
305        std::fs::create_dir_all(&self.output_dir).map_err(|e| {
306            NetworkPolicyError::Backend(format!("mkdir {}: {e}", self.output_dir.display()))
307        })?;
308        std::fs::write(&file, yaml)
309            .map_err(|e| NetworkPolicyError::Backend(format!("write {}: {e}", file.display())))?;
310        self.inner
311            .lock()
312            .await
313            .rules
314            .insert(rule.policy_id.clone(), rule.clone());
315        Ok(())
316    }
317
318    async fn remove(&self, policy_id: &str) -> Result<(), NetworkPolicyError> {
319        let filename = format!("{}.yaml", policy_id.replace('/', "-"));
320        let file = self.output_dir.join(filename);
321        let _ = std::fs::remove_file(&file);
322        self.inner.lock().await.rules.remove(policy_id);
323        Ok(())
324    }
325
326    async fn list(&self) -> Result<Vec<NetworkPolicyRule>, NetworkPolicyError> {
327        Ok(self.inner.lock().await.rules.values().cloned().collect())
328    }
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334
335    fn sample_rule() -> NetworkPolicyRule {
336        let mut sel = BTreeMap::new();
337        sel.insert("app".to_string(), "podinfo".to_string());
338        NetworkPolicyRule {
339            policy_id: "default/allow-frontend".into(),
340            pod_selector: sel,
341            direction: Direction::Ingress,
342            allowed_peers: vec![PeerSelector::PodSelector {
343                match_labels: {
344                    let mut m = BTreeMap::new();
345                    m.insert("app".to_string(), "frontend".to_string());
346                    m
347                },
348            }],
349            allowed_ports: vec![PortSpec {
350                port: 80,
351                end_port: None,
352                protocol: "TCP".into(),
353            }],
354        }
355    }
356
357    // ── Fake ─────────────────────────────────────────────────
358
359    #[tokio::test]
360    async fn fake_upsert_inserts_rule() {
361        let b = FakeNetworkPolicyEnforcer::new();
362        b.upsert(&sample_rule()).await.unwrap();
363        assert_eq!(b.rule_count().await, 1);
364    }
365
366    #[tokio::test]
367    async fn fake_rejects_empty_policy_id() {
368        let b = FakeNetworkPolicyEnforcer::new();
369        let mut r = sample_rule();
370        r.policy_id = String::new();
371        let err = b.upsert(&r).await.unwrap_err();
372        assert_eq!(err.kind(), "invalid_policy");
373    }
374
375    #[tokio::test]
376    async fn fake_remove_clears_rule() {
377        let b = FakeNetworkPolicyEnforcer::new();
378        let r = sample_rule();
379        b.upsert(&r).await.unwrap();
380        b.remove(&r.policy_id).await.unwrap();
381        assert_eq!(b.rule_count().await, 0);
382    }
383
384    #[tokio::test]
385    async fn fake_events_record_in_order() {
386        let b = FakeNetworkPolicyEnforcer::new();
387        let r = sample_rule();
388        b.upsert(&r).await.unwrap();
389        b.remove(&r.policy_id).await.unwrap();
390        let evs = b.events().await;
391        assert_eq!(evs.len(), 2);
392        assert!(matches!(&evs[0], FakeNpEvent::Upsert(_)));
393        assert!(matches!(&evs[1], FakeNpEvent::Remove(_)));
394    }
395
396    #[tokio::test]
397    async fn fake_list_returns_rules() {
398        let b = FakeNetworkPolicyEnforcer::new();
399        b.upsert(&sample_rule()).await.unwrap();
400        assert_eq!(b.list().await.unwrap().len(), 1);
401    }
402
403    // ── Cilium ───────────────────────────────────────────────
404
405    #[test]
406    fn cilium_render_crd_contains_selector_and_direction() {
407        let yaml = CiliumNetworkPolicyAdapter::render_crd(&sample_rule());
408        assert!(yaml.contains("apiVersion: cilium.io/v2"));
409        assert!(yaml.contains("kind: CiliumNetworkPolicy"));
410        assert!(yaml.contains("name: default-allow-frontend"));
411        assert!(yaml.contains("app: podinfo"));
412        assert!(yaml.contains("ingress:"));
413    }
414
415    #[test]
416    fn cilium_render_crd_egress_direction() {
417        let mut r = sample_rule();
418        r.direction = Direction::Egress;
419        let yaml = CiliumNetworkPolicyAdapter::render_crd(&r);
420        assert!(yaml.contains("egress:"));
421        assert!(!yaml.contains("ingress:"));
422    }
423
424    #[tokio::test]
425    async fn cilium_upsert_writes_file() {
426        let dir = std::env::temp_dir().join(format!("engenho-np-test-{}", std::process::id()));
427        let _ = std::fs::remove_dir_all(&dir);
428        let b = CiliumNetworkPolicyAdapter::new(&dir);
429        b.upsert(&sample_rule()).await.unwrap();
430        let files: Vec<_> = std::fs::read_dir(&dir)
431            .unwrap()
432            .filter_map(|e| e.ok().map(|e| e.path()))
433            .collect();
434        assert_eq!(files.len(), 1);
435        let content = std::fs::read_to_string(&files[0]).unwrap();
436        assert!(content.contains("CiliumNetworkPolicy"));
437        let _ = std::fs::remove_dir_all(&dir);
438    }
439
440    #[tokio::test]
441    async fn cilium_remove_deletes_file() {
442        let dir = std::env::temp_dir().join(format!("engenho-np-rm-{}", std::process::id()));
443        let _ = std::fs::remove_dir_all(&dir);
444        let b = CiliumNetworkPolicyAdapter::new(&dir);
445        let r = sample_rule();
446        b.upsert(&r).await.unwrap();
447        b.remove(&r.policy_id).await.unwrap();
448        let count = std::fs::read_dir(&dir).map_or(0, std::iter::Iterator::count);
449        assert_eq!(count, 0);
450        let _ = std::fs::remove_dir_all(&dir);
451    }
452
453    #[test]
454    fn direction_serializes_pascal_case() {
455        assert_eq!(
456            serde_json::to_string(&Direction::Ingress).unwrap(),
457            "\"Ingress\""
458        );
459    }
460
461    #[test]
462    fn peer_selector_serializes_snake_case() {
463        let p = PeerSelector::IpBlock {
464            cidr: "10.0.0.0/8".into(),
465            except: vec![],
466        };
467        let json = serde_json::to_string(&p).unwrap();
468        assert!(json.contains("\"ip_block\""));
469    }
470
471    #[test]
472    fn error_kinds_are_stable() {
473        assert_eq!(NetworkPolicyError::Backend("x".into()).kind(), "backend");
474        assert_eq!(
475            NetworkPolicyError::InvalidPolicy("x".into()).kind(),
476            "invalid_policy"
477        );
478    }
479
480    #[test]
481    fn backend_names_are_stable() {
482        assert_eq!(FakeNetworkPolicyEnforcer::new().name(), "fake");
483        assert_eq!(CiliumNetworkPolicyAdapter::new("/tmp").name(), "cilium");
484    }
485}
486
487// =================================================================
488// ComputedNetworkPolicyEnforcer — the honest PRODUCTION backend for a
489// topology that cannot host a packet filter.
490// =================================================================
491
492/// The production backend on a host with no filter to install into
493/// (engenho on darwin, pods inside a podman VM).
494///
495/// ★ WHY THIS EXISTS SEPARATELY FROM `FakeNetworkPolicyEnforcer` WHEN THE
496/// BEHAVIOUR IS IDENTICAL. It is not duplicated — the tracking is
497/// DELEGATED to the same implementation. What differs is the only two
498/// things that matter at a boundary: the `name()` that appears in an
499/// operator-facing event and in logs, and the fact that wiring a struct
500/// called `Fake…` into a production runtime is how a test double quietly
501/// becomes the shipped answer. A backend an operator sees named `fake` in
502/// a warning is a bug report; one named `computed` is the truth.
503#[derive(Default, Clone)]
504pub struct ComputedNetworkPolicyEnforcer {
505    inner: FakeNetworkPolicyEnforcer,
506}
507
508impl ComputedNetworkPolicyEnforcer {
509    /// Fresh backend.
510    #[must_use]
511    pub fn new() -> Self {
512        Self::default()
513    }
514}
515
516#[async_trait]
517impl NetworkPolicyEnforcer for ComputedNetworkPolicyEnforcer {
518    fn name(&self) -> &'static str {
519        "computed"
520    }
521
522    /// Computed, always. This backend has no path to `Installed`, so the
523    /// permissive answer cannot be reached by a configuration mistake.
524    fn datapath(&self) -> PolicyDatapath {
525        PolicyDatapath::Computed
526    }
527
528    async fn upsert(&self, rule: &NetworkPolicyRule) -> Result<(), NetworkPolicyError> {
529        self.inner.upsert(rule).await
530    }
531
532    async fn remove(&self, policy_id: &str) -> Result<(), NetworkPolicyError> {
533        self.inner.remove(policy_id).await
534    }
535
536    async fn list(&self) -> Result<Vec<NetworkPolicyRule>, NetworkPolicyError> {
537        self.inner.list().await
538    }
539}
540
541#[cfg(test)]
542mod computed_backend_tests {
543    use super::*;
544
545    #[tokio::test]
546    async fn the_production_computed_backend_tracks_but_never_claims_enforcement() {
547        let e = ComputedNetworkPolicyEnforcer::new();
548        assert_eq!(e.datapath(), PolicyDatapath::Computed);
549        // The operator-facing name must not be the word "fake": that is the
550        // whole reason this type is not the test double.
551        assert_eq!(e.name(), "computed");
552        e.upsert(&NetworkPolicyRule {
553            policy_id: "ns/p#ingress:0".into(),
554            pod_selector: BTreeMap::new(),
555            direction: Direction::Ingress,
556            allowed_peers: vec![],
557            allowed_ports: vec![],
558        })
559        .await
560        .unwrap();
561        assert_eq!(e.list().await.unwrap().len(), 1, "rules are still tracked");
562    }
563}