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 config_reload;
67pub mod config_check;
68/// RSA public keys and RS256 / rsa-sha256 signature verification (no `rsa` crate).
69#[cfg(any(feature = "auth-asymmetric", feature = "sso"))]
70pub mod rsa_key;
71pub mod server_config;
72pub mod feature;
73pub mod maintenance;
74pub mod metrics;
75pub mod mcp;
76pub mod request_log;
77pub mod request_id;
78#[cfg(not(target_arch = "wasm32"))]
79pub mod otel;
80#[cfg(feature = "acme")]
81pub mod acme;
82pub mod middleware;
83pub mod rate_limit;
84pub mod router;
85pub mod schema;
86pub mod state;
87pub mod test_client;
88pub mod application;
89pub mod body;
90pub mod client_hint;
91pub mod controller;
92pub mod core;
93pub mod cors;
94pub mod entry_point;
95pub mod ext;
96pub mod header;
97pub mod http;
98pub mod json;
99pub mod language;
100#[cfg(not(target_arch = "wasm32"))]
101pub mod log;
102pub mod mime_type;
103pub mod null;
104pub mod range;
105pub mod request;
106pub mod response;
107pub mod server;
108pub mod symbol;
109#[cfg(not(target_arch = "wasm32"))]
110pub mod thread_pool;
111pub mod url;
112pub mod pagination;
113#[cfg(not(target_arch = "wasm32"))]
114pub mod proxy;
115pub mod rewrite;
116pub mod scheduler;
117#[cfg(not(target_arch = "wasm32"))]
118pub mod tcp_proxy;
119#[cfg(not(target_arch = "wasm32"))]
120pub mod udp_proxy;
121#[cfg(not(target_arch = "wasm32"))]
122pub mod ws_proxy;
123#[cfg(not(target_arch = "wasm32"))]
124pub mod canary;
125#[cfg(not(target_arch = "wasm32"))]
126pub mod circuit_breaker;
127// `BackendPool`/`DiscoverySource` (DNS/etcd/Consul/Docker) are native-only —
128// gated internally in service_discovery/mod.rs, not at this declaration —
129// because `json_lite` (a plain JSON parser, no sockets) must stay available
130// for `secrets`'s Vault/AWS-SM/Key-Vault backends on every target.
131pub mod service_discovery;
132pub mod config_binding;
133pub mod di;
134#[cfg(not(target_arch = "wasm32"))]
135pub mod proxy_config;
136#[cfg(not(target_arch = "wasm32"))]
137pub mod ingress;
138#[cfg(feature = "tera")]
139pub mod template;
140pub mod validate;
141pub mod virtual_host;
142#[cfg(any(feature = "model-sqlite", feature = "model-postgres", feature = "model-mysql"))]
143pub mod model;
144#[cfg(not(target_arch = "wasm32"))]
145pub mod websocket;
146// Has both a native (TcpStream/rustls) and a wasm32 (wasi:http outgoing-handler)
147// backend behind Client::send() — see the #[cfg(target_arch = "wasm32")]
148// `send_once` in this module. spec/WASM_SHIM.md Phase 2 item 7.
149pub mod http_client;
150#[cfg(feature = "crypto")]
151pub mod crypto;
152#[cfg(feature = "csrf")]
153pub mod csrf;
154#[cfg(feature = "sso")]
155pub mod sso;
156// SMTP is a raw-TCP protocol with no wasi:http equivalent (unlike
157// http_client, which the host can proxy via outgoing-handler) — genuinely
158// can't work in a wasi:http guest, not just ungated. spec/WASM_SHIM.md.
159#[cfg(all(feature = "mailer", not(target_arch = "wasm32")))]
160pub mod mailer;
161#[cfg(feature = "jobs")]
162pub mod jobs;
163// Also compiled under `secrets` — `secrets::aws_secrets_manager`/`azure_key_vault`
164// reuse `StorageError` and the SigV4/Managed-Identity credential helpers from here.
165#[cfg(any(feature = "storage-local", feature = "storage-s3", feature = "storage-azure", feature = "secrets"))]
166pub mod storage;
167#[cfg(feature = "openapi")]
168pub mod openapi;
169#[cfg(feature = "webhook")]
170pub mod webhook;
171#[cfg(feature = "secrets")]
172pub mod secrets;
173// Runs wrapped work on a background OS thread to bound wait time — needs
174// `std::thread::spawn`, unavailable on wasm32-wasip2. See spec/WASM_SHIM.md.
175#[cfg(not(target_arch = "wasm32"))]
176pub mod timeout;
177pub mod prelude;
178
179#[cfg(feature = "http2")]
180#[doc(hidden)]
181pub mod tls;
182
183#[cfg(feature = "http2")]
184#[doc(hidden)]
185pub mod h2_server;
186
187#[cfg(feature = "http3")]
188#[doc(hidden)]
189pub mod h3_handler;
190
191/// Shared infrastructure for tests that write process-wide environment variables.
192///
193/// Tests that call `override_environment_variables_from_config` or
194/// `CommandLineArgument::set_environment_variable` must hold this lock for
195/// their entire duration so they don't race with other tests reading the
196/// same variables.
197#[cfg(test)]
198mod stack_depth_tests;
199
200/// A rustls client-config builder with this crate's crypto provider
201/// (aws-lc-rs) named explicitly. `rustls::ClientConfig::builder()` uses the
202/// process-wide default provider and panics when none is installed and more
203/// than one is compiled in — which happens as soon as any dependency enables
204/// rustls's `ring` backend (e.g. sqlx). Every outbound TLS client in the
205/// crate starts here.
206#[cfg(all(any(feature = "http-client", feature = "http2"), not(target_arch = "wasm32")))]
207pub(crate) fn tls_client_builder() -> rustls::ConfigBuilder<rustls::ClientConfig, rustls::WantsVerifier> {
208    rustls::ClientConfig::builder_with_provider(std::sync::Arc::new(rustls::crypto::aws_lc_rs::default_provider()))
209        .with_safe_default_protocol_versions()
210        .expect("aws-lc-rs supports rustls's default protocol versions")
211}
212
213#[cfg(test)]
214pub mod test_env {
215    use std::sync::{Mutex, OnceLock};
216    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
217    pub fn lock() -> std::sync::MutexGuard<'static, ()> {
218        LOCK.get_or_init(|| Mutex::new(()))
219            .lock()
220            .unwrap_or_else(|e| e.into_inner())
221    }
222
223    /// A per-process path under the OS temp dir that is deleted (file or
224    /// directory) when dropped — so a test cleans up even when an assertion
225    /// fails before its last line.
226    pub struct TempPath(std::path::PathBuf);
227
228    impl TempPath {
229        pub fn new(name: &str) -> Self {
230            TempPath(std::env::temp_dir().join(format!("rws_test_{}_{}", std::process::id(), name)))
231        }
232
233        /// The same in the working directory (the static-file root), for
234        /// tests that need a file the server would serve.
235        pub fn new_in_cwd(name: &str) -> Self {
236            TempPath(std::env::current_dir().expect("working directory").join(format!("rws_test_{}_{}", std::process::id(), name)))
237        }
238
239        pub fn as_str(&self) -> &str {
240            self.0.to_str().expect("temp dir path is UTF-8")
241        }
242    }
243
244    impl std::ops::Deref for TempPath {
245        type Target = std::path::Path;
246        fn deref(&self) -> &std::path::Path {
247            &self.0
248        }
249    }
250
251    impl Drop for TempPath {
252        fn drop(&mut self) {
253            // A symlink is removed itself, never followed (a test may link
254            // to a system directory).
255            let is_link = std::fs::symlink_metadata(&self.0).is_ok_and(|m| m.file_type().is_symlink());
256            if is_link {
257                let _ = std::fs::remove_file(&self.0);
258            } else if self.0.is_dir() {
259                let _ = std::fs::remove_dir_all(&self.0);
260            } else {
261                let _ = std::fs::remove_file(&self.0);
262            }
263        }
264    }
265}
266
267/// Entry points for `fuzz/` targets that reach crate-private parsers.
268/// Compiled only under `--cfg fuzzing`, which `cargo fuzz` sets — never part
269/// of the public API.
270#[cfg(fuzzing)]
271#[doc(hidden)]
272pub mod fuzz_api {
273    /// Proxy route-matching normalization of a request target (#50): any
274    /// input, and normalizing twice changes nothing.
275    pub fn proxy_normalize_target(data: &[u8]) {
276        let Ok(target) = std::str::from_utf8(data) else { return };
277        let once = crate::proxy_config::normalize_request_target(target).into_owned();
278        let twice = crate::proxy_config::normalize_request_target(&once).into_owned();
279        assert_eq!(once, twice, "normalization is not idempotent for {:?}", target);
280    }
281
282    /// Static-file request-path decoding (#55). Must never panic; the
283    /// decoded path never carries a `..` segment past the web-root check.
284    pub fn static_path_decode(data: &[u8]) {
285        let Ok(path) = std::str::from_utf8(data) else { return };
286        if let Ok(fs_path) = crate::app::controller::static_resource::static_fs_path(path) {
287            let relative = &fs_path[crate::app::controller::static_resource::working_directory().len()..];
288            assert!(!relative.split(['/', '\\']).any(|segment| segment == ".."), "{:?} -> {:?}", path, fs_path);
289        }
290    }
291
292    /// An upstream MCP server's reply as the gateway reads it (#62): a JSON
293    /// body or an event stream, then the response's tools. Must never panic.
294    pub fn mcp_gateway_reply(data: &[u8]) {
295        for content_type in ["application/json", "text/event-stream"] {
296            if let Ok(result) = crate::mcp::gateway::parse_reply(content_type, data, 1) {
297                let _ = crate::mcp::gateway::fuzzing::tools(&result);
298            }
299        }
300    }
301
302    /// What ACME renewal parses from the CA (#1): certificate DER (validity,
303    /// serial, Authority Key Identifier), renewalInfo windows (RFC 3339) and
304    /// directory profile names. Must never panic.
305    #[cfg(feature = "acme")]
306    pub fn acme_renewal(data: &[u8]) {
307        let _ = crate::acme::fuzzing::cert_info_from_der(data);
308        if let Ok(text) = std::str::from_utf8(data) {
309            let _ = crate::acme::fuzzing::parse_suggested_window(text);
310            let _ = crate::acme::fuzzing::parse_rfc3339(text);
311            let _ = crate::acme::fuzzing::json_object_keys(text, "profiles");
312        }
313    }
314
315    /// The SAML XML parser (`sso::saml::xml`), fed IdP-supplied documents.
316    #[cfg(feature = "sso-saml")]
317    pub fn saml_xml_parse(xml: &str) {
318        let _ = crate::sso::saml::xml_parse_for_fuzzing(xml);
319    }
320
321    /// HTTP/1.1 request framing (`server::framing`) over a raw connection
322    /// buffer: head detection, body framing, and the chunked body decoder,
323    /// fed in two pieces split at the first byte to mimic separate reads.
324    pub fn http1_framing(data: &[u8]) {
325        use crate::server::framing::{self, BodyFraming, ChunkedBody, HeadScan};
326        let mut pending = data.to_vec();
327        framing::skip_leading_empty_lines(&mut pending);
328        let HeadScan::Complete(head_len) = framing::scan_head(&pending) else { return };
329        assert!(head_len <= pending.len() && head_len <= framing::MAX_HEAD_SIZE);
330        let Ok(request) = crate::request::Request::parse(&pending[..head_len]) else { return };
331        for header in &request.headers {
332            let _ = crate::http::date::parse(&header.value);
333        }
334        let _ = framing::validate_head(&pending[..head_len], &request);
335        let _ = framing::keep_alive(&request);
336        let body = &pending[head_len..];
337        if let Ok(BodyFraming::Chunked) = framing::body_framing(&request) {
338            let split = data.first().map_or(0, |&b| b as usize).min(body.len());
339            let mut decoder = ChunkedBody::new(1 << 20);
340            let mut buffer = body[..split].to_vec();
341            for next in [&body[split..], &[][..]] {
342                match decoder.feed(&buffer) {
343                    Ok((consumed, _)) => {
344                        assert!(consumed <= buffer.len());
345                        buffer.drain(..consumed);
346                    }
347                    Err(_) => return,
348                }
349                buffer.extend_from_slice(next);
350            }
351            assert!(decoder.body.len() <= 1 << 20);
352        }
353    }
354}
355
356
357/// Compiles the README's Rust example as a doctest, so it can't drift from the API.
358#[cfg(all(doctest, feature = "http3"))]
359#[doc = include_str!("../README.md")]
360pub struct ReadmeDoctests;