Skip to main content

engenho_controllers/
ingress.rs

1//! R14 — Ingress dimension.
2//!
3//! HTTP/HTTPS routing from public hostnames to in-cluster services.
4//! Pluggable [`IngressBackend`] trait — [`FakeIngressBackend`] for
5//! tests, [`TraefikIngressBackend`] renders Traefik `IngressRoute` CRDs,
6//! [`NginxIngressBackend`] renders nginx server-block files. Whether the
7//! daemon runs this controller, and why not, is recorded once, in
8//! engenho-runtime's dormant-controller catalog (`Dormant::Ingress`).
9//!
10//! ## Reconcile rule
11//!
12//! 1. List `Ingress` objects from the store.
13//! 2. For each Ingress, compute typed [`IngressRoute`] entries —
14//!    one per (host, path, backend service:port) tuple.
15//! 3. Diff against backend's installed routes.
16//! 4. upsert mismatches; remove orphans.
17//! 5. Idempotent — re-tick is no-op.
18
19use std::collections::BTreeMap;
20use std::sync::Arc;
21
22use async_trait::async_trait;
23use engenho_store::StoreMesh;
24use serde::{Deserialize, Serialize};
25use thiserror::Error;
26use tokio::sync::Mutex;
27
28use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
29use crate::effect::Effect;
30use crate::error::ControllerError;
31
32/// One ingress routing rule — public hostname + path → service backend.
33#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
34pub struct IngressRoute {
35    /// `namespace/name` of the Ingress resource owning this rule.
36    pub ingress_id: String,
37    /// Host header to match (e.g. "podinfo.example.com").
38    pub host: String,
39    /// URL path prefix (e.g. "/", "/api").
40    pub path: String,
41    /// Path-matching strategy. Default is Prefix.
42    pub path_type: PathType,
43    /// Backend service name (in the same namespace).
44    pub backend_service: String,
45    /// Backend service port.
46    pub backend_port: u16,
47    /// Optional TLS secret name. None = HTTP-only.
48    pub tls_secret: Option<String>,
49}
50
51/// K8s Ingress pathType enum.
52#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
53#[serde(rename_all = "PascalCase")]
54#[derive(Default)]
55pub enum PathType {
56    /// Match the path exactly.
57    Exact,
58    /// Match the path as a prefix (default).
59    #[default]
60    Prefix,
61    /// Implementation-specific.
62    ImplementationSpecific,
63}
64
65/// Ingress backend errors.
66#[derive(Debug, Clone, Error)]
67pub enum IngressError {
68    /// Backend (Traefik, nginx, external API) returned an error.
69    #[error("backend: {0}")]
70    Backend(String),
71    /// Invalid route (empty host, etc).
72    #[error("invalid route: {0}")]
73    InvalidRoute(String),
74}
75
76engenho_substrate::impl_error_kind! {
77    IngressError {
78        (Backend(_)) => "backend",
79        (InvalidRoute(_)) => "invalid_route",
80    }
81}
82
83/// Pluggable ingress backend trait.
84#[async_trait]
85pub trait IngressBackend: Send + Sync {
86    /// Backend identifier for telemetry.
87    fn name(&self) -> &'static str;
88
89    /// Install / refresh `route`. Idempotent.
90    ///
91    /// # Errors
92    /// [`IngressError::Backend`] on backend failure;
93    /// [`IngressError::InvalidRoute`] for malformed input.
94    async fn upsert(&self, route: &IngressRoute) -> Result<(), IngressError>;
95
96    /// Remove a route by (`ingress_id`, host, path) triple — the
97    /// unique key. The backend identifies the route by this key.
98    ///
99    /// # Errors
100    /// [`IngressError::Backend`] on backend failure.
101    async fn remove(&self, ingress_id: &str, host: &str, path: &str) -> Result<(), IngressError>;
102
103    /// Currently-installed routes.
104    ///
105    /// # Errors
106    /// [`IngressError::Backend`] on backend failure.
107    async fn list(&self) -> Result<Vec<IngressRoute>, IngressError>;
108}
109
110// =================================================================
111// FakeIngressBackend — deterministic in-memory backend
112// =================================================================
113
114/// In-memory backend. Tracks routes in a `BTreeMap` keyed by
115/// (`ingress_id`, host, path). Records every call for test assertion.
116#[derive(Default, Clone)]
117pub struct FakeIngressBackend {
118    inner: Arc<Mutex<FakeIngressState>>,
119}
120
121#[derive(Default)]
122struct FakeIngressState {
123    routes: BTreeMap<(String, String, String), IngressRoute>,
124    events: Vec<FakeIngressEvent>,
125}
126
127/// Per-call event log.
128#[derive(Clone, Debug, PartialEq, Eq)]
129pub enum FakeIngressEvent {
130    /// `upsert(ingress_id, host, path)`.
131    Upsert(String, String, String),
132    /// `remove(ingress_id, host, path)`.
133    Remove(String, String, String),
134}
135
136impl FakeIngressBackend {
137    /// Fresh empty backend.
138    #[must_use]
139    pub fn new() -> Self {
140        Self::default()
141    }
142
143    /// Snapshot of events.
144    pub async fn events(&self) -> Vec<FakeIngressEvent> {
145        self.inner.lock().await.events.clone()
146    }
147
148    /// Count of installed routes.
149    pub async fn route_count(&self) -> usize {
150        self.inner.lock().await.routes.len()
151    }
152}
153
154#[async_trait]
155impl IngressBackend for FakeIngressBackend {
156    fn name(&self) -> &'static str {
157        "fake"
158    }
159
160    async fn upsert(&self, route: &IngressRoute) -> Result<(), IngressError> {
161        if route.host.is_empty() {
162            return Err(IngressError::InvalidRoute("empty host".into()));
163        }
164        if route.backend_service.is_empty() {
165            return Err(IngressError::InvalidRoute("empty backend_service".into()));
166        }
167        let key = (
168            route.ingress_id.clone(),
169            route.host.clone(),
170            route.path.clone(),
171        );
172        let mut state = self.inner.lock().await;
173        state.routes.insert(key.clone(), route.clone());
174        state
175            .events
176            .push(FakeIngressEvent::Upsert(key.0, key.1, key.2));
177        Ok(())
178    }
179
180    async fn remove(&self, ingress_id: &str, host: &str, path: &str) -> Result<(), IngressError> {
181        let key = (ingress_id.to_string(), host.to_string(), path.to_string());
182        let mut state = self.inner.lock().await;
183        state.routes.remove(&key);
184        state
185            .events
186            .push(FakeIngressEvent::Remove(key.0, key.1, key.2));
187        Ok(())
188    }
189
190    async fn list(&self) -> Result<Vec<IngressRoute>, IngressError> {
191        Ok(self.inner.lock().await.routes.values().cloned().collect())
192    }
193}
194
195// =================================================================
196// TraefikIngressBackend — renders typed IngressRoute CRD YAML
197// =================================================================
198
199/// Renders the [`IngressRoute`] catalog as Traefik `IngressRoute`
200/// CRD YAML documents + writes them to a configured directory
201/// (Traefik's file-provider watches the directory + hot-reloads).
202///
203/// No shell-out — Traefik consumes the YAML directly via its
204/// file provider. The renderer is pure; the I/O boundary is
205/// `std::fs::write` through engenho-substrate's `atomic_write`.
206#[derive(Clone)]
207pub struct TraefikIngressBackend {
208    /// Directory Traefik watches (e.g. `/etc/traefik/dynamic/`).
209    output_dir: std::path::PathBuf,
210    inner: Arc<Mutex<TraefikState>>,
211}
212
213#[derive(Default)]
214struct TraefikState {
215    routes: BTreeMap<(String, String, String), IngressRoute>,
216}
217
218impl TraefikIngressBackend {
219    /// New backend writing dynamic config to `output_dir`.
220    #[must_use]
221    pub fn new(output_dir: impl Into<std::path::PathBuf>) -> Self {
222        Self {
223            output_dir: output_dir.into(),
224            inner: Arc::new(Mutex::new(TraefikState::default())),
225        }
226    }
227
228    /// Render the Traefik `IngressRoute` CRD YAML for one route.
229    /// Pure — no I/O. Test helper.
230    ///
231    /// The Traefik match expression is domain logic (path-type →
232    /// `Path`/`PathPrefix`); the YAML document itself is built as a
233    /// typed [`engenho_types::egress::TraefikIngressRoute`] + rendered
234    /// through `serde_norway` (★★ TYPED EMISSION — no `format!()` of
235    /// YAML syntax).
236    #[must_use]
237    pub fn render_crd(route: &IngressRoute) -> String {
238        use engenho_types::egress::TraefikIngressRoute;
239        let match_rule = match route.path_type {
240            PathType::Exact => format!("Host(`{}`) && Path(`{}`)", route.host, route.path),
241            PathType::Prefix | PathType::ImplementationSpecific => {
242                format!("Host(`{}`) && PathPrefix(`{}`)", route.host, route.path)
243            }
244        };
245        TraefikIngressRoute::new(
246            sanitize_name(&route.ingress_id, &route.host, &route.path),
247            match_rule,
248            route.backend_service.clone(),
249            route.backend_port,
250            route.tls_secret.clone(),
251        )
252        .to_yaml()
253    }
254
255    fn route_filename(route: &IngressRoute) -> String {
256        format!(
257            "{}.yaml",
258            sanitize_name(&route.ingress_id, &route.host, &route.path)
259        )
260    }
261}
262
263fn sanitize_name(ingress_id: &str, host: &str, path: &str) -> String {
264    let raw = format!("{ingress_id}-{host}{path}");
265    raw.chars()
266        .map(|c| match c {
267            'a'..='z' | 'A'..='Z' | '0'..='9' | '-' => c,
268            _ => '-',
269        })
270        .collect::<String>()
271        .trim_matches('-')
272        .to_string()
273        .to_lowercase()
274}
275
276#[async_trait]
277impl IngressBackend for TraefikIngressBackend {
278    fn name(&self) -> &'static str {
279        "traefik"
280    }
281
282    async fn upsert(&self, route: &IngressRoute) -> Result<(), IngressError> {
283        if route.host.is_empty() {
284            return Err(IngressError::InvalidRoute("empty host".into()));
285        }
286        let yaml = Self::render_crd(route);
287        let file = self.output_dir.join(Self::route_filename(route));
288        std::fs::create_dir_all(&self.output_dir).map_err(|e| {
289            IngressError::Backend(format!("mkdir {}: {e}", self.output_dir.display()))
290        })?;
291        std::fs::write(&file, yaml)
292            .map_err(|e| IngressError::Backend(format!("write {}: {e}", file.display())))?;
293        let key = (
294            route.ingress_id.clone(),
295            route.host.clone(),
296            route.path.clone(),
297        );
298        self.inner.lock().await.routes.insert(key, route.clone());
299        Ok(())
300    }
301
302    async fn remove(&self, ingress_id: &str, host: &str, path: &str) -> Result<(), IngressError> {
303        let key = (ingress_id.to_string(), host.to_string(), path.to_string());
304        // Build the route shell so the filename matches what upsert wrote.
305        let proxy = IngressRoute {
306            ingress_id: key.0.clone(),
307            host: key.1.clone(),
308            path: key.2.clone(),
309            path_type: PathType::Prefix,
310            backend_service: String::new(),
311            backend_port: 0,
312            tls_secret: None,
313        };
314        let file = self.output_dir.join(Self::route_filename(&proxy));
315        let _ = std::fs::remove_file(&file); // tolerate already-gone
316        self.inner.lock().await.routes.remove(&key);
317        Ok(())
318    }
319
320    async fn list(&self) -> Result<Vec<IngressRoute>, IngressError> {
321        Ok(self.inner.lock().await.routes.values().cloned().collect())
322    }
323}
324
325// =================================================================
326// NginxIngressBackend — R14b — renders nginx server-block snippets
327// =================================================================
328
329/// Renders [`IngressRoute`] as nginx server-block snippets +
330/// writes them to a `conf.d/` directory nginx includes. Nginx
331/// reloads via `nginx -s reload` (out-of-band — operator
332/// configures inotify or systemd path-watch to trigger).
333///
334/// No shell-out — pure Rust + `std::fs`.
335#[derive(Clone)]
336pub struct NginxIngressBackend {
337    output_dir: std::path::PathBuf,
338    inner: Arc<Mutex<NginxIngressState>>,
339}
340
341#[derive(Default)]
342struct NginxIngressState {
343    routes: BTreeMap<(String, String, String), IngressRoute>,
344}
345
346impl NginxIngressBackend {
347    /// New backend writing server-blocks to `output_dir`.
348    #[must_use]
349    pub fn new(output_dir: impl Into<std::path::PathBuf>) -> Self {
350        Self {
351            output_dir: output_dir.into(),
352            inner: Arc::new(Mutex::new(NginxIngressState::default())),
353        }
354    }
355
356    /// Render the nginx server-block snippet for one route. Pure.
357    ///
358    /// Builds a typed [`engenho_types::egress::NginxServerBlock`] +
359    /// renders it through the block's `Display` chokepoint (★★ TYPED
360    /// EMISSION — no `format!()` of nginx syntax: the matcher and the
361    /// upstream are typed values). The `listen` / `location` matcher
362    /// choices are domain logic.
363    #[must_use]
364    pub fn render_server_block(route: &IngressRoute) -> String {
365        use engenho_types::egress::{NginxLocation, NginxServerBlock, NginxUpstream};
366        let listen = if route.tls_secret.is_some() {
367            "443 ssl"
368        } else {
369            "80"
370        };
371        let location = match route.path_type {
372            PathType::Exact => NginxLocation::Exact(route.path.clone()),
373            PathType::Prefix | PathType::ImplementationSpecific => {
374                NginxLocation::Prefix(route.path.clone())
375            }
376        };
377        NginxServerBlock {
378            listen: listen.to_string(),
379            server_name: route.host.clone(),
380            tls_secret: route.tls_secret.clone(),
381            location,
382            proxy_pass: NginxUpstream {
383                host: route.backend_service.clone(),
384                port: route.backend_port,
385            },
386        }
387        .to_string()
388    }
389
390    fn route_filename(route: &IngressRoute) -> String {
391        format!(
392            "{}.conf",
393            sanitize_name(&route.ingress_id, &route.host, &route.path)
394        )
395    }
396}
397
398#[async_trait]
399impl IngressBackend for NginxIngressBackend {
400    fn name(&self) -> &'static str {
401        "nginx"
402    }
403
404    async fn upsert(&self, route: &IngressRoute) -> Result<(), IngressError> {
405        if route.host.is_empty() {
406            return Err(IngressError::InvalidRoute("empty host".into()));
407        }
408        let snippet = Self::render_server_block(route);
409        let file = self.output_dir.join(Self::route_filename(route));
410        std::fs::create_dir_all(&self.output_dir).map_err(|e| {
411            IngressError::Backend(format!("mkdir {}: {e}", self.output_dir.display()))
412        })?;
413        std::fs::write(&file, snippet)
414            .map_err(|e| IngressError::Backend(format!("write {}: {e}", file.display())))?;
415        let key = (
416            route.ingress_id.clone(),
417            route.host.clone(),
418            route.path.clone(),
419        );
420        self.inner.lock().await.routes.insert(key, route.clone());
421        Ok(())
422    }
423
424    async fn remove(&self, ingress_id: &str, host: &str, path: &str) -> Result<(), IngressError> {
425        let key = (ingress_id.to_string(), host.to_string(), path.to_string());
426        let proxy = IngressRoute {
427            ingress_id: key.0.clone(),
428            host: key.1.clone(),
429            path: key.2.clone(),
430            path_type: PathType::Prefix,
431            backend_service: String::new(),
432            backend_port: 0,
433            tls_secret: None,
434        };
435        let file = self.output_dir.join(Self::route_filename(&proxy));
436        let _ = std::fs::remove_file(&file);
437        self.inner.lock().await.routes.remove(&key);
438        Ok(())
439    }
440
441    async fn list(&self) -> Result<Vec<IngressRoute>, IngressError> {
442        Ok(self.inner.lock().await.routes.values().cloned().collect())
443    }
444}
445
446// =================================================================
447// IngressController — reads store, drives the backend
448// =================================================================
449
450/// Controller that materializes ingress routes from K8s Ingress
451/// objects in the store.
452pub struct IngressController {
453    store: Arc<StoreMesh>,
454    backend: Arc<dyn IngressBackend>,
455    namespace: Option<String>,
456}
457
458impl IngressController {
459    /// Construct an ingress controller.
460    #[must_use]
461    pub fn new(
462        store: Arc<StoreMesh>,
463        backend: Arc<dyn IngressBackend>,
464        namespace: Option<String>,
465    ) -> Self {
466        Self {
467            store,
468            backend,
469            namespace,
470        }
471    }
472
473    /// Extract the typed routes from a K8s Ingress manifest.
474    /// Pure — no I/O. Public so callers can introspect.
475    #[must_use]
476    pub fn extract_routes(ingress_id: &str, ingress: &serde_json::Value) -> Vec<IngressRoute> {
477        let spec = match ingress.get("spec") {
478            Some(s) => s,
479            None => return Vec::new(),
480        };
481        // TLS secrets keyed by host.
482        let tls_secrets: BTreeMap<String, String> = spec
483            .get("tls")
484            .and_then(|t| t.as_array())
485            .map(|arr| {
486                arr.iter()
487                    .flat_map(|t| {
488                        let secret = t
489                            .get("secretName")
490                            .and_then(|s| s.as_str())
491                            .unwrap_or("")
492                            .to_string();
493                        t.get("hosts")
494                            .and_then(|h| h.as_array())
495                            .into_iter()
496                            .flatten()
497                            .filter_map(|h| {
498                                h.as_str().map(|host| (host.to_string(), secret.clone()))
499                            })
500                            .collect::<Vec<_>>()
501                    })
502                    .collect()
503            })
504            .unwrap_or_default();
505
506        let rules = match spec.get("rules").and_then(|r| r.as_array()) {
507            Some(r) => r,
508            None => return Vec::new(),
509        };
510        let mut routes = Vec::new();
511        for rule in rules {
512            let host = rule
513                .get("host")
514                .and_then(|h| h.as_str())
515                .unwrap_or("")
516                .to_string();
517            let paths = match rule
518                .get("http")
519                .and_then(|h| h.get("paths"))
520                .and_then(|p| p.as_array())
521            {
522                Some(p) => p,
523                None => continue,
524            };
525            for path in paths {
526                let path_str = path
527                    .get("path")
528                    .and_then(|p| p.as_str())
529                    .unwrap_or("/")
530                    .to_string();
531                let path_type = match path.get("pathType").and_then(|p| p.as_str()) {
532                    Some("Exact") => PathType::Exact,
533                    Some("ImplementationSpecific") => PathType::ImplementationSpecific,
534                    _ => PathType::Prefix,
535                };
536                let backend = path
537                    .get("backend")
538                    .and_then(|b| b.get("service"))
539                    .cloned()
540                    .unwrap_or(serde_json::Value::Null);
541                let service_name = backend
542                    .get("name")
543                    .and_then(|n| n.as_str())
544                    .unwrap_or("")
545                    .to_string();
546                let service_port = backend
547                    .get("port")
548                    .and_then(|p| p.get("number"))
549                    .and_then(serde_json::Value::as_u64)
550                    .unwrap_or(80) as u16;
551                let tls = tls_secrets.get(&host).cloned();
552                routes.push(IngressRoute {
553                    ingress_id: ingress_id.to_string(),
554                    host: host.clone(),
555                    path: path_str,
556                    path_type,
557                    backend_service: service_name,
558                    backend_port: service_port,
559                    tls_secret: tls,
560                });
561            }
562        }
563        routes
564    }
565}
566
567#[async_trait]
568impl Controller for IngressController {
569    fn name(&self) -> &'static str {
570        "ingress"
571    }
572
573    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
574        let ingresses = self
575            .store
576            .list(
577                "networking.k8s.io",
578                "v1",
579                "Ingress",
580                self.namespace.as_deref(),
581            )
582            .await;
583        let mut report = ReconcileReport::default();
584        report.objects_examined = ingresses.len();
585
586        let mut desired: BTreeMap<(String, String, String), IngressRoute> = BTreeMap::new();
587        for (key, value) in &ingresses {
588            let id = format!(
589                "{}/{}",
590                key.namespace.as_deref().unwrap_or("default"),
591                key.name
592            );
593            for route in Self::extract_routes(&id, value) {
594                desired.insert(
595                    (
596                        route.ingress_id.clone(),
597                        route.host.clone(),
598                        route.path.clone(),
599                    ),
600                    route,
601                );
602            }
603        }
604
605        let installed = self
606            .backend
607            .list()
608            .await
609            .map_err(|e| ControllerError::Internal(e.to_string()))?;
610        let installed_keys: BTreeMap<(String, String, String), IngressRoute> = installed
611            .into_iter()
612            .map(|r| ((r.ingress_id.clone(), r.host.clone(), r.path.clone()), r))
613            .collect();
614
615        for (key, route) in &desired {
616            if installed_keys.get(key) != Some(route) {
617                let applied = Effect::applied(self.backend.upsert(route).await)
618                    .map_err(|e| ControllerError::Internal(e.to_string()))?;
619                report.record(applied);
620            }
621        }
622        for key in installed_keys.keys() {
623            if !desired.contains_key(key) {
624                let applied = Effect::applied(self.backend.remove(&key.0, &key.1, &key.2).await)
625                    .map_err(|e| ControllerError::Internal(e.to_string()))?;
626                report.record(applied);
627            }
628        }
629        Ok(report.into())
630    }
631}
632
633#[cfg(test)]
634mod tests {
635    use super::*;
636    use serde_json::json;
637
638    fn sample_route() -> IngressRoute {
639        IngressRoute {
640            ingress_id: "default/web".into(),
641            host: "podinfo.example.com".into(),
642            path: "/".into(),
643            path_type: PathType::Prefix,
644            backend_service: "podinfo".into(),
645            backend_port: 80,
646            tls_secret: None,
647        }
648    }
649
650    // ── FakeIngressBackend ─────────────────────────────────────
651
652    #[tokio::test]
653    async fn fake_upsert_inserts_route() {
654        let b = FakeIngressBackend::new();
655        b.upsert(&sample_route()).await.unwrap();
656        assert_eq!(b.route_count().await, 1);
657    }
658
659    #[tokio::test]
660    async fn fake_rejects_empty_host() {
661        let b = FakeIngressBackend::new();
662        let mut r = sample_route();
663        r.host = String::new();
664        let err = b.upsert(&r).await.unwrap_err();
665        assert_eq!(err.kind(), "invalid_route");
666    }
667
668    #[tokio::test]
669    async fn fake_rejects_empty_backend_service() {
670        let b = FakeIngressBackend::new();
671        let mut r = sample_route();
672        r.backend_service = String::new();
673        let err = b.upsert(&r).await.unwrap_err();
674        assert_eq!(err.kind(), "invalid_route");
675    }
676
677    #[tokio::test]
678    async fn fake_remove_by_triple_clears() {
679        let b = FakeIngressBackend::new();
680        let r = sample_route();
681        b.upsert(&r).await.unwrap();
682        b.remove(&r.ingress_id, &r.host, &r.path).await.unwrap();
683        assert_eq!(b.route_count().await, 0);
684    }
685
686    #[tokio::test]
687    async fn fake_events_record_in_order() {
688        let b = FakeIngressBackend::new();
689        let r = sample_route();
690        b.upsert(&r).await.unwrap();
691        b.remove(&r.ingress_id, &r.host, &r.path).await.unwrap();
692        let evs = b.events().await;
693        assert_eq!(evs.len(), 2);
694        assert!(matches!(&evs[0], FakeIngressEvent::Upsert(_, _, _)));
695        assert!(matches!(&evs[1], FakeIngressEvent::Remove(_, _, _)));
696    }
697
698    #[tokio::test]
699    async fn fake_list_returns_routes() {
700        let b = FakeIngressBackend::new();
701        b.upsert(&sample_route()).await.unwrap();
702        assert_eq!(b.list().await.unwrap().len(), 1);
703    }
704
705    // ── TraefikIngressBackend ─────────────────────────────────
706
707    // ── NginxIngressBackend (R14b) ─────────────────────────────
708
709    #[test]
710    fn nginx_render_server_block_contains_listen_and_proxy_pass() {
711        let snippet = NginxIngressBackend::render_server_block(&sample_route());
712        assert!(snippet.contains("server {"));
713        assert!(snippet.contains("listen 80;"));
714        assert!(snippet.contains("server_name podinfo.example.com;"));
715        assert!(snippet.contains("location / {"));
716        assert!(snippet.contains("proxy_pass http://podinfo:80;"));
717        assert!(snippet.contains("proxy_set_header Host $host;"));
718    }
719
720    #[test]
721    fn nginx_render_with_tls_uses_listen_443_and_ssl_block() {
722        let mut r = sample_route();
723        r.tls_secret = Some("podinfo-tls".into());
724        let snippet = NginxIngressBackend::render_server_block(&r);
725        assert!(snippet.contains("listen 443 ssl;"));
726        assert!(snippet.contains("ssl_certificate     /etc/nginx/tls/podinfo-tls.crt;"));
727        assert!(snippet.contains("ssl_certificate_key /etc/nginx/tls/podinfo-tls.key;"));
728    }
729
730    #[test]
731    fn nginx_render_exact_path_uses_location_equals() {
732        let mut r = sample_route();
733        r.path = "/api".into();
734        r.path_type = PathType::Exact;
735        let snippet = NginxIngressBackend::render_server_block(&r);
736        assert!(snippet.contains("location = /api {"));
737    }
738
739    #[tokio::test]
740    async fn nginx_upsert_writes_conf_file() {
741        let dir = std::env::temp_dir().join(format!("engenho-nginx-test-{}", std::process::id()));
742        let _ = std::fs::remove_dir_all(&dir);
743        let b = NginxIngressBackend::new(&dir);
744        b.upsert(&sample_route()).await.unwrap();
745        let files: Vec<_> = std::fs::read_dir(&dir)
746            .unwrap()
747            .filter_map(|e| e.ok().map(|e| e.path()))
748            .collect();
749        assert_eq!(files.len(), 1);
750        assert_eq!(files[0].extension().unwrap(), "conf");
751        let content = std::fs::read_to_string(&files[0]).unwrap();
752        assert!(content.contains("server {"));
753        let _ = std::fs::remove_dir_all(&dir);
754    }
755
756    #[test]
757    fn nginx_backend_name_is_stable() {
758        let b = NginxIngressBackend::new("/tmp");
759        assert_eq!(b.name(), "nginx");
760    }
761
762    #[test]
763    fn traefik_render_crd_contains_match_rule() {
764        let yaml = TraefikIngressBackend::render_crd(&sample_route());
765        assert!(yaml.contains("apiVersion: traefik.io/v1alpha1"));
766        assert!(yaml.contains("kind: IngressRoute"));
767        assert!(yaml.contains("Host(`podinfo.example.com`)"));
768        assert!(yaml.contains("PathPrefix(`/`)"));
769        assert!(yaml.contains("name: podinfo"));
770        assert!(yaml.contains("port: 80"));
771        // No TLS → web entry point.
772        assert!(yaml.contains("- web"));
773    }
774
775    #[test]
776    fn traefik_render_crd_uses_path_exact_match() {
777        let mut r = sample_route();
778        r.path = "/api/v1".into();
779        r.path_type = PathType::Exact;
780        let yaml = TraefikIngressBackend::render_crd(&r);
781        assert!(yaml.contains("Path(`/api/v1`)"));
782        assert!(!yaml.contains("PathPrefix"));
783    }
784
785    #[test]
786    fn traefik_render_crd_with_tls_uses_websecure() {
787        let mut r = sample_route();
788        r.tls_secret = Some("podinfo-tls".into());
789        let yaml = TraefikIngressBackend::render_crd(&r);
790        assert!(yaml.contains("- websecure"));
791        assert!(yaml.contains("secretName: podinfo-tls"));
792    }
793
794    #[tokio::test]
795    async fn traefik_upsert_writes_file() {
796        let dir = std::env::temp_dir().join(format!("engenho-ingress-test-{}", std::process::id()));
797        let _ = std::fs::remove_dir_all(&dir);
798        let b = TraefikIngressBackend::new(&dir);
799        b.upsert(&sample_route()).await.unwrap();
800        let files: Vec<_> = std::fs::read_dir(&dir)
801            .unwrap()
802            .filter_map(|e| e.ok().map(|e| e.path()))
803            .collect();
804        assert_eq!(files.len(), 1);
805        let content = std::fs::read_to_string(&files[0]).unwrap();
806        assert!(content.contains("kind: IngressRoute"));
807        let _ = std::fs::remove_dir_all(&dir);
808    }
809
810    #[tokio::test]
811    async fn traefik_remove_deletes_file() {
812        let dir = std::env::temp_dir().join(format!("engenho-ingress-rm-{}", std::process::id()));
813        let _ = std::fs::remove_dir_all(&dir);
814        let b = TraefikIngressBackend::new(&dir);
815        let r = sample_route();
816        b.upsert(&r).await.unwrap();
817        b.remove(&r.ingress_id, &r.host, &r.path).await.unwrap();
818        let count = std::fs::read_dir(&dir).map_or(0, std::iter::Iterator::count);
819        assert_eq!(count, 0);
820        let _ = std::fs::remove_dir_all(&dir);
821    }
822
823    #[test]
824    fn sanitize_name_produces_safe_filename() {
825        let n = sanitize_name("default/web", "podinfo.example.com", "/api/v1");
826        assert!(!n.contains('/'));
827        assert!(!n.contains('.'));
828        assert!(!n.starts_with('-'));
829        assert!(!n.ends_with('-'));
830        // Lowercase chars + dashes only.
831        assert!(
832            n.chars()
833                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
834        );
835    }
836
837    #[test]
838    fn traefik_backend_name_is_stable() {
839        let b = TraefikIngressBackend::new("/tmp");
840        assert_eq!(b.name(), "traefik");
841    }
842
843    // ── IngressController extract_routes ──────────────────────
844
845    #[test]
846    fn extract_routes_parses_standard_ingress() {
847        let ingress = json!({
848            "spec": {
849                "rules": [{
850                    "host": "x.example.com",
851                    "http": {
852                        "paths": [{
853                            "path": "/",
854                            "pathType": "Prefix",
855                            "backend": {
856                                "service": {
857                                    "name": "x",
858                                    "port": {"number": 80}
859                                }
860                            }
861                        }]
862                    }
863                }]
864            }
865        });
866        let routes = IngressController::extract_routes("default/x", &ingress);
867        assert_eq!(routes.len(), 1);
868        assert_eq!(routes[0].host, "x.example.com");
869        assert_eq!(routes[0].backend_service, "x");
870        assert_eq!(routes[0].backend_port, 80);
871        assert!(routes[0].tls_secret.is_none());
872    }
873
874    #[test]
875    fn extract_routes_picks_up_tls_secret_per_host() {
876        let ingress = json!({
877            "spec": {
878                "tls": [{
879                    "hosts": ["x.example.com"],
880                    "secretName": "x-tls"
881                }],
882                "rules": [{
883                    "host": "x.example.com",
884                    "http": {
885                        "paths": [{
886                            "path": "/",
887                            "backend": {"service": {"name": "x", "port": {"number": 443}}}
888                        }]
889                    }
890                }]
891            }
892        });
893        let routes = IngressController::extract_routes("default/x", &ingress);
894        assert_eq!(routes[0].tls_secret.as_deref(), Some("x-tls"));
895    }
896
897    #[test]
898    fn extract_routes_handles_multiple_paths_per_host() {
899        let ingress = json!({
900            "spec": {
901                "rules": [{
902                    "host": "api.example.com",
903                    "http": {
904                        "paths": [
905                            {"path": "/v1", "backend": {"service": {"name": "api-v1", "port": {"number": 8080}}}},
906                            {"path": "/v2", "backend": {"service": {"name": "api-v2", "port": {"number": 8080}}}}
907                        ]
908                    }
909                }]
910            }
911        });
912        let routes = IngressController::extract_routes("default/api", &ingress);
913        assert_eq!(routes.len(), 2);
914        assert_eq!(routes[0].path, "/v1");
915        assert_eq!(routes[1].path, "/v2");
916    }
917
918    #[test]
919    fn extract_routes_defaults_to_prefix_path_type() {
920        let ingress = json!({
921            "spec": {
922                "rules": [{
923                    "host": "x",
924                    "http": {
925                        "paths": [{
926                            "path": "/",
927                            "backend": {"service": {"name": "x", "port": {"number": 80}}}
928                        }]
929                    }
930                }]
931            }
932        });
933        let routes = IngressController::extract_routes("d/x", &ingress);
934        assert_eq!(routes[0].path_type, PathType::Prefix);
935    }
936
937    #[test]
938    fn extract_routes_handles_exact_path_type() {
939        let ingress = json!({
940            "spec": {
941                "rules": [{
942                    "host": "x",
943                    "http": {
944                        "paths": [{
945                            "path": "/api",
946                            "pathType": "Exact",
947                            "backend": {"service": {"name": "x", "port": {"number": 80}}}
948                        }]
949                    }
950                }]
951            }
952        });
953        let routes = IngressController::extract_routes("d/x", &ingress);
954        assert_eq!(routes[0].path_type, PathType::Exact);
955    }
956
957    #[test]
958    fn extract_routes_empty_for_missing_spec() {
959        let ingress = json!({"metadata": {"name": "x"}});
960        let routes = IngressController::extract_routes("d/x", &ingress);
961        assert!(routes.is_empty());
962    }
963
964    #[test]
965    fn path_type_default_is_prefix() {
966        assert_eq!(PathType::default(), PathType::Prefix);
967    }
968
969    #[test]
970    fn path_type_serializes_pascal_case() {
971        let json = serde_json::to_string(&PathType::ImplementationSpecific).unwrap();
972        assert_eq!(json, "\"ImplementationSpecific\"");
973    }
974
975    #[test]
976    fn error_kinds_are_stable() {
977        assert_eq!(IngressError::Backend("x".into()).kind(), "backend");
978        assert_eq!(
979            IngressError::InvalidRoute("x".into()).kind(),
980            "invalid_route"
981        );
982    }
983
984    #[test]
985    fn controller_name_is_stable() {
986        struct Fake;
987        #[async_trait]
988        impl Controller for Fake {
989            fn name(&self) -> &'static str {
990                "ingress"
991            }
992            async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
993                Ok(ReconcileReport::default().into())
994            }
995        }
996        assert_eq!(Fake.name(), "ingress");
997    }
998}