use indexmap::IndexMap;
use std::hash::BuildHasher;
#[must_use]
pub fn collect_request_headers<SH: BuildHasher + Default>(
headers: &hyper::HeaderMap,
name: impl Fn(&str) -> String,
) -> IndexMap<String, Vec<String>, SH> {
let mut out: IndexMap<String, Vec<String>, SH> =
IndexMap::with_capacity_and_hasher(headers.keys_len(), SH::default());
let mut dropped: Vec<String> = Vec::new();
for (header_name, value) in headers {
match std::str::from_utf8(value.as_bytes()) {
Ok(text) => {
out.entry(name(header_name.as_str()))
.or_default()
.push(text.to_string());
}
Err(_) => {
let dropped_name = name(header_name.as_str());
if !dropped.contains(&dropped_name) {
dropped.push(dropped_name);
}
}
}
}
if !dropped.is_empty() {
tracing::warn!(
headers = %dropped.join(", "),
"dropping non-UTF-8 request header value(s); they are invisible to matching, forwarding, and recording"
);
}
out
}
#[must_use]
pub(crate) fn collect_response_headers(headers: &hyper::HeaderMap) -> Vec<(String, String)> {
let mut out = Vec::with_capacity(headers.len());
let mut dropped: Vec<String> = Vec::new();
for (name, value) in headers {
match std::str::from_utf8(value.as_bytes()) {
Ok(text) => out.push((name.to_string(), text.to_string())),
Err(_) => {
let name = name.to_string();
if !dropped.contains(&name) {
dropped.push(name);
}
}
}
}
if !dropped.is_empty() {
tracing::warn!(
headers = %dropped.join(", "),
"dropping non-UTF-8 upstream response header value(s); they are invisible to the client and the recorded stub"
);
}
out
}
#[derive(Debug, Clone, Copy)]
pub struct StubRef<'a> {
pub port: u16,
pub index: usize,
pub id: Option<&'a str>,
}
#[must_use]
pub(crate) fn sanitize_header_value(value: &str, stub: StubRef<'_>) -> String {
let mut sanitized = String::with_capacity(value.len());
let mut removed: Vec<char> = Vec::new();
for c in value.chars() {
if c == '\t' || !c.is_ascii_control() {
sanitized.push(c);
} else if !removed.contains(&c) {
removed.push(c);
}
}
if !removed.is_empty() {
tracing::warn!(
target: "rift::template",
port = stub.port,
stub = stub.index,
stub_id = stub.id.unwrap_or(""),
value = ?crate::imposter::response::truncate_with_ellipsis(value, 256),
removed = ?removed,
"removed characters a header value cannot carry from a templated header value; a CR or LF here would have terminated the header line (header injection)"
);
}
debug_assert!(
hyper::header::HeaderValue::from_str(&sanitized).is_ok(),
"the filter above *is* the `HeaderValue` validity rule, so what survives it is always \
representable; a failure here means the two have drifted apart"
);
sanitized
}
#[cfg(test)]
mod tests {
use super::*;
use hyper::header::HeaderValue;
fn title_case(name: &str) -> String {
crate::behaviors::header_to_title_case(name)
}
#[test]
fn collector_keeps_the_order_names_were_sent() {
let mut headers = hyper::HeaderMap::new();
for (name, value) in [
("zulu", "1"),
("alpha", "2"),
("mike", "3"),
("alpha", "4"),
("bravo", "5"),
] {
headers.append(name, HeaderValue::from_static(value));
}
let collected: crate::util::OrderedMap<String, Vec<String>> =
collect_request_headers(&headers, title_case);
let entries: Vec<(&str, Vec<&str>)> = collected
.iter()
.map(|(k, v)| (k.as_str(), v.iter().map(String::as_str).collect()))
.collect();
assert_eq!(
entries,
[
("Zulu", vec!["1"]),
("Alpha", vec!["2", "4"]),
("Mike", vec!["3"]),
("Bravo", vec!["5"]),
]
);
}
#[test]
fn collector_keeps_every_value_in_send_order() {
let mut headers = hyper::HeaderMap::new();
headers.append("x-test", HeaderValue::from_static("first"));
headers.append("x-test", HeaderValue::from_static("second"));
headers.insert("content-type", HeaderValue::from_static("application/json"));
let collected: crate::util::OrderedMap<String, Vec<String>> =
collect_request_headers(&headers, title_case);
assert_eq!(
collected.get("X-Test").map(Vec::as_slice),
Some(["first".to_string(), "second".to_string()].as_slice()),
"both values, in the order the client sent them"
);
assert_eq!(
collected.get("Content-Type").map(Vec::as_slice),
Some(["application/json".to_string()].as_slice()),
"a single-valued header is a one-element list, not a special case"
);
}
#[test]
#[tracing_test::traced_test]
fn collector_keeps_valid_non_ascii_utf8_and_does_not_warn_about_it() {
let disposition = r#"attachment; filename="résumé.pdf""#;
let mut headers = hyper::HeaderMap::new();
headers.insert(
"content-disposition",
HeaderValue::from_bytes(disposition.as_bytes()).expect("obs-text is a legal value"),
);
headers.insert(
"x-user-name",
HeaderValue::from_bytes("José".as_bytes()).unwrap(),
);
let collected: crate::util::OrderedMap<String, Vec<String>> =
collect_request_headers(&headers, title_case);
assert_eq!(
collected.get("Content-Disposition").map(Vec::as_slice),
Some([disposition.to_string()].as_slice()),
"valid UTF-8 beyond ASCII must survive byte-exact"
);
assert_eq!(
collected.get("X-User-Name").map(Vec::as_slice),
Some(["José".to_string()].as_slice())
);
assert!(
!logs_contain("dropping non-UTF-8 request header value"),
"nothing was dropped, so nothing may be warned about — the old code warned that a \
valid UTF-8 value was not UTF-8"
);
let collected_value = &collected["Content-Disposition"][0];
assert!(
HeaderValue::from_str(collected_value).is_ok(),
"the serving side must accept back exactly what the collector produced"
);
}
#[test]
#[tracing_test::traced_test]
fn collector_names_a_repeatedly_undecodable_header_once() {
let bad = HeaderValue::from_bytes(&[0xFF, 0xFE]).unwrap();
let mut headers = hyper::HeaderMap::new();
headers.append("x-bin", bad.clone());
headers.append("x-bin", bad);
let collected: crate::util::OrderedMap<String, Vec<String>> =
collect_request_headers(&headers, title_case);
assert!(!collected.contains_key("X-Bin"));
logs_assert(|lines: &[&str]| {
let named = lines
.iter()
.filter(|l| l.contains("dropping non-UTF-8 request header value"))
.map(|l| l.matches("X-Bin").count())
.sum::<usize>();
if named == 1 {
Ok(())
} else {
Err(format!(
"expected the name once in the warning, saw it {named} times"
))
}
});
}
#[test]
#[tracing_test::traced_test]
fn collector_drops_non_utf8_values_and_omits_a_name_left_with_none() {
let non_utf8 =
HeaderValue::from_bytes(&[0xFF, 0xFE]).expect("a legal but non-UTF-8 header value");
let mut headers = hyper::HeaderMap::new();
headers.insert("x-bin", non_utf8.clone());
headers.append("x-mixed", HeaderValue::from_static("readable"));
headers.append("x-mixed", non_utf8);
let collected: crate::util::OrderedMap<String, Vec<String>> =
collect_request_headers(&headers, title_case);
assert!(
!collected.contains_key("X-Bin"),
"a name whose only value is non-UTF-8 is ABSENT, not present-with-an-empty-value — \
otherwise `exists` is true and `equals \"\"` matches bytes the client never sent"
);
assert_eq!(
collected.get("X-Mixed").map(Vec::as_slice),
Some(["readable".to_string()].as_slice()),
"the readable value of a partly-undecodable name survives, alone"
);
assert!(
logs_contain("dropping non-UTF-8 request header value"),
"a dropped value must be warned, not silently discarded"
);
assert!(
logs_contain("X-Bin") && logs_contain("X-Mixed"),
"the warning must name every header it dropped a value from, or an operator cannot \
tell which of a request's headers went missing"
);
}
#[test]
fn collector_applies_the_callers_name_function() {
let mut headers = hyper::HeaderMap::new();
headers.insert("x-my-header", HeaderValue::from_static("v"));
let titled: crate::util::OrderedMap<String, Vec<String>> =
collect_request_headers(&headers, title_case);
assert!(titled.contains_key("X-My-Header"), "imposter shape");
let identity: crate::util::OrderedMap<String, Vec<String>> =
collect_request_headers(&headers, str::to_string);
assert!(identity.contains_key("x-my-header"), "intercept shape");
}
#[test]
fn flow_id_takes_the_first_value_of_a_repeated_header() {
let config: crate::imposter::types::ImposterConfig =
serde_json::from_value(serde_json::json!({
"port": 0, "protocol": "http", "stubs": [],
"_rift": { "flowState": { "flowIdSource": "header:X-Flow" } }
}))
.expect("config");
let imposter = crate::imposter::Imposter::new(config).expect("imposter");
let mut headers = hyper::HeaderMap::new();
headers.append("x-flow", HeaderValue::from_static("tenant-a"));
headers.append("x-flow", HeaderValue::from_static("tenant-b"));
let collected: crate::util::OrderedMap<String, Vec<String>> =
collect_request_headers(&headers, title_case);
assert_eq!(
imposter.resolve_flow_id(&collected),
"tenant-a",
"the first value wins, matching resolve_flow_id_recorded (#238)"
);
}
#[test]
#[tracing_test::traced_test]
fn collector_returns_an_empty_map_for_a_request_with_no_headers() {
let collected: crate::util::OrderedMap<String, Vec<String>> =
collect_request_headers(&hyper::HeaderMap::new(), title_case);
assert!(collected.is_empty());
assert!(
!logs_contain("dropping non-UTF-8 request header value"),
"a request that dropped nothing must not warn — an unconditional warning would be \
noise on every request and would train an operator to ignore the real one"
);
}
#[test]
fn collect_request_headers_keeps_every_repeated_value_and_drops_non_utf8() {
let mut headers = hyper::HeaderMap::new();
headers.append("x-repeat", HeaderValue::from_static("first"));
headers.append("x-repeat", HeaderValue::from_static("second"));
headers.insert("Content-Type", HeaderValue::from_static("application/json"));
headers.insert(
"x-binary",
HeaderValue::from_bytes(&[0xFF, 0xFE]).expect("a legal but non-UTF-8 header value"),
);
let collected: crate::imposter::Headers = collect_request_headers(&headers, str::to_string);
assert_eq!(
collected.get("x-repeat").map(Vec::as_slice),
Some(["first".to_string(), "second".to_string()].as_slice()),
"a repeated header keeps every value, in send order (issue #994)"
);
assert_eq!(
collected.get("content-type").map(Vec::as_slice),
Some(["application/json".to_string()].as_slice()),
"lookups stay case-insensitive because hyper's header names are already lowercase"
);
assert!(
!collected.contains_key("x-binary"),
"a non-UTF-8 value is dropped, not mangled into U+FFFD for predicates to match"
);
}
#[test]
fn response_collector_drops_a_non_utf8_value_rather_than_blanking_it() {
let mut h = hyper::HeaderMap::new();
h.insert("x-bin", HeaderValue::from_bytes(&[0xff, 0xfe]).unwrap());
h.insert("x-ok", HeaderValue::from_static("1"));
let out = collect_response_headers(&h);
assert_eq!(
out,
vec![("x-ok".to_string(), "1".to_string())],
"the undecodable header is absent entirely; before #1041 it relayed as `x-bin: \"\"` \
and was persisted into the generated stub"
);
}
#[test]
#[tracing_test::traced_test]
fn response_collector_warns_once_per_response_naming_every_dropped_header() {
let bad = HeaderValue::from_bytes(&[0xff, 0xfe]).unwrap();
let mut h = hyper::HeaderMap::new();
h.insert("x-bin", bad.clone());
h.insert("x-also-bin", bad.clone());
h.append("x-mixed", HeaderValue::from_static("ok"));
h.append("x-mixed", bad);
let out = collect_response_headers(&h);
assert_eq!(out, vec![("x-mixed".to_string(), "ok".to_string())]);
assert!(
logs_contain("dropping non-UTF-8 upstream response header value"),
"a dropped value must be warned, not silently discarded"
);
assert!(
logs_contain("x-bin") && logs_contain("x-also-bin") && logs_contain("x-mixed"),
"the warning must name every header it dropped a value from, or an operator cannot \
tell which of a response's headers went missing"
);
logs_assert(|lines: &[&str]| {
let warns = lines
.iter()
.filter(|l| l.contains("dropping non-UTF-8 upstream response header value"))
.count();
if warns == 1 {
Ok(())
} else {
Err(format!(
"expected exactly one warning for a response that dropped three values, got \
{warns} — a per-value warn is an unbounded log-volume lever for a hostile or \
broken upstream under proxyAlways (#718)"
))
}
});
}
#[test]
#[tracing_test::traced_test]
fn response_collector_stays_silent_when_nothing_is_dropped() {
let mut h = hyper::HeaderMap::new();
h.insert("x-ok", HeaderValue::from_static("1"));
let _ = collect_response_headers(&h);
assert!(
!logs_contain("dropping non-UTF-8 upstream response header value"),
"an ordinary response must not warn"
);
}
#[test]
fn response_collector_keeps_valid_utf8_that_is_not_ascii() {
let mut h = hyper::HeaderMap::new();
let disposition = r#"attachment; filename="résumé.pdf""#;
h.insert(
"content-disposition",
HeaderValue::from_bytes(disposition.as_bytes()).unwrap(),
);
let out = collect_response_headers(&h);
assert_eq!(
out,
vec![("content-disposition".to_string(), disposition.to_string())],
"valid UTF-8 beyond ASCII must relay byte-exact"
);
assert!(HeaderValue::from_str(disposition).is_ok());
}
#[test]
fn response_collector_keeps_every_value_of_a_repeated_header_in_send_order() {
let mut h = hyper::HeaderMap::new();
h.append("set-cookie", HeaderValue::from_static("a=1"));
h.append("set-cookie", HeaderValue::from_static("b=2"));
let out = collect_response_headers(&h);
assert_eq!(
out,
vec![
("set-cookie".to_string(), "a=1".to_string()),
("set-cookie".to_string(), "b=2".to_string()),
],
"RFC 7230 §3.2.2 forbids folding Set-Cookie, so multiplicity survives the relay"
);
}
#[test]
fn response_collector_keeps_the_good_value_of_a_partly_undecodable_repeated_header() {
let mut h = hyper::HeaderMap::new();
h.append("x-mixed", HeaderValue::from_bytes(&[0xff]).unwrap());
h.append("x-mixed", HeaderValue::from_static("good"));
let out = collect_response_headers(&h);
assert_eq!(
out,
vec![("x-mixed".to_string(), "good".to_string())],
"only the undecodable occurrence is dropped, not the whole name"
);
}
#[test]
fn response_collector_on_empty_headers_yields_no_pairs() {
assert!(collect_response_headers(&hyper::HeaderMap::new()).is_empty());
}
}
#[cfg(test)]
mod sanitize_header_value_tests {
use super::{StubRef, sanitize_header_value};
use hyper::header::HeaderValue;
const FIXTURE_STUB: StubRef<'static> = StubRef {
port: 0,
index: 0,
id: None,
};
use crate::test_support::{CapturedEvent, captured_logs};
fn one_event(value: &str) -> CapturedEvent {
let events = captured_logs(|| {
let _ = sanitize_header_value(value, FIXTURE_STUB);
});
assert_eq!(
events.len(),
1,
"a sanitized value warns exactly once, got {} events",
events.len()
);
events[0].clone()
}
#[test]
fn a_horizontal_tab_is_a_legal_header_value_character_and_is_kept() {
let events =
captured_logs(|| assert_eq!(sanitize_header_value("a\tb", FIXTURE_STUB), "a\tb"));
assert!(
events.is_empty(),
"a legal value must not be reported as sanitized"
);
}
#[test]
fn unicode_c1_controls_are_legal_obs_text_and_are_kept() {
let events = captured_logs(|| {
assert_eq!(sanitize_header_value("a\u{85}b", FIXTURE_STUB), "a\u{85}b");
assert_eq!(sanitize_header_value("a\u{80}b", FIXTURE_STUB), "a\u{80}b");
assert_eq!(sanitize_header_value("a\u{9f}b", FIXTURE_STUB), "a\u{9f}b");
});
assert!(
events.is_empty(),
"C1 obs-text must not be reported as sanitized"
);
}
#[test]
fn ordinary_non_ascii_passes_through_byte_exact() {
let events =
captured_logs(|| assert_eq!(sanitize_header_value("José", FIXTURE_STUB), "José"));
assert!(events.is_empty());
}
#[test]
fn an_empty_value_is_unchanged() {
let events = captured_logs(|| assert_eq!(sanitize_header_value("", FIXTURE_STUB), ""));
assert!(events.is_empty());
}
#[test]
fn repairing_an_already_repaired_value_changes_nothing_and_does_not_warn_again() {
let once = sanitize_header_value("safe\r\nInjected: yes", FIXTURE_STUB);
assert_eq!(once, "safeInjected: yes");
let events = captured_logs(|| {
assert_eq!(
sanitize_header_value(&once, FIXTURE_STUB),
"safeInjected: yes",
"a repaired value is a fixed point of the repair"
);
});
assert!(
events.is_empty(),
"nothing was removed the second time, so nothing may be logged, got: {:?}",
events.len()
);
}
#[test]
fn the_warning_names_the_port_and_the_stub() {
let events = captured_logs(|| {
let _ = sanitize_header_value(
"safe\r\nInjected: yes",
StubRef {
port: 4545,
index: 3,
id: Some("checkout"),
},
);
});
assert_eq!(events.len(), 1, "one removal, one warning");
assert_eq!(events[0].field("port"), Some("4545"));
assert_eq!(events[0].field("stub"), Some("3"));
assert_eq!(events[0].field("stub_id"), Some("checkout"));
}
#[test]
fn a_stub_without_an_id_still_logs_an_empty_stub_id() {
let events = captured_logs(|| {
let _ = sanitize_header_value(
"a\0b",
StubRef {
port: 4545,
index: 0,
id: None,
},
);
});
assert_eq!(events.len(), 1);
assert_eq!(events[0].field("port"), Some("4545"));
assert_eq!(events[0].field("stub"), Some("0"));
assert_eq!(events[0].field("stub_id"), Some(""));
}
#[test]
fn the_identity_does_not_depend_on_the_thread_the_repair_runs_on() {
let stub = StubRef {
port: 9090,
index: 7,
id: None,
};
let events = std::thread::scope(|scope| {
scope
.spawn(|| {
captured_logs(|| {
let _ = sanitize_header_value("a\rb", stub);
})
})
.join()
.expect("capture thread")
});
assert_eq!(events.len(), 1, "the warning still fires off-thread");
assert_eq!(events[0].field("port"), Some("9090"));
assert_eq!(events[0].field("stub"), Some("7"));
}
#[test]
fn the_warning_carries_no_client_controlled_location() {
let events = captured_logs(|| {
let _ = sanitize_header_value(
"a\rb",
StubRef {
port: 1,
index: 0,
id: None,
},
);
});
assert_eq!(events.len(), 1);
assert!(events[0].field("path").is_none(), "no request path field");
assert!(events[0].field("query").is_none(), "no query field");
}
#[test]
fn crlf_is_still_stripped_and_still_warned() {
let events = captured_logs(|| {
assert_eq!(
sanitize_header_value("safe\r\nInjected: yes", FIXTURE_STUB),
"safeInjected: yes"
);
});
assert_eq!(events.len(), 1, "CR/LF removal must stay loud");
assert!(
events[0]
.field("message")
.is_some_and(|m| m.contains("header injection")),
"CR/LF removal is the #359 B3 injection defence and must still name it, got: {:?}",
events[0].field("message")
);
}
#[test]
fn the_warning_does_not_echo_a_raw_control_character_into_the_log() {
let event = one_event("safe\r\nInjected: yes");
for (name, rendered) in &event.fields {
assert!(
!rendered.contains('\r') && !rendered.contains('\n'),
"field `{name}` carries a raw CR/LF, which forges a second log line: {rendered:?}"
);
}
assert_eq!(
event.field("value"),
Some(r#""safe\r\nInjected: yes""#),
"the offending value stays legible, escaped"
);
}
#[test]
fn the_warning_names_the_characters_it_removed() {
assert_eq!(
one_event("safe\r\nInjected: yes").field("removed"),
Some(r"['\r', '\n']"),
"an operator must be able to tell CR/LF from a stray NUL"
);
assert_eq!(one_event("a\u{0}b").field("removed"), Some(r"['\0']"));
}
#[test]
fn a_repeated_control_character_is_reported_once() {
assert_eq!(
one_event("a\0\0\0\0\0b").field("removed"),
Some(r"['\0']"),
"the removed set names each character once"
);
}
#[test]
fn the_logged_value_is_capped_however_long_the_input_is() {
let value = format!("{}\u{1b}", "x".repeat(100_000));
let event = one_event(&value);
let logged = event.field("value").expect("value field present");
assert!(
logged.len() < 1_000,
"the logged value must be capped, got {} chars",
logged.len()
);
assert!(
logged.contains("..."),
"a truncated value must say so, got: {logged}"
);
}
#[test]
fn bytes_a_header_value_cannot_hold_are_stripped() {
assert_eq!(sanitize_header_value("a\u{0}b", FIXTURE_STUB), "ab");
assert_eq!(sanitize_header_value("a\u{7f}b", FIXTURE_STUB), "ab");
assert_eq!(sanitize_header_value("a\u{1b}b", FIXTURE_STUB), "ab");
assert_eq!(sanitize_header_value("\r\n\0", FIXTURE_STUB), "");
}
#[test]
fn every_byte_agrees_with_the_http_crate_on_what_a_header_value_may_hold() {
for cp in (0u32..=0xFF).chain([0x100, 0x2028, 0x10FFFF]) {
let Some(c) = char::from_u32(cp) else {
continue;
};
let kept = sanitize_header_value(&c.to_string(), FIXTURE_STUB) == c.to_string();
let representable = HeaderValue::from_str(&c.to_string()).is_ok();
assert_eq!(
kept, representable,
"U+{cp:04X} ({c:?}): sanitizer kept={kept}, HeaderValue accepts={representable}"
);
}
}
#[test]
fn every_sanitized_value_is_accepted_by_header_value() {
for raw in [
"a\tb",
"a\u{85}b",
"José",
"safe\r\nInjected: yes",
"a\u{0}b",
"a\u{7f}b",
"",
"\r\n\0",
] {
let out = sanitize_header_value(raw, FIXTURE_STUB);
assert!(
HeaderValue::from_str(&out).is_ok(),
"sanitized {raw:?} -> {out:?} must be a representable header value"
);
}
}
}