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