Skip to main content

engenho_controllers/
network_policy_controller.rs

1//! `NetworkPolicyController` — the PRODUCER `NetworkPolicyEnforcer` never had.
2//!
3//! ★ THE GAP THIS CLOSES. `network_policy.rs` shipped a typed rule model, a
4//! trait, a `FakeNetworkPolicyEnforcer` and a `CiliumNetworkPolicyAdapter`,
5//! all tested — and nothing anywhere constructed a rule from a real
6//! `NetworkPolicy` object or called `upsert`. Measured 2026-08-30:
7//!
8//! ```text
9//! $ grep -rn 'NetworkPolicyEnforcer' --include=*.rs . | grep -v network_policy.rs
10//! engenho-controllers/src/lib.rs:136:   (the re-export)
11//! ```
12//!
13//! Zero consumers. That is instance #8 of "type + backend + no producer" in
14//! this codebase, and it is the most dangerous one so far: every other
15//! instance was a missing feature, while this one is a POLICY OBJECT THAT
16//! APPLIES SUCCESSFULLY AND RESTRICTS NOTHING. An operator writes a
17//! default-deny policy, `kubectl` says `created`, and every packet still
18//! flows.
19//!
20//! ★ TWO SEPARATE JOBS, DELIBERATELY NOT COLLAPSED.
21//!
22//! 1. **Translate + install.** `spec` → [`NetworkPolicyRule`]s → the
23//!    enforcer. This is the feature.
24//! 2. **Say which one happened.** If the enforcer's
25//!    [`PolicyDatapath`] is `Computed` — the darwin topology, where there is
26//!    no kernel to install a filter into — the policy is annotated and an
27//!    event is emitted saying the traffic is unrestricted.
28//!
29//! Job 2 is not decoration and it does not wait for job 1 to be perfect. A
30//! computed-only policy is indistinguishable from an enforced one by every
31//! `kubectl` command there is, so the *only* thing standing between an
32//! operator and a false sense of containment is this annotation.
33//!
34//! ★ WHY "ALLOW FROM ANYWHERE" IS ENCODED AS `0.0.0.0/0` AND NOT AS AN
35//! EMPTY PEER LIST. Upstream's `from: []` (absent) means *allow all*, while
36//! a policyType naming a direction with no rules at all means *deny all*.
37//! [`NetworkPolicyRule`] already fixes empty `allowed_peers` to mean deny,
38//! so the two cases would collapse onto the same value and the permissive
39//! one would silently become a deny — or, read the other way, a deny would
40//! become permissive. Rendering allow-all as an explicit
41//! `IpBlock { cidr: "0.0.0.0/0" }` keeps them distinct without widening the
42//! rule type, and it is what every real enforcer emits for that case anyway.
43
44use 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
65/// The annotation carrying the enforcement verdict, so the distinction is
66/// machine-queryable (`kubectl get netpol -o json`) and not only visible in
67/// an event that ages out.
68pub const ENFORCEMENT_ANNOTATION: &str = "engenho.io/network-policy-enforcement";
69
70/// Upstream's allow-all CIDR. See the module header for why allow-all is
71/// encoded this way rather than as an empty peer list.
72pub const ALLOW_ALL_CIDR: &str = "0.0.0.0/0";
73
74// =====================================================================
75// TRANSLATION — pure, and therefore the part that can be exhaustively
76// tested without a store, an enforcer or a clock.
77// =====================================================================
78
79/// The `policyTypes` a `NetworkPolicy` is effectively subject to.
80///
81/// Upstream's defaulting rule, which is easy to get subtly wrong: when
82/// `policyTypes` is absent it is `[Ingress]`, PLUS `Egress` if and only if
83/// the policy has any `egress` rules. It is NOT "whichever sections are
84/// present" — a policy with neither section is still an ingress deny-all.
85#[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
114/// One `from`/`to` entry → a peer.
115///
116/// Returns `None` for an entry naming neither a selector nor a CIDR: an
117/// unrecognised peer must never widen the rule to allow-all, so it is
118/// dropped rather than defaulted.
119fn 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    // A `namespaceSelector` present alongside a `podSelector` is upstream's
134    // AND semantics. The flat rule model has no conjunction, so the
135    // namespace selector — the WIDER of the two — is dropped and the pod
136    // selector kept, which narrows rather than widens. Narrowing an allow
137    // rule can break traffic loudly; widening it fails open silently, and
138    // between those two this picks the one an operator can see.
139    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            // A named port (`port: "http"`) cannot be resolved without the
160            // target pod's containerPort table, which translation does not
161            // have. Dropping the ENTRY (not the port field) is the safe
162            // direction: keeping it with a defaulted port number would
163            // allow traffic on a port nobody asked for.
164            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/// The stable id of one translated rule.
183///
184/// `<ns>/<name>#<direction>:<index>` — a policy produces several rules, and
185/// the enforcer keys on this string, so it has to be unique per rule AND
186/// prefix-derivable from the policy so deletion can find them all.
187#[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/// The prefix every rule of one policy shares. Used to reap on delete.
197#[must_use]
198pub fn policy_prefix(namespace: &str, name: &str) -> String {
199    format!("{namespace}/{name}#")
200}
201
202/// Translate one `NetworkPolicy` object into flat enforcer rules.
203///
204/// Total: never panics, never returns an error. A malformed policy yields
205/// fewer rules, never a wrong one.
206#[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    // `get("spec")` on `{"spec": null}` returns `Some(Null)`, not `None` —
221    // so requiring an OBJECT is what actually rejects a malformed policy.
222    // Without this a null spec defaults to "policyTypes absent" and
223    // translates to a deny-all ingress rule: engenho would invent a
224    // restriction the operator never wrote. Found by T8, not by reading.
225    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            // A direction named in policyTypes with no rules is upstream's
243            // DENY ALL. Empty `allowed_peers` is exactly that.
244            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                        // Absent or empty `from`/`to` is ALLOW ALL — the
259                        // case that must not collapse onto deny-all.
260                        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                            // Every entry was unrecognised. Emitting a rule
267                            // with no peers here would turn an ALLOW into a
268                            // DENY; emitting allow-all would ignore the
269                            // operator's intent entirely. Skip the rule and
270                            // let the direction's other rules stand.
271                            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// =====================================================================
292// HONESTY — the annotation, kept idempotent.
293// =====================================================================
294
295/// The annotation value for a datapath verdict.
296#[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/// Whether the policy already carries the right verdict.
305///
306/// Keeps the controller idempotent: rewriting an unchanged annotation every
307/// tick advances the store revision forever, which is the hot-loop class
308/// the node lease already hit once in this codebase.
309#[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
319/// Where a policy's annotations live.
320const ANNOTATIONS: &[&str] = &["metadata", "annotations"];
321
322/// The policy with the enforcement verdict annotated.
323///
324/// Absent or `null` `metadata`/`annotations` are the empty case and get
325/// the annotation.
326///
327/// # Errors
328///
329/// [`ShapeError`] when the policy, its `metadata`, or its `annotations`
330/// holds the wrong JSON type. It used to `expect` here, and the panic took
331/// the controller task with it, so no policy after the malformed one was
332/// ever annotated.
333pub 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/// The message an operator reads when a policy restricts nothing.
343///
344/// Names the CONSEQUENCE, not the absence — the same rule the inert-kind
345/// messages follow.
346#[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
354// =====================================================================
355// THE PRODUCER
356// =====================================================================
357
358/// Translates every `NetworkPolicy` into enforcer rules, installs them, and
359/// records whether they are actually enforced.
360pub struct NetworkPolicyController {
361    store: Arc<StoreMesh>,
362    enforcer: Arc<dyn NetworkPolicyEnforcer>,
363    events: Arc<dyn EventSink>,
364    /// Per-policy isolation: a policy whose annotations cannot be written
365    /// gets a `FailedUpdate` Event and the others are still annotated.
366    sweep: Sweep,
367}
368
369/// The component this controller signs its Events with.
370const COMPONENT: &str = "network-policy-controller";
371
372impl NetworkPolicyController {
373    /// New controller over `store`, installing through `enforcer`.
374    #[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    /// Builder: wire the event sink so a computed-only policy, and a policy
385    /// whose verdict cannot be annotated, is visible in `kubectl describe`.
386    #[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    /// One policy: install its rules, then annotate the verdict (and, on a
394    /// computed-only datapath, say so once, on the transition).
395    ///
396    /// A failed rule install or a failed store write is a skip, as it
397    /// always was here; a policy whose annotations have the wrong shape is
398    /// an Item failure the sweep announces on the policy.
399    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        // The event fires only on the transition — the annotation check
437        // above already returned for a policy seen on a previous tick —
438        // so this does not spam one event per policy per tick. And only
439        // when the annotation landed: a write that changed nothing
440        // announced nothing.
441        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
473/// The policies it translates into enforcer rules.
474impl 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        // Every policy's rules, translated once. The ids are every rule
496        // this pass believes should exist: anything the enforcer holds that
497        // is NOT among them belongs to a deleted policy and is reaped below
498        // — which is how a `kubectl delete netpol` actually stops
499        // enforcing, rather than leaving the filter installed forever.
500        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        // Each policy isolated: one whose annotations have the wrong shape
511        // is announced on itself, and every other policy is still installed
512        // and annotated. Nothing here returns a store error (a failed write
513        // is a skip), so the sweep always reaches the reap.
514        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        // A reaped rule belongs to no listed policy, so the sweep did not
528        // count it; the legacy counter does, for each removal that landed.
529        let mut outcome = ReconcileOutcome::from(report);
530
531        // Reap rules whose policy is gone. A removal the enforcer refused
532        // is not a change: the filter is still installed, and a deleted
533        // policy is still being enforced, so it is said once per tick at
534        // WARN until the removal lands.
535        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    // T1 — the defaulting rule that is easy to get subtly wrong.
570    #[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        // Present-but-empty egress does NOT turn egress on: upstream keys
578        // the default off the presence of RULES, not of the field.
579        assert_eq!(
580            effective_policy_types(&json!({ "egress": [] })),
581            (true, false)
582        );
583        // An explicit list wins over every inference.
584        assert_eq!(
585            effective_policy_types(&json!({ "policyTypes": ["Egress"], "ingress": [{}] })),
586            (false, true)
587        );
588    }
589
590    // T2 — THE load-bearing distinction. Deny-all and allow-all differ by
591    // one absent field in the source and must never render the same.
592    #[test]
593    fn deny_all_and_allow_all_do_not_collapse_onto_each_other() {
594        // No ingress section at all ⇒ deny all ingress.
595        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        // One ingress rule with no `from` ⇒ allow from anywhere.
603        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    // T3 — an explicitly empty `from: []` is also allow-all upstream.
616    #[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    // T4 — every rule of one policy shares a reapable prefix and has a
624    // unique id, or the enforcer's keyed map silently loses rules.
625    #[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    // T5 — ports, including the named-port case that cannot be resolved.
644    #[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    // T6 — protocol defaults to TCP, as upstream does.
659    #[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    // T7 — a rule whose every peer is unrecognised is SKIPPED, because
669    // both alternatives are wrong: no peers would flip an allow into a
670    // deny, and allow-all would ignore the operator entirely.
671    #[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    // T8 — totality. A malformed policy yields fewer rules, never a panic
681    // and never a wrong one.
682    #[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        // A policy with a name but a null spec field.
689        assert!(translate(&json!({ "metadata": { "name": "p" }, "spec": null })).is_empty());
690    }
691
692    // T9 — the pod selector reaches every rule, or the rules apply to the
693    // wrong pods.
694    #[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    // T10 — namespace defaulting, since a rule id keyed on the wrong
705    // namespace collides across namespaces.
706    #[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        // A rewrite every tick advances the store revision forever — the
728        // hot-loop class the node lease already hit in this codebase.
729        assert_eq!(once, annotated(&once, PolicyDatapath::Computed).unwrap());
730    }
731
732    #[test]
733    fn a_computed_annotation_does_not_satisfy_an_installed_check() {
734        // The direction that matters: a policy that is NOT enforced must
735        // never read as enforced.
736        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    /// `null` annotations (or metadata) are the empty case: annotated, not a
753    /// panic. On HEAD before T4.3 this was `expect("annotations is an
754    /// object")`.
755    #[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    /// The wrong type is an error naming the field, never a panic.
767    #[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        // The default is deliberately the CLAIM, so a backend that forgets
788        // is caught by an honesty test rather than defaulting to the
789        // permissive answer nobody notices.
790        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        // And the test double, which installs nothing, says so.
817        assert_eq!(
818            crate::network_policy::FakeNetworkPolicyEnforcer::new().datapath(),
819            PolicyDatapath::Computed
820        );
821    }
822}