use std::borrow::Cow;
use std::fmt;
use std::str::Utf8Error;
use http::HeaderValue;
use http::header::ToStrError;
use percent_encoding::{
AsciiSet, CONTROLS, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode,
};
const HEADER_ESCAPE: &AsciiSet = &CONTROLS.add(b'%');
const EXT_VALUE_ESCAPE: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'!')
.remove(b'#')
.remove(b'$')
.remove(b'&')
.remove(b'+')
.remove(b'-')
.remove(b'.')
.remove(b'^')
.remove(b'_')
.remove(b'`')
.remove(b'|')
.remove(b'~');
pub fn encode_header_value(value: &str) -> HeaderValue {
HeaderValue::from_str(&encode_header_str(value))
.expect("escaped value is always a valid header value")
}
pub fn encode_header_str(value: &str) -> Cow<'_, str> {
utf8_percent_encode(value, HEADER_ESCAPE).into()
}
#[derive(Debug, thiserror::Error)]
pub enum DecodeError {
#[error("header value is not visible ASCII")]
NotAscii(#[from] ToStrError),
#[error("header value is not valid percent-encoded UTF-8")]
InvalidUtf8(#[from] Utf8Error),
}
pub fn decode_header_value(value: &HeaderValue) -> Result<String, DecodeError> {
Ok(decode_header_str(value.to_str()?)?)
}
pub fn decode_header_str(value: &str) -> Result<String, Utf8Error> {
Ok(percent_decode_str(value).decode_utf8()?.into_owned())
}
#[derive(Debug)]
pub struct ExtValue<'a>(pub &'a str);
impl fmt::Display for ExtValue<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("UTF-8''")?;
fmt::Display::fmt(&utf8_percent_encode(self.0, EXT_VALUE_ESCAPE), f)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encodes_non_ascii() {
assert_eq!(
encode_header_value("réport-📄.pdf"),
"r%C3%A9port-%F0%9F%93%84.pdf",
);
}
#[test]
fn encodes_percent() {
assert_eq!(encode_header_value("100% done"), "100%25 done");
}
#[test]
fn encodes_control_characters() {
assert_eq!(encode_header_value("a\r\nb\tc\x7f"), "a%0D%0Ab%09c%7F");
}
#[test]
fn encodes_to_a_borrowed_str_when_unchanged() {
std::assert_matches!(encode_header_str("report.pdf"), Cow::Borrowed(_));
std::assert_matches!(encode_header_str("réport.pdf"), Cow::Owned(_));
}
#[test]
fn leaves_visible_ascii_alone() {
let value = r#"has"quote path/to.txt!$&'()*+,;=:@?<>[]{}|^`~#"#;
assert_eq!(encode_header_value(value), value);
}
#[test]
fn roundtrips() {
for value in [
"réport-📄.pdf",
"100% done",
"50%.pdf",
"plain.txt",
"a\r\nb",
"",
] {
let encoded = encode_header_str(value);
assert!(encoded.is_ascii(), "{encoded} is not ascii");
assert_eq!(decode_header_str(&encoded).unwrap(), value);
assert_eq!(
decode_header_value(&encode_header_value(value)).unwrap(),
value,
);
}
}
#[test]
fn decodes_aggressively_escaped_values() {
assert_eq!(decode_header_str("%6B%65%79%2D%31").unwrap(), "key-1");
}
#[test]
fn decode_rejects_invalid_utf8() {
let header = HeaderValue::from_static("%FF.pdf");
std::assert_matches!(
decode_header_value(&header),
Err(DecodeError::InvalidUtf8(_)),
);
assert!(decode_header_str("%FF.pdf").is_err());
}
#[test]
fn decode_rejects_raw_non_ascii() {
let header = HeaderValue::from_bytes("réport.pdf".as_bytes()).unwrap();
std::assert_matches!(decode_header_value(&header), Err(DecodeError::NotAscii(_)),);
}
#[test]
fn ext_value_escapes_reserved_characters() {
assert_eq!(
ExtValue("réport 📄.pdf").to_string(),
"UTF-8''r%C3%A9port%20%F0%9F%93%84.pdf",
);
assert_eq!(ExtValue("a\"b;c").to_string(), "UTF-8''a%22b%3Bc");
}
}