1extern crate self as rust_web_server;
39
40pub use rws_server::app;
41#[cfg(feature = "auth")]
42pub use rws_server::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 use rws_server::async_state;
50#[cfg(feature = "http2")]
51pub(crate) use rws_server::async_bridge;
52pub use rws_server::session;
53#[cfg(not(target_arch = "wasm32"))]
56pub(crate) use rws_server::redis_protocol;
57pub use rws_server::sse;
58pub use rws_http::compression;
59pub use rws_server::cookie;
60pub use rws_http::error;
61pub use rws_http::extract;
62#[cfg(all(test, feature = "macros"))]
63mod extract_derive_tests;
64#[cfg(test)]
65mod http_tests;
66#[cfg(test)]
67mod server_tests;
68#[cfg(test)]
69mod feature_tests;
70pub mod i18n;
71pub use rws_proxy::a2a;
72#[cfg(all(unix, any(feature = "http1", feature = "http2")))]
73pub use rws_server::systemd;
74pub use rws_server::ip_filter;
75pub mod macros;
76pub use rws_server::blocklist;
77pub use rws_server::cache;
78pub use rws_server::early_hints;
79pub use rws_server::disk_guard;
80pub use rws_proxy::traffic;
81pub use rws_server::authz;
82pub use rws_server::config_reload;
83#[cfg(not(target_arch = "wasm32"))]
84pub use rws_server::config_watch;
85pub use rws_proxy::config_check;
86#[cfg(any(feature = "auth-asymmetric", feature = "sso"))]
88pub use rws_server::rsa_key;
89pub use rws_http::server_config;
90pub use rws_server::feature;
91pub use rws_server::maintenance;
92pub use rws_server::metrics;
93pub use rws_server::mcp;
94pub use rws_server::request_log;
95pub use rws_server::request_id;
96#[cfg(not(target_arch = "wasm32"))]
97pub use rws_server::otel;
98#[cfg(feature = "acme")]
99pub use rws_acme::acme;
100pub use rws_server::middleware;
101pub use rws_server::rate_limit;
102pub use rws_server::router;
103pub use rws_server::schema;
104pub use rws_server::state;
105pub use rws_server::test_client;
106pub use rws_server::application;
107pub use rws_http::body;
108pub use rws_http::client_hint;
109pub use rws_server::controller;
110pub use rws_base::core;
111pub use rws_http::cors;
112pub use rws_http::entry_point;
113pub use rws_base::ext;
114pub use rws_http::header;
115pub use rws_base::http;
116pub use rws_http::json;
117pub use rws_server::language;
118#[cfg(not(target_arch = "wasm32"))]
119pub use rws_server::log;
120pub use rws_base::mime_type;
121pub use rws_base::null;
122pub use rws_http::range;
123pub use rws_http::request;
124pub use rws_http::response;
125pub use rws_server::server;
126pub use rws_base::symbol;
127#[cfg(not(target_arch = "wasm32"))]
128pub use rws_server::thread_pool;
129pub use rws_base::url;
130pub use rws_server::pagination;
131#[cfg(not(target_arch = "wasm32"))]
132pub use rws_proxy::proxy;
133pub use rws_server::rewrite;
134pub use rws_server::scheduler;
135#[cfg(not(target_arch = "wasm32"))]
136pub use rws_proxy::tcp_proxy;
137#[cfg(not(target_arch = "wasm32"))]
138pub use rws_proxy::udp_proxy;
139#[cfg(not(target_arch = "wasm32"))]
140pub use rws_proxy::ws_proxy;
141#[cfg(not(target_arch = "wasm32"))]
142pub use rws_proxy::canary;
143#[cfg(not(target_arch = "wasm32"))]
144pub use rws_server::circuit_breaker;
145pub use rws_server::service_discovery;
150pub(crate) use rws_base::dns;
152pub use rws_server::config_binding;
153pub use rws_server::di;
154#[cfg(not(target_arch = "wasm32"))]
155pub use rws_proxy::proxy_config;
156#[cfg(not(target_arch = "wasm32"))]
157pub use rws_proxy::llm;
158#[cfg(not(target_arch = "wasm32"))]
159pub use rws_proxy::admin;
160#[cfg(all(feature = "http2", not(target_arch = "wasm32")))]
162pub use rws_proxy::fleet;
163pub use rws_proxy::waf;
165#[cfg(not(target_arch = "wasm32"))]
167pub use rws_proxy::cluster;
168#[cfg(not(target_arch = "wasm32"))]
170pub use rws_proxy::fastcgi;
171#[cfg(not(target_arch = "wasm32"))]
173pub mod ctl;
174#[cfg(feature = "wasm-plugins")]
175pub use rws_wasm_plugin::wasm_plugin;
176#[cfg(not(target_arch = "wasm32"))]
177pub use rws_proxy::ingress;
178#[cfg(feature = "tera")]
179pub mod template;
180pub use rws_server::validate;
181pub use rws_http::virtual_host;
182#[cfg(any(feature = "model-sqlite", feature = "model-postgres", feature = "model-mysql"))]
183pub use rws_server::model;
184#[cfg(not(target_arch = "wasm32"))]
185pub use rws_server::websocket;
186pub use rws_server::http_client;
190#[cfg(feature = "crypto")]
191pub use rws_server::crypto;
192#[cfg(feature = "csrf")]
193pub use rws_server::csrf;
194#[cfg(feature = "sso")]
195pub use rws_server::sso;
196#[cfg(all(feature = "mailer", not(target_arch = "wasm32")))]
200pub mod mailer;
201#[cfg(feature = "jobs")]
202pub mod jobs;
203#[cfg(any(feature = "storage-local", feature = "storage-s3", feature = "storage-azure", feature = "storage-gcs"))]
206pub use rws_storage::storage;
207#[cfg(all(feature = "secrets", not(any(feature = "storage-local", feature = "storage-s3", feature = "storage-azure", feature = "storage-gcs"))))]
209pub use rws_server::storage;
210#[cfg(feature = "openapi")]
211pub use rws_server::openapi;
212#[cfg(feature = "tower")]
213pub use rws_tower::tower;
214#[cfg(feature = "gateway-api")]
215pub use rws_gateway_api::gateway_api;
216#[cfg(feature = "webhook")]
217pub mod webhook;
218#[cfg(feature = "secrets")]
219pub use rws_server::secrets;
220#[cfg(not(target_arch = "wasm32"))]
223pub use rws_server::timeout;
224pub mod prelude;
225
226#[cfg(feature = "http2")]
227#[doc(hidden)]
228pub use rws_server::tls;
229
230#[cfg(feature = "http2")]
231#[doc(hidden)]
232pub use rws_server::h2_server;
233
234#[cfg(feature = "http3")]
235#[doc(hidden)]
236pub use rws_server::h3_handler;
237
238#[cfg(test)]
245mod stack_depth_tests;
246
247#[cfg(all(any(feature = "http-client", feature = "http2"), not(target_arch = "wasm32")))]
250pub use rws_server::crypto_provider;
251pub use rws_server::FIPS;
252#[cfg(all(any(feature = "http-client", feature = "http2"), not(target_arch = "wasm32")))]
253pub(crate) use rws_server::tls_client_builder;
254
255#[cfg(test)]
256pub mod test_env {
257 use std::sync::{Mutex, OnceLock};
258 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
259 pub fn lock() -> std::sync::MutexGuard<'static, ()> {
260 LOCK.get_or_init(|| Mutex::new(()))
261 .lock()
262 .unwrap_or_else(|e| e.into_inner())
263 }
264
265 pub struct TempPath(std::path::PathBuf);
269
270 impl TempPath {
271 pub fn new(name: &str) -> Self {
272 TempPath(std::env::temp_dir().join(format!("rws_test_{}_{}", std::process::id(), name)))
273 }
274
275 pub fn new_in_cwd(name: &str) -> Self {
278 TempPath(std::env::current_dir().expect("working directory").join(format!("rws_test_{}_{}", std::process::id(), name)))
279 }
280
281 pub fn as_str(&self) -> &str {
282 self.0.to_str().expect("temp dir path is UTF-8")
283 }
284 }
285
286 impl std::ops::Deref for TempPath {
287 type Target = std::path::Path;
288 fn deref(&self) -> &std::path::Path {
289 &self.0
290 }
291 }
292
293 impl Drop for TempPath {
294 fn drop(&mut self) {
295 let is_link = std::fs::symlink_metadata(&self.0).is_ok_and(|m| m.file_type().is_symlink());
298 if is_link {
299 let _ = std::fs::remove_file(&self.0);
300 } else if self.0.is_dir() {
301 let _ = std::fs::remove_dir_all(&self.0);
302 } else {
303 let _ = std::fs::remove_file(&self.0);
304 }
305 }
306 }
307}
308
309#[cfg(fuzzing)]
313#[doc(hidden)]
314pub mod fuzz_api {
315 #[cfg(all(feature = "http2", not(target_arch = "wasm32")))]
319 pub fn fleet_signature(data: &[u8]) {
320 let _ = crate::fleet::parse_signature(data);
321 let (body, sig) = data.split_at(data.len() / 2);
322 assert!(crate::fleet::verify(body, sig, &[7u8; 32]).is_err(), "a fuzzed signature verified");
323 }
324
325 pub fn base64_decode(data: &[u8]) {
328 use crate::core::base64::{Base64, Decoder};
329 for d in [Decoder::STANDARD, Decoder::URL_SAFE, Decoder::EITHER.skip_whitespace(), Decoder::EITHER.skip_invalid()] {
330 if let Ok(bytes) = d.decode(data) {
331 let again = Decoder::STANDARD.decode(Base64::encode(&bytes).unwrap()).unwrap();
332 assert_eq!(bytes, again, "base64 round trip changed the bytes");
333 }
334 }
335 }
336
337 #[cfg(feature = "pkcs11")]
339 pub fn pkcs11_uri(data: &[u8]) {
340 if let Ok(text) = std::str::from_utf8(data) {
341 let _ = crate::tls::pkcs11::Pkcs11Uri::parse(text);
342 let _ = crate::entry_point::shown("RWS_CONFIG_TLS_KEY_FILE", text);
343 }
344 }
345
346 pub fn proxy_normalize_target(data: &[u8]) {
349 let Ok(target) = std::str::from_utf8(data) else { return };
350 let once = crate::proxy_config::normalize_request_target(target).into_owned();
351 let twice = crate::proxy_config::normalize_request_target(&once).into_owned();
352 assert_eq!(once, twice, "normalization is not idempotent for {:?}", target);
353 }
354
355 pub fn static_path_decode(data: &[u8]) {
358 let Ok(path) = std::str::from_utf8(data) else { return };
359 if let Ok(fs_path) = crate::app::controller::static_resource::static_fs_path(path) {
360 let relative = &fs_path[crate::app::controller::static_resource::working_directory().len()..];
361 assert!(!relative.split(['/', '\\']).any(|segment| segment == ".."), "{:?} -> {:?}", path, fs_path);
362 }
363 }
364
365 pub fn openapi_to_mcp(data: &[u8]) {
368 let Ok(spec) = std::str::from_utf8(data) else { return };
369 let options = crate::mcp::openapi_tools::ToolOptions::default();
370 let Ok(found) = crate::mcp::openapi_tools::tools(spec, &options) else { return };
371 for tool in found {
372 assert!(crate::service_discovery::json_lite::parse(&tool.input_schema).is_ok());
373 assert!(tool.name.len() <= 64 && tool.name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-'), "{}", tool.name);
374 let _ = tool.request(r#"{"id":"1","body":{"a":[1,2]},"q":["x","y"]}"#);
375 }
376 }
377
378 pub fn a2a_request(data: &[u8]) {
381 use crate::application::Application;
382 thread_local! {
383 static AGENT: crate::a2a::A2aServer = crate::a2a::A2aServer::new(crate::a2a::AgentCard::new("fuzz", "fuzz", "1"))
384 .on_message(|ctx, message| match message.text().len() % 3 {
385 0 => crate::a2a::A2aReply::Message(crate::a2a::Message::agent_text(message.text())),
386 1 => crate::a2a::A2aReply::Task(ctx.input_required("more?")),
387 _ => crate::a2a::A2aReply::Task(ctx.complete(vec![crate::a2a::Artifact::text("a", message.text())])),
388 });
389 }
390 let request = crate::request::Request {
391 method: "POST".to_string(),
392 request_uri: "/a2a".to_string(),
393 http_version: "HTTP/1.1".to_string(),
394 headers: vec![crate::header::Header::new("A2A-Version", "1.0".to_string())],
395 body: data.to_vec().into(),
396 };
397 let connection = crate::server::ConnectionInfo::default();
398 let response = AGENT.with(|agent| agent.execute(&request, &connection)).expect("A2A never errs");
399 if response.status_code == 200 {
400 let body = String::from_utf8(response.content_range_list[0].body.clone()).expect("UTF-8");
401 assert!(crate::service_discovery::json_lite::parse(&body).is_ok(), "not JSON: {body}");
402 }
403 }
404
405 pub fn accept_language(data: &[u8]) {
409 let Ok(value) = std::str::from_utf8(data) else { return };
410 let preferences = crate::i18n::AcceptLanguage::parse(value);
411 assert!(preferences.0.len() <= crate::i18n::MAX_LANGUAGE_RANGES);
412 let available = ["en", "en-GB", "uk", "pt-BR"];
413 if let Some(chosen) = preferences.negotiate(&available) {
414 assert!(available.contains(&chosen));
415 }
416 }
417
418 pub fn i18n_catalog(data: &[u8]) {
421 let Ok(text) = std::str::from_utf8(data) else { return };
422 if let Ok(catalogs) = crate::i18n::Catalogs::new("en").add("en", text) {
423 let t = catalogs.for_language("en");
424 for line in text.lines() {
425 let key = line.split('=').next().unwrap_or("").trim();
426 let _ = t.t_with(key, &[("name", "x")]);
427 let _ = t.plural(key.trim_end_matches(".one").trim_end_matches(".other"), 3);
428 }
429 }
430 }
431
432 pub fn accept_encoding(data: &[u8]) {
436 let Ok(value) = std::str::from_utf8(data) else { return };
437 let request = crate::request::Request {
438 method: "GET".to_string(),
439 request_uri: "/".to_string(),
440 http_version: "HTTP/1.1".to_string(),
441 headers: vec![crate::header::Header::new(crate::header::Header::_ACCEPT_ENCODING, value.to_string())],
442 body: Default::default(),
443 };
444 for preference in [crate::compression::DYNAMIC_PREFERENCE, crate::compression::STATIC_PREFERENCE] {
445 if let Some(chosen) = crate::compression::negotiate(&request, preference) {
446 assert!(preference.contains(&chosen));
447 let refused = value.split(',').any(|c| {
449 let mut parts = c.split(';');
450 parts.next().unwrap_or("").trim().eq_ignore_ascii_case(chosen.token())
451 && parts
452 .map(str::trim)
453 .find(|p| p.as_bytes().get(..2).is_some_and(|b| b.eq_ignore_ascii_case(b"q=")))
454 .is_some_and(|q| q[2..].trim().parse::<f32>() == Ok(0.0))
455 });
456 let listed_once = value.split(',').filter(|c| c.split(';').next().unwrap_or("").trim().eq_ignore_ascii_case(chosen.token())).count() == 1;
457 assert!(!(refused && listed_once), "{value:?} refused {chosen:?}");
458 }
459 }
460 }
461
462 #[cfg(feature = "wasm-plugins")]
465 pub fn wasm_plugin_output(data: &[u8]) {
466 let _ = crate::wasm_plugin::parse_request_output(data);
467 let _ = crate::wasm_plugin::parse_response_output(data);
468 }
469
470 pub fn cache_entry(data: &[u8]) {
473 if let Some((_, _, _, offset)) = crate::cache::disk::parse_entry_header(data) {
474 let _ = crate::response::Response::parse_upstream(&data[offset..], crate::response::REGENERATED_OR_HOP_BY_HOP);
475 }
476 }
477
478 pub fn traffic_classify(data: &[u8]) {
481 let text = String::from_utf8_lossy(data);
482 let (ua, path) = text.split_once('\n').unwrap_or((&text, "/"));
483 let ip = std::net::IpAddr::from([data.first().copied().unwrap_or(1), 2, 3, 4]);
484 let class = crate::traffic::classify(ip, Some(ua), path);
485 let _ = (class.group(), class.kind.label());
486 }
487
488 pub fn authz_parse(data: &[u8]) {
491 let text = String::from_utf8_lossy(data);
492 let _ = crate::authz::Tuple::parse(&text);
493 let _ = crate::authz::Subject::parse(&text);
494 if let Ok(terms) = crate::authz::rebac::parse_expression(&text) {
495 let _ = terms.len();
496 let _ = crate::authz::Schema::new().relation("t", "r", &text).and_then(|s| s.validate());
497 }
498 }
499
500 pub fn available_dictionary(data: &[u8]) {
503 use crate::compression::dictionary::{decode, parse_available_dictionary, DictionaryEncoding};
504 let _ = parse_available_dictionary(&String::from_utf8_lossy(data));
505 for encoding in [DictionaryEncoding::Dcz, DictionaryEncoding::Dcb] {
506 let _ = decode(encoding, data, b"dictionary", 1 << 16);
507 }
508 }
509
510 pub fn llm_usage(data: &[u8]) {
514 for content_type in ["application/json", "text/event-stream"] {
515 let mut parser = crate::llm::UsageParser::new(content_type);
516 for piece in data.chunks(7) {
517 parser.feed(piece);
518 }
519 let _ = parser.finish();
520 }
521 let mut decoder = crate::llm::usage::ChunkDecoder::default();
522 let mut out = Vec::new();
523 let _ = decoder.decode(data, &mut out);
524 }
525
526 pub fn mcp_gateway_reply(data: &[u8]) {
529 for content_type in ["application/json", "text/event-stream"] {
530 if let Ok(result) = crate::mcp::gateway::parse_reply(content_type, data, 1) {
531 let _ = crate::mcp::gateway::fuzzing::tools(&result);
532 }
533 }
534 }
535
536 #[cfg(not(target_arch = "wasm32"))]
539 pub fn websocket_frame(data: &[u8]) {
540 let mut cursor = std::io::Cursor::new(data);
541 while let Ok(frame) = crate::websocket::WebSocket::read_frame_limited(&mut cursor, 4096) {
542 let len = match &frame {
543 crate::websocket::Frame::Text(t) => t.len(),
544 crate::websocket::Frame::Binary(b) | crate::websocket::Frame::Ping(b) | crate::websocket::Frame::Pong(b) => b.len(),
545 crate::websocket::Frame::Continuation { data, .. } => data.len(),
546 crate::websocket::Frame::Close(_, reason) => reason.len() + 2,
547 };
548 assert!(len <= 4096 + 2);
549 }
550 }
551
552 #[cfg(not(target_arch = "wasm32"))]
554 pub fn dns_srv_response(data: &[u8]) {
555 let id = data.get(..2).map_or(0, |b| u16::from_be_bytes([b[0], b[1]]));
556 let _ = crate::service_discovery::dns_srv::parse_response(data, id);
557 }
558
559 pub fn x509_subject_alt_names(data: &[u8]) {
564 let _ = crate::core::x509::subject_alt_names(data);
565 }
566
567 pub fn dns_message(data: &[u8]) {
568 if let Ok(message) = crate::dns::parse(data) {
569 for record in message.answers.iter().chain(&message.authority).chain(&message.additional) {
570 let _ = crate::dns::txt_value(&data[record.rdata.clone()]);
571 }
572 }
573 #[cfg(feature = "acme")]
574 let _ = crate::acme::dns01::check_update_reply(data, 0);
575 }
576
577 #[cfg(not(target_arch = "wasm32"))]
579 pub fn redis_reply(data: &[u8]) {
580 let _ = crate::redis_protocol::read_reply(&mut std::io::Cursor::new(data));
581 }
582
583 pub fn cookie_header(data: &[u8]) {
585 let Ok(value) = std::str::from_utf8(data) else { return };
586 let jar = crate::cookie::CookieJar::parse(value);
587 assert!(jar.cookies.iter().all(|c| !c.name.is_empty()));
588 }
589
590 #[cfg(not(target_arch = "wasm32"))]
593 pub fn otel_baggage(data: &[u8]) {
594 let Ok(value) = std::str::from_utf8(data) else { return };
595 let baggage = crate::otel::Baggage::parse(value);
596 assert!(baggage.len() <= crate::otel::baggage::MAX_MEMBERS);
597 let again = crate::otel::Baggage::parse(&baggage.to_header());
598 for (key, value) in baggage.iter() {
599 if let Some(round_tripped) = again.get(key) {
600 assert_eq!(value, round_tripped);
601 }
602 }
603 }
604
605 #[cfg(feature = "acme")]
609 pub fn acme_renewal(data: &[u8]) {
610 let _ = crate::acme::fuzzing::cert_info_from_der(data);
611 if let Ok(text) = std::str::from_utf8(data) {
612 let _ = crate::acme::fuzzing::parse_suggested_window(text);
613 let _ = crate::acme::fuzzing::parse_rfc3339(text);
614 let _ = crate::acme::fuzzing::json_object_keys(text, "profiles");
615 }
616 }
617
618 #[cfg(feature = "sso-saml")]
620 pub fn saml_xml_parse(xml: &str) {
621 let _ = crate::sso::saml::xml_parse_for_fuzzing(xml);
622 }
623
624 pub fn http1_framing(data: &[u8]) {
628 use crate::server::framing::{self, BodyFraming, ChunkedBody, HeadScan};
629 let mut pending = data.to_vec();
630 framing::skip_leading_empty_lines(&mut pending);
631 let HeadScan::Complete(head_len) = framing::scan_head(&pending) else { return };
632 assert!(head_len <= pending.len() && head_len <= framing::MAX_HEAD_SIZE);
633 let Ok(request) = crate::request::Request::parse(&pending[..head_len]) else { return };
634 for header in &request.headers {
635 let _ = crate::http::date::parse(&header.value);
636 }
637 let _ = framing::validate_head(&pending[..head_len], &request);
638 let _ = framing::keep_alive(&request);
639 let body = &pending[head_len..];
640 if let Ok(BodyFraming::Chunked) = framing::body_framing(&request) {
641 let split = data.first().map_or(0, |&b| b as usize).min(body.len());
642 let mut decoder = ChunkedBody::new(1 << 20);
643 let mut buffer = body[..split].to_vec();
644 for next in [&body[split..], &[][..]] {
645 match decoder.feed(&buffer) {
646 Ok((consumed, _)) => {
647 assert!(consumed <= buffer.len());
648 buffer.drain(..consumed);
649 }
650 Err(_) => return,
651 }
652 buffer.extend_from_slice(next);
653 }
654 assert!(decoder.body.len() <= 1 << 20);
655 }
656 }
657}
658
659
660#[cfg(all(doctest, feature = "http3"))]
662#[doc = include_str!("../README.md")]
663pub struct ReadmeDoctests;