|
| 1 | +//! Parse and handle custom HTTP headers. |
| 2 | +//! |
| 3 | +//! Provides utilities for taking user-provided HTTP header strings |
| 4 | +//! (e.g. from the CLI or config files) and converting them into strongly |
| 5 | +//! typed `reqwest` headers. |
| 6 | +
|
| 7 | +use anyhow::{Error, Result, anyhow}; |
| 8 | +use clap::builder::TypedValueParser; |
| 9 | +use http::{ |
| 10 | + HeaderMap, |
| 11 | + header::{HeaderName, HeaderValue}, |
| 12 | +}; |
| 13 | +use std::{collections::HashMap, str::FromStr}; |
| 14 | + |
| 15 | +/// Parse a single header into a [`HeaderName`] and [`HeaderValue`] |
| 16 | +/// |
| 17 | +/// Headers are expected to be in format `Header-Name: Header-Value`. |
| 18 | +/// The header name and value are trimmed of whitespace. |
| 19 | +/// |
| 20 | +/// If the header contains multiple colons, the part after the first colon is |
| 21 | +/// considered the value. |
| 22 | +/// |
| 23 | +/// # Errors |
| 24 | +/// |
| 25 | +/// This fails if the header does not contain exactly one `:` character or |
| 26 | +/// if the header name contains non-ASCII characters. |
| 27 | +pub(crate) fn parse_single_header(header: &str) -> Result<(HeaderName, HeaderValue)> { |
| 28 | + let parts: Vec<&str> = header.splitn(2, ':').collect(); |
| 29 | + match parts.as_slice() { |
| 30 | + [name, value] => { |
| 31 | + let name = name.trim(); |
| 32 | + let name = HeaderName::from_str(name) |
| 33 | + .map_err(|e| anyhow!("Unable to convert header name '{name}': {e}"))?; |
| 34 | + let value = HeaderValue::from_str(value.trim()) |
| 35 | + .map_err(|e| anyhow!("Unable to read value of header with name '{name}': {e}"))?; |
| 36 | + Ok((name, value)) |
| 37 | + } |
| 38 | + _ => Err(anyhow!( |
| 39 | + "Invalid header format. Expected colon-separated string in the format 'HeaderName: HeaderValue'" |
| 40 | + )), |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +/// Parses a single HTTP header into a tuple of (String, String) |
| 45 | +/// |
| 46 | +/// This does NOT merge multiple headers into one. |
| 47 | +#[derive(Clone, Debug)] |
| 48 | +pub(crate) struct HeaderParser; |
| 49 | + |
| 50 | +impl TypedValueParser for HeaderParser { |
| 51 | + type Value = (String, String); |
| 52 | + |
| 53 | + fn parse_ref( |
| 54 | + &self, |
| 55 | + _cmd: &clap::Command, |
| 56 | + _arg: Option<&clap::Arg>, |
| 57 | + value: &std::ffi::OsStr, |
| 58 | + ) -> Result<Self::Value, clap::Error> { |
| 59 | + let header_str = value.to_str().ok_or_else(|| { |
| 60 | + clap::Error::raw( |
| 61 | + clap::error::ErrorKind::InvalidValue, |
| 62 | + "Header value contains invalid UTF-8", |
| 63 | + ) |
| 64 | + })?; |
| 65 | + |
| 66 | + match parse_single_header(header_str) { |
| 67 | + Ok((name, value)) => { |
| 68 | + let Ok(value) = value.to_str() else { |
| 69 | + return Err(clap::Error::raw( |
| 70 | + clap::error::ErrorKind::InvalidValue, |
| 71 | + "Header value contains invalid UTF-8", |
| 72 | + )); |
| 73 | + }; |
| 74 | + |
| 75 | + Ok((name.to_string(), value.to_string())) |
| 76 | + } |
| 77 | + Err(e) => Err(clap::Error::raw( |
| 78 | + clap::error::ErrorKind::InvalidValue, |
| 79 | + e.to_string(), |
| 80 | + )), |
| 81 | + } |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +impl clap::builder::ValueParserFactory for HeaderParser { |
| 86 | + type Parser = HeaderParser; |
| 87 | + fn value_parser() -> Self::Parser { |
| 88 | + HeaderParser |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +/// Extension trait for converting a map of header pairs to a `HeaderMap` |
| 93 | +pub(crate) trait HeaderMapExt { |
| 94 | + /// Convert a collection of header key-value pairs to a `HeaderMap` |
| 95 | + /// |
| 96 | + /// # Errors |
| 97 | + /// |
| 98 | + /// This fails if any header name or value cannot be parsed into a valid |
| 99 | + /// `HeaderName` or `HeaderValue` respectively. |
| 100 | + fn from_header_pairs(headers: &HashMap<String, String>) -> Result<HeaderMap, Error>; |
| 101 | +} |
| 102 | + |
| 103 | +impl HeaderMapExt for HeaderMap { |
| 104 | + fn from_header_pairs(headers: &HashMap<String, String>) -> Result<HeaderMap, Error> { |
| 105 | + let mut header_map = HeaderMap::new(); |
| 106 | + for (name, value) in headers { |
| 107 | + let header_name = HeaderName::from_bytes(name.as_bytes()) |
| 108 | + .map_err(|e| anyhow!("Invalid header name '{name}': {e}"))?; |
| 109 | + let header_value = HeaderValue::from_str(value) |
| 110 | + .map_err(|e| anyhow!("Invalid header value '{value}': {e}"))?; |
| 111 | + header_map.insert(header_name, header_value); |
| 112 | + } |
| 113 | + Ok(header_map) |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +#[cfg(test)] |
| 118 | +mod tests { |
| 119 | + use super::*; |
| 120 | + |
| 121 | + #[test] |
| 122 | + fn test_parse_custom_headers() { |
| 123 | + assert_eq!( |
| 124 | + parse_single_header("accept:text/html").unwrap(), |
| 125 | + ( |
| 126 | + HeaderName::from_static("accept"), |
| 127 | + HeaderValue::from_static("text/html") |
| 128 | + ) |
| 129 | + ); |
| 130 | + } |
| 131 | + |
| 132 | + #[test] |
| 133 | + fn test_parse_custom_header_multiple_colons() { |
| 134 | + assert_eq!( |
| 135 | + parse_single_header("key:x-test:check=this").unwrap(), |
| 136 | + ( |
| 137 | + HeaderName::from_static("key"), |
| 138 | + HeaderValue::from_static("x-test:check=this") |
| 139 | + ) |
| 140 | + ); |
| 141 | + } |
| 142 | + |
| 143 | + #[test] |
| 144 | + fn test_parse_custom_headers_with_equals() { |
| 145 | + assert_eq!( |
| 146 | + parse_single_header("key:x-test=check=this").unwrap(), |
| 147 | + ( |
| 148 | + HeaderName::from_static("key"), |
| 149 | + HeaderValue::from_static("x-test=check=this") |
| 150 | + ) |
| 151 | + ); |
| 152 | + } |
| 153 | + |
| 154 | + #[test] |
| 155 | + /// We should not reveal potentially sensitive data contained in the headers. |
| 156 | + /// See: [#1297](https://github.com/lycheeverse/lychee/issues/1297) |
| 157 | + fn test_does_not_echo_sensitive_data() { |
| 158 | + let error = parse_single_header("My-Header💣: secret") |
| 159 | + .expect_err("Should not allow unicode as key"); |
| 160 | + assert!(!error.to_string().contains("secret")); |
| 161 | + |
| 162 | + let error = parse_single_header("secret").expect_err("Should fail when no `:` given"); |
| 163 | + assert!(!error.to_string().contains("secret")); |
| 164 | + } |
| 165 | +} |
0 commit comments