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(crate) mod dns;
136pub mod config_binding;
137pub mod di;
138#[cfg(not(target_arch = "wasm32"))]
139pub mod proxy_config;
140#[cfg(not(target_arch = "wasm32"))]
141pub mod ingress;
142#[cfg(feature = "tera")]
143pub mod template;
144pub mod validate;
145pub mod virtual_host;
146#[cfg(any(feature = "model-sqlite", feature = "model-postgres", feature = "model-mysql"))]
147pub mod model;
148#[cfg(not(target_arch = "wasm32"))]
149pub mod websocket;
150pub mod http_client;
154#[cfg(feature = "crypto")]
155pub mod crypto;
156#[cfg(feature = "csrf")]
157pub mod csrf;
158#[cfg(feature = "sso")]
159pub mod sso;
160#[cfg(all(feature = "mailer", not(target_arch = "wasm32")))]
164pub mod mailer;
165#[cfg(feature = "jobs")]
166pub mod jobs;
167#[cfg(any(feature = "storage-local", feature = "storage-s3", feature = "storage-azure", feature = "secrets"))]
170pub mod storage;
171#[cfg(feature = "openapi")]
172pub mod openapi;
173#[cfg(feature = "tower")]
174pub mod tower;
175#[cfg(feature = "webhook")]
176pub mod webhook;
177#[cfg(feature = "secrets")]
178pub mod secrets;
179#[cfg(not(target_arch = "wasm32"))]
182pub mod timeout;
183pub mod prelude;
184
185#[cfg(feature = "http2")]
186#[doc(hidden)]
187pub mod tls;
188
189#[cfg(feature = "http2")]
190#[doc(hidden)]
191pub mod h2_server;
192
193#[cfg(feature = "http3")]
194#[doc(hidden)]
195pub mod h3_handler;
196
197#[cfg(test)]
204mod stack_depth_tests;
205
206#[cfg(all(any(feature = "http-client", feature = "http2"), not(target_arch = "wasm32")))]
213pub(crate) fn tls_client_builder() -> rustls::ConfigBuilder<rustls::ClientConfig, rustls::WantsVerifier> {
214 rustls::ClientConfig::builder_with_provider(std::sync::Arc::new(rustls::crypto::aws_lc_rs::default_provider()))
215 .with_safe_default_protocol_versions()
216 .expect("aws-lc-rs supports rustls's default protocol versions")
217}
218
219#[cfg(test)]
220pub mod test_env {
221 use std::sync::{Mutex, OnceLock};
222 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
223 pub fn lock() -> std::sync::MutexGuard<'static, ()> {
224 LOCK.get_or_init(|| Mutex::new(()))
225 .lock()
226 .unwrap_or_else(|e| e.into_inner())
227 }
228
229 pub struct TempPath(std::path::PathBuf);
233
234 impl TempPath {
235 pub fn new(name: &str) -> Self {
236 TempPath(std::env::temp_dir().join(format!("rws_test_{}_{}", std::process::id(), name)))
237 }
238
239 pub fn new_in_cwd(name: &str) -> Self {
242 TempPath(std::env::current_dir().expect("working directory").join(format!("rws_test_{}_{}", std::process::id(), name)))
243 }
244
245 pub fn as_str(&self) -> &str {
246 self.0.to_str().expect("temp dir path is UTF-8")
247 }
248 }
249
250 impl std::ops::Deref for TempPath {
251 type Target = std::path::Path;
252 fn deref(&self) -> &std::path::Path {
253 &self.0
254 }
255 }
256
257 impl Drop for TempPath {
258 fn drop(&mut self) {
259 let is_link = std::fs::symlink_metadata(&self.0).is_ok_and(|m| m.file_type().is_symlink());
262 if is_link {
263 let _ = std::fs::remove_file(&self.0);
264 } else if self.0.is_dir() {
265 let _ = std::fs::remove_dir_all(&self.0);
266 } else {
267 let _ = std::fs::remove_file(&self.0);
268 }
269 }
270 }
271}
272
273#[cfg(fuzzing)]
277#[doc(hidden)]
278pub mod fuzz_api {
279 pub fn proxy_normalize_target(data: &[u8]) {
282 let Ok(target) = std::str::from_utf8(data) else { return };
283 let once = crate::proxy_config::normalize_request_target(target).into_owned();
284 let twice = crate::proxy_config::normalize_request_target(&once).into_owned();
285 assert_eq!(once, twice, "normalization is not idempotent for {:?}", target);
286 }
287
288 pub fn static_path_decode(data: &[u8]) {
291 let Ok(path) = std::str::from_utf8(data) else { return };
292 if let Ok(fs_path) = crate::app::controller::static_resource::static_fs_path(path) {
293 let relative = &fs_path[crate::app::controller::static_resource::working_directory().len()..];
294 assert!(!relative.split(['/', '\\']).any(|segment| segment == ".."), "{:?} -> {:?}", path, fs_path);
295 }
296 }
297
298 pub fn accept_encoding(data: &[u8]) {
302 let Ok(value) = std::str::from_utf8(data) else { return };
303 let request = crate::request::Request {
304 method: "GET".to_string(),
305 request_uri: "/".to_string(),
306 http_version: "HTTP/1.1".to_string(),
307 headers: vec![crate::header::Header::new(crate::header::Header::_ACCEPT_ENCODING, value.to_string())],
308 body: Default::default(),
309 };
310 for preference in [crate::compression::DYNAMIC_PREFERENCE, crate::compression::STATIC_PREFERENCE] {
311 if let Some(chosen) = crate::compression::negotiate(&request, preference) {
312 assert!(preference.contains(&chosen));
313 let refused = value.split(',').any(|c| {
315 let mut parts = c.split(';');
316 parts.next().unwrap_or("").trim().eq_ignore_ascii_case(chosen.token())
317 && parts
318 .map(str::trim)
319 .find(|p| p.as_bytes().get(..2).is_some_and(|b| b.eq_ignore_ascii_case(b"q=")))
320 .is_some_and(|q| q[2..].trim().parse::<f32>() == Ok(0.0))
321 });
322 let listed_once = value.split(',').filter(|c| c.split(';').next().unwrap_or("").trim().eq_ignore_ascii_case(chosen.token())).count() == 1;
323 assert!(!(refused && listed_once), "{value:?} refused {chosen:?}");
324 }
325 }
326 }
327
328 pub fn mcp_gateway_reply(data: &[u8]) {
331 for content_type in ["application/json", "text/event-stream"] {
332 if let Ok(result) = crate::mcp::gateway::parse_reply(content_type, data, 1) {
333 let _ = crate::mcp::gateway::fuzzing::tools(&result);
334 }
335 }
336 }
337
338 #[cfg(not(target_arch = "wasm32"))]
341 pub fn websocket_frame(data: &[u8]) {
342 let mut cursor = std::io::Cursor::new(data);
343 while let Ok(frame) = crate::websocket::WebSocket::read_frame_limited(&mut cursor, 4096) {
344 let len = match &frame {
345 crate::websocket::Frame::Text(t) => t.len(),
346 crate::websocket::Frame::Binary(b) | crate::websocket::Frame::Ping(b) | crate::websocket::Frame::Pong(b) => b.len(),
347 crate::websocket::Frame::Continuation { data, .. } => data.len(),
348 crate::websocket::Frame::Close(_, reason) => reason.len() + 2,
349 };
350 assert!(len <= 4096 + 2);
351 }
352 }
353
354 #[cfg(not(target_arch = "wasm32"))]
356 pub fn dns_srv_response(data: &[u8]) {
357 let id = data.get(..2).map_or(0, |b| u16::from_be_bytes([b[0], b[1]]));
358 let _ = crate::service_discovery::dns_srv::parse_response(data, id);
359 }
360
361 pub fn dns_message(data: &[u8]) {
364 if let Ok(message) = crate::dns::parse(data) {
365 for record in message.answers.iter().chain(&message.authority).chain(&message.additional) {
366 let _ = crate::dns::txt_value(&data[record.rdata.clone()]);
367 }
368 }
369 #[cfg(feature = "acme")]
370 let _ = crate::acme::dns01::check_update_reply(data, 0);
371 }
372
373 #[cfg(not(target_arch = "wasm32"))]
375 pub fn redis_reply(data: &[u8]) {
376 let _ = crate::redis_protocol::read_reply(&mut std::io::Cursor::new(data));
377 }
378
379 pub fn cookie_header(data: &[u8]) {
381 let Ok(value) = std::str::from_utf8(data) else { return };
382 let jar = crate::cookie::CookieJar::parse(value);
383 assert!(jar.cookies.iter().all(|c| !c.name.is_empty()));
384 }
385
386 #[cfg(not(target_arch = "wasm32"))]
389 pub fn otel_baggage(data: &[u8]) {
390 let Ok(value) = std::str::from_utf8(data) else { return };
391 let baggage = crate::otel::Baggage::parse(value);
392 assert!(baggage.len() <= crate::otel::baggage::MAX_MEMBERS);
393 let again = crate::otel::Baggage::parse(&baggage.to_header());
394 for (key, value) in baggage.iter() {
395 if let Some(round_tripped) = again.get(key) {
396 assert_eq!(value, round_tripped);
397 }
398 }
399 }
400
401 #[cfg(feature = "acme")]
405 pub fn acme_renewal(data: &[u8]) {
406 let _ = crate::acme::fuzzing::cert_info_from_der(data);
407 if let Ok(text) = std::str::from_utf8(data) {
408 let _ = crate::acme::fuzzing::parse_suggested_window(text);
409 let _ = crate::acme::fuzzing::parse_rfc3339(text);
410 let _ = crate::acme::fuzzing::json_object_keys(text, "profiles");
411 }
412 }
413
414 #[cfg(feature = "sso-saml")]
416 pub fn saml_xml_parse(xml: &str) {
417 let _ = crate::sso::saml::xml_parse_for_fuzzing(xml);
418 }
419
420 pub fn http1_framing(data: &[u8]) {
424 use crate::server::framing::{self, BodyFraming, ChunkedBody, HeadScan};
425 let mut pending = data.to_vec();
426 framing::skip_leading_empty_lines(&mut pending);
427 let HeadScan::Complete(head_len) = framing::scan_head(&pending) else { return };
428 assert!(head_len <= pending.len() && head_len <= framing::MAX_HEAD_SIZE);
429 let Ok(request) = crate::request::Request::parse(&pending[..head_len]) else { return };
430 for header in &request.headers {
431 let _ = crate::http::date::parse(&header.value);
432 }
433 let _ = framing::validate_head(&pending[..head_len], &request);
434 let _ = framing::keep_alive(&request);
435 let body = &pending[head_len..];
436 if let Ok(BodyFraming::Chunked) = framing::body_framing(&request) {
437 let split = data.first().map_or(0, |&b| b as usize).min(body.len());
438 let mut decoder = ChunkedBody::new(1 << 20);
439 let mut buffer = body[..split].to_vec();
440 for next in [&body[split..], &[][..]] {
441 match decoder.feed(&buffer) {
442 Ok((consumed, _)) => {
443 assert!(consumed <= buffer.len());
444 buffer.drain(..consumed);
445 }
446 Err(_) => return,
447 }
448 buffer.extend_from_slice(next);
449 }
450 assert!(decoder.body.len() <= 1 << 20);
451 }
452 }
453}
454
455
456#[cfg(all(doctest, feature = "http3"))]
458#[doc = include_str!("../README.md")]
459pub struct ReadmeDoctests;