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        if s.contains(['\r', '\n']) {
221            std::borrow::Cow::Owned(s.replace(['\r', '\n'], " "))
222        } else {
223            std::borrow::Cow::Borrowed(s)
224        }
225    }
226
227    pub const _DO_NOT_STORE_CACHE: &'static str = "no-store, no-cache, private, max-age=0, must-revalidate, proxy-revalidate";
228
229
230
231    /// Build the standard response header list using settings from
232    /// [`ServerConfig`].
233    ///
234    /// Prefer this method inside [`App::execute`] and any call-site that has
235    /// an `App`-level config available. It avoids reading environment variables
236    /// at request time, which enables proper test isolation via
237    /// [`App::with_config`].
238    pub fn get_header_list_with_config(
239        request: &Request,
240        config: &crate::server_config::ServerConfig,
241    ) -> Vec<Header> {
242        // CORS depends on the request and the date changes; everything else
243        // depends only on the CSP setting, so it's built once per CSP value
244        // and cloned (joining the client-hint and Vary lists per request was
245        // a measurable share of a small response's CPU).
246        let fixed = Header::fixed_headers(&config.csp, config.client_hints, config.security_headers);
247        let mut header_list = Cors::get_headers_from_config(request, config);
248        header_list.reserve(fixed.before_date.len() + 2 + fixed.after_date.len());
249        header_list.extend(fixed.before_date.iter().cloned());
250        header_list.push(Header { name: Header::_DATE.into(), value: crate::http::date::now().into() });
251        if config.nanos_headers {
252            header_list.push(Header::get_date_iso_8601_header());
253        }
254        header_list.extend(fixed.after_date.iter().cloned());
255        header_list
256    }
257
258    /// The request-independent part of [`Header::get_header_list_with_config`]
259    /// for a CSP value, client-hint and security-header setting, cached for
260    /// the last seen.
261    fn fixed_headers(csp: &str, client_hints: bool, security_headers: bool) -> std::sync::Arc<FixedHeaders> {
262        use std::sync::{Arc, RwLock};
263        static CACHE: RwLock<Option<(String, bool, bool, Arc<FixedHeaders>)>> = RwLock::new(None);
264        if let Some((cached_csp, cached_hints, cached_security, fixed)) = CACHE.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
265            if cached_csp == csp && *cached_hints == client_hints && *cached_security == security_headers {
266                return Arc::clone(fixed);
267            }
268        }
269        // Client hints are opt-in (RWS_CONFIG_CLIENT_HINTS): ~700 bytes on
270        // every response otherwise, and Critical-CH makes Chromium retry.
271        let mut before_date = Vec::with_capacity(6);
272        let vary = if client_hints {
273            before_date.push(ClientHint::get_accept_client_hints_header());
274            before_date.push(ClientHint::get_critical_client_hints_header());
275            [Cors::get_vary_header_value(), ClientHint::get_vary_header_value()].join(", ")
276        } else {
277            Cors::get_vary_header_value()
278        };
279        before_date.push(Header { name: Header::_VARY.into(), value: vary.into() });
280        before_date.push(Header::get_x_content_type_options_header());
281        before_date.push(Header::get_accept_ranges_header());
282        // Opt-in since 18.0.0 (RWS_CONFIG_SECURITY_HEADERS).
283        if security_headers {
284            before_date.push(Header::get_x_frame_options_header());
285        }
286        let mut after_date = vec![Header::get_no_cache_header()];
287        if security_headers {
288            after_date.push(Header { name: Header::_REFERRER_POLICY.into(), value: Header::_REFERRER_POLICY_VALUE_DEFAULT.into() });
289            after_date.push(Header { name: Header::_PERMISSIONS_POLICY.into(), value: Header::_PERMISSIONS_POLICY_VALUE_DEFAULT.into() });
290        }
291        if !csp.is_empty() {
292            after_date.push(Header { name: Header::_CONTENT_SECURITY_POLICY.into(), value: csp.to_string().into() });
293        }
294        // Borrowed values clone for free: everything here is per CSP value,
295        // not per request, so the built strings are interned for good.
296        let before_date = before_date.into_iter().map(Header::interned).collect();
297        let after_date = after_date.into_iter().map(Header::interned).collect();
298        let fixed = Arc::new(FixedHeaders { before_date, after_date });
299        *CACHE.write().unwrap_or_else(|e| e.into_inner()) = Some((csp.to_string(), client_hints, security_headers, Arc::clone(&fixed)));
300        fixed
301    }
302
303    /// `self` with an owned name or value turned into a `&'static str`
304    /// leaked once per distinct string (a process-wide set), so cloning it
305    /// never allocates. Only for values from a small, bounded set — the
306    /// fixed response headers, which change only with the CSP setting.
307    fn interned(self) -> Header {
308        fn intern(s: Cow<'static, str>) -> Cow<'static, str> {
309            use std::collections::HashSet;
310            use std::sync::{Mutex, OnceLock};
311            let owned = match s {
312                Cow::Borrowed(_) => return s,
313                Cow::Owned(owned) => owned,
314            };
315            static INTERNED: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
316            let mut set = INTERNED.get_or_init(|| Mutex::new(HashSet::new())).lock().unwrap_or_else(|e| e.into_inner());
317            if let Some(existing) = set.get(owned.as_str()) {
318                return Cow::Borrowed(existing);
319            }
320            let leaked: &'static str = Box::leak(owned.into_boxed_str());
321            set.insert(leaked);
322            Cow::Borrowed(leaked)
323        }
324        Header { name: intern(self.name), value: intern(self.value) }
325    }
326
327    /// Build the standard response header list, reading CORS and CSP settings
328    /// from environment variables.
329    ///
330    /// This is the legacy entry point retained for call-sites that do not yet
331    /// have access to a [`ServerConfig`] (e.g. error helpers in
332    /// `src/extract/mod.rs`). For all call-sites inside [`App::execute`] use
333    /// [`get_header_list_with_config`] instead.
334    pub fn get_header_list(request: &Request) -> Vec<Header> {
335        Self::get_header_list_with_config(request, &crate::server_config::ServerConfig::current())
336    }
337
338
339    pub fn get_x_content_type_options_header() -> Header {
340        Header {
341            name: Header::_X_CONTENT_TYPE_OPTIONS.into(),
342            value: Header::_X_CONTENT_TYPE_OPTIONS_VALUE_NOSNIFF.into(),
343        }
344    }
345
346    pub fn get_accept_ranges_header() -> Header {
347        Header {
348            name: Header::_ACCEPT_RANGES.into(),
349            value: Range::BYTES.into(),
350        }
351    }
352
353    pub fn get_x_frame_options_header() -> Header {
354        Header {
355            name: Header::_X_FRAME_OPTIONS.into(),
356            value: Header::_X_FRAME_OPTIONS_VALUE_SAME_ORIGIN.into(),
357        }
358    }
359
360    pub fn get_date_iso_8601_header() -> Header {
361        Header {
362            name: Header::_DATE_UNIX_EPOCH_NANOS.into(),
363            value: crate::ext::decimal::Decimal::new(DateTimeExt::_now_unix_epoch_nanos()).as_str().to_string().into(),
364        }
365    }
366
367    pub fn get_no_cache_header() -> Header {
368        Header {
369            name: Header::_CACHE_CONTROL.into(),
370            value: Header::_DO_NOT_STORE_CACHE.into(),
371        }
372    }
373
374    pub fn get_hsts_header() -> Header {
375        Header {
376            name: Header::_STRICT_TRANSPORT_SECURITY.into(),
377            value: Header::_STRICT_TRANSPORT_SECURITY_VALUE_DEFAULT.into(),
378        }
379    }
380
381    pub fn parse_header(raw_header: &str) -> Result<Header, String> {
382        let escaped_header = StringExt::filter_ascii_control_characters(raw_header);
383        let escaped_header = StringExt::truncate_new_line_carriage_return(&escaped_header);
384
385        let boxed_split = escaped_header.split_once(SYMBOL.colon);
386        if boxed_split.is_none() {
387            let message = format!("Unable to parse header: {}", escaped_header);
388            return Err(message)
389        }
390
391        let (name, value) = boxed_split.unwrap();
392
393        let header = Header {
394            name: name.trim().to_string().into(),
395            value: value.trim().to_string().into(),
396        };
397
398        Ok(header)
399    }
400
401    pub fn parse(raw_header: &str) -> Result<Header, String> {
402        Header::parse_header(raw_header)
403    }
404
405    pub fn generate(&self) -> String {
406        self.as_string()
407    }
408
409}
410