actix_web_lab/
header.rs

1//! Experimental typed headers.
2
3use std::{fmt, str::FromStr};
4
5use actix_http::{error::ParseError, header::HeaderValue};
6
7#[cfg(test)]
8pub(crate) use self::header_test_helpers::{assert_parse_eq, assert_parse_fail};
9pub use crate::{
10    cache_control::{CacheControl, CacheDirective},
11    clear_site_data::{ClearSiteData, ClearSiteDataDirective},
12    content_length::ContentLength,
13    forwarded::Forwarded,
14    strict_transport_security::StrictTransportSecurity,
15    x_forwarded_prefix::{X_FORWARDED_PREFIX, XForwardedPrefix},
16};
17
18/// Parses a group of comma-delimited quoted-string headers.
19///
20/// Notes that `T`'s [`FromStr`] implementation SHOULD NOT try to strip leading or trailing quotes
21/// when parsing (or try to enforce them), since the quoted-string grammar itself enforces them and
22/// so this function checks for their existence, and strips them before passing to [`FromStr`].
23#[inline]
24pub(crate) fn from_comma_delimited_quoted_strings<'a, I, T>(all: I) -> Result<Vec<T>, ParseError>
25where
26    I: Iterator<Item = &'a HeaderValue> + 'a,
27    T: FromStr,
28{
29    let size_guess = all.size_hint().1.unwrap_or(2);
30    let mut result = Vec::with_capacity(size_guess);
31
32    for hdr in all {
33        let hdr_str = hdr.to_str().map_err(|_| ParseError::Header)?;
34
35        for part in hdr_str.split(',').filter_map(|x| match x.trim() {
36            "" => None,
37            y => Some(y),
38        }) {
39            if let Ok(part) = part
40                .strip_prefix('"')
41                .and_then(|part| part.strip_suffix('"'))
42                // reject headers which are not properly quoted-string formatted
43                .ok_or(ParseError::Header)?
44                .parse()
45            {
46                result.push(part);
47            }
48        }
49    }
50
51    Ok(result)
52}
53
54/// Formats a list of headers into a comma-delimited quoted-string string.
55#[inline]
56pub(crate) fn fmt_comma_delimited_quoted_strings<'a, I, T>(
57    f: &mut fmt::Formatter<'_>,
58    mut parts: I,
59) -> fmt::Result
60where
61    I: Iterator<Item = &'a T> + 'a,
62    T: 'a + fmt::Display,
63{
64    let Some(part) = parts.next() else {
65        return Ok(());
66    };
67
68    write!(f, "\"{part}\"")?;
69
70    for part in parts {
71        write!(f, ", \"{part}\"")?;
72    }
73
74    Ok(())
75}
76
77#[cfg(test)]
78mod header_test_helpers {
79    use std::fmt;
80
81    use actix_http::header::Header;
82    use actix_web::{HttpRequest, test};
83
84    fn req_from_raw_headers<H: Header, I: IntoIterator<Item = V>, V: AsRef<[u8]>>(
85        header_lines: I,
86    ) -> HttpRequest {
87        header_lines
88            .into_iter()
89            .fold(test::TestRequest::default(), |req, item| {
90                req.append_header((H::name(), item.as_ref().to_vec()))
91            })
92            .to_http_request()
93    }
94
95    #[track_caller]
96    pub(crate) fn assert_parse_eq<
97        H: Header + fmt::Debug + PartialEq,
98        I: IntoIterator<Item = V>,
99        V: AsRef<[u8]>,
100    >(
101        headers: I,
102        expect: H,
103    ) {
104        let req = req_from_raw_headers::<H, _, _>(headers);
105        assert_eq!(H::parse(&req).unwrap(), expect);
106    }
107
108    #[track_caller]
109    pub(crate) fn assert_parse_fail<
110        H: Header + fmt::Debug,
111        I: IntoIterator<Item = V>,
112        V: AsRef<[u8]>,
113    >(
114        headers: I,
115    ) {
116        let req = req_from_raw_headers::<H, _, _>(headers);
117        H::parse(&req).unwrap_err();
118    }
119}