Skip to main content

rust_web_server/
lib.rs

1//! # rust-web-server
2//!
3//! An HTTP/1.1, HTTP/2, and HTTP/3 (QUIC) server, reverse proxy, and
4//! application framework in one crate. HTTP/1.1 parsing, routing, middleware,
5//! JSON, WebSocket, and SSE are implemented in-crate; HTTP/2 and HTTP/3
6//! framing use the `h2` and `quinn`/`h3` crates, and TLS uses `rustls`.
7//!
8//! ## Use as a library
9//!
10//! Add to `Cargo.toml`:
11//!
12//! ```toml
13//! [dependencies]
14//! rust-web-server = "17"
15//! ```
16//!
17//! ## Quick start
18//!
19//! ```rust,no_run
20//! use rust_web_server::prelude::*;
21//!
22//! fn hello(_: &Request, _: &PathParams, _: &ConnectionInfo, _: &()) -> Response {
23//!     Response::text(STATUS_CODE_REASON_PHRASE.n200_ok, "Hello, world!")
24//! }
25//!
26//! fn main() {
27//!     let app = App::with_state(()).get("/hello", hello);
28//!     let (listener, pool) = Server::setup().unwrap();
29//!     Server::run(listener, pool, app);
30//! }
31//! ```
32//!
33//! See [DEVELOPER.md](https://github.com/bohdaq/rust-web-server/blob/main/DEVELOPER.md)
34//! for the full building blocks reference and use case examples.
35
36// Allows `::rust_web_server::…` paths to resolve from within this crate's own
37// tests, which is required by proc-macro derive output that uses that prefix.
38extern 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// Socket-coupled — see spec/WASM_SHIM.md for what a wasm32-wasip2 build
54// excludes and why (no OS threads, no raw TCP/TLS in a WASI guest).
55#[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;
64pub mod ip_filter;
65pub mod macros;
66pub mod blocklist;
67pub mod cache;
68pub mod early_hints;
69pub mod disk_guard;
70pub mod traffic;
71pub mod authz;
72pub mod config_reload;
73#[cfg(not(target_arch = "wasm32"))]
74pub mod config_watch;
75pub mod config_check;
76/// RSA public keys and RS256 / rsa-sha256 signature verification (no `rsa` crate).
77#[cfg(any(feature = "auth-asymmetric", feature = "sso"))]
78pub mod rsa_key;
79pub mod server_config;
80pub mod feature;
81pub mod maintenance;
82pub mod metrics;
83pub mod mcp;
84pub mod request_log;
85pub mod request_id;
86#[cfg(not(target_arch = "wasm32"))]
87pub mod otel;
88#[cfg(feature = "acme")]
89pub mod acme;
90pub mod middleware;
91pub mod rate_limit;
92pub mod router;
93pub mod schema;
94pub mod state;
95pub mod test_client;
96pub mod application;
97pub mod body;
98pub mod client_hint;
99pub mod controller;
100pub mod core;
101pub mod cors;
102pub mod entry_point;
103pub mod ext;
104pub mod header;
105pub mod http;
106pub mod json;
107pub mod language;
108#[cfg(not(target_arch = "wasm32"))]
109pub mod log;
110pub mod mime_type;
111pub mod null;
112pub mod range;
113pub mod request;
114pub mod response;
115pub mod server;
116pub mod symbol;
117#[cfg(not(target_arch = "wasm32"))]
118pub mod thread_pool;
119pub mod url;
120pub mod pagination;
121#[cfg(not(target_arch = "wasm32"))]
122pub mod proxy;
123pub mod rewrite;
124pub mod scheduler;
125#[cfg(not(target_arch = "wasm32"))]
126pub mod tcp_proxy;
127#[cfg(not(target_arch = "wasm32"))]
128pub mod udp_proxy;
129#[cfg(not(target_arch = "wasm32"))]
130pub mod ws_proxy;
131#[cfg(not(target_arch = "wasm32"))]
132pub mod canary;
133#[cfg(not(target_arch = "wasm32"))]
134pub mod circuit_breaker;
135// `BackendPool`/`DiscoverySource` (DNS/etcd/Consul/Docker) are native-only —
136// gated internally in service_discovery/mod.rs, not at this declaration —
137// because `json_lite` (a plain JSON parser, no sockets) must stay available
138// for `secrets`'s Vault/AWS-SM/Key-Vault backends on every target.
139pub mod service_discovery;
140/// DNS wire format, shared by the SRV service discovery and ACME's DNS-01.
141pub(crate) mod dns;
142pub mod config_binding;
143pub mod di;
144#[cfg(not(target_arch = "wasm32"))]
145pub mod proxy_config;
146#[cfg(not(target_arch = "wasm32"))]
147pub mod llm;
148#[cfg(not(target_arch = "wasm32"))]
149pub mod admin;
150#[cfg(feature = "wasm-plugins")]
151pub mod wasm_plugin;
152#[cfg(not(target_arch = "wasm32"))]
153pub mod ingress;
154#[cfg(feature = "tera")]
155pub mod template;
156pub mod validate;
157pub mod virtual_host;
158#[cfg(any(feature = "model-sqlite", feature = "model-postgres", feature = "model-mysql"))]
159pub mod model;
160#[cfg(not(target_arch = "wasm32"))]
161pub mod websocket;
162// Has both a native (TcpStream/rustls) and a wasm32 (wasi:http outgoing-handler)
163// backend behind Client::send() — see the #[cfg(target_arch = "wasm32")]
164// `send_once` in this module. spec/WASM_SHIM.md Phase 2 item 7.
165pub mod http_client;
166#[cfg(feature = "crypto")]
167pub mod crypto;
168#[cfg(feature = "csrf")]
169pub mod csrf;
170#[cfg(feature = "sso")]
171pub mod sso;
172// SMTP is a raw-TCP protocol with no wasi:http equivalent (unlike
173// http_client, which the host can proxy via outgoing-handler) — genuinely
174// can't work in a wasi:http guest, not just ungated. spec/WASM_SHIM.md.
175#[cfg(all(feature = "mailer", not(target_arch = "wasm32")))]
176pub mod mailer;
177#[cfg(feature = "jobs")]
178pub mod jobs;
179// Also compiled under `secrets` — `secrets::aws_secrets_manager`/`azure_key_vault`
180// reuse `StorageError` and the SigV4/Managed-Identity credential helpers from here.
181#[cfg(any(feature = "storage-local", feature = "storage-s3", feature = "storage-azure", feature = "storage-gcs", feature = "secrets"))]
182pub mod storage;
183#[cfg(feature = "openapi")]
184pub mod openapi;
185#[cfg(feature = "tower")]
186pub mod tower;
187#[cfg(feature = "gateway-api")]
188pub mod gateway_api;
189#[cfg(feature = "webhook")]
190pub mod webhook;
191#[cfg(feature = "secrets")]
192pub mod secrets;
193// Runs wrapped work on a background OS thread to bound wait time — needs
194// `std::thread::spawn`, unavailable on wasm32-wasip2. See spec/WASM_SHIM.md.
195#[cfg(not(target_arch = "wasm32"))]
196pub mod timeout;
197pub mod prelude;
198
199#[cfg(feature = "http2")]
200#[doc(hidden)]
201pub mod tls;
202
203#[cfg(feature = "http2")]
204#[doc(hidden)]
205pub mod h2_server;
206
207#[cfg(feature = "http3")]
208#[doc(hidden)]
209pub mod h3_handler;
210
211/// Shared infrastructure for tests that write process-wide environment variables.
212///
213/// Tests that call `override_environment_variables_from_config` or
214/// `CommandLineArgument::set_environment_variable` must hold this lock for
215/// their entire duration so they don't race with other tests reading the
216/// same variables.
217#[cfg(test)]
218mod stack_depth_tests;
219
220/// A rustls client-config builder with this crate's crypto provider
221/// (aws-lc-rs) named explicitly. `rustls::ClientConfig::builder()` uses the
222/// process-wide default provider and panics when none is installed and more
223/// than one is compiled in — which happens as soon as any dependency enables
224/// rustls's `ring` backend (e.g. sqlx). Every outbound TLS client in the
225/// crate starts here.
226#[cfg(all(any(feature = "http-client", feature = "http2"), not(target_arch = "wasm32")))]
227pub(crate) fn tls_client_builder() -> rustls::ConfigBuilder<rustls::ClientConfig, rustls::WantsVerifier> {
228    rustls::ClientConfig::builder_with_provider(std::sync::Arc::new(rustls::crypto::aws_lc_rs::default_provider()))
229        .with_safe_default_protocol_versions()
230        .expect("aws-lc-rs supports rustls's default protocol versions")
231}
232
233#[cfg(test)]
234pub mod test_env {
235    use std::sync::{Mutex, OnceLock};
236    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
237    pub fn lock() -> std::sync::MutexGuard<'static, ()> {
238        LOCK.get_or_init(|| Mutex::new(()))
239            .lock()
240            .unwrap_or_else(|e| e.into_inner())
241    }
242
243    /// A per-process path under the OS temp dir that is deleted (file or
244    /// directory) when dropped — so a test cleans up even when an assertion
245    /// fails before its last line.
246    pub struct TempPath(std::path::PathBuf);
247
248    impl TempPath {
249        pub fn new(name: &str) -> Self {
250            TempPath(std::env::temp_dir().join(format!("rws_test_{}_{}", std::process::id(), name)))
251        }
252
253        /// The same in the working directory (the static-file root), for
254        /// tests that need a file the server would serve.
255        pub fn new_in_cwd(name: &str) -> Self {
256            TempPath(std::env::current_dir().expect("working directory").join(format!("rws_test_{}_{}", std::process::id(), name)))
257        }
258
259        pub fn as_str(&self) -> &str {
260            self.0.to_str().expect("temp dir path is UTF-8")
261        }
262    }
263
264    impl std::ops::Deref for TempPath {
265        type Target = std::path::Path;
266        fn deref(&self) -> &std::path::Path {
267            &self.0
268        }
269    }
270
271    impl Drop for TempPath {
272        fn drop(&mut self) {
273            // A symlink is removed itself, never followed (a test may link
274            // to a system directory).
275            let is_link = std::fs::symlink_metadata(&self.0).is_ok_and(|m| m.file_type().is_symlink());
276            if is_link {
277                let _ = std::fs::remove_file(&self.0);
278            } else if self.0.is_dir() {
279                let _ = std::fs::remove_dir_all(&self.0);
280            } else {
281                let _ = std::fs::remove_file(&self.0);
282            }
283        }
284    }
285}
286
287/// Entry points for `fuzz/` targets that reach crate-private parsers.
288/// Compiled only under `--cfg fuzzing`, which `cargo fuzz` sets — never part
289/// of the public API.
290#[cfg(fuzzing)]
291#[doc(hidden)]
292pub mod fuzz_api {
293    /// Proxy route-matching normalization of a request target (#50): any
294    /// input, and normalizing twice changes nothing.
295    pub fn proxy_normalize_target(data: &[u8]) {
296        let Ok(target) = std::str::from_utf8(data) else { return };
297        let once = crate::proxy_config::normalize_request_target(target).into_owned();
298        let twice = crate::proxy_config::normalize_request_target(&once).into_owned();
299        assert_eq!(once, twice, "normalization is not idempotent for {:?}", target);
300    }
301
302    /// Static-file request-path decoding (#55). Must never panic; the
303    /// decoded path never carries a `..` segment past the web-root check.
304    pub fn static_path_decode(data: &[u8]) {
305        let Ok(path) = std::str::from_utf8(data) else { return };
306        if let Ok(fs_path) = crate::app::controller::static_resource::static_fs_path(path) {
307            let relative = &fs_path[crate::app::controller::static_resource::working_directory().len()..];
308            assert!(!relative.split(['/', '\\']).any(|segment| segment == ".."), "{:?} -> {:?}", path, fs_path);
309        }
310    }
311
312    /// OpenAPI documents to MCP tools (#66): any bytes. Must never panic;
313    /// every tool's schemas are JSON and its requests build or err cleanly.
314    pub fn openapi_to_mcp(data: &[u8]) {
315        let Ok(spec) = std::str::from_utf8(data) else { return };
316        let options = crate::mcp::openapi_tools::ToolOptions::default();
317        let Ok(found) = crate::mcp::openapi_tools::tools(spec, &options) else { return };
318        for tool in found {
319            assert!(crate::service_discovery::json_lite::parse(&tool.input_schema).is_ok());
320            assert!(tool.name.len() <= 64 && tool.name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-'), "{}", tool.name);
321            let _ = tool.request(r#"{"id":"1","body":{"a":[1,2]},"q":["x","y"]}"#);
322        }
323    }
324
325    /// An A2A JSON-RPC request body (#65): any bytes. Must never panic, and
326    /// the answer is always a JSON-RPC response (or a 413).
327    pub fn a2a_request(data: &[u8]) {
328        use crate::application::Application;
329        thread_local! {
330            static AGENT: crate::a2a::A2aServer = crate::a2a::A2aServer::new(crate::a2a::AgentCard::new("fuzz", "fuzz", "1"))
331                .on_message(|ctx, message| match message.text().len() % 3 {
332                    0 => crate::a2a::A2aReply::Message(crate::a2a::Message::agent_text(message.text())),
333                    1 => crate::a2a::A2aReply::Task(ctx.input_required("more?")),
334                    _ => crate::a2a::A2aReply::Task(ctx.complete(vec![crate::a2a::Artifact::text("a", message.text())])),
335                });
336        }
337        let request = crate::request::Request {
338            method: "POST".to_string(),
339            request_uri: "/a2a".to_string(),
340            http_version: "HTTP/1.1".to_string(),
341            headers: vec![crate::header::Header::new("A2A-Version", "1.0".to_string())],
342            body: data.to_vec().into(),
343        };
344        let connection = crate::server::ConnectionInfo::default();
345        let response = AGENT.with(|agent| agent.execute(&request, &connection)).expect("A2A never errs");
346        if response.status_code == 200 {
347            let body = String::from_utf8(response.content_range_list[0].body.clone()).expect("UTF-8");
348            assert!(crate::service_discovery::json_lite::parse(&body).is_ok(), "not JSON: {body}");
349        }
350    }
351
352    /// `Accept-Language` parsing and negotiation (#33): any header value;
353    /// at most `MAX_LANGUAGE_RANGES` ranges, and the language chosen is
354    /// always one of those offered.
355    pub fn accept_language(data: &[u8]) {
356        let Ok(value) = std::str::from_utf8(data) else { return };
357        let preferences = crate::i18n::AcceptLanguage::parse(value);
358        assert!(preferences.0.len() <= crate::i18n::MAX_LANGUAGE_RANGES);
359        let available = ["en", "en-GB", "uk", "pt-BR"];
360        if let Some(chosen) = preferences.negotiate(&available) {
361            assert!(available.contains(&chosen));
362        }
363    }
364
365    /// i18n catalog text (#33): any input; whatever parses translates
366    /// without panicking, plurals and placeholders included.
367    pub fn i18n_catalog(data: &[u8]) {
368        let Ok(text) = std::str::from_utf8(data) else { return };
369        if let Ok(catalogs) = crate::i18n::Catalogs::new("en").add("en", text) {
370            let t = catalogs.for_language("en");
371            for line in text.lines() {
372                let key = line.split('=').next().unwrap_or("").trim();
373                let _ = t.t_with(key, &[("name", "x")]);
374                let _ = t.plural(key.trim_end_matches(".one").trim_end_matches(".other"), 3);
375            }
376        }
377    }
378
379    /// `Accept-Encoding` negotiation (#7): any header value; the choice is
380    /// always one of the offered codings, and a coding the value refuses
381    /// (its first `q=` parameter is 0) is never chosen.
382    pub fn accept_encoding(data: &[u8]) {
383        let Ok(value) = std::str::from_utf8(data) else { return };
384        let request = crate::request::Request {
385            method: "GET".to_string(),
386            request_uri: "/".to_string(),
387            http_version: "HTTP/1.1".to_string(),
388            headers: vec![crate::header::Header::new(crate::header::Header::_ACCEPT_ENCODING, value.to_string())],
389            body: Default::default(),
390        };
391        for preference in [crate::compression::DYNAMIC_PREFERENCE, crate::compression::STATIC_PREFERENCE] {
392            if let Some(chosen) = crate::compression::negotiate(&request, preference) {
393                assert!(preference.contains(&chosen));
394                // Refused: the coding's first `q=` parameter is exactly 0.
395                let refused = value.split(',').any(|c| {
396                    let mut parts = c.split(';');
397                    parts.next().unwrap_or("").trim().eq_ignore_ascii_case(chosen.token())
398                        && parts
399                            .map(str::trim)
400                            .find(|p| p.as_bytes().get(..2).is_some_and(|b| b.eq_ignore_ascii_case(b"q=")))
401                            .is_some_and(|q| q[2..].trim().parse::<f32>() == Ok(0.0))
402                });
403                let listed_once = value.split(',').filter(|c| c.split(';').next().unwrap_or("").trim().eq_ignore_ascii_case(chosen.token())).count() == 1;
404                assert!(!(refused && listed_once), "{value:?} refused {chosen:?}");
405            }
406        }
407    }
408
409    /// What a WebAssembly plugin returns, as the host reads it (#40).
410    /// Must never panic.
411    #[cfg(feature = "wasm-plugins")]
412    pub fn wasm_plugin_output(data: &[u8]) {
413        let _ = crate::wasm_plugin::parse_request_output(data);
414        let _ = crate::wasm_plugin::parse_response_output(data);
415    }
416
417    /// A disk-cache entry file as the cache reads it back (#39): the header
418    /// line and key, then the stored response. Must never panic.
419    pub fn cache_entry(data: &[u8]) {
420        if let Some((_, _, _, offset)) = crate::cache::disk::parse_entry_header(data) {
421            let _ = crate::response::Response::parse_upstream(&data[offset..], crate::proxy::REGENERATED_OR_HOP_BY_HOP);
422        }
423    }
424
425    /// A request as the traffic classifier sees it: the first line is the
426    /// User-Agent, the rest the path; the address comes from the first byte.
427    pub fn traffic_classify(data: &[u8]) {
428        let text = String::from_utf8_lossy(data);
429        let (ua, path) = text.split_once('\n').unwrap_or((&text, "/"));
430        let ip = std::net::IpAddr::from([data.first().copied().unwrap_or(1), 2, 3, 4]);
431        let class = crate::traffic::classify(ip, Some(ua), path);
432        let _ = (class.group(), class.kind.label());
433    }
434
435    /// Authorization text as the admin API and config file read it (#32):
436    /// a tuple, a subject, and a relation definition.
437    pub fn authz_parse(data: &[u8]) {
438        let text = String::from_utf8_lossy(data);
439        let _ = crate::authz::Tuple::parse(&text);
440        let _ = crate::authz::Subject::parse(&text);
441        if let Ok(terms) = crate::authz::rebac::parse_expression(&text) {
442            let _ = terms.len();
443            let _ = crate::authz::Schema::new().relation("t", "r", &text).and_then(|s| s.validate());
444        }
445    }
446
447    /// An `Available-Dictionary` header value, and dictionary-compressed
448    /// bodies through both decoders (#38).
449    pub fn available_dictionary(data: &[u8]) {
450        use crate::compression::dictionary::{decode, parse_available_dictionary, DictionaryEncoding};
451        let _ = parse_available_dictionary(&String::from_utf8_lossy(data));
452        for encoding in [DictionaryEncoding::Dcz, DictionaryEncoding::Dcb] {
453            let _ = decode(encoding, data, b"dictionary", 1 << 16);
454        }
455    }
456
457    /// Provider responses as the LLM proxy reads them (#41): usage from a
458    /// JSON body or an event stream fed in pieces, and chunked framing.
459    /// Must never panic.
460    pub fn llm_usage(data: &[u8]) {
461        for content_type in ["application/json", "text/event-stream"] {
462            let mut parser = crate::llm::UsageParser::new(content_type);
463            for piece in data.chunks(7) {
464                parser.feed(piece);
465            }
466            let _ = parser.finish();
467        }
468        let mut decoder = crate::llm::usage::ChunkDecoder::default();
469        let mut out = Vec::new();
470        let _ = decoder.decode(data, &mut out);
471    }
472
473    /// An upstream MCP server's reply as the gateway reads it (#62): a JSON
474    /// body or an event stream, then the response's tools. Must never panic.
475    pub fn mcp_gateway_reply(data: &[u8]) {
476        for content_type in ["application/json", "text/event-stream"] {
477            if let Ok(result) = crate::mcp::gateway::parse_reply(content_type, data, 1) {
478                let _ = crate::mcp::gateway::fuzzing::tools(&result);
479            }
480        }
481    }
482
483    /// A WebSocket frame from a client (#8): any bytes; a frame never holds
484    /// more payload than the limit allows. Must never panic.
485    #[cfg(not(target_arch = "wasm32"))]
486    pub fn websocket_frame(data: &[u8]) {
487        let mut cursor = std::io::Cursor::new(data);
488        while let Ok(frame) = crate::websocket::WebSocket::read_frame_limited(&mut cursor, 4096) {
489            let len = match &frame {
490                crate::websocket::Frame::Text(t) => t.len(),
491                crate::websocket::Frame::Binary(b) | crate::websocket::Frame::Ping(b) | crate::websocket::Frame::Pong(b) => b.len(),
492                crate::websocket::Frame::Continuation { data, .. } => data.len(),
493                crate::websocket::Frame::Close(_, reason) => reason.len() + 2,
494            };
495            assert!(len <= 4096 + 2);
496        }
497    }
498
499    /// A DNS response read for SRV records (#8). Must never panic.
500    #[cfg(not(target_arch = "wasm32"))]
501    pub fn dns_srv_response(data: &[u8]) {
502        let id = data.get(..2).map_or(0, |b| u16::from_be_bytes([b[0], b[1]]));
503        let _ = crate::service_discovery::dns_srv::parse_response(data, id);
504    }
505
506    /// A DNS message: the shared parser (SRV discovery, ACME DNS-01), TXT
507    /// values and, with `acme`, a DNS UPDATE reply. Must never panic.
508    /// A certificate's subjectAltNames, as a BackendTLSPolicy checks a
509    /// backend's (untrusted) certificate. Must never panic.
510    pub fn x509_subject_alt_names(data: &[u8]) {
511        let _ = crate::core::x509::subject_alt_names(data);
512    }
513
514    pub fn dns_message(data: &[u8]) {
515        if let Ok(message) = crate::dns::parse(data) {
516            for record in message.answers.iter().chain(&message.authority).chain(&message.additional) {
517                let _ = crate::dns::txt_value(&data[record.rdata.clone()]);
518            }
519        }
520        #[cfg(feature = "acme")]
521        let _ = crate::acme::dns01::check_update_reply(data, 0);
522    }
523
524    /// A Redis (RESP) reply (#8). Must never panic.
525    #[cfg(not(target_arch = "wasm32"))]
526    pub fn redis_reply(data: &[u8]) {
527        let _ = crate::redis_protocol::read_reply(&mut std::io::Cursor::new(data));
528    }
529
530    /// A `Cookie` request header (#8): every parsed cookie has a name.
531    pub fn cookie_header(data: &[u8]) {
532        let Ok(value) = std::str::from_utf8(data) else { return };
533        let jar = crate::cookie::CookieJar::parse(value);
534        assert!(jar.cookies.iter().all(|c| !c.name.is_empty()));
535    }
536
537    /// A W3C `baggage` header (#25): members survive a round trip through
538    /// the header. Must never panic.
539    #[cfg(not(target_arch = "wasm32"))]
540    pub fn otel_baggage(data: &[u8]) {
541        let Ok(value) = std::str::from_utf8(data) else { return };
542        let baggage = crate::otel::Baggage::parse(value);
543        assert!(baggage.len() <= crate::otel::baggage::MAX_MEMBERS);
544        let again = crate::otel::Baggage::parse(&baggage.to_header());
545        for (key, value) in baggage.iter() {
546            if let Some(round_tripped) = again.get(key) {
547                assert_eq!(value, round_tripped);
548            }
549        }
550    }
551
552    /// What ACME renewal parses from the CA (#1): certificate DER (validity,
553    /// serial, Authority Key Identifier), renewalInfo windows (RFC 3339) and
554    /// directory profile names. Must never panic.
555    #[cfg(feature = "acme")]
556    pub fn acme_renewal(data: &[u8]) {
557        let _ = crate::acme::fuzzing::cert_info_from_der(data);
558        if let Ok(text) = std::str::from_utf8(data) {
559            let _ = crate::acme::fuzzing::parse_suggested_window(text);
560            let _ = crate::acme::fuzzing::parse_rfc3339(text);
561            let _ = crate::acme::fuzzing::json_object_keys(text, "profiles");
562        }
563    }
564
565    /// The SAML XML parser (`sso::saml::xml`), fed IdP-supplied documents.
566    #[cfg(feature = "sso-saml")]
567    pub fn saml_xml_parse(xml: &str) {
568        let _ = crate::sso::saml::xml_parse_for_fuzzing(xml);
569    }
570
571    /// HTTP/1.1 request framing (`server::framing`) over a raw connection
572    /// buffer: head detection, body framing, and the chunked body decoder,
573    /// fed in two pieces split at the first byte to mimic separate reads.
574    pub fn http1_framing(data: &[u8]) {
575        use crate::server::framing::{self, BodyFraming, ChunkedBody, HeadScan};
576        let mut pending = data.to_vec();
577        framing::skip_leading_empty_lines(&mut pending);
578        let HeadScan::Complete(head_len) = framing::scan_head(&pending) else { return };
579        assert!(head_len <= pending.len() && head_len <= framing::MAX_HEAD_SIZE);
580        let Ok(request) = crate::request::Request::parse(&pending[..head_len]) else { return };
581        for header in &request.headers {
582            let _ = crate::http::date::parse(&header.value);
583        }
584        let _ = framing::validate_head(&pending[..head_len], &request);
585        let _ = framing::keep_alive(&request);
586        let body = &pending[head_len..];
587        if let Ok(BodyFraming::Chunked) = framing::body_framing(&request) {
588            let split = data.first().map_or(0, |&b| b as usize).min(body.len());
589            let mut decoder = ChunkedBody::new(1 << 20);
590            let mut buffer = body[..split].to_vec();
591            for next in [&body[split..], &[][..]] {
592                match decoder.feed(&buffer) {
593                    Ok((consumed, _)) => {
594                        assert!(consumed <= buffer.len());
595                        buffer.drain(..consumed);
596                    }
597                    Err(_) => return,
598                }
599                buffer.extend_from_slice(next);
600            }
601            assert!(decoder.body.len() <= 1 << 20);
602        }
603    }
604}
605
606
607/// Compiles the README's Rust example as a doctest, so it can't drift from the API.
608#[cfg(all(doctest, feature = "http3"))]
609#[doc = include_str!("../README.md")]
610pub struct ReadmeDoctests;