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