Skip to main content

rust_web_server/
lib.rs

1//! # rust-web-server
2//!
3//! An HTTP/1.1, HTTP/2, and HTTP/3 (QUIC) server, reverse proxy, and
4//! application framework in one crate. HTTP/1.1 parsing, routing, middleware,
5//! JSON, WebSocket, and SSE are implemented in-crate; HTTP/2 and HTTP/3
6//! framing use the `h2` and `quinn`/`h3` crates, and TLS uses `rustls`.
7//!
8//! ## Use as a library
9//!
10//! Add to `Cargo.toml`:
11//!
12//! ```toml
13//! [dependencies]
14//! rust-web-server = "17"
15//! ```
16//!
17//! ## Quick start
18//!
19//! ```rust,no_run
20//! use rust_web_server::prelude::*;
21//!
22//! fn hello(_: &Request, _: &PathParams, _: &ConnectionInfo, _: &()) -> Response {
23//!     Response::text(STATUS_CODE_REASON_PHRASE.n200_ok, "Hello, world!")
24//! }
25//!
26//! fn main() {
27//!     let app = App::with_state(()).get("/hello", hello);
28//!     let (listener, pool) = Server::setup().unwrap();
29//!     Server::run(listener, pool, app);
30//! }
31//! ```
32//!
33//! See [DEVELOPER.md](https://github.com/bohdaq/rust-web-server/blob/main/DEVELOPER.md)
34//! for the full building blocks reference and use case examples.
35
36// Allows `::rust_web_server::…` paths to resolve from within this crate's own
37// tests, which is required by proc-macro derive output that uses that prefix.
38extern crate self as rust_web_server;
39
40pub mod app;
41#[cfg(feature = "auth")]
42pub mod auth;
43
44#[cfg(feature = "macros")]
45pub use rws_macros::{delete, get, patch, post, put, route, Config, FromRequest, JsonSchema, Validate};
46#[cfg(all(feature = "macros", any(feature = "model-sqlite", feature = "model-postgres", feature = "model-mysql")))]
47pub use rws_macros::Model;
48#[cfg(feature = "http2")]
49pub mod async_state;
50#[cfg(feature = "http2")]
51pub(crate) mod async_bridge;
52pub mod session;
53// Socket-coupled — see spec/WASM_SHIM.md for what a wasm32-wasip2 build
54// excludes and why (no OS threads, no raw TCP/TLS in a WASI guest).
55#[cfg(not(target_arch = "wasm32"))]
56pub(crate) mod redis_protocol;
57pub mod sse;
58pub mod compression;
59pub mod cookie;
60pub mod error;
61pub mod extract;
62pub mod ip_filter;
63pub mod macros;
64pub mod blocklist;
65pub mod cache;
66pub mod early_hints;
67pub mod config_reload;
68#[cfg(not(target_arch = "wasm32"))]
69pub mod config_watch;
70pub mod config_check;
71/// RSA public keys and RS256 / rsa-sha256 signature verification (no `rsa` crate).
72#[cfg(any(feature = "auth-asymmetric", feature = "sso"))]
73pub mod rsa_key;
74pub mod server_config;
75pub mod feature;
76pub mod maintenance;
77pub mod metrics;
78pub mod mcp;
79pub mod request_log;
80pub mod request_id;
81#[cfg(not(target_arch = "wasm32"))]
82pub mod otel;
83#[cfg(feature = "acme")]
84pub mod acme;
85pub mod middleware;
86pub mod rate_limit;
87pub mod router;
88pub mod schema;
89pub mod state;
90pub mod test_client;
91pub mod application;
92pub mod body;
93pub mod client_hint;
94pub mod controller;
95pub mod core;
96pub mod cors;
97pub mod entry_point;
98pub mod ext;
99pub mod header;
100pub mod http;
101pub mod json;
102pub mod language;
103#[cfg(not(target_arch = "wasm32"))]
104pub mod log;
105pub mod mime_type;
106pub mod null;
107pub mod range;
108pub mod request;
109pub mod response;
110pub mod server;
111pub mod symbol;
112#[cfg(not(target_arch = "wasm32"))]
113pub mod thread_pool;
114pub mod url;
115pub mod pagination;
116#[cfg(not(target_arch = "wasm32"))]
117pub mod proxy;
118pub mod rewrite;
119pub mod scheduler;
120#[cfg(not(target_arch = "wasm32"))]
121pub mod tcp_proxy;
122#[cfg(not(target_arch = "wasm32"))]
123pub mod udp_proxy;
124#[cfg(not(target_arch = "wasm32"))]
125pub mod ws_proxy;
126#[cfg(not(target_arch = "wasm32"))]
127pub mod canary;
128#[cfg(not(target_arch = "wasm32"))]
129pub mod circuit_breaker;
130// `BackendPool`/`DiscoverySource` (DNS/etcd/Consul/Docker) are native-only —
131// gated internally in service_discovery/mod.rs, not at this declaration —
132// because `json_lite` (a plain JSON parser, no sockets) must stay available
133// for `secrets`'s Vault/AWS-SM/Key-Vault backends on every target.
134pub mod service_discovery;
135/// DNS wire format, shared by the SRV service discovery and ACME's DNS-01.
136pub(crate) mod dns;
137pub mod config_binding;
138pub mod di;
139#[cfg(not(target_arch = "wasm32"))]
140pub mod proxy_config;
141#[cfg(not(target_arch = "wasm32"))]
142pub mod llm;
143#[cfg(not(target_arch = "wasm32"))]
144pub mod admin;
145#[cfg(feature = "wasm-plugins")]
146pub mod wasm_plugin;
147#[cfg(not(target_arch = "wasm32"))]
148pub mod ingress;
149#[cfg(feature = "tera")]
150pub mod template;
151pub mod validate;
152pub mod virtual_host;
153#[cfg(any(feature = "model-sqlite", feature = "model-postgres", feature = "model-mysql"))]
154pub mod model;
155#[cfg(not(target_arch = "wasm32"))]
156pub mod websocket;
157// Has both a native (TcpStream/rustls) and a wasm32 (wasi:http outgoing-handler)
158// backend behind Client::send() — see the #[cfg(target_arch = "wasm32")]
159// `send_once` in this module. spec/WASM_SHIM.md Phase 2 item 7.
160pub mod http_client;
161#[cfg(feature = "crypto")]
162pub mod crypto;
163#[cfg(feature = "csrf")]
164pub mod csrf;
165#[cfg(feature = "sso")]
166pub mod sso;
167// SMTP is a raw-TCP protocol with no wasi:http equivalent (unlike
168// http_client, which the host can proxy via outgoing-handler) — genuinely
169// can't work in a wasi:http guest, not just ungated. spec/WASM_SHIM.md.
170#[cfg(all(feature = "mailer", not(target_arch = "wasm32")))]
171pub mod mailer;
172#[cfg(feature = "jobs")]
173pub mod jobs;
174// Also compiled under `secrets` — `secrets::aws_secrets_manager`/`azure_key_vault`
175// reuse `StorageError` and the SigV4/Managed-Identity credential helpers from here.
176#[cfg(any(feature = "storage-local", feature = "storage-s3", feature = "storage-azure", feature = "secrets"))]
177pub mod storage;
178#[cfg(feature = "openapi")]
179pub mod openapi;
180#[cfg(feature = "tower")]
181pub mod tower;
182#[cfg(feature = "gateway-api")]
183pub mod gateway_api;
184#[cfg(feature = "webhook")]
185pub mod webhook;
186#[cfg(feature = "secrets")]
187pub mod secrets;
188// Runs wrapped work on a background OS thread to bound wait time — needs
189// `std::thread::spawn`, unavailable on wasm32-wasip2. See spec/WASM_SHIM.md.
190#[cfg(not(target_arch = "wasm32"))]
191pub mod timeout;
192pub mod prelude;
193
194#[cfg(feature = "http2")]
195#[doc(hidden)]
196pub mod tls;
197
198#[cfg(feature = "http2")]
199#[doc(hidden)]
200pub mod h2_server;
201
202#[cfg(feature = "http3")]
203#[doc(hidden)]
204pub mod h3_handler;
205
206/// Shared infrastructure for tests that write process-wide environment variables.
207///
208/// Tests that call `override_environment_variables_from_config` or
209/// `CommandLineArgument::set_environment_variable` must hold this lock for
210/// their entire duration so they don't race with other tests reading the
211/// same variables.
212#[cfg(test)]
213mod stack_depth_tests;
214
215/// A rustls client-config builder with this crate's crypto provider
216/// (aws-lc-rs) named explicitly. `rustls::ClientConfig::builder()` uses the
217/// process-wide default provider and panics when none is installed and more
218/// than one is compiled in — which happens as soon as any dependency enables
219/// rustls's `ring` backend (e.g. sqlx). Every outbound TLS client in the
220/// crate starts here.
221#[cfg(all(any(feature = "http-client", feature = "http2"), not(target_arch = "wasm32")))]
222pub(crate) fn tls_client_builder() -> rustls::ConfigBuilder<rustls::ClientConfig, rustls::WantsVerifier> {
223    rustls::ClientConfig::builder_with_provider(std::sync::Arc::new(rustls::crypto::aws_lc_rs::default_provider()))
224        .with_safe_default_protocol_versions()
225        .expect("aws-lc-rs supports rustls's default protocol versions")
226}
227
228#[cfg(test)]
229pub mod test_env {
230    use std::sync::{Mutex, OnceLock};
231    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
232    pub fn lock() -> std::sync::MutexGuard<'static, ()> {
233        LOCK.get_or_init(|| Mutex::new(()))
234            .lock()
235            .unwrap_or_else(|e| e.into_inner())
236    }
237
238    /// A per-process path under the OS temp dir that is deleted (file or
239    /// directory) when dropped — so a test cleans up even when an assertion
240    /// fails before its last line.
241    pub struct TempPath(std::path::PathBuf);
242
243    impl TempPath {
244        pub fn new(name: &str) -> Self {
245            TempPath(std::env::temp_dir().join(format!("rws_test_{}_{}", std::process::id(), name)))
246        }
247
248        /// The same in the working directory (the static-file root), for
249        /// tests that need a file the server would serve.
250        pub fn new_in_cwd(name: &str) -> Self {
251            TempPath(std::env::current_dir().expect("working directory").join(format!("rws_test_{}_{}", std::process::id(), name)))
252        }
253
254        pub fn as_str(&self) -> &str {
255            self.0.to_str().expect("temp dir path is UTF-8")
256        }
257    }
258
259    impl std::ops::Deref for TempPath {
260        type Target = std::path::Path;
261        fn deref(&self) -> &std::path::Path {
262            &self.0
263        }
264    }
265
266    impl Drop for TempPath {
267        fn drop(&mut self) {
268            // A symlink is removed itself, never followed (a test may link
269            // to a system directory).
270            let is_link = std::fs::symlink_metadata(&self.0).is_ok_and(|m| m.file_type().is_symlink());
271            if is_link {
272                let _ = std::fs::remove_file(&self.0);
273            } else if self.0.is_dir() {
274                let _ = std::fs::remove_dir_all(&self.0);
275            } else {
276                let _ = std::fs::remove_file(&self.0);
277            }
278        }
279    }
280}
281
282/// Entry points for `fuzz/` targets that reach crate-private parsers.
283/// Compiled only under `--cfg fuzzing`, which `cargo fuzz` sets — never part
284/// of the public API.
285#[cfg(fuzzing)]
286#[doc(hidden)]
287pub mod fuzz_api {
288    /// Proxy route-matching normalization of a request target (#50): any
289    /// input, and normalizing twice changes nothing.
290    pub fn proxy_normalize_target(data: &[u8]) {
291        let Ok(target) = std::str::from_utf8(data) else { return };
292        let once = crate::proxy_config::normalize_request_target(target).into_owned();
293        let twice = crate::proxy_config::normalize_request_target(&once).into_owned();
294        assert_eq!(once, twice, "normalization is not idempotent for {:?}", target);
295    }
296
297    /// Static-file request-path decoding (#55). Must never panic; the
298    /// decoded path never carries a `..` segment past the web-root check.
299    pub fn static_path_decode(data: &[u8]) {
300        let Ok(path) = std::str::from_utf8(data) else { return };
301        if let Ok(fs_path) = crate::app::controller::static_resource::static_fs_path(path) {
302            let relative = &fs_path[crate::app::controller::static_resource::working_directory().len()..];
303            assert!(!relative.split(['/', '\\']).any(|segment| segment == ".."), "{:?} -> {:?}", path, fs_path);
304        }
305    }
306
307    /// `Accept-Encoding` negotiation (#7): any header value; the choice is
308    /// always one of the offered codings, and a coding the value refuses
309    /// (its first `q=` parameter is 0) is never chosen.
310    pub fn accept_encoding(data: &[u8]) {
311        let Ok(value) = std::str::from_utf8(data) else { return };
312        let request = crate::request::Request {
313            method: "GET".to_string(),
314            request_uri: "/".to_string(),
315            http_version: "HTTP/1.1".to_string(),
316            headers: vec![crate::header::Header::new(crate::header::Header::_ACCEPT_ENCODING, value.to_string())],
317            body: Default::default(),
318        };
319        for preference in [crate::compression::DYNAMIC_PREFERENCE, crate::compression::STATIC_PREFERENCE] {
320            if let Some(chosen) = crate::compression::negotiate(&request, preference) {
321                assert!(preference.contains(&chosen));
322                // Refused: the coding's first `q=` parameter is exactly 0.
323                let refused = value.split(',').any(|c| {
324                    let mut parts = c.split(';');
325                    parts.next().unwrap_or("").trim().eq_ignore_ascii_case(chosen.token())
326                        && parts
327                            .map(str::trim)
328                            .find(|p| p.as_bytes().get(..2).is_some_and(|b| b.eq_ignore_ascii_case(b"q=")))
329                            .is_some_and(|q| q[2..].trim().parse::<f32>() == Ok(0.0))
330                });
331                let listed_once = value.split(',').filter(|c| c.split(';').next().unwrap_or("").trim().eq_ignore_ascii_case(chosen.token())).count() == 1;
332                assert!(!(refused && listed_once), "{value:?} refused {chosen:?}");
333            }
334        }
335    }
336
337    /// What a WebAssembly plugin returns, as the host reads it (#40).
338    /// Must never panic.
339    #[cfg(feature = "wasm-plugins")]
340    pub fn wasm_plugin_output(data: &[u8]) {
341        let _ = crate::wasm_plugin::parse_request_output(data);
342        let _ = crate::wasm_plugin::parse_response_output(data);
343    }
344
345    /// A disk-cache entry file as the cache reads it back (#39): the header
346    /// line and key, then the stored response. Must never panic.
347    pub fn cache_entry(data: &[u8]) {
348        if let Some((_, _, _, offset)) = crate::cache::disk::parse_entry_header(data) {
349            let _ = crate::response::Response::parse_upstream(&data[offset..], crate::proxy::REGENERATED_OR_HOP_BY_HOP);
350        }
351    }
352
353    /// An `Available-Dictionary` header value, and dictionary-compressed
354    /// bodies through both decoders (#38).
355    pub fn available_dictionary(data: &[u8]) {
356        use crate::compression::dictionary::{decode, parse_available_dictionary, DictionaryEncoding};
357        let _ = parse_available_dictionary(&String::from_utf8_lossy(data));
358        for encoding in [DictionaryEncoding::Dcz, DictionaryEncoding::Dcb] {
359            let _ = decode(encoding, data, b"dictionary", 1 << 16);
360        }
361    }
362
363    /// Provider responses as the LLM proxy reads them (#41): usage from a
364    /// JSON body or an event stream fed in pieces, and chunked framing.
365    /// Must never panic.
366    pub fn llm_usage(data: &[u8]) {
367        for content_type in ["application/json", "text/event-stream"] {
368            let mut parser = crate::llm::UsageParser::new(content_type);
369            for piece in data.chunks(7) {
370                parser.feed(piece);
371            }
372            let _ = parser.finish();
373        }
374        let mut decoder = crate::llm::usage::ChunkDecoder::default();
375        let mut out = Vec::new();
376        let _ = decoder.decode(data, &mut out);
377    }
378
379    /// An upstream MCP server's reply as the gateway reads it (#62): a JSON
380    /// body or an event stream, then the response's tools. Must never panic.
381    pub fn mcp_gateway_reply(data: &[u8]) {
382        for content_type in ["application/json", "text/event-stream"] {
383            if let Ok(result) = crate::mcp::gateway::parse_reply(content_type, data, 1) {
384                let _ = crate::mcp::gateway::fuzzing::tools(&result);
385            }
386        }
387    }
388
389    /// A WebSocket frame from a client (#8): any bytes; a frame never holds
390    /// more payload than the limit allows. Must never panic.
391    #[cfg(not(target_arch = "wasm32"))]
392    pub fn websocket_frame(data: &[u8]) {
393        let mut cursor = std::io::Cursor::new(data);
394        while let Ok(frame) = crate::websocket::WebSocket::read_frame_limited(&mut cursor, 4096) {
395            let len = match &frame {
396                crate::websocket::Frame::Text(t) => t.len(),
397                crate::websocket::Frame::Binary(b) | crate::websocket::Frame::Ping(b) | crate::websocket::Frame::Pong(b) => b.len(),
398                crate::websocket::Frame::Continuation { data, .. } => data.len(),
399                crate::websocket::Frame::Close(_, reason) => reason.len() + 2,
400            };
401            assert!(len <= 4096 + 2);
402        }
403    }
404
405    /// A DNS response read for SRV records (#8). Must never panic.
406    #[cfg(not(target_arch = "wasm32"))]
407    pub fn dns_srv_response(data: &[u8]) {
408        let id = data.get(..2).map_or(0, |b| u16::from_be_bytes([b[0], b[1]]));
409        let _ = crate::service_discovery::dns_srv::parse_response(data, id);
410    }
411
412    /// A DNS message: the shared parser (SRV discovery, ACME DNS-01), TXT
413    /// values and, with `acme`, a DNS UPDATE reply. Must never panic.
414    /// A certificate's subjectAltNames, as a BackendTLSPolicy checks a
415    /// backend's (untrusted) certificate. Must never panic.
416    pub fn x509_subject_alt_names(data: &[u8]) {
417        let _ = crate::core::x509::subject_alt_names(data);
418    }
419
420    pub fn dns_message(data: &[u8]) {
421        if let Ok(message) = crate::dns::parse(data) {
422            for record in message.answers.iter().chain(&message.authority).chain(&message.additional) {
423                let _ = crate::dns::txt_value(&data[record.rdata.clone()]);
424            }
425        }
426        #[cfg(feature = "acme")]
427        let _ = crate::acme::dns01::check_update_reply(data, 0);
428    }
429
430    /// A Redis (RESP) reply (#8). Must never panic.
431    #[cfg(not(target_arch = "wasm32"))]
432    pub fn redis_reply(data: &[u8]) {
433        let _ = crate::redis_protocol::read_reply(&mut std::io::Cursor::new(data));
434    }
435
436    /// A `Cookie` request header (#8): every parsed cookie has a name.
437    pub fn cookie_header(data: &[u8]) {
438        let Ok(value) = std::str::from_utf8(data) else { return };
439        let jar = crate::cookie::CookieJar::parse(value);
440        assert!(jar.cookies.iter().all(|c| !c.name.is_empty()));
441    }
442
443    /// A W3C `baggage` header (#25): members survive a round trip through
444    /// the header. Must never panic.
445    #[cfg(not(target_arch = "wasm32"))]
446    pub fn otel_baggage(data: &[u8]) {
447        let Ok(value) = std::str::from_utf8(data) else { return };
448        let baggage = crate::otel::Baggage::parse(value);
449        assert!(baggage.len() <= crate::otel::baggage::MAX_MEMBERS);
450        let again = crate::otel::Baggage::parse(&baggage.to_header());
451        for (key, value) in baggage.iter() {
452            if let Some(round_tripped) = again.get(key) {
453                assert_eq!(value, round_tripped);
454            }
455        }
456    }
457
458    /// What ACME renewal parses from the CA (#1): certificate DER (validity,
459    /// serial, Authority Key Identifier), renewalInfo windows (RFC 3339) and
460    /// directory profile names. Must never panic.
461    #[cfg(feature = "acme")]
462    pub fn acme_renewal(data: &[u8]) {
463        let _ = crate::acme::fuzzing::cert_info_from_der(data);
464        if let Ok(text) = std::str::from_utf8(data) {
465            let _ = crate::acme::fuzzing::parse_suggested_window(text);
466            let _ = crate::acme::fuzzing::parse_rfc3339(text);
467            let _ = crate::acme::fuzzing::json_object_keys(text, "profiles");
468        }
469    }
470
471    /// The SAML XML parser (`sso::saml::xml`), fed IdP-supplied documents.
472    #[cfg(feature = "sso-saml")]
473    pub fn saml_xml_parse(xml: &str) {
474        let _ = crate::sso::saml::xml_parse_for_fuzzing(xml);
475    }
476
477    /// HTTP/1.1 request framing (`server::framing`) over a raw connection
478    /// buffer: head detection, body framing, and the chunked body decoder,
479    /// fed in two pieces split at the first byte to mimic separate reads.
480    pub fn http1_framing(data: &[u8]) {
481        use crate::server::framing::{self, BodyFraming, ChunkedBody, HeadScan};
482        let mut pending = data.to_vec();
483        framing::skip_leading_empty_lines(&mut pending);
484        let HeadScan::Complete(head_len) = framing::scan_head(&pending) else { return };
485        assert!(head_len <= pending.len() && head_len <= framing::MAX_HEAD_SIZE);
486        let Ok(request) = crate::request::Request::parse(&pending[..head_len]) else { return };
487        for header in &request.headers {
488            let _ = crate::http::date::parse(&header.value);
489        }
490        let _ = framing::validate_head(&pending[..head_len], &request);
491        let _ = framing::keep_alive(&request);
492        let body = &pending[head_len..];
493        if let Ok(BodyFraming::Chunked) = framing::body_framing(&request) {
494            let split = data.first().map_or(0, |&b| b as usize).min(body.len());
495            let mut decoder = ChunkedBody::new(1 << 20);
496            let mut buffer = body[..split].to_vec();
497            for next in [&body[split..], &[][..]] {
498                match decoder.feed(&buffer) {
499                    Ok((consumed, _)) => {
500                        assert!(consumed <= buffer.len());
501                        buffer.drain(..consumed);
502                    }
503                    Err(_) => return,
504                }
505                buffer.extend_from_slice(next);
506            }
507            assert!(decoder.body.len() <= 1 << 20);
508        }
509    }
510}
511
512
513/// Compiles the README's Rust example as a doctest, so it can't drift from the API.
514#[cfg(all(doctest, feature = "http3"))]
515#[doc = include_str!("../README.md")]
516pub struct ReadmeDoctests;