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 i18n;
63pub mod a2a;
64#[cfg(all(unix, any(feature = "http1", feature = "http2")))]
65pub mod systemd;
66pub mod ip_filter;
67pub mod macros;
68pub mod blocklist;
69pub mod cache;
70pub mod early_hints;
71pub mod disk_guard;
72pub mod traffic;
73pub mod authz;
74pub mod config_reload;
75#[cfg(not(target_arch = "wasm32"))]
76pub mod config_watch;
77pub mod config_check;
78#[cfg(any(feature = "auth-asymmetric", feature = "sso"))]
80pub mod rsa_key;
81pub mod server_config;
82pub mod feature;
83pub mod maintenance;
84pub mod metrics;
85pub mod mcp;
86pub mod request_log;
87pub mod request_id;
88#[cfg(not(target_arch = "wasm32"))]
89pub mod otel;
90#[cfg(feature = "acme")]
91pub mod acme;
92pub mod middleware;
93pub mod rate_limit;
94pub mod router;
95pub mod schema;
96pub mod state;
97pub mod test_client;
98pub mod application;
99pub mod body;
100pub mod client_hint;
101pub mod controller;
102pub mod core;
103pub mod cors;
104pub mod entry_point;
105pub mod ext;
106pub mod header;
107pub mod http;
108pub mod json;
109pub mod language;
110#[cfg(not(target_arch = "wasm32"))]
111pub mod log;
112pub mod mime_type;
113pub mod null;
114pub mod range;
115pub mod request;
116pub mod response;
117pub mod server;
118pub mod symbol;
119#[cfg(not(target_arch = "wasm32"))]
120pub mod thread_pool;
121pub mod url;
122pub mod pagination;
123#[cfg(not(target_arch = "wasm32"))]
124pub mod proxy;
125pub mod rewrite;
126pub mod scheduler;
127#[cfg(not(target_arch = "wasm32"))]
128pub mod tcp_proxy;
129#[cfg(not(target_arch = "wasm32"))]
130pub mod udp_proxy;
131#[cfg(not(target_arch = "wasm32"))]
132pub mod ws_proxy;
133#[cfg(not(target_arch = "wasm32"))]
134pub mod canary;
135#[cfg(not(target_arch = "wasm32"))]
136pub mod circuit_breaker;
137pub mod service_discovery;
142pub(crate) mod dns;
144pub mod config_binding;
145pub mod di;
146#[cfg(not(target_arch = "wasm32"))]
147pub mod proxy_config;
148#[cfg(not(target_arch = "wasm32"))]
149pub mod llm;
150#[cfg(not(target_arch = "wasm32"))]
151pub mod admin;
152#[cfg(all(feature = "http2", not(target_arch = "wasm32")))]
154pub mod fleet;
155pub mod waf;
157#[cfg(not(target_arch = "wasm32"))]
159pub mod cluster;
160#[cfg(not(target_arch = "wasm32"))]
162pub mod fastcgi;
163#[cfg(not(target_arch = "wasm32"))]
165pub mod ctl;
166#[cfg(feature = "wasm-plugins")]
167pub mod wasm_plugin;
168#[cfg(not(target_arch = "wasm32"))]
169pub mod ingress;
170#[cfg(feature = "tera")]
171pub mod template;
172pub mod validate;
173pub mod virtual_host;
174#[cfg(any(feature = "model-sqlite", feature = "model-postgres", feature = "model-mysql"))]
175pub mod model;
176#[cfg(not(target_arch = "wasm32"))]
177pub mod websocket;
178pub mod http_client;
182#[cfg(feature = "crypto")]
183pub mod crypto;
184#[cfg(feature = "csrf")]
185pub mod csrf;
186#[cfg(feature = "sso")]
187pub mod sso;
188#[cfg(all(feature = "mailer", not(target_arch = "wasm32")))]
192pub mod mailer;
193#[cfg(feature = "jobs")]
194pub mod jobs;
195#[cfg(any(feature = "storage-local", feature = "storage-s3", feature = "storage-azure", feature = "storage-gcs", feature = "secrets"))]
198pub mod storage;
199#[cfg(feature = "openapi")]
200pub mod openapi;
201#[cfg(feature = "tower")]
202pub mod tower;
203#[cfg(feature = "gateway-api")]
204pub mod gateway_api;
205#[cfg(feature = "webhook")]
206pub mod webhook;
207#[cfg(feature = "secrets")]
208pub mod secrets;
209#[cfg(not(target_arch = "wasm32"))]
212pub mod timeout;
213pub mod prelude;
214
215#[cfg(feature = "http2")]
216#[doc(hidden)]
217pub mod tls;
218
219#[cfg(feature = "http2")]
220#[doc(hidden)]
221pub mod h2_server;
222
223#[cfg(feature = "http3")]
224#[doc(hidden)]
225pub mod h3_handler;
226
227#[cfg(test)]
234mod stack_depth_tests;
235
236#[cfg(all(any(feature = "http-client", feature = "http2"), not(target_arch = "wasm32")))]
240pub fn crypto_provider() -> rustls::crypto::CryptoProvider {
241 #[cfg(feature = "fips")]
242 return rustls::crypto::default_fips_provider();
243 #[cfg(not(feature = "fips"))]
244 rustls::crypto::aws_lc_rs::default_provider()
245}
246
247pub const FIPS: bool = cfg!(feature = "fips");
249
250#[cfg(all(any(feature = "http-client", feature = "http2"), not(target_arch = "wasm32")))]
257pub(crate) fn tls_client_builder() -> rustls::ConfigBuilder<rustls::ClientConfig, rustls::WantsVerifier> {
258 rustls::ClientConfig::builder_with_provider(std::sync::Arc::new(crate::crypto_provider()))
259 .with_safe_default_protocol_versions()
260 .expect("aws-lc-rs supports rustls's default protocol versions")
261}
262
263#[cfg(test)]
264pub mod test_env {
265 use std::sync::{Mutex, OnceLock};
266 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
267 pub fn lock() -> std::sync::MutexGuard<'static, ()> {
268 LOCK.get_or_init(|| Mutex::new(()))
269 .lock()
270 .unwrap_or_else(|e| e.into_inner())
271 }
272
273 pub struct TempPath(std::path::PathBuf);
277
278 impl TempPath {
279 pub fn new(name: &str) -> Self {
280 TempPath(std::env::temp_dir().join(format!("rws_test_{}_{}", std::process::id(), name)))
281 }
282
283 pub fn new_in_cwd(name: &str) -> Self {
286 TempPath(std::env::current_dir().expect("working directory").join(format!("rws_test_{}_{}", std::process::id(), name)))
287 }
288
289 pub fn as_str(&self) -> &str {
290 self.0.to_str().expect("temp dir path is UTF-8")
291 }
292 }
293
294 impl std::ops::Deref for TempPath {
295 type Target = std::path::Path;
296 fn deref(&self) -> &std::path::Path {
297 &self.0
298 }
299 }
300
301 impl Drop for TempPath {
302 fn drop(&mut self) {
303 let is_link = std::fs::symlink_metadata(&self.0).is_ok_and(|m| m.file_type().is_symlink());
306 if is_link {
307 let _ = std::fs::remove_file(&self.0);
308 } else if self.0.is_dir() {
309 let _ = std::fs::remove_dir_all(&self.0);
310 } else {
311 let _ = std::fs::remove_file(&self.0);
312 }
313 }
314 }
315}
316
317#[cfg(fuzzing)]
321#[doc(hidden)]
322pub mod fuzz_api {
323 pub fn proxy_normalize_target(data: &[u8]) {
326 let Ok(target) = std::str::from_utf8(data) else { return };
327 let once = crate::proxy_config::normalize_request_target(target).into_owned();
328 let twice = crate::proxy_config::normalize_request_target(&once).into_owned();
329 assert_eq!(once, twice, "normalization is not idempotent for {:?}", target);
330 }
331
332 pub fn static_path_decode(data: &[u8]) {
335 let Ok(path) = std::str::from_utf8(data) else { return };
336 if let Ok(fs_path) = crate::app::controller::static_resource::static_fs_path(path) {
337 let relative = &fs_path[crate::app::controller::static_resource::working_directory().len()..];
338 assert!(!relative.split(['/', '\\']).any(|segment| segment == ".."), "{:?} -> {:?}", path, fs_path);
339 }
340 }
341
342 pub fn openapi_to_mcp(data: &[u8]) {
345 let Ok(spec) = std::str::from_utf8(data) else { return };
346 let options = crate::mcp::openapi_tools::ToolOptions::default();
347 let Ok(found) = crate::mcp::openapi_tools::tools(spec, &options) else { return };
348 for tool in found {
349 assert!(crate::service_discovery::json_lite::parse(&tool.input_schema).is_ok());
350 assert!(tool.name.len() <= 64 && tool.name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-'), "{}", tool.name);
351 let _ = tool.request(r#"{"id":"1","body":{"a":[1,2]},"q":["x","y"]}"#);
352 }
353 }
354
355 pub fn a2a_request(data: &[u8]) {
358 use crate::application::Application;
359 thread_local! {
360 static AGENT: crate::a2a::A2aServer = crate::a2a::A2aServer::new(crate::a2a::AgentCard::new("fuzz", "fuzz", "1"))
361 .on_message(|ctx, message| match message.text().len() % 3 {
362 0 => crate::a2a::A2aReply::Message(crate::a2a::Message::agent_text(message.text())),
363 1 => crate::a2a::A2aReply::Task(ctx.input_required("more?")),
364 _ => crate::a2a::A2aReply::Task(ctx.complete(vec![crate::a2a::Artifact::text("a", message.text())])),
365 });
366 }
367 let request = crate::request::Request {
368 method: "POST".to_string(),
369 request_uri: "/a2a".to_string(),
370 http_version: "HTTP/1.1".to_string(),
371 headers: vec![crate::header::Header::new("A2A-Version", "1.0".to_string())],
372 body: data.to_vec().into(),
373 };
374 let connection = crate::server::ConnectionInfo::default();
375 let response = AGENT.with(|agent| agent.execute(&request, &connection)).expect("A2A never errs");
376 if response.status_code == 200 {
377 let body = String::from_utf8(response.content_range_list[0].body.clone()).expect("UTF-8");
378 assert!(crate::service_discovery::json_lite::parse(&body).is_ok(), "not JSON: {body}");
379 }
380 }
381
382 pub fn accept_language(data: &[u8]) {
386 let Ok(value) = std::str::from_utf8(data) else { return };
387 let preferences = crate::i18n::AcceptLanguage::parse(value);
388 assert!(preferences.0.len() <= crate::i18n::MAX_LANGUAGE_RANGES);
389 let available = ["en", "en-GB", "uk", "pt-BR"];
390 if let Some(chosen) = preferences.negotiate(&available) {
391 assert!(available.contains(&chosen));
392 }
393 }
394
395 pub fn i18n_catalog(data: &[u8]) {
398 let Ok(text) = std::str::from_utf8(data) else { return };
399 if let Ok(catalogs) = crate::i18n::Catalogs::new("en").add("en", text) {
400 let t = catalogs.for_language("en");
401 for line in text.lines() {
402 let key = line.split('=').next().unwrap_or("").trim();
403 let _ = t.t_with(key, &[("name", "x")]);
404 let _ = t.plural(key.trim_end_matches(".one").trim_end_matches(".other"), 3);
405 }
406 }
407 }
408
409 pub fn accept_encoding(data: &[u8]) {
413 let Ok(value) = std::str::from_utf8(data) else { return };
414 let request = crate::request::Request {
415 method: "GET".to_string(),
416 request_uri: "/".to_string(),
417 http_version: "HTTP/1.1".to_string(),
418 headers: vec![crate::header::Header::new(crate::header::Header::_ACCEPT_ENCODING, value.to_string())],
419 body: Default::default(),
420 };
421 for preference in [crate::compression::DYNAMIC_PREFERENCE, crate::compression::STATIC_PREFERENCE] {
422 if let Some(chosen) = crate::compression::negotiate(&request, preference) {
423 assert!(preference.contains(&chosen));
424 let refused = value.split(',').any(|c| {
426 let mut parts = c.split(';');
427 parts.next().unwrap_or("").trim().eq_ignore_ascii_case(chosen.token())
428 && parts
429 .map(str::trim)
430 .find(|p| p.as_bytes().get(..2).is_some_and(|b| b.eq_ignore_ascii_case(b"q=")))
431 .is_some_and(|q| q[2..].trim().parse::<f32>() == Ok(0.0))
432 });
433 let listed_once = value.split(',').filter(|c| c.split(';').next().unwrap_or("").trim().eq_ignore_ascii_case(chosen.token())).count() == 1;
434 assert!(!(refused && listed_once), "{value:?} refused {chosen:?}");
435 }
436 }
437 }
438
439 #[cfg(feature = "wasm-plugins")]
442 pub fn wasm_plugin_output(data: &[u8]) {
443 let _ = crate::wasm_plugin::parse_request_output(data);
444 let _ = crate::wasm_plugin::parse_response_output(data);
445 }
446
447 pub fn cache_entry(data: &[u8]) {
450 if let Some((_, _, _, offset)) = crate::cache::disk::parse_entry_header(data) {
451 let _ = crate::response::Response::parse_upstream(&data[offset..], crate::proxy::REGENERATED_OR_HOP_BY_HOP);
452 }
453 }
454
455 pub fn traffic_classify(data: &[u8]) {
458 let text = String::from_utf8_lossy(data);
459 let (ua, path) = text.split_once('\n').unwrap_or((&text, "/"));
460 let ip = std::net::IpAddr::from([data.first().copied().unwrap_or(1), 2, 3, 4]);
461 let class = crate::traffic::classify(ip, Some(ua), path);
462 let _ = (class.group(), class.kind.label());
463 }
464
465 pub fn authz_parse(data: &[u8]) {
468 let text = String::from_utf8_lossy(data);
469 let _ = crate::authz::Tuple::parse(&text);
470 let _ = crate::authz::Subject::parse(&text);
471 if let Ok(terms) = crate::authz::rebac::parse_expression(&text) {
472 let _ = terms.len();
473 let _ = crate::authz::Schema::new().relation("t", "r", &text).and_then(|s| s.validate());
474 }
475 }
476
477 pub fn available_dictionary(data: &[u8]) {
480 use crate::compression::dictionary::{decode, parse_available_dictionary, DictionaryEncoding};
481 let _ = parse_available_dictionary(&String::from_utf8_lossy(data));
482 for encoding in [DictionaryEncoding::Dcz, DictionaryEncoding::Dcb] {
483 let _ = decode(encoding, data, b"dictionary", 1 << 16);
484 }
485 }
486
487 pub fn llm_usage(data: &[u8]) {
491 for content_type in ["application/json", "text/event-stream"] {
492 let mut parser = crate::llm::UsageParser::new(content_type);
493 for piece in data.chunks(7) {
494 parser.feed(piece);
495 }
496 let _ = parser.finish();
497 }
498 let mut decoder = crate::llm::usage::ChunkDecoder::default();
499 let mut out = Vec::new();
500 let _ = decoder.decode(data, &mut out);
501 }
502
503 pub fn mcp_gateway_reply(data: &[u8]) {
506 for content_type in ["application/json", "text/event-stream"] {
507 if let Ok(result) = crate::mcp::gateway::parse_reply(content_type, data, 1) {
508 let _ = crate::mcp::gateway::fuzzing::tools(&result);
509 }
510 }
511 }
512
513 #[cfg(not(target_arch = "wasm32"))]
516 pub fn websocket_frame(data: &[u8]) {
517 let mut cursor = std::io::Cursor::new(data);
518 while let Ok(frame) = crate::websocket::WebSocket::read_frame_limited(&mut cursor, 4096) {
519 let len = match &frame {
520 crate::websocket::Frame::Text(t) => t.len(),
521 crate::websocket::Frame::Binary(b) | crate::websocket::Frame::Ping(b) | crate::websocket::Frame::Pong(b) => b.len(),
522 crate::websocket::Frame::Continuation { data, .. } => data.len(),
523 crate::websocket::Frame::Close(_, reason) => reason.len() + 2,
524 };
525 assert!(len <= 4096 + 2);
526 }
527 }
528
529 #[cfg(not(target_arch = "wasm32"))]
531 pub fn dns_srv_response(data: &[u8]) {
532 let id = data.get(..2).map_or(0, |b| u16::from_be_bytes([b[0], b[1]]));
533 let _ = crate::service_discovery::dns_srv::parse_response(data, id);
534 }
535
536 pub fn x509_subject_alt_names(data: &[u8]) {
541 let _ = crate::core::x509::subject_alt_names(data);
542 }
543
544 pub fn dns_message(data: &[u8]) {
545 if let Ok(message) = crate::dns::parse(data) {
546 for record in message.answers.iter().chain(&message.authority).chain(&message.additional) {
547 let _ = crate::dns::txt_value(&data[record.rdata.clone()]);
548 }
549 }
550 #[cfg(feature = "acme")]
551 let _ = crate::acme::dns01::check_update_reply(data, 0);
552 }
553
554 #[cfg(not(target_arch = "wasm32"))]
556 pub fn redis_reply(data: &[u8]) {
557 let _ = crate::redis_protocol::read_reply(&mut std::io::Cursor::new(data));
558 }
559
560 pub fn cookie_header(data: &[u8]) {
562 let Ok(value) = std::str::from_utf8(data) else { return };
563 let jar = crate::cookie::CookieJar::parse(value);
564 assert!(jar.cookies.iter().all(|c| !c.name.is_empty()));
565 }
566
567 #[cfg(not(target_arch = "wasm32"))]
570 pub fn otel_baggage(data: &[u8]) {
571 let Ok(value) = std::str::from_utf8(data) else { return };
572 let baggage = crate::otel::Baggage::parse(value);
573 assert!(baggage.len() <= crate::otel::baggage::MAX_MEMBERS);
574 let again = crate::otel::Baggage::parse(&baggage.to_header());
575 for (key, value) in baggage.iter() {
576 if let Some(round_tripped) = again.get(key) {
577 assert_eq!(value, round_tripped);
578 }
579 }
580 }
581
582 #[cfg(feature = "acme")]
586 pub fn acme_renewal(data: &[u8]) {
587 let _ = crate::acme::fuzzing::cert_info_from_der(data);
588 if let Ok(text) = std::str::from_utf8(data) {
589 let _ = crate::acme::fuzzing::parse_suggested_window(text);
590 let _ = crate::acme::fuzzing::parse_rfc3339(text);
591 let _ = crate::acme::fuzzing::json_object_keys(text, "profiles");
592 }
593 }
594
595 #[cfg(feature = "sso-saml")]
597 pub fn saml_xml_parse(xml: &str) {
598 let _ = crate::sso::saml::xml_parse_for_fuzzing(xml);
599 }
600
601 pub fn http1_framing(data: &[u8]) {
605 use crate::server::framing::{self, BodyFraming, ChunkedBody, HeadScan};
606 let mut pending = data.to_vec();
607 framing::skip_leading_empty_lines(&mut pending);
608 let HeadScan::Complete(head_len) = framing::scan_head(&pending) else { return };
609 assert!(head_len <= pending.len() && head_len <= framing::MAX_HEAD_SIZE);
610 let Ok(request) = crate::request::Request::parse(&pending[..head_len]) else { return };
611 for header in &request.headers {
612 let _ = crate::http::date::parse(&header.value);
613 }
614 let _ = framing::validate_head(&pending[..head_len], &request);
615 let _ = framing::keep_alive(&request);
616 let body = &pending[head_len..];
617 if let Ok(BodyFraming::Chunked) = framing::body_framing(&request) {
618 let split = data.first().map_or(0, |&b| b as usize).min(body.len());
619 let mut decoder = ChunkedBody::new(1 << 20);
620 let mut buffer = body[..split].to_vec();
621 for next in [&body[split..], &[][..]] {
622 match decoder.feed(&buffer) {
623 Ok((consumed, _)) => {
624 assert!(consumed <= buffer.len());
625 buffer.drain(..consumed);
626 }
627 Err(_) => return,
628 }
629 buffer.extend_from_slice(next);
630 }
631 assert!(decoder.body.len() <= 1 << 20);
632 }
633 }
634}
635
636
637#[cfg(all(doctest, feature = "http3"))]
639#[doc = include_str!("../README.md")]
640pub struct ReadmeDoctests;