Skip to main content

rust_web_server/header/
mod.rs

1//! HTTP header fields.
2//!
3//! A [`Header`] is a name and a value, both `Cow<'static, str>`: build the
4//! standard ones from the `Header::_X` name constants and `&'static str` values
5//! (borrowed, no allocation), other values from a `String` with
6//! [`Header::new`]. Read a field through deref (`&*h.value`). [`Header::parse`]
7//! turns a `Name: value` line into a `Header`; `generate` does the reverse.
8//!
9//! Header text must be UTF-8 without control characters. Examples:
10//! `src/header/example/`.
11
12use std::borrow::Cow;
13use crate::client_hint::ClientHint;
14use crate::cors::Cors;
15use crate::ext::date_time_ext::DateTimeExt;
16use crate::ext::string_ext::StringExt;
17use crate::range::Range;
18use crate::request::Request;
19use crate::symbol::SYMBOL;
20
21#[cfg(test)]
22mod tests;
23
24pub mod content_disposition;
25
26#[cfg(test)]
27mod example;
28
29/// An HTTP header name/value pair.
30///
31/// Use the associated string constants (e.g. [`Header::_CONTENT_TYPE`]) for header names.
32/// [`Header::get_header_list`] returns the standard set of response headers (client hints,
33/// CORS, cache control, security headers) that should be included on every response.
34///
35/// Name and value are `Cow<'static, str>` (18.0.0; `String` before): the
36/// built-in names and fixed values are borrowed `&'static str`s, so building
37/// and cloning the standard header set allocates nothing. Construct with
38/// [`Header::new`] (or `.into()` on each field); read through `Deref<Target =
39/// str>` (`&*header.value`, `header.value.trim()`, `header.value == "x"`).
40#[derive(PartialEq, Eq, Clone, Debug)]
41pub struct Header {
42    /// Header name, e.g. `"Content-Type"`.
43    pub name: Cow<'static, str>,
44    /// Header value, e.g. `"application/json"`.
45    pub value: Cow<'static, str>,
46}
47
48/// Headers every built-in response carries, around the per-request `Date`.
49struct FixedHeaders {
50    before_date: Vec<Header>,
51    after_date: Vec<Header>,
52}
53
54impl Header {
55
56    /// A header from anything that converts into `Cow<'static, str>`: a
57    /// `&'static str` (borrowed, no allocation) or a `String` (owned).
58    ///
59    /// ```
60    /// use rust_web_server::header::Header;
61    /// let h = Header::new(Header::_CONTENT_TYPE, format!("text/{}", "plain"));
62    /// assert_eq!("text/plain", h.value);
63    /// ```
64    pub fn new(name: impl Into<Cow<'static, str>>, value: impl Into<Cow<'static, str>>) -> Header {
65        Header { name: name.into(), value: value.into() }
66    }
67
68    /// A header name taken from a parsed message: borrowed when it is one
69    /// of the common names spelled exactly as listed (canonical or lower
70    /// case — the forms clients and servers actually send), owned otherwise.
71    /// Same text either way; it only saves the allocation.
72    pub(crate) fn name_from(name: &str) -> Cow<'static, str> {
73        const COMMON: &[&str] = &[
74            "Host", "host", "User-Agent", "user-agent", "Accept", "accept",
75            "Accept-Encoding", "accept-encoding", "Accept-Language", "accept-language",
76            "Connection", "connection", "Content-Type", "content-type",
77            "Content-Length", "content-length", "Date", "date", "Server", "server",
78            "Last-Modified", "last-modified", "ETag", "etag", "Accept-Ranges", "accept-ranges",
79            "Cache-Control", "cache-control", "Cookie", "cookie", "Set-Cookie", "set-cookie",
80            "Referer", "referer", "Origin", "origin", "Authorization", "authorization",
81            "If-None-Match", "if-none-match", "If-Modified-Since", "if-modified-since",
82            "Transfer-Encoding", "transfer-encoding", "Keep-Alive", "keep-alive",
83            "Vary", "vary", "Upgrade-Insecure-Requests", "upgrade-insecure-requests",
84            "X-Forwarded-For", "x-forwarded-for", "Via", "via",
85        ];
86        match COMMON.iter().find(|common| **common == name) {
87            Some(common) => Cow::Borrowed(common),
88            None => Cow::Owned(name.to_string()),
89        }
90    }
91
92    pub fn as_string(&self) -> String {
93        let formatted = format!("{}: {}", self.name, self.value);
94        formatted
95    }
96
97    pub const _ACCESS_CONTROL_REQUEST_METHOD: &'static str = "Access-Control-Request-Method";
98    pub const _ACCESS_CONTROL_REQUEST_HEADERS: &'static str = "Access-Control-Request-Headers";
99    pub const _ACCESS_CONTROL_ALLOW_ORIGIN: &'static str = "Access-Control-Allow-Origin";
100    pub const _ACCESS_CONTROL_ALLOW_METHODS: &'static str = "Access-Control-Allow-Methods";
101    pub const _ACCESS_CONTROL_ALLOW_HEADERS: &'static str = "Access-Control-Allow-Headers";
102    pub const _ACCESS_CONTROL_ALLOW_CREDENTIALS: &'static str = "Access-Control-Allow-Credentials";
103    pub const _ACCESS_CONTROL_MAX_AGE: &'static str = "Access-Control-Max-Age";
104    pub const _ACCESS_CONTROL_EXPOSE_HEADERS: &'static str = "Access-Control-Expose-Headers";
105
106    pub const _ACCEPT: &'static str = "Accept";
107    pub const _ACCEPT_RANGES: &'static str = "Accept-Ranges";
108    pub const _ACCEPT_CH: &'static str = "Accept-CH";
109    pub const _ACCEPT_ENCODING: &'static str = "Accept-Encoding";
110    pub const _ACCEPT_LANGUAGE: &'static str = "Accept-Language";
111    pub const _ACCEPT_PATCH: &'static str = "Accept-Patch";
112    pub const _ACCEPT_POST: &'static str = "Accept-Post";
113    pub const _AGE: &'static str = "Age";
114    pub const _ALLOW: &'static str = "Allow";
115    pub const _ALT_SVC: &'static str = "Alt-Svc";
116    pub const _AUTHORIZATION: &'static str = "Authorization";
117    pub const _CACHE_CONTROL: &'static str = "Cache-Control";
118    pub const _CONNECTION: &'static str = "Connection";
119    pub const _CLEAR_SITE_DATA: &'static str = "Clear-Site-Data";
120    pub const _CONTENT_TYPE: &'static str = "Content-Type";
121    pub const _CONTENT_LENGTH: &'static str = "Content-Length";
122    pub const _CONTENT_RANGE: &'static str = "Content-Range";
123    pub const _CONTENT_DISPOSITION: &'static str = "Content-Disposition";
124    pub const _CONTENT_ENCODING: &'static str = "Content-Encoding";
125    pub const _CONTENT_LANGUAGE: &'static str = "Content-Language";
126    pub const _CONTENT_LOCATION: &'static str = "Content-Location";
127    pub const _CONTENT_SECURITY_POLICY: &'static str = "Content-Security-Policy";
128    pub const _CONTENT_SECURITY_POLICY_REPORT_ONLY: &'static str = "Content-Security-Policy-Report-Only";
129    pub const _COOKIE: &'static str = "Cookie";
130    pub const _CROSS_ORIGIN_EMBEDDER_POLICY: &'static str = "Cross-Origin-Embedder-Policy";
131    pub const _CROSS_ORIGIN_OPENER_POLICY: &'static str = "Cross-Origin-Opener-Policy";
132    pub const _CROSS_ORIGIN_RESOURCE_POLICY: &'static str = "Cross-Origin-Resource-Policy";
133    pub const _DATE: &'static str = "Date";
134    pub const _DATE_UNIX_EPOCH_NANOS: &'static str = "Date-Unix-Epoch-Nanos";
135    pub const _DEVICE_MEMORY: &'static str = "Device-Memory";
136    pub const _DIGEST: &'static str = "Digest";
137    pub const _DOWNLINK: &'static str = "Downlink";
138    pub const _EARLY_DATA: &'static str = "Early-Data";
139    pub const _ECT: &'static str = "ECT";
140    pub const _ETAG: &'static str = "ETag";
141    pub const _EXPECT: &'static str = "Expect";
142    pub const _EXPIRES: &'static str = "Expires";
143    pub const _FEATURE_POLICY: &'static str = "Feature-Policy";
144    pub const _PERMISSIONS_POLICY: &'static str = "Permissions-Policy";
145    pub const _FORWARDED: &'static str = "Forwarded";
146    pub const _FROM: &'static str = "From";
147    pub const _HOST: &'static str = "Host";
148    pub const _IF_MATCH: &'static str = "If-Match";
149    pub const _IF_MODIFIED_SINCE: &'static str = "If-Modified-Since";
150    pub const _IF_NONE_MATCH: &'static str = "If-None-Match";
151    pub const _IF_RANGE: &'static str = "If-Range";
152    pub const _IF_UNMODIFIED_SINCE: &'static str = "If-Unmodified-Since";
153    pub const _LAST_MODIFIED: &'static str = "Last-Modified";
154    pub const _LAST_MODIFIED_UNIX_EPOCH_NANOS: &'static str = "Last-Modified-Unix-Epoch-Nanos";
155    pub const _LINK: &'static str = "Link";
156    pub const _LOCATION: &'static str = "Location";
157    pub const _MAX_FORWARDS: &'static str = "Max-Forwards";
158    pub const _NEL: &'static str = "NEL";
159    pub const _ORIGIN: &'static str = "Origin";
160    pub const _PROXY_AUTHENTICATE: &'static str = "Proxy-Authenticate";
161    pub const _PROXY_AUTHORIZATION: &'static str = "Proxy-Authorization";
162    pub const _RANGE: &'static str = "Range";
163    pub const _REFERER: &'static str = "Referer";
164    pub const _REFERRER_POLICY: &'static str = "Referrer-Policy";
165    pub const _RETRY_AFTER: &'static str = "Retry-After";
166    pub const _RTT: &'static str = "RTT";
167    pub const _SAVE_DATA: &'static str = "Save-Data";
168    pub const _SEC_CH_UA: &'static str = "Sec-CH-UA";
169    pub const _SEC_CH_UA_ARCH: &'static str = "Sec-CH-UA-Arch";
170    pub const _SEC_CH_UA_BITNESS: &'static str = "Sec-CH-UA-Bitness";
171    pub const _SEC_CH_UA_FULL_VERSION_LIST: &'static str = "Sec-CH-UA-Full-Version-List";
172    pub const _SEC_CH_UA_MOBILE: &'static str = "Sec-CH-UA-Mobile";
173    pub const _SEC_CH_UA_MODEL: &'static str = "Sec-CH-UA-Model";
174    pub const _SEC_CH_UA_PLATFORM: &'static str = "Sec-CH-UA-Platform";
175    pub const _SEC_CH_UA_PLATFORM_VERSION: &'static str = "Sec-CH-UA-Platform-Version";
176    pub const _SEC_FETCH_DEST: &'static str = "Sec-Fetch-Dest";
177    pub const _SEC_FETCH_MODE: &'static str = "Sec-Fetch-Mode";
178    pub const _SEC_FETCH_SITE: &'static str = "Sec-Fetch-Site";
179    pub const _SEC_FETCH_USER: &'static str = "Sec-Fetch-User";
180    pub const _SEC_GPC: &'static str = "Sec-GPC";
181    pub const _SERVER: &'static str = "Server";
182    pub const _SERVER_TIMING: &'static str = "Server-Timing";
183    pub const _SERVICE_WORKER_NAVIGATION_PRELOAD: &'static str = "Service-Worker-Navigation-Preload";
184    pub const _SET_COOKIE: &'static str = "Set-Cookie";
185    pub const _SOURCE_MAP: &'static str = "SourceMap";
186    pub const _STRICT_TRANSPORT_SECURITY: &'static str = "Strict-Transport-Security";
187    pub const _TE: &'static str = "TE";
188    pub const _TIMING_ALLOW_ORIGIN: &'static str = "Timing-Allow-Origin";
189    pub const _TRAILER: &'static str = "Trailer";
190    pub const _TRANSFER_ENCODING: &'static str = "Transfer-Encoding";
191    pub const _UPGRADE: &'static str = "Upgrade";
192    pub const _UPGRADE_INSECURE_REQUESTS: &'static str = "Upgrade-Insecure-Requests";
193    pub const _USER_AGENT: &'static str = "User-Agent";
194    pub const _VARY: &'static str = "Vary";
195    pub const _VIA: &'static str = "Via";
196    pub const _WANT_DIGEST: &'static str = "Want-Digest";
197    pub const _WWW_AUTHENTICATE: &'static str = "WWW-Authenticate";
198    pub const _X_CONTENT_TYPE_OPTIONS: &'static str = "X-Content-Type-Options";
199    pub const _X_CONTENT_TYPE_OPTIONS_VALUE_NOSNIFF: &'static str = "nosniff";
200    pub const _X_FRAME_OPTIONS: &'static str = "X-Frame-Options";
201    pub const _X_FRAME_OPTIONS_VALUE_DENY: &'static str = "DENY";
202    pub const _X_FRAME_OPTIONS_VALUE_SAME_ORIGIN: &'static str = "SAMEORIGIN";
203
204    pub const _STRICT_TRANSPORT_SECURITY_VALUE_DEFAULT: &'static str = "max-age=31536000; includeSubDomains";
205    pub const _REFERRER_POLICY_VALUE_DEFAULT: &'static str = "strict-origin-when-cross-origin";
206    pub const _PERMISSIONS_POLICY_VALUE_DEFAULT: &'static str = "geolocation=(), microphone=(), camera=()";
207    pub const _CONTENT_SECURITY_POLICY_VALUE_DEFAULT: &'static str = "default-src 'self'";
208
209
210
211
212    pub const NAME_VALUE_SEPARATOR: &'static str = ": ";
213
214    /// `s` safe to write on one header line: CR and LF become spaces
215    /// (borrowed when there are none). Every HTTP/1.1 writer passes header
216    /// names, values and the reason phrase through it, so a value carrying
217    /// user input (a redirect target, an upstream header) can't end the line
218    /// and inject headers or a second response (#47).
219    pub fn single_line(s: &str) -> std::borrow::Cow<'_, str> {
220        // A byte search: `contains(['\r', '\n'])` decoded every char, and
221        // this runs for every name and value of every response written.
222        if memchr::memchr2(b'\r', b'\n', s.as_bytes()).is_some() {
223            std::borrow::Cow::Owned(s.replace(['\r', '\n'], " "))
224        } else {
225            std::borrow::Cow::Borrowed(s)
226        }
227    }
228
229    pub const _DO_NOT_STORE_CACHE: &'static str = "no-store, no-cache, private, max-age=0, must-revalidate, proxy-revalidate";
230
231
232
233    /// Build the standard response header list using settings from
234    /// [`ServerConfig`].
235    ///
236    /// Prefer this method inside [`App::execute`] and any call-site that has
237    /// an `App`-level config available. It avoids reading environment variables
238    /// at request time, which enables proper test isolation via
239    /// [`App::with_config`].
240    pub fn get_header_list_with_config(
241        request: &Request,
242        config: &crate::server_config::ServerConfig,
243    ) -> Vec<Header> {
244        // CORS depends on the request and the date changes; everything else
245        // depends only on the CSP setting, so it's built once per CSP value
246        // and cloned (joining the client-hint and Vary lists per request was
247        // a measurable share of a small response's CPU).
248        let fixed = Header::fixed_headers(&config.csp, config.client_hints, config.security_headers);
249        let mut header_list = Cors::get_headers_from_config(request, config);
250        header_list.reserve(fixed.before_date.len() + 2 + fixed.after_date.len());
251        header_list.extend(fixed.before_date.iter().cloned());
252        header_list.push(Header { name: Header::_DATE.into(), value: crate::http::date::now().into() });
253        if config.nanos_headers {
254            header_list.push(Header::get_date_iso_8601_header());
255        }
256        header_list.extend(fixed.after_date.iter().cloned());
257        header_list
258    }
259
260    /// The request-independent part of [`Header::get_header_list_with_config`]
261    /// for a CSP value, client-hint and security-header setting, cached for
262    /// the last seen.
263    fn fixed_headers(csp: &str, client_hints: bool, security_headers: bool) -> std::sync::Arc<FixedHeaders> {
264        use std::sync::{Arc, RwLock};
265        static CACHE: RwLock<Option<(String, bool, bool, Arc<FixedHeaders>)>> = RwLock::new(None);
266        if let Some((cached_csp, cached_hints, cached_security, fixed)) = CACHE.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
267            if cached_csp == csp && *cached_hints == client_hints && *cached_security == security_headers {
268                return Arc::clone(fixed);
269            }
270        }
271        // Client hints are opt-in (RWS_CONFIG_CLIENT_HINTS): ~700 bytes on
272        // every response otherwise, and Critical-CH makes Chromium retry.
273        let mut before_date = Vec::with_capacity(6);
274        let vary = if client_hints {
275            before_date.push(ClientHint::get_accept_client_hints_header());
276            before_date.push(ClientHint::get_critical_client_hints_header());
277            [Cors::get_vary_header_value(), ClientHint::get_vary_header_value()].join(", ")
278        } else {
279            Cors::get_vary_header_value()
280        };
281        before_date.push(Header { name: Header::_VARY.into(), value: vary.into() });
282        before_date.push(Header::get_x_content_type_options_header());
283        before_date.push(Header::get_accept_ranges_header());
284        // Opt-in since 18.0.0 (RWS_CONFIG_SECURITY_HEADERS).
285        if security_headers {
286            before_date.push(Header::get_x_frame_options_header());
287        }
288        let mut after_date = vec![Header::get_no_cache_header()];
289        if security_headers {
290            after_date.push(Header { name: Header::_REFERRER_POLICY.into(), value: Header::_REFERRER_POLICY_VALUE_DEFAULT.into() });
291            after_date.push(Header { name: Header::_PERMISSIONS_POLICY.into(), value: Header::_PERMISSIONS_POLICY_VALUE_DEFAULT.into() });
292        }
293        if !csp.is_empty() {
294            after_date.push(Header { name: Header::_CONTENT_SECURITY_POLICY.into(), value: csp.to_string().into() });
295        }
296        // Borrowed values clone for free: everything here is per CSP value,
297        // not per request, so the built strings are interned for good.
298        let before_date = before_date.into_iter().map(Header::interned).collect();
299        let after_date = after_date.into_iter().map(Header::interned).collect();
300        let fixed = Arc::new(FixedHeaders { before_date, after_date });
301        *CACHE.write().unwrap_or_else(|e| e.into_inner()) = Some((csp.to_string(), client_hints, security_headers, Arc::clone(&fixed)));
302        fixed
303    }
304
305    /// `self` with an owned name or value turned into a `&'static str`
306    /// leaked once per distinct string (a process-wide set), so cloning it
307    /// never allocates. Only for values from a small, bounded set — the
308    /// fixed response headers, which change only with the CSP setting.
309    fn interned(self) -> Header {
310        fn intern(s: Cow<'static, str>) -> Cow<'static, str> {
311            use std::collections::HashSet;
312            use std::sync::{Mutex, OnceLock};
313            let owned = match s {
314                Cow::Borrowed(_) => return s,
315                Cow::Owned(owned) => owned,
316            };
317            static INTERNED: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
318            let mut set = INTERNED.get_or_init(|| Mutex::new(HashSet::new())).lock().unwrap_or_else(|e| e.into_inner());
319            if let Some(existing) = set.get(owned.as_str()) {
320                return Cow::Borrowed(existing);
321            }
322            let leaked: &'static str = Box::leak(owned.into_boxed_str());
323            set.insert(leaked);
324            Cow::Borrowed(leaked)
325        }
326        Header { name: intern(self.name), value: intern(self.value) }
327    }
328
329    /// Build the standard response header list, reading CORS and CSP settings
330    /// from environment variables.
331    ///
332    /// This is the legacy entry point retained for call-sites that do not yet
333    /// have access to a [`ServerConfig`] (e.g. error helpers in
334    /// `src/extract/mod.rs`). For all call-sites inside [`App::execute`] use
335    /// [`get_header_list_with_config`] instead.
336    pub fn get_header_list(request: &Request) -> Vec<Header> {
337        Self::get_header_list_with_config(request, &crate::server_config::ServerConfig::current())
338    }
339
340
341    pub fn get_x_content_type_options_header() -> Header {
342        Header {
343            name: Header::_X_CONTENT_TYPE_OPTIONS.into(),
344            value: Header::_X_CONTENT_TYPE_OPTIONS_VALUE_NOSNIFF.into(),
345        }
346    }
347
348    pub fn get_accept_ranges_header() -> Header {
349        Header {
350            name: Header::_ACCEPT_RANGES.into(),
351            value: Range::BYTES.into(),
352        }
353    }
354
355    pub fn get_x_frame_options_header() -> Header {
356        Header {
357            name: Header::_X_FRAME_OPTIONS.into(),
358            value: Header::_X_FRAME_OPTIONS_VALUE_SAME_ORIGIN.into(),
359        }
360    }
361
362    pub fn get_date_iso_8601_header() -> Header {
363        Header {
364            name: Header::_DATE_UNIX_EPOCH_NANOS.into(),
365            value: crate::ext::decimal::Decimal::new(DateTimeExt::_now_unix_epoch_nanos()).as_str().to_string().into(),
366        }
367    }
368
369    pub fn get_no_cache_header() -> Header {
370        Header {
371            name: Header::_CACHE_CONTROL.into(),
372            value: Header::_DO_NOT_STORE_CACHE.into(),
373        }
374    }
375
376    pub fn get_hsts_header() -> Header {
377        Header {
378            name: Header::_STRICT_TRANSPORT_SECURITY.into(),
379            value: Header::_STRICT_TRANSPORT_SECURITY_VALUE_DEFAULT.into(),
380        }
381    }
382
383    pub fn parse_header(raw_header: &str) -> Result<Header, String> {
384        let escaped_header = StringExt::filter_ascii_control_characters(raw_header);
385        let escaped_header = StringExt::truncate_new_line_carriage_return(&escaped_header);
386
387        let boxed_split = escaped_header.split_once(SYMBOL.colon);
388        if boxed_split.is_none() {
389            let message = format!("Unable to parse header: {}", escaped_header);
390            return Err(message)
391        }
392
393        let (name, value) = boxed_split.unwrap();
394
395        let header = Header {
396            name: name.trim().to_string().into(),
397            value: value.trim().to_string().into(),
398        };
399
400        Ok(header)
401    }
402
403    pub fn parse(raw_header: &str) -> Result<Header, String> {
404        Header::parse_header(raw_header)
405    }
406
407    pub fn generate(&self) -> String {
408        self.as_string()
409    }
410
411}
412