Skip to main content

rust_web_server/ingress/
mod.rs

1//! Kubernetes Ingress watcher and router.
2//!
3//! [`KubernetesIngressWatcher`] watches the Kubernetes API for Ingress
4//! resources and maintains a live route table. [`IngressRouter`] implements
5//! [`Application`] and routes incoming HTTP requests to the appropriate
6//! upstream service using the live rule table.
7//!
8//! # Prerequisites
9//!
10//! The watcher communicates with the Kubernetes API over plain HTTP/1.1 by
11//! default. For in-cluster use, expose the API via `kubectl proxy` and point
12//! the watcher at `http://localhost:8001`:
13//!
14//! ```text
15//! kubectl proxy &
16//! export RWS_K8S_API_SERVER=http://localhost:8001
17//! export RWS_K8S_TOKEN=
18//! export RWS_K8S_NAMESPACE=default
19//! ```
20//!
21//! Or, with the `http-client` or `http2` feature enabled, connect directly
22//! to the in-cluster API server over TLS — see
23//! [`KubernetesIngressWatcher::from_service_account`].
24//!
25//! # Example
26//!
27//! ```rust,no_run
28//! use rust_web_server::ingress::{IngressRouter, KubernetesIngressWatcher};
29//! use rust_web_server::server::Server;
30//!
31//! let watcher = KubernetesIngressWatcher::from_env().expect("K8s env not set");
32//! watcher.start();
33//!
34//! let app = IngressRouter::new(watcher);
35//! // Server::run(app);  // pass to your server
36//! ```
37
38#[cfg(test)]
39mod tests;
40
41#[cfg(any(feature = "http-client", feature = "http2"))]
42mod tls;
43mod watch;
44
45use std::io::{Read, Write};
46use std::net::TcpStream;
47use std::sync::{Arc, RwLock};
48use std::time::Duration;
49
50use crate::application::Application;
51use crate::core::New;
52use crate::mime_type::MimeType;
53use crate::range::Range;
54use crate::request::Request;
55use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
56use crate::server::ConnectionInfo;
57
58/// How long a watch connection is allowed to sit idle before we treat it
59/// as stalled and reconnect. Generous — legitimate watch connections can
60/// be quiet for long stretches on an unchanging cluster.
61const WATCH_READ_TIMEOUT: Duration = Duration::from_secs(300);
62/// Backoff between watch reconnect attempts (including the very first
63/// connection failing, e.g. because the API server doesn't support watch).
64const WATCH_RECONNECT_BACKOFF: Duration = Duration::from_secs(2);
65
66// ── PathType ──────────────────────────────────────────────────────────────────
67
68/// Mirrors Kubernetes' `Ingress.spec.rules[].http.paths[].pathType`.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum PathType {
71    /// Element-wise path-segment prefix match (the Kubernetes default and
72    /// this crate's fallback when `pathType` is absent from older/lenient
73    /// API responses).
74    Prefix,
75    /// The request path must equal the rule's path exactly (ignoring any
76    /// query string).
77    Exact,
78    /// Matching is left to the Ingress controller. This router treats it
79    /// the same as `Prefix`, same as most controllers do in practice.
80    ImplementationSpecific,
81}
82
83impl PathType {
84    fn parse(s: &str) -> Self {
85        match s {
86            "Exact" => PathType::Exact,
87            "ImplementationSpecific" => PathType::ImplementationSpecific,
88            _ => PathType::Prefix,
89        }
90    }
91}
92
93// ── IngressRule ───────────────────────────────────────────────────────────────
94
95/// A single routing rule parsed from a Kubernetes Ingress resource.
96#[derive(Debug, Clone, PartialEq)]
97pub struct IngressRule {
98    /// Value of `spec.rules[].host`.  Empty string means match-all.
99    pub host: String,
100    /// Value of `spec.rules[].http.paths[].path`.
101    pub path: String,
102    /// Value of `spec.rules[].http.paths[].pathType`. Defaults to
103    /// [`PathType::Prefix`] if the field is absent.
104    pub path_type: PathType,
105    /// Kubernetes service name (`spec.rules[].http.paths[].backend.service.name`).
106    pub service_name: String,
107    /// Kubernetes service port number.
108    pub service_port: u16,
109    /// Namespace the Ingress lives in.
110    pub namespace: String,
111}
112
113impl IngressRule {
114    /// Build the upstream Kubernetes DNS address.
115    ///
116    /// Returns `"{service_name}.{namespace}.svc.cluster.local:{service_port}"`.
117    pub fn upstream_addr(&self) -> String {
118        format!(
119            "{}.{}.svc.cluster.local:{}",
120            self.service_name, self.namespace, self.service_port
121        )
122    }
123
124    /// Returns `true` if this rule matches the given `host` header value and
125    /// request `uri`.
126    ///
127    /// * If `self.host` is non-empty, the incoming `host` must match
128    ///   (case-insensitive).
129    /// * Any query string on `uri` is ignored for path matching.
130    /// * [`PathType::Exact`] requires the request path to equal `self.path`
131    ///   exactly.
132    /// * [`PathType::Prefix`] (and [`PathType::ImplementationSpecific`])
133    ///   match on whole path segments — `/foo` matches `/foo`, `/foo/`, and
134    ///   `/foo/bar`, but **not** `/foobar` — not a raw byte prefix.
135    pub fn matches(&self, host: &str, uri: &str) -> bool {
136        if !self.host.is_empty() && !self.host.eq_ignore_ascii_case(host) {
137            return false;
138        }
139        let request_path = uri.split('?').next().unwrap_or(uri);
140        match self.path_type {
141            PathType::Exact => request_path == self.path,
142            PathType::Prefix | PathType::ImplementationSpecific => {
143                path_prefix_matches(&self.path, request_path)
144            }
145        }
146    }
147}
148
149/// Element-wise prefix match per Kubernetes' `pathType: Prefix` semantics.
150fn path_prefix_matches(prefix: &str, request_path: &str) -> bool {
151    if prefix == "/" {
152        return true;
153    }
154    let trimmed = prefix.trim_end_matches('/');
155    request_path == trimmed || request_path.starts_with(&format!("{trimmed}/"))
156}
157
158// ── JSON helpers ──────────────────────────────────────────────────────────────
159
160/// Find the first occurrence of `"field": "VALUE"` in `json` and return `VALUE`.
161fn extract_str_field<'a>(json: &'a str, field: &str) -> Option<&'a str> {
162    let needle = format!("\"{}\":", field);
163    let start = json.find(needle.as_str())?;
164    let after_colon = &json[start + needle.len()..];
165    let after_colon = after_colon.trim_start_matches(' ');
166    if !after_colon.starts_with('"') {
167        return None;
168    }
169    let inner = &after_colon[1..];
170    let end = inner.find('"')?;
171    Some(&inner[..end])
172}
173
174/// Find the *last* occurrence of `"field": "VALUE"` in `json` and return
175/// `VALUE` — used to find the `namespace` field belonging to *this*
176/// Ingress item by searching backward from its `spec`, since `metadata`
177/// (and the `namespace` field within it) always precedes `spec` in a real
178/// Kubernetes object's JSON encoding.
179fn extract_last_str_field<'a>(json: &'a str, field: &str) -> Option<&'a str> {
180    let needle = format!("\"{}\":", field);
181    let start = json.rfind(needle.as_str())?;
182    let after_colon = &json[start + needle.len()..];
183    let after_colon = after_colon.trim_start_matches(' ');
184    if !after_colon.starts_with('"') {
185        return None;
186    }
187    let inner = &after_colon[1..];
188    let end = inner.find('"')?;
189    Some(&inner[..end])
190}
191
192/// Find the first occurrence of `"field": NUMBER` in `json` and parse as `u16`.
193fn extract_u16_field(json: &str, field: &str) -> Option<u16> {
194    let needle = format!("\"{}\":", field);
195    let start = json.find(needle.as_str())?;
196    let after_colon = &json[start + needle.len()..];
197    let after_colon = after_colon.trim_start_matches(' ');
198    let end = after_colon.find(|c: char| !c.is_ascii_digit())?;
199    after_colon[..end].parse().ok()
200}
201
202// ── parse_ingress_list ────────────────────────────────────────────────────────
203
204/// Parse a Kubernetes Ingress list JSON body into a `Vec<IngressRule>`.
205///
206/// This is a minimal, hand-rolled parser that handles the common formatting
207/// returned by the Kubernetes API server.  It does not depend on any external
208/// JSON library.
209///
210/// `ingress_class`, if `Some`, restricts the result to Ingress objects whose
211/// `spec.ingressClassName` equals it exactly — an Ingress with no
212/// `ingressClassName` at all never matches a `Some` filter. Pass `None` to
213/// accept every Ingress regardless of class (the historical, and still
214/// default, behavior — see [`KubernetesIngressWatcher::ingress_class`]).
215pub fn parse_ingress_list(json: &str, ingress_class: Option<&str>) -> Vec<IngressRule> {
216    let mut rules = Vec::new();
217
218    // Every `"spec"` occurrence starts one Ingress item's spec object. The
219    // section between this occurrence and the next one (or end of string)
220    // is exactly what the old split()-based version of this parser treated
221    // as "the current item" — kept as-is here, just computed via explicit
222    // byte offsets instead of `str::split` so we can also look *backward*
223    // from each occurrence (see `extract_last_str_field` below).
224    let spec_positions: Vec<usize> = json.match_indices("\"spec\"").map(|(i, _)| i).collect();
225    for (idx, &pos) in spec_positions.iter().enumerate() {
226        let section_start = pos + "\"spec\"".len();
227        let section_end = spec_positions.get(idx + 1).copied().unwrap_or(json.len());
228        let section = &json[section_start..section_end];
229
230        // `namespace` lives in `metadata`, which precedes `spec` for every
231        // real Kubernetes object — search backward from this `spec`
232        // occurrence, not forward into `section`. (A prior version of this
233        // parser searched `section` itself, which never actually contains
234        // `namespace` for a real API response — metadata always comes
235        // first — so it silently always fell back to `"default"` unless
236        // the real namespace happened to also be "default".)
237        let namespace = extract_last_str_field(&json[..pos], "namespace")
238            .unwrap_or("default")
239            .to_string();
240
241        if let Some(wanted) = ingress_class {
242            if extract_str_field(section, "ingressClassName") != Some(wanted) {
243                continue;
244            }
245        }
246
247        // Within this spec section, look for rules.
248        let rules_sections: Vec<&str> = section.split("\"rules\"").collect();
249        for rules_section in rules_sections.iter().skip(1) {
250            // Extract host (may be absent).
251            let host = extract_str_field(rules_section, "host").unwrap_or("").to_string();
252
253            // Within the rules section, split on "paths".
254            let paths_sections: Vec<&str> = rules_section.split("\"paths\"").collect();
255            for paths_section in paths_sections.iter().skip(1) {
256                // Within each paths entry, split on path objects.
257                // Each path entry looks like: {"path":"/foo","backend":...}
258                // We split on `"path"` and take alternating sections.
259                let path_entries: Vec<&str> = paths_section.split("\"path\"").collect();
260                for path_entry in path_entries.iter().skip(1) {
261                    let path = extract_str_field(path_entry, "path")
262                        .or_else(|| {
263                            // The split consumed "path" so the value comes right after ":"
264                            let after_colon = path_entry.trim_start_matches(':').trim_start_matches(' ');
265                            if after_colon.starts_with('"') {
266                                let inner = &after_colon[1..];
267                                inner.find('"').map(|end| &inner[..end])
268                            } else {
269                                None
270                            }
271                        })
272                        .unwrap_or("/")
273                        .to_string();
274                    let path_type = extract_str_field(path_entry, "pathType")
275                        .map(PathType::parse)
276                        .unwrap_or(PathType::Prefix);
277
278                    let service_name =
279                        extract_str_field(path_entry, "name").unwrap_or("").to_string();
280                    let service_port =
281                        extract_u16_field(path_entry, "number").unwrap_or(80);
282
283                    if !service_name.is_empty() {
284                        rules.push(IngressRule {
285                            host: host.clone(),
286                            path,
287                            path_type,
288                            service_name,
289                            service_port,
290                            namespace: namespace.clone(),
291                        });
292                    }
293                }
294            }
295        }
296    }
297
298    rules
299}
300
301// ── KubernetesIngressWatcher ──────────────────────────────────────────────────
302
303/// Watches a Kubernetes API server for Ingress resources and maintains a live
304/// routing table.
305pub struct KubernetesIngressWatcher {
306    api_server: String,
307    token: String,
308    namespace: String,
309    ingress_class: Option<String>,
310    poll_interval_secs: u64,
311    rules: Arc<RwLock<Vec<IngressRule>>>,
312    #[cfg(any(feature = "http-client", feature = "http2"))]
313    tls: Option<Arc<tls::InClusterConfig>>,
314}
315
316impl KubernetesIngressWatcher {
317    /// Create a watcher from explicit values.
318    ///
319    /// `api_server` should be a plain-HTTP URL such as `http://localhost:8001`.
320    /// The default namespace is `"default"`.
321    pub fn new(api_server: impl Into<String>, token: impl Into<String>) -> Self {
322        Self {
323            api_server: api_server.into(),
324            token: token.into(),
325            namespace: "default".to_string(),
326            ingress_class: None,
327            poll_interval_secs: 30,
328            rules: Arc::new(RwLock::new(Vec::new())),
329            #[cfg(any(feature = "http-client", feature = "http2"))]
330            tls: None,
331        }
332    }
333
334    /// Configure from the Kubernetes service account files mounted at
335    /// `/var/run/secrets/kubernetes.io/serviceaccount/` and the
336    /// `KUBERNETES_SERVICE_HOST`/`KUBERNETES_SERVICE_PORT` environment
337    /// variables Kubernetes injects into every pod, connecting to the
338    /// in-cluster API server directly over TLS — no `kubectl proxy`
339    /// sidecar needed.
340    ///
341    /// Requires the `http-client` or `http2` feature (both already pull in
342    /// `rustls`); trusts only the cluster's own CA certificate
343    /// (`.../ca.crt`), not the public root store `crate::http_client` uses,
344    /// since the API server's certificate is signed by that private CA.
345    #[cfg(any(feature = "http-client", feature = "http2"))]
346    pub fn from_service_account() -> Result<Self, String> {
347        let cfg = tls::load()?;
348        let namespace = cfg.namespace.clone();
349        let mut watcher = Self::new("", "");
350        watcher.namespace = namespace;
351        watcher.tls = Some(Arc::new(cfg));
352        Ok(watcher)
353    }
354
355    /// Attempt to configure from the Kubernetes service account files at
356    /// `/var/run/secrets/kubernetes.io/serviceaccount/`.
357    ///
358    /// Building without the `http-client` or `http2` feature has no TLS
359    /// implementation available, so this always fails — use `kubectl
360    /// proxy` and configure via environment variables instead:
361    ///
362    /// ```text
363    /// kubectl proxy &
364    /// export RWS_K8S_API_SERVER=http://localhost:8001
365    /// ```
366    #[cfg(not(any(feature = "http-client", feature = "http2")))]
367    pub fn from_service_account() -> Result<Self, String> {
368        Err(
369            "In-cluster TLS (https://kubernetes.default.svc) requires the `http-client` or \
370             `http2` feature. Enable one of those, or use `kubectl proxy` and set \
371             RWS_K8S_API_SERVER=http://localhost:8001 along with RWS_K8S_TOKEN and \
372             RWS_K8S_NAMESPACE, then call KubernetesIngressWatcher::from_env()."
373                .to_string(),
374        )
375    }
376
377    /// Configure from environment variables `RWS_K8S_API_SERVER`, `RWS_K8S_TOKEN`,
378    /// and (optionally) `RWS_K8S_NAMESPACE`.
379    ///
380    /// Returns `Err` if `RWS_K8S_API_SERVER` is not set.
381    pub fn from_env() -> Result<Self, String> {
382        let api_server = std::env::var("RWS_K8S_API_SERVER").map_err(|_| {
383            "RWS_K8S_API_SERVER environment variable is not set".to_string()
384        })?;
385        let token = std::env::var("RWS_K8S_TOKEN").unwrap_or_default();
386        let namespace = std::env::var("RWS_K8S_NAMESPACE").unwrap_or_else(|_| "default".to_string());
387        let mut watcher = Self::new(api_server, token);
388        watcher.namespace = namespace;
389        Ok(watcher)
390    }
391
392    /// Override the namespace filter.  Use `"all"` or empty string for all namespaces.
393    pub fn namespace(mut self, ns: impl Into<String>) -> Self {
394        self.namespace = ns.into();
395        self
396    }
397
398    /// Restrict watched Ingress objects to those whose
399    /// `spec.ingressClassName` equals `class` exactly. Unset (the default)
400    /// accepts every Ingress cluster- or namespace-wide regardless of
401    /// class — fine for a single-controller cluster, but on a
402    /// multi-controller cluster (e.g. running alongside `nginx-ingress`)
403    /// leaves this watcher picking up Ingress objects meant for the other
404    /// controller too, so set this explicitly in that case.
405    pub fn ingress_class(mut self, class: impl Into<String>) -> Self {
406        self.ingress_class = Some(class.into());
407        self
408    }
409
410    /// Override the polling interval in seconds (default: 30).
411    ///
412    /// This remains a periodic full resync even when the watch connection
413    /// (always attempted alongside it — see the [module docs](self)) is
414    /// healthy, the same "trust but verify" pattern real Kubernetes
415    /// controllers use: the watch stream delivers low-latency updates, and
416    /// this interval is the safety net against a missed or silently
417    /// swallowed event.
418    pub fn poll_interval_secs(mut self, secs: u64) -> Self {
419        self.poll_interval_secs = secs;
420        self
421    }
422
423    /// Spawn background threads that keep the rule table up to date: a
424    /// periodic full resync every `poll_interval_secs`, and (best-effort) a
425    /// long-lived watch connection that triggers an immediate resync on any
426    /// change instead of waiting for the next interval. Call once at
427    /// startup.
428    pub fn start(&self) {
429        self.clone_inner().poll_loop();
430        self.clone_inner().watch_loop();
431    }
432
433    fn clone_inner(&self) -> WatcherHandle {
434        WatcherHandle {
435            api_server: self.api_server.clone(),
436            token: self.token.clone(),
437            namespace: self.namespace.clone(),
438            ingress_class: self.ingress_class.clone(),
439            poll_interval_secs: self.poll_interval_secs,
440            rules: Arc::clone(&self.rules),
441            #[cfg(any(feature = "http-client", feature = "http2"))]
442            tls: self.tls.clone(),
443        }
444    }
445
446    /// Return a snapshot of the current rule list.
447    pub fn rules(&self) -> Vec<IngressRule> {
448        self.rules.read().unwrap().clone()
449    }
450
451    /// Perform one synchronous poll cycle.
452    ///
453    /// Exported for testing without starting the background thread.
454    pub fn poll(&self) -> Result<(), String> {
455        let new_rules = self.do_poll()?;
456        *self.rules.write().unwrap() = new_rules;
457        Ok(())
458    }
459
460    fn list_path(&self) -> String {
461        list_path(&self.namespace)
462    }
463
464    fn do_poll(&self) -> Result<Vec<IngressRule>, String> {
465        let path = self.list_path();
466        #[cfg(any(feature = "http-client", feature = "http2"))]
467        let body = fetch(&self.api_server, &self.token, self.tls.as_deref(), &path)?;
468        #[cfg(not(any(feature = "http-client", feature = "http2")))]
469        let body = http_get_plain(&self.api_server, &path, &self.token)?;
470        Ok(parse_ingress_list(&body, self.ingress_class.as_deref()))
471    }
472}
473
474fn list_path(namespace: &str) -> String {
475    if namespace.is_empty() || namespace == "all" {
476        "/apis/networking.k8s.io/v1/ingresses".to_string()
477    } else {
478        format!("/apis/networking.k8s.io/v1/namespaces/{namespace}/ingresses")
479    }
480}
481
482/// Fetch the ingress list body, over TLS if `tls_cfg` is configured,
483/// falling back to plain HTTP otherwise. Shared by
484/// [`KubernetesIngressWatcher::do_poll`] and [`WatcherHandle::poll_once`].
485#[cfg(any(feature = "http-client", feature = "http2"))]
486fn fetch(
487    api_server: &str,
488    token: &str,
489    tls_cfg: Option<&tls::InClusterConfig>,
490    path: &str,
491) -> Result<String, String> {
492    if let Some(cfg) = tls_cfg {
493        return tls::https_get(
494            &cfg.host,
495            cfg.port,
496            "kubernetes.default.svc",
497            cfg.client_config.clone(),
498            &cfg.token,
499            path,
500            Duration::from_secs(10),
501        );
502    }
503    http_get_plain(api_server, path, token)
504}
505
506// Internal handle used by the background threads (avoids having to make
507// KubernetesIngressWatcher Clone while sharing the rules Arc).
508struct WatcherHandle {
509    api_server: String,
510    token: String,
511    namespace: String,
512    ingress_class: Option<String>,
513    poll_interval_secs: u64,
514    rules: Arc<RwLock<Vec<IngressRule>>>,
515    #[cfg(any(feature = "http-client", feature = "http2"))]
516    tls: Option<Arc<tls::InClusterConfig>>,
517}
518
519impl WatcherHandle {
520    fn poll_loop(self) {
521        // Do an initial poll before sleeping.
522        self.poll_once();
523        let interval = Duration::from_secs(self.poll_interval_secs);
524        std::thread::spawn(move || loop {
525            std::thread::sleep(interval);
526            self.poll_once();
527        });
528    }
529
530    fn poll_once(&self) {
531        let path = list_path(&self.namespace);
532        let result = {
533            #[cfg(any(feature = "http-client", feature = "http2"))]
534            {
535                fetch(&self.api_server, &self.token, self.tls.as_deref(), &path)
536            }
537            #[cfg(not(any(feature = "http-client", feature = "http2")))]
538            {
539                http_get_plain(&self.api_server, &path, &self.token)
540            }
541        };
542        match result {
543            Ok(body) => {
544                let new_rules = parse_ingress_list(&body, self.ingress_class.as_deref());
545                *self.rules.write().unwrap() = new_rules;
546            }
547            Err(e) => {
548                eprintln!("ingress watcher: poll failed: {}", e);
549            }
550        }
551    }
552
553    /// Spawn the watch-connection thread — see the [module docs](self) (and
554    /// `watch`'s own docs) for why this triggers a full re-list on any event
555    /// rather than applying deltas incrementally.
556    fn watch_loop(self) {
557        std::thread::spawn(move || loop {
558            if let Err(e) = self.watch_once() {
559                eprintln!("ingress watcher: watch connection error: {e}");
560            }
561            std::thread::sleep(WATCH_RECONNECT_BACKOFF);
562        });
563    }
564
565    fn watch_once(&self) -> Result<(), String> {
566        let path = format!("{}?watch=true", list_path(&self.namespace));
567
568        #[cfg(any(feature = "http-client", feature = "http2"))]
569        if let Some(cfg) = &self.tls {
570            let stream = tls::tls_connect(
571                &cfg.host,
572                cfg.port,
573                "kubernetes.default.svc",
574                cfg.client_config.clone(),
575                WATCH_READ_TIMEOUT,
576            )?;
577            return self.stream_watch(stream, "kubernetes.default.svc", &cfg.token, &path);
578        }
579
580        let (host, addr) = parse_plain_host_addr(&self.api_server)?;
581        let tcp = TcpStream::connect(&addr)
582            .map_err(|e| format!("ingress watcher: connect to {addr} failed: {e}"))?;
583        tcp.set_read_timeout(Some(WATCH_READ_TIMEOUT)).map_err(|e| e.to_string())?;
584        tcp.set_write_timeout(Some(Duration::from_secs(5))).map_err(|e| e.to_string())?;
585        self.stream_watch(tcp, &host, &self.token, &path)
586    }
587
588    fn stream_watch<S: Read + Write>(
589        &self,
590        mut stream: S,
591        host_header: &str,
592        token: &str,
593        path: &str,
594    ) -> Result<(), String> {
595        let auth_header = if token.is_empty() {
596            String::new()
597        } else {
598            format!("Authorization: Bearer {token}\r\n")
599        };
600        let request = format!(
601            "GET {path} HTTP/1.1\r\nHost: {host_header}\r\n{auth_header}Accept: application/json\r\nConnection: keep-alive\r\n\r\n"
602        );
603        stream
604            .write_all(request.as_bytes())
605            .map_err(|e| format!("ingress watcher: watch request write failed: {e}"))?;
606
607        watch::read_chunked_lines(stream, |_line| {
608            // Every event (ADDED/MODIFIED/DELETED/ERROR) is treated
609            // identically: it means *something* changed, so re-list from
610            // scratch rather than trying to apply it as a delta — see the
611            // module docs for why.
612            self.poll_once();
613        })
614    }
615}
616
617/// Parse `host:port` out of a plain-HTTP `api_server` URL, returning both
618/// the bare host (for the `Host:` header) and the `host:port` dial address.
619fn parse_plain_host_addr(api_server: &str) -> Result<(String, String), String> {
620    let rest = api_server
621        .strip_prefix("http://")
622        .ok_or_else(|| format!("ingress watcher: api_server must start with http://, got: {api_server}"))?;
623    let host_port = rest.split('/').next().unwrap_or(rest);
624    let (host, port) = if let Some(colon) = host_port.rfind(':') {
625        let port_str = &host_port[colon + 1..];
626        if let Ok(p) = port_str.parse::<u16>() {
627            (&host_port[..colon], p)
628        } else {
629            (host_port, 80u16)
630        }
631    } else {
632        (host_port, 80u16)
633    };
634    Ok((host.to_string(), format!("{host}:{port}")))
635}
636
637// ── plain-HTTP/1.1 GET helper ─────────────────────────────────────────────────
638
639/// Issue a plain-HTTP/1.1 GET to `{api_server}{path}` with an optional Bearer
640/// token and return the response body as a string.
641fn http_get_plain(api_server: &str, path: &str, token: &str) -> Result<String, String> {
642    let (host, addr) = parse_plain_host_addr(api_server)?;
643    let mut stream = TcpStream::connect(&addr)
644        .map_err(|e| format!("ingress watcher: connect to {} failed: {}", addr, e))?;
645    stream.set_read_timeout(Some(Duration::from_secs(10))).map_err(|e| e.to_string())?;
646    stream.set_write_timeout(Some(Duration::from_secs(5))).map_err(|e| e.to_string())?;
647
648    let auth_header = if token.is_empty() {
649        String::new()
650    } else {
651        format!("Authorization: Bearer {}\r\n", token)
652    };
653
654    let request = format!(
655        "GET {} HTTP/1.1\r\nHost: {}\r\n{}Accept: application/json\r\nConnection: close\r\n\r\n",
656        path, host, auth_header
657    );
658
659    stream.write_all(request.as_bytes()).map_err(|e| e.to_string())?;
660
661    let mut buf = Vec::with_capacity(8192);
662    let mut tmp = [0u8; 4096];
663    loop {
664        match stream.read(&mut tmp) {
665            Ok(0) => break,
666            Ok(n) => buf.extend_from_slice(&tmp[..n]),
667            Err(e) => return Err(format!("ingress watcher: read failed: {}", e)),
668        }
669    }
670
671    parse_http1_response(&buf)
672}
673
674/// Split a complete HTTP/1.1 response into its status code and body,
675/// returning the body as a string if the status is 2xx. Shared by the
676/// plain-HTTP path above and the TLS path in `tls::https_get`.
677fn parse_http1_response(buf: &[u8]) -> Result<String, String> {
678    let header_end = buf
679        .windows(4)
680        .position(|w| w == b"\r\n\r\n")
681        .ok_or_else(|| "ingress watcher: incomplete HTTP response (no header end)".to_string())?;
682
683    let header_str = std::str::from_utf8(&buf[..header_end]).unwrap_or("");
684    let status_line = header_str.lines().next().unwrap_or("");
685    let parts: Vec<&str> = status_line.splitn(3, ' ').collect();
686    if parts.len() < 2 {
687        return Err(format!("ingress watcher: malformed status line: {}", status_line));
688    }
689    let status: u16 = parts[1].parse().unwrap_or(0);
690    if status < 200 || status >= 300 {
691        return Err(format!("ingress watcher: API returned status {}", status));
692    }
693
694    let body_bytes = &buf[header_end + 4..];
695    std::str::from_utf8(body_bytes)
696        .map(|s| s.to_string())
697        .map_err(|e| format!("ingress watcher: non-UTF-8 response body: {}", e))
698}
699
700// ── IngressRouter ─────────────────────────────────────────────────────────────
701
702/// An [`Application`] that routes incoming requests using the live Ingress rule table.
703///
704/// Finds the first matching [`IngressRule`] and forwards the request to
705/// `{service_name}.{namespace}.svc.cluster.local:{service_port}` over HTTP/1.1.
706/// Returns `404 Not Found` when no rule matches.
707pub struct IngressRouter {
708    watcher: KubernetesIngressWatcher,
709    connect_timeout: Duration,
710    read_timeout: Duration,
711}
712
713impl IngressRouter {
714    /// Wrap a watcher in an `IngressRouter` with default timeouts.
715    pub fn new(watcher: KubernetesIngressWatcher) -> Self {
716        Self {
717            watcher,
718            connect_timeout: Duration::from_secs(5),
719            read_timeout: Duration::from_secs(30),
720        }
721    }
722
723    /// Override the TCP connect timeout (default: 5 000 ms).
724    pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
725        self.connect_timeout = Duration::from_millis(ms);
726        self
727    }
728
729    /// Override the response read timeout (default: 30 000 ms).
730    pub fn read_timeout_ms(mut self, ms: u64) -> Self {
731        self.read_timeout = Duration::from_millis(ms);
732        self
733    }
734}
735
736impl Application for IngressRouter {
737    fn execute(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
738        let host = request
739            .get_header("host".to_string())
740            .map(|h| h.value.as_str())
741            .unwrap_or("");
742
743        let rules = self.watcher.rules();
744        let matched = rules.iter().find(|r| r.matches(host, &request.request_uri));
745
746        match matched {
747            Some(rule) => {
748                let upstream_host = format!(
749                    "{}.{}.svc.cluster.local",
750                    rule.service_name, rule.namespace
751                );
752                crate::proxy::proxy_http1(
753                    request,
754                    &connection.client.ip,
755                    &upstream_host,
756                    rule.service_port,
757                    self.connect_timeout,
758                    self.read_timeout,
759                )
760                .or_else(|_| Ok(bad_gateway()))
761            }
762            None => Ok(not_found()),
763        }
764    }
765}
766
767fn bad_gateway() -> Response {
768    let cr = Range::get_content_range(
769        b"502 Bad Gateway".to_vec(),
770        MimeType::TEXT_PLAIN.to_string(),
771    );
772    let mut r = Response::new();
773    r.status_code = *STATUS_CODE_REASON_PHRASE.n502_bad_gateway.status_code;
774    r.reason_phrase = STATUS_CODE_REASON_PHRASE.n502_bad_gateway.reason_phrase.to_string();
775    r.content_range_list = vec![cr];
776    r
777}
778
779fn not_found() -> Response {
780    let cr = Range::get_content_range(
781        b"404 No matching ingress rule".to_vec(),
782        MimeType::TEXT_PLAIN.to_string(),
783    );
784    let mut r = Response::new();
785    r.status_code = *STATUS_CODE_REASON_PHRASE.n404_not_found.status_code;
786    r.reason_phrase = STATUS_CODE_REASON_PHRASE.n404_not_found.reason_phrase.to_string();
787    r.content_range_list = vec![cr];
788    r
789}