rust-web-server 17.45.0

An HTTP web framework, reverse proxy, and server for Rust supporting HTTP/1.1, HTTP/2, and HTTP/3. Config-driven proxy mode (rws.config.toml with [[route]] / [[upstream]]) or library crate. No third-party HTTP dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Kubernetes Ingress watcher and router.
//!
//! [`KubernetesIngressWatcher`] polls the Kubernetes API for Ingress resources
//! and maintains a live route table.  [`IngressRouter`] implements
//! [`Application`] and routes incoming HTTP requests to the appropriate
//! upstream service using the live rule table.
//!
//! # Prerequisites
//!
//! The watcher communicates with the Kubernetes API over plain HTTP/1.1.  For
//! in-cluster use, expose the API via `kubectl proxy` and point the watcher at
//! `http://localhost:8001`:
//!
//! ```text
//! kubectl proxy &
//! export RWS_K8S_API_SERVER=http://localhost:8001
//! export RWS_K8S_TOKEN=
//! export RWS_K8S_NAMESPACE=default
//! ```
//!
//! # Example
//!
//! ```rust,no_run
//! use rust_web_server::ingress::{IngressRouter, KubernetesIngressWatcher};
//! use rust_web_server::server::Server;
//!
//! let watcher = KubernetesIngressWatcher::from_env().expect("K8s env not set");
//! watcher.start();
//!
//! let app = IngressRouter::new(watcher);
//! // Server::run(app);  // pass to your server
//! ```

#[cfg(test)]
mod tests;

use std::io::{Read, Write};
use std::net::TcpStream;
use std::sync::{Arc, RwLock};
use std::time::Duration;

use crate::application::Application;
use crate::core::New;
use crate::mime_type::MimeType;
use crate::range::Range;
use crate::request::Request;
use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
use crate::server::ConnectionInfo;

// ── IngressRule ───────────────────────────────────────────────────────────────

/// A single routing rule parsed from a Kubernetes Ingress resource.
#[derive(Debug, Clone, PartialEq)]
pub struct IngressRule {
    /// Value of `spec.rules[].host`.  Empty string means match-all.
    pub host: String,
    /// Value of `spec.rules[].http.paths[].path`.  Prefix match.
    pub path: String,
    /// Kubernetes service name (`spec.rules[].http.paths[].backend.service.name`).
    pub service_name: String,
    /// Kubernetes service port number.
    pub service_port: u16,
    /// Namespace the Ingress lives in.
    pub namespace: String,
}

impl IngressRule {
    /// Build the upstream Kubernetes DNS address.
    ///
    /// Returns `"{service_name}.{namespace}.svc.cluster.local:{service_port}"`.
    pub fn upstream_addr(&self) -> String {
        format!(
            "{}.{}.svc.cluster.local:{}",
            self.service_name, self.namespace, self.service_port
        )
    }

    /// Returns `true` if this rule matches the given `host` header value and
    /// request `uri`.
    ///
    /// * If `self.host` is non-empty, the incoming `host` must match
    ///   (case-insensitive).
    /// * The `uri` must start with `self.path`, or `self.path` must be `"/"`.
    pub fn matches(&self, host: &str, uri: &str) -> bool {
        if !self.host.is_empty() && !self.host.eq_ignore_ascii_case(host) {
            return false;
        }
        self.path == "/" || uri.starts_with(&self.path)
    }
}

// ── JSON helpers ──────────────────────────────────────────────────────────────

/// Find the first occurrence of `"field": "VALUE"` in `json` and return `VALUE`.
fn extract_str_field<'a>(json: &'a str, field: &str) -> Option<&'a str> {
    let needle = format!("\"{}\":", field);
    let start = json.find(needle.as_str())?;
    let after_colon = &json[start + needle.len()..];
    let after_colon = after_colon.trim_start_matches(' ');
    if !after_colon.starts_with('"') {
        return None;
    }
    let inner = &after_colon[1..];
    let end = inner.find('"')?;
    Some(&inner[..end])
}

/// Find the first occurrence of `"field": NUMBER` in `json` and parse as `u16`.
fn extract_u16_field(json: &str, field: &str) -> Option<u16> {
    let needle = format!("\"{}\":", field);
    let start = json.find(needle.as_str())?;
    let after_colon = &json[start + needle.len()..];
    let after_colon = after_colon.trim_start_matches(' ');
    let end = after_colon.find(|c: char| !c.is_ascii_digit())?;
    after_colon[..end].parse().ok()
}

// ── parse_ingress_list ────────────────────────────────────────────────────────

/// Parse a Kubernetes Ingress list JSON body into a `Vec<IngressRule>`.
///
/// This is a minimal, hand-rolled parser that handles the common formatting
/// returned by the Kubernetes API server.  It does not depend on any external
/// JSON library.
pub fn parse_ingress_list(json: &str) -> Vec<IngressRule> {
    let mut rules = Vec::new();

    // Split on "spec" to get per-item sections.  The first chunk is before the
    // first item so we skip it.
    let spec_sections: Vec<&str> = json.split("\"spec\"").collect();
    for section in spec_sections.iter().skip(1) {
        // Extract namespace from the surrounding item (look backwards in the
        // original JSON for the nearest "namespace" field before this "spec").
        // We do a simple search within the section for "namespace".
        let namespace = extract_str_field(section, "namespace")
            .unwrap_or("default")
            .to_string();

        // Within this spec section, look for rules.
        let rules_sections: Vec<&str> = section.split("\"rules\"").collect();
        for rules_section in rules_sections.iter().skip(1) {
            // Extract host (may be absent).
            let host = extract_str_field(rules_section, "host").unwrap_or("").to_string();

            // Within the rules section, split on "paths".
            let paths_sections: Vec<&str> = rules_section.split("\"paths\"").collect();
            for paths_section in paths_sections.iter().skip(1) {
                // Within each paths entry, split on path objects.
                // Each path entry looks like: {"path":"/foo","backend":...}
                // We split on `"path"` and take alternating sections.
                let path_entries: Vec<&str> = paths_section.split("\"path\"").collect();
                for path_entry in path_entries.iter().skip(1) {
                    let path = extract_str_field(path_entry, "path")
                        .or_else(|| {
                            // The split consumed "path" so the value comes right after ":"
                            let after_colon = path_entry.trim_start_matches(':').trim_start_matches(' ');
                            if after_colon.starts_with('"') {
                                let inner = &after_colon[1..];
                                inner.find('"').map(|end| &inner[..end])
                            } else {
                                None
                            }
                        })
                        .unwrap_or("/")
                        .to_string();

                    let service_name =
                        extract_str_field(path_entry, "name").unwrap_or("").to_string();
                    let service_port =
                        extract_u16_field(path_entry, "number").unwrap_or(80);

                    if !service_name.is_empty() {
                        rules.push(IngressRule {
                            host: host.clone(),
                            path,
                            service_name,
                            service_port,
                            namespace: namespace.clone(),
                        });
                    }
                }
            }
        }
    }

    rules
}

// ── KubernetesIngressWatcher ──────────────────────────────────────────────────

/// Watches a Kubernetes API server for Ingress resources and maintains a live
/// routing table.
pub struct KubernetesIngressWatcher {
    api_server: String,
    token: String,
    namespace: String,
    poll_interval_secs: u64,
    rules: Arc<RwLock<Vec<IngressRule>>>,
}

impl KubernetesIngressWatcher {
    /// Create a watcher from explicit values.
    ///
    /// `api_server` should be a plain-HTTP URL such as `http://localhost:8001`.
    /// The default namespace is `"default"`.
    pub fn new(api_server: impl Into<String>, token: impl Into<String>) -> Self {
        Self {
            api_server: api_server.into(),
            token: token.into(),
            namespace: "default".to_string(),
            poll_interval_secs: 30,
            rules: Arc::new(RwLock::new(Vec::new())),
        }
    }

    /// Attempt to configure from the Kubernetes service account files at
    /// `/var/run/secrets/kubernetes.io/serviceaccount/`.
    ///
    /// In-cluster TLS to `kubernetes.default.svc` is not yet implemented.
    /// Use `kubectl proxy` and configure via environment variables instead:
    ///
    /// ```text
    /// kubectl proxy &
    /// export RWS_K8S_API_SERVER=http://localhost:8001
    /// ```
    pub fn from_service_account() -> Result<Self, String> {
        Err(
            "In-cluster TLS (https://kubernetes.default.svc) is not yet supported. \
             Use `kubectl proxy` and set RWS_K8S_API_SERVER=http://localhost:8001 \
             along with RWS_K8S_TOKEN and RWS_K8S_NAMESPACE, then call \
             KubernetesIngressWatcher::from_env()."
                .to_string(),
        )
    }

    /// Configure from environment variables `RWS_K8S_API_SERVER`, `RWS_K8S_TOKEN`,
    /// and (optionally) `RWS_K8S_NAMESPACE`.
    ///
    /// Returns `Err` if `RWS_K8S_API_SERVER` is not set.
    pub fn from_env() -> Result<Self, String> {
        let api_server = std::env::var("RWS_K8S_API_SERVER").map_err(|_| {
            "RWS_K8S_API_SERVER environment variable is not set".to_string()
        })?;
        let token = std::env::var("RWS_K8S_TOKEN").unwrap_or_default();
        let namespace = std::env::var("RWS_K8S_NAMESPACE").unwrap_or_else(|_| "default".to_string());
        let mut watcher = Self::new(api_server, token);
        watcher.namespace = namespace;
        Ok(watcher)
    }

    /// Override the namespace filter.  Use `"all"` or empty string for all namespaces.
    pub fn namespace(mut self, ns: impl Into<String>) -> Self {
        self.namespace = ns.into();
        self
    }

    /// Override the polling interval in seconds (default: 30).
    pub fn poll_interval_secs(mut self, secs: u64) -> Self {
        self.poll_interval_secs = secs;
        self
    }

    /// Spawn a background thread that polls the Kubernetes API at the configured
    /// interval.  Call once at startup.
    pub fn start(&self) {
        self.clone_inner().poll_loop();
    }

    fn clone_inner(&self) -> WatcherHandle {
        WatcherHandle {
            api_server: self.api_server.clone(),
            token: self.token.clone(),
            namespace: self.namespace.clone(),
            poll_interval_secs: self.poll_interval_secs,
            rules: Arc::clone(&self.rules),
        }
    }

    /// Return a snapshot of the current rule list.
    pub fn rules(&self) -> Vec<IngressRule> {
        self.rules.read().unwrap().clone()
    }

    /// Perform one synchronous poll cycle.
    ///
    /// Exported for testing without starting the background thread.
    pub fn poll(&self) -> Result<(), String> {
        let new_rules = self.do_poll()?;
        *self.rules.write().unwrap() = new_rules;
        Ok(())
    }

    fn do_poll(&self) -> Result<Vec<IngressRule>, String> {
        let path = if self.namespace.is_empty() || self.namespace == "all" {
            "/apis/networking.k8s.io/v1/ingresses".to_string()
        } else {
            format!(
                "/apis/networking.k8s.io/v1/namespaces/{}/ingresses",
                self.namespace
            )
        };

        let body = http_get_plain(&self.api_server, &path, &self.token)?;
        Ok(parse_ingress_list(&body))
    }
}

// Internal handle used by the background thread (avoids having to make
// KubernetesIngressWatcher Clone while sharing the rules Arc).
struct WatcherHandle {
    api_server: String,
    token: String,
    namespace: String,
    poll_interval_secs: u64,
    rules: Arc<RwLock<Vec<IngressRule>>>,
}

impl WatcherHandle {
    fn poll_loop(self) {
        // Do an initial poll before sleeping.
        self.poll_once();
        let interval = Duration::from_secs(self.poll_interval_secs);
        std::thread::spawn(move || loop {
            std::thread::sleep(interval);
            self.poll_once();
        });
    }

    fn poll_once(&self) {
        let path = if self.namespace.is_empty() || self.namespace == "all" {
            "/apis/networking.k8s.io/v1/ingresses".to_string()
        } else {
            format!(
                "/apis/networking.k8s.io/v1/namespaces/{}/ingresses",
                self.namespace
            )
        };
        match http_get_plain(&self.api_server, &path, &self.token) {
            Ok(body) => {
                let new_rules = parse_ingress_list(&body);
                *self.rules.write().unwrap() = new_rules;
            }
            Err(e) => {
                eprintln!("ingress watcher: poll failed: {}", e);
            }
        }
    }
}

// ── plain-HTTP/1.1 GET helper ─────────────────────────────────────────────────

/// Issue a plain-HTTP/1.1 GET to `{api_server}{path}` with an optional Bearer
/// token and return the response body as a string.
fn http_get_plain(api_server: &str, path: &str, token: &str) -> Result<String, String> {
    // Parse host:port from api_server URL.
    let rest = api_server
        .strip_prefix("http://")
        .ok_or_else(|| format!("ingress watcher: api_server must start with http://, got: {}", api_server))?;
    let host_port = rest.split('/').next().unwrap_or(rest);
    let (host, port) = if let Some(colon) = host_port.rfind(':') {
        let port_str = &host_port[colon + 1..];
        if let Ok(p) = port_str.parse::<u16>() {
            (&host_port[..colon], p)
        } else {
            (host_port, 80u16)
        }
    } else {
        (host_port, 80u16)
    };

    let addr = format!("{}:{}", host, port);
    let mut stream = TcpStream::connect(&addr)
        .map_err(|e| format!("ingress watcher: connect to {} failed: {}", addr, e))?;
    stream.set_read_timeout(Some(Duration::from_secs(10))).map_err(|e| e.to_string())?;
    stream.set_write_timeout(Some(Duration::from_secs(5))).map_err(|e| e.to_string())?;

    let auth_header = if token.is_empty() {
        String::new()
    } else {
        format!("Authorization: Bearer {}\r\n", token)
    };

    let request = format!(
        "GET {} HTTP/1.1\r\nHost: {}\r\n{}Accept: application/json\r\nConnection: close\r\n\r\n",
        path, host, auth_header
    );

    stream.write_all(request.as_bytes()).map_err(|e| e.to_string())?;

    let mut buf = Vec::with_capacity(8192);
    let mut tmp = [0u8; 4096];
    loop {
        match stream.read(&mut tmp) {
            Ok(0) => break,
            Ok(n) => buf.extend_from_slice(&tmp[..n]),
            Err(e) => return Err(format!("ingress watcher: read failed: {}", e)),
        }
    }

    // Split headers from body.
    let header_end = buf
        .windows(4)
        .position(|w| w == b"\r\n\r\n")
        .ok_or_else(|| "ingress watcher: incomplete HTTP response (no header end)".to_string())?;

    let header_str = std::str::from_utf8(&buf[..header_end]).unwrap_or("");
    let status_line = header_str.lines().next().unwrap_or("");
    let parts: Vec<&str> = status_line.splitn(3, ' ').collect();
    if parts.len() < 2 {
        return Err(format!("ingress watcher: malformed status line: {}", status_line));
    }
    let status: u16 = parts[1].parse().unwrap_or(0);
    if status < 200 || status >= 300 {
        return Err(format!("ingress watcher: API returned status {}", status));
    }

    let body_bytes = &buf[header_end + 4..];
    std::str::from_utf8(body_bytes)
        .map(|s| s.to_string())
        .map_err(|e| format!("ingress watcher: non-UTF-8 response body: {}", e))
}

// ── IngressRouter ─────────────────────────────────────────────────────────────

/// An [`Application`] that routes incoming requests using the live Ingress rule table.
///
/// Finds the first matching [`IngressRule`] and forwards the request to
/// `{service_name}.{namespace}.svc.cluster.local:{service_port}` over HTTP/1.1.
/// Returns `404 Not Found` when no rule matches.
pub struct IngressRouter {
    watcher: KubernetesIngressWatcher,
    connect_timeout: Duration,
    read_timeout: Duration,
}

impl IngressRouter {
    /// Wrap a watcher in an `IngressRouter` with default timeouts.
    pub fn new(watcher: KubernetesIngressWatcher) -> Self {
        Self {
            watcher,
            connect_timeout: Duration::from_secs(5),
            read_timeout: Duration::from_secs(30),
        }
    }

    /// Override the TCP connect timeout (default: 5 000 ms).
    pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
        self.connect_timeout = Duration::from_millis(ms);
        self
    }

    /// Override the response read timeout (default: 30 000 ms).
    pub fn read_timeout_ms(mut self, ms: u64) -> Self {
        self.read_timeout = Duration::from_millis(ms);
        self
    }
}

impl Application for IngressRouter {
    fn execute(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
        let host = request
            .get_header("host".to_string())
            .map(|h| h.value.as_str())
            .unwrap_or("");

        let rules = self.watcher.rules();
        let matched = rules.iter().find(|r| r.matches(host, &request.request_uri));

        match matched {
            Some(rule) => {
                let upstream_host = format!(
                    "{}.{}.svc.cluster.local",
                    rule.service_name, rule.namespace
                );
                crate::proxy::proxy_http1(
                    request,
                    &connection.client.ip,
                    &upstream_host,
                    rule.service_port,
                    self.connect_timeout,
                    self.read_timeout,
                )
                .or_else(|_| Ok(bad_gateway()))
            }
            None => Ok(not_found()),
        }
    }
}

fn bad_gateway() -> Response {
    let cr = Range::get_content_range(
        b"502 Bad Gateway".to_vec(),
        MimeType::TEXT_PLAIN.to_string(),
    );
    let mut r = Response::new();
    r.status_code = *STATUS_CODE_REASON_PHRASE.n502_bad_gateway.status_code;
    r.reason_phrase = STATUS_CODE_REASON_PHRASE.n502_bad_gateway.reason_phrase.to_string();
    r.content_range_list = vec![cr];
    r
}

fn not_found() -> Response {
    let cr = Range::get_content_range(
        b"404 No matching ingress rule".to_vec(),
        MimeType::TEXT_PLAIN.to_string(),
    );
    let mut r = Response::new();
    r.status_code = *STATUS_CODE_REASON_PHRASE.n404_not_found.status_code;
    r.reason_phrase = STATUS_CODE_REASON_PHRASE.n404_not_found.reason_phrase.to_string();
    r.content_range_list = vec![cr];
    r
}