1extern 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#[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;
67#[cfg(not(target_arch = "wasm32"))]
68pub mod config_watch;
69pub mod config_check;
70#[cfg(any(feature = "auth-asymmetric", feature = "sso"))]
72pub mod rsa_key;
73pub mod server_config;
74pub mod feature;
75pub mod maintenance;
76pub mod metrics;
77pub mod mcp;
78pub mod request_log;
79pub mod request_id;
80#[cfg(not(target_arch = "wasm32"))]
81pub mod otel;
82#[cfg(feature = "acme")]
83pub mod acme;
84pub mod middleware;
85pub mod rate_limit;
86pub mod router;
87pub mod schema;
88pub mod state;
89pub mod test_client;
90pub mod application;
91pub mod body;
92pub mod client_hint;
93pub mod controller;
94pub mod core;
95pub mod cors;
96pub mod entry_point;
97pub mod ext;
98pub mod header;
99pub mod http;
100pub mod json;
101pub mod language;
102#[cfg(not(target_arch = "wasm32"))]
103pub mod log;
104pub mod mime_type;
105pub mod null;
106pub mod range;
107pub mod request;
108pub mod response;
109pub mod server;
110pub mod symbol;
111#[cfg(not(target_arch = "wasm32"))]
112pub mod thread_pool;
113pub mod url;
114pub mod pagination;
115#[cfg(not(target_arch = "wasm32"))]
116pub mod proxy;
117pub mod rewrite;
118pub mod scheduler;
119#[cfg(not(target_arch = "wasm32"))]
120pub mod tcp_proxy;
121#[cfg(not(target_arch = "wasm32"))]
122pub mod udp_proxy;
123#[cfg(not(target_arch = "wasm32"))]
124pub mod ws_proxy;
125#[cfg(not(target_arch = "wasm32"))]
126pub mod canary;
127#[cfg(not(target_arch = "wasm32"))]
128pub mod circuit_breaker;
129pub mod service_discovery;
134pub mod config_binding;
135pub mod di;
136#[cfg(not(target_arch = "wasm32"))]
137pub mod proxy_config;
138#[cfg(not(target_arch = "wasm32"))]
139pub mod ingress;
140#[cfg(feature = "tera")]
141pub mod template;
142pub mod validate;
143pub mod virtual_host;
144#[cfg(any(feature = "model-sqlite", feature = "model-postgres", feature = "model-mysql"))]
145pub mod model;
146#[cfg(not(target_arch = "wasm32"))]
147pub mod websocket;
148pub mod http_client;
152#[cfg(feature = "crypto")]
153pub mod crypto;
154#[cfg(feature = "csrf")]
155pub mod csrf;
156#[cfg(feature = "sso")]
157pub mod sso;
158#[cfg(all(feature = "mailer", not(target_arch = "wasm32")))]
162pub mod mailer;
163#[cfg(feature = "jobs")]
164pub mod jobs;
165#[cfg(any(feature = "storage-local", feature = "storage-s3", feature = "storage-azure", feature = "secrets"))]
168pub mod storage;
169#[cfg(feature = "openapi")]
170pub mod openapi;
171#[cfg(feature = "webhook")]
172pub mod webhook;
173#[cfg(feature = "secrets")]
174pub mod secrets;
175#[cfg(not(target_arch = "wasm32"))]
178pub mod timeout;
179pub mod prelude;
180
181#[cfg(feature = "http2")]
182#[doc(hidden)]
183pub mod tls;
184
185#[cfg(feature = "http2")]
186#[doc(hidden)]
187pub mod h2_server;
188
189#[cfg(feature = "http3")]
190#[doc(hidden)]
191pub mod h3_handler;
192
193#[cfg(test)]
200mod stack_depth_tests;
201
202#[cfg(all(any(feature = "http-client", feature = "http2"), not(target_arch = "wasm32")))]
209pub(crate) fn tls_client_builder() -> rustls::ConfigBuilder<rustls::ClientConfig, rustls::WantsVerifier> {
210 rustls::ClientConfig::builder_with_provider(std::sync::Arc::new(rustls::crypto::aws_lc_rs::default_provider()))
211 .with_safe_default_protocol_versions()
212 .expect("aws-lc-rs supports rustls's default protocol versions")
213}
214
215#[cfg(test)]
216pub mod test_env {
217 use std::sync::{Mutex, OnceLock};
218 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
219 pub fn lock() -> std::sync::MutexGuard<'static, ()> {
220 LOCK.get_or_init(|| Mutex::new(()))
221 .lock()
222 .unwrap_or_else(|e| e.into_inner())
223 }
224
225 pub struct TempPath(std::path::PathBuf);
229
230 impl TempPath {
231 pub fn new(name: &str) -> Self {
232 TempPath(std::env::temp_dir().join(format!("rws_test_{}_{}", std::process::id(), name)))
233 }
234
235 pub fn new_in_cwd(name: &str) -> Self {
238 TempPath(std::env::current_dir().expect("working directory").join(format!("rws_test_{}_{}", std::process::id(), name)))
239 }
240
241 pub fn as_str(&self) -> &str {
242 self.0.to_str().expect("temp dir path is UTF-8")
243 }
244 }
245
246 impl std::ops::Deref for TempPath {
247 type Target = std::path::Path;
248 fn deref(&self) -> &std::path::Path {
249 &self.0
250 }
251 }
252
253 impl Drop for TempPath {
254 fn drop(&mut self) {
255 let is_link = std::fs::symlink_metadata(&self.0).is_ok_and(|m| m.file_type().is_symlink());
258 if is_link {
259 let _ = std::fs::remove_file(&self.0);
260 } else if self.0.is_dir() {
261 let _ = std::fs::remove_dir_all(&self.0);
262 } else {
263 let _ = std::fs::remove_file(&self.0);
264 }
265 }
266 }
267}
268
269#[cfg(fuzzing)]
273#[doc(hidden)]
274pub mod fuzz_api {
275 pub fn proxy_normalize_target(data: &[u8]) {
278 let Ok(target) = std::str::from_utf8(data) else { return };
279 let once = crate::proxy_config::normalize_request_target(target).into_owned();
280 let twice = crate::proxy_config::normalize_request_target(&once).into_owned();
281 assert_eq!(once, twice, "normalization is not idempotent for {:?}", target);
282 }
283
284 pub fn static_path_decode(data: &[u8]) {
287 let Ok(path) = std::str::from_utf8(data) else { return };
288 if let Ok(fs_path) = crate::app::controller::static_resource::static_fs_path(path) {
289 let relative = &fs_path[crate::app::controller::static_resource::working_directory().len()..];
290 assert!(!relative.split(['/', '\\']).any(|segment| segment == ".."), "{:?} -> {:?}", path, fs_path);
291 }
292 }
293
294 pub fn accept_encoding(data: &[u8]) {
298 let Ok(value) = std::str::from_utf8(data) else { return };
299 let request = crate::request::Request {
300 method: "GET".to_string(),
301 request_uri: "/".to_string(),
302 http_version: "HTTP/1.1".to_string(),
303 headers: vec![crate::header::Header::new(crate::header::Header::_ACCEPT_ENCODING, value.to_string())],
304 body: Default::default(),
305 };
306 for preference in [crate::compression::DYNAMIC_PREFERENCE, crate::compression::STATIC_PREFERENCE] {
307 if let Some(chosen) = crate::compression::negotiate(&request, preference) {
308 assert!(preference.contains(&chosen));
309 let refused = value.split(',').any(|c| {
311 let mut parts = c.split(';');
312 parts.next().unwrap_or("").trim().eq_ignore_ascii_case(chosen.token())
313 && parts
314 .map(str::trim)
315 .find(|p| p.as_bytes().get(..2).is_some_and(|b| b.eq_ignore_ascii_case(b"q=")))
316 .is_some_and(|q| q[2..].trim().parse::<f32>() == Ok(0.0))
317 });
318 let listed_once = value.split(',').filter(|c| c.split(';').next().unwrap_or("").trim().eq_ignore_ascii_case(chosen.token())).count() == 1;
319 assert!(!(refused && listed_once), "{value:?} refused {chosen:?}");
320 }
321 }
322 }
323
324 pub fn mcp_gateway_reply(data: &[u8]) {
327 for content_type in ["application/json", "text/event-stream"] {
328 if let Ok(result) = crate::mcp::gateway::parse_reply(content_type, data, 1) {
329 let _ = crate::mcp::gateway::fuzzing::tools(&result);
330 }
331 }
332 }
333
334 #[cfg(not(target_arch = "wasm32"))]
337 pub fn websocket_frame(data: &[u8]) {
338 let mut cursor = std::io::Cursor::new(data);
339 while let Ok(frame) = crate::websocket::WebSocket::read_frame_limited(&mut cursor, 4096) {
340 let len = match &frame {
341 crate::websocket::Frame::Text(t) => t.len(),
342 crate::websocket::Frame::Binary(b) | crate::websocket::Frame::Ping(b) | crate::websocket::Frame::Pong(b) => b.len(),
343 crate::websocket::Frame::Continuation { data, .. } => data.len(),
344 crate::websocket::Frame::Close(_, reason) => reason.len() + 2,
345 };
346 assert!(len <= 4096 + 2);
347 }
348 }
349
350 #[cfg(not(target_arch = "wasm32"))]
352 pub fn dns_srv_response(data: &[u8]) {
353 let id = data.get(..2).map_or(0, |b| u16::from_be_bytes([b[0], b[1]]));
354 let _ = crate::service_discovery::dns_srv::parse_response(data, id);
355 }
356
357 #[cfg(not(target_arch = "wasm32"))]
359 pub fn redis_reply(data: &[u8]) {
360 let _ = crate::redis_protocol::read_reply(&mut std::io::Cursor::new(data));
361 }
362
363 pub fn cookie_header(data: &[u8]) {
365 let Ok(value) = std::str::from_utf8(data) else { return };
366 let jar = crate::cookie::CookieJar::parse(value);
367 assert!(jar.cookies.iter().all(|c| !c.name.is_empty()));
368 }
369
370 #[cfg(feature = "acme")]
374 pub fn acme_renewal(data: &[u8]) {
375 let _ = crate::acme::fuzzing::cert_info_from_der(data);
376 if let Ok(text) = std::str::from_utf8(data) {
377 let _ = crate::acme::fuzzing::parse_suggested_window(text);
378 let _ = crate::acme::fuzzing::parse_rfc3339(text);
379 let _ = crate::acme::fuzzing::json_object_keys(text, "profiles");
380 }
381 }
382
383 #[cfg(feature = "sso-saml")]
385 pub fn saml_xml_parse(xml: &str) {
386 let _ = crate::sso::saml::xml_parse_for_fuzzing(xml);
387 }
388
389 pub fn http1_framing(data: &[u8]) {
393 use crate::server::framing::{self, BodyFraming, ChunkedBody, HeadScan};
394 let mut pending = data.to_vec();
395 framing::skip_leading_empty_lines(&mut pending);
396 let HeadScan::Complete(head_len) = framing::scan_head(&pending) else { return };
397 assert!(head_len <= pending.len() && head_len <= framing::MAX_HEAD_SIZE);
398 let Ok(request) = crate::request::Request::parse(&pending[..head_len]) else { return };
399 for header in &request.headers {
400 let _ = crate::http::date::parse(&header.value);
401 }
402 let _ = framing::validate_head(&pending[..head_len], &request);
403 let _ = framing::keep_alive(&request);
404 let body = &pending[head_len..];
405 if let Ok(BodyFraming::Chunked) = framing::body_framing(&request) {
406 let split = data.first().map_or(0, |&b| b as usize).min(body.len());
407 let mut decoder = ChunkedBody::new(1 << 20);
408 let mut buffer = body[..split].to_vec();
409 for next in [&body[split..], &[][..]] {
410 match decoder.feed(&buffer) {
411 Ok((consumed, _)) => {
412 assert!(consumed <= buffer.len());
413 buffer.drain(..consumed);
414 }
415 Err(_) => return,
416 }
417 buffer.extend_from_slice(next);
418 }
419 assert!(decoder.body.len() <= 1 << 20);
420 }
421 }
422}
423
424
425#[cfg(all(doctest, feature = "http3"))]
427#[doc = include_str!("../README.md")]
428pub struct ReadmeDoctests;