From de449d74e5bd5f8867778c1a28eaeebaaa87de8e Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Wed, 28 Oct 2026 19:05:07 +0000 Subject: [PATCH 1/3] fix(matching): normalise repeated headers using the header's own grammar normalise_list split every header with the plain list grammar, so the fast path treated whitespace inside Link targets (<...>) and Via comments (...) as list separators. Values that differed only there compared as equal. Split with Grammar::for_header(name) instead, and add cases for Link, Via and Set-Cookie sent on separate lines. Co-Authored-By: Claude Opus 5.5 --- rust/pact_matching/src/repeated_headers.rs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/rust/pact_matching/src/repeated_headers.rs b/rust/pact_matching/src/repeated_headers.rs index 357480789..a1840f259 100644 --- a/rust/pact_matching/src/repeated_headers.rs +++ b/rust/pact_matching/src/repeated_headers.rs @@ -115,9 +115,9 @@ fn list_elements(value: &str, grammar: Grammar) -> Vec<&str> { } /// Normalises a list value for comparison: whitespace around commas outside quoted strings -/// is dropped, as are empty elements. -pub(crate) fn normalise_list(value: &str) -> String { - list_elements(value, Grammar::Plain).join(",") +/// and the header's delimiters is dropped, as are empty elements. +pub(crate) fn normalise_list(name: &str, value: &str) -> String { + list_elements(value, Grammar::for_header(name)).join(",") } /// Splits a header's field lines into its list elements. @@ -234,7 +234,7 @@ pub(crate) fn match_repeated_header( let joined_expected = join_field_lines(expected); let joined_actual = join_field_lines(actual); - if normalise_list(&joined_expected) == normalise_list(&joined_actual) { + if normalise_list(key, &joined_expected) == normalise_list(key, &joined_actual) { RepeatedHeaderResult::default() } else if match_header_lines(key, expected, actual, context).is_empty() { RepeatedHeaderResult { @@ -440,7 +440,7 @@ mod tests { #[case(r#""x\", y", z"#, r#""x\", y",z"#)] #[case("", "")] fn normalise_list_ignores_whitespace_and_empty_elements_outside_quotes(#[case] value: &str, #[case] normalised: &str) { - assert_eq!(normalise_list(value), normalised); + assert_eq!(normalise_list("X-Request", value), normalised); } } @@ -556,7 +556,13 @@ pub(crate) mod cases { plain("missing member", "X-Request", &["request1", "request2"], &["request1"], false, false), plain("quoted whole", "X-Request", &["request1", "request2"], &["\"request1, request2\""], false, false), plain("quoted OWS fallback", "X-Request", &["\"x , y\"", "z"], &["\"x, y\"", "z"], true, true), - plain("singleton untouched", "Set-Cookie", &["one", "two"], &["one, two"], false, false) + plain("singleton untouched", "Set-Cookie", &["one", "two"], &["one, two"], false, false), + plain("singleton separate lines", "Set-Cookie", &["a=1; Path=/", "b=2; Expires=Sat, 01 Mar 2025 00:00:00 GMT"], + &["a=1; Path=/", "b=2; Expires=Sat, 01 Mar 2025 00:00:00 GMT"], true, false), + plain("link whitespace inside target", "Link", + &[r#"; rel="a""#, r#"; rel="b""#], + &[r#"; rel="a", ; rel="b""#], false, false), + plain("via comment whitespace", "Via", &["1.0 fred (a,b)", "1.1 p"], &["1.0 fred (a, b), 1.1 p"], false, false) ] } } From fd5ed24ef20223ad948b62f90e83b6ec159797ec Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Wed, 28 Oct 2026 21:17:21 +0000 Subject: [PATCH 2/3] fix(matching): use the header grammar when comparing single header values A header with one value on each side and no matching rule was compared after splitting on every comma and trimming, so whitespace inside a Link , a Via comment or a quoted string was ignored (`` matched ``). Use normalise_list, which only treats list-separating commas as insignificant, in the legacy matcher and in the V2 engine's multi-value header normalisation. The "quoted OWS fallback" case relied on that and now mismatches; the per-line deprecation warning test uses an unbalanced quote instead. Co-Authored-By: Claude Opus 5.5 --- rust/pact_matching/src/engine/interpreter.rs | 7 +++---- rust/pact_matching/src/engine/mod.rs | 4 ++-- rust/pact_matching/src/headers.rs | 13 +++++-------- rust/pact_matching/src/repeated_headers.rs | 18 +++++++++++++----- 4 files changed, 23 insertions(+), 19 deletions(-) diff --git a/rust/pact_matching/src/engine/interpreter.rs b/rust/pact_matching/src/engine/interpreter.rs index 7c3dba2ee..c37ba28eb 100644 --- a/rust/pact_matching/src/engine/interpreter.rs +++ b/rust/pact_matching/src/engine/interpreter.rs @@ -24,7 +24,7 @@ use crate::{CoreMatchingContext, DiffConfig}; use crate::headers::{parse_charset_parameters, strip_whitespace}; use crate::json::type_of; use crate::matchingrules::DoMatch; -use crate::repeated_headers::match_repeated_header; +use crate::repeated_headers::{match_repeated_header, normalise_list}; #[cfg(feature = "xml")] use crate::xml::resolve_attr_namespaces; /// Main interpreter for the matching plan AST @@ -2523,9 +2523,8 @@ impl ExecutionPlanInterpreter { Err(value) => return value }; - let normalize = |s: &str| -> String { - s.split(',').map(|v| v.trim()).collect::>().join(",") - }; + // Only MULTI_VALUE_HEADERS reach this action, and they all use the plain list grammar. + let normalize = |s: &str| normalise_list("", s); let results = values.iter() .map(|v| { diff --git a/rust/pact_matching/src/engine/mod.rs b/rust/pact_matching/src/engine/mod.rs index 312adb76d..0b241fe39 100644 --- a/rust/pact_matching/src/engine/mod.rs +++ b/rust/pact_matching/src/engine/mod.rs @@ -35,7 +35,7 @@ use crate::headers::{parse_charset_parameters, strip_whitespace}; use crate::{BodyMatchResult, Mismatch}; use crate::matchingrules::{DoMatch, value_for_mismatch}; use crate::Mismatch::{BodyMismatch, HeaderMismatch, MetadataMismatch, QueryMismatch}; -use crate::repeated_headers::{header_kind, HeaderKind}; +use crate::repeated_headers::{header_kind, normalise_list, HeaderKind}; mod bodies; mod value_resolvers; @@ -2064,7 +2064,7 @@ fn setup_header_plan( // for known multi-value headers. Custom headers (e.g. JSON payloads) must not // be normalised as commas are semantically significant there. let normalized_value = if let NodeValue::STRING(s) = &item_value { - NodeValue::STRING(s.split(',').map(|v| v.trim()).collect::>().join(",")) + NodeValue::STRING(normalise_list(key, s)) } else { item_value.clone() }; diff --git a/rust/pact_matching/src/headers.rs b/rust/pact_matching/src/headers.rs index 8be508774..1b6f4282c 100644 --- a/rust/pact_matching/src/headers.rs +++ b/rust/pact_matching/src/headers.rs @@ -12,7 +12,7 @@ use tracing::{instrument, debug, warn}; use crate::{CommonMismatch, MatchingContext, Mismatch}; use crate::field_rules::FieldMatchScope; use crate::matchingrules::{compare_lists_with_matchingrules, DoMatch, match_values}; -use crate::repeated_headers::{header_kind, is_repeated, match_repeated_header, HeaderKind}; +use crate::repeated_headers::{header_kind, is_repeated, match_repeated_header, normalise_list, HeaderKind}; pub(crate) fn strip_whitespace<'a, T: FromIterator<&'a str>>(val: &'a str, split_by: &'a str) -> T { val.split(split_by).map(|v| v.trim()).filter(|v| !v.is_empty()).collect() @@ -104,13 +104,10 @@ pub(crate) fn match_header_value( } else if PARAMETERISED_HEADERS.contains(&key.to_lowercase().as_str()) { match_parameter_header(expected, actual, key, "header", index, single_value) } else { - // Normalize whitespace around commas for comparison, since RFC 7230 allows optional whitespace - // after commas in header values. This ensures "a,b" matches "a, b". - let normalize_comma_whitespace = |s: &str| -> String { - s.split(',').map(|v| v.trim()).collect::>().join(",") - }; - let normalized_expected = normalize_comma_whitespace(expected); - let normalized_actual = normalize_comma_whitespace(actual); + // RFC 9110 §5.6.1 allows optional whitespace around list commas, so "a,b" matches "a, b". Only commas + // that separate list elements in the header's grammar count, not ones inside a Link or a quoted string. + let normalized_expected = normalise_list(key, expected); + let normalized_actual = normalise_list(key, actual); MatchingRule::Equality.match_value(normalized_expected.as_str(), normalized_actual.as_str(), false, false) .map_err(|err| { if single_value { diff --git a/rust/pact_matching/src/repeated_headers.rs b/rust/pact_matching/src/repeated_headers.rs index a1840f259..a60af24d6 100644 --- a/rust/pact_matching/src/repeated_headers.rs +++ b/rust/pact_matching/src/repeated_headers.rs @@ -280,14 +280,15 @@ mod tests { #[test] fn per_line_fallback_warns_of_deprecation() { - let expected = vec!["\"x , y\"".to_string(), "z".to_string()]; - let actual = vec!["\"x, y\"".to_string(), "z".to_string()]; + // An unbalanced quote runs to the end of the joined value, but not past the end of its own line. + let expected = vec!["\"a".to_string(), "b".to_string()]; + let actual = vec!["\"a ".to_string(), "b".to_string()]; let result = match_repeated_header("X-Request", &expected, &actual, &CoreMatchingContext::default()); assert!(result.mismatches.is_empty(), "{:?}", result.mismatches); assert_eq!(result.warning.as_deref(), Some("Header 'X-Request' only matched when its field lines were \ compared one at a time. Per-line matching of repeated headers is deprecated: RFC 9110 §5.3 treats \ repeated field lines as one line with the values joined by commas, and a future release will compare \ - only the joined value '\"x, y\", z'.")); + only the joined value '\"a , b'.")); assert!(result.warning.unwrap().contains("deprecated")); } @@ -555,14 +556,21 @@ pub(crate) mod cases { plain("extra member", "X-Request", &["request1", "request2"], &["request1, request2, extra"], false, false), plain("missing member", "X-Request", &["request1", "request2"], &["request1"], false, false), plain("quoted whole", "X-Request", &["request1", "request2"], &["\"request1, request2\""], false, false), - plain("quoted OWS fallback", "X-Request", &["\"x , y\"", "z"], &["\"x, y\"", "z"], true, true), + plain("quoted OWS", "X-Request", &["\"x , y\"", "z"], &["\"x, y\"", "z"], false, false), + plain("unbalanced quote fallback", "X-Request", &["\"a", "b"], &["\"a ", "b"], true, true), plain("singleton untouched", "Set-Cookie", &["one", "two"], &["one, two"], false, false), plain("singleton separate lines", "Set-Cookie", &["a=1; Path=/", "b=2; Expires=Sat, 01 Mar 2025 00:00:00 GMT"], &["a=1; Path=/", "b=2; Expires=Sat, 01 Mar 2025 00:00:00 GMT"], true, false), plain("link whitespace inside target", "Link", &[r#"; rel="a""#, r#"; rel="b""#], &[r#"; rel="a", ; rel="b""#], false, false), - plain("via comment whitespace", "Via", &["1.0 fred (a,b)", "1.1 p"], &["1.0 fred (a, b), 1.1 p"], false, false) + plain("via comment whitespace", "Via", &["1.0 fred (a,b)", "1.1 p"], &["1.0 fred (a, b), 1.1 p"], false, false), + plain("single multi-value OWS", "Cache-Control", &["no-cache,no-store"], &["no-cache, no-store"], true, false), + plain("single multi-value quoted whitespace", "Cache-Control", &["private=\"x,y\""], &["private=\"x, y\""], false, false), + plain("single link whitespace inside target", "Link", + &[r#"; rel="a""#], &[r#"; rel="a""#], false, false), + plain("single quoted whitespace", "X-Request", &["\"x,y\""], &["\"x, y\""], false, false), + plain("single via comment whitespace", "Via", &["1.0 fred (a,b)"], &["1.0 fred (a, b)"], false, false) ] } } From 7d06dcb1b3ebc8030b683eb2f572b58c31783b4b Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Wed, 28 Oct 2026 22:17:10 +0000 Subject: [PATCH 3/3] fix(matching): name the failing value when a repeated header fails a scalar rule A scalar rule on a repeated header reported only the joined mismatch ("Expected '1000, 1234, 9999ABC' to match '\d{1,4}'"), which doesn't say which value failed. Report the per-line mismatches as well, and pass the real list index to match_header_value in the matcher path instead of 0. Fixes the V2 compatibility-suite scenario "Supports matchers for repeated request headers (negative case)". Co-Authored-By: Claude Opus 5.5 --- .../src/engine/tests/header_tests.rs | 2 +- rust/pact_matching/src/headers.rs | 19 +++++++++++++++--- rust/pact_matching/src/repeated_headers.rs | 20 +++++++++++++++++-- 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/rust/pact_matching/src/engine/tests/header_tests.rs b/rust/pact_matching/src/engine/tests/header_tests.rs index 632fb0537..1433e8096 100644 --- a/rust/pact_matching/src/engine/tests/header_tests.rs +++ b/rust/pact_matching/src/engine/tests/header_tests.rs @@ -1358,7 +1358,7 @@ fn match_headers_with_number_type_matching_rule() { ['1234'] => ['1234'], $.headers['REF-ID'] => ['1111', 'two'], json:{"ref-id":{"combine":"AND","matchers":[{"match":"integer"}]}} => json:{"ref-id":{"combine":"AND","matchers":[{"match":"integer"}]}} - ) => ERROR(Mismatch with header 'REF-ID': Expected '1111, two' to match an integer number), + ) => ERROR(Mismatch with header 'REF-ID': Expected '1111, two' to match an integer number, Mismatch with header 'REF-ID': Expected 'two' to match an integer number for value at index 1), %match:integer ( '1234', $.headers['REF-ID'], diff --git a/rust/pact_matching/src/headers.rs b/rust/pact_matching/src/headers.rs index 1b6f4282c..85b9db5a5 100644 --- a/rust/pact_matching/src/headers.rs +++ b/rust/pact_matching/src/headers.rs @@ -7,7 +7,7 @@ use itertools::Itertools; use maplit::hashmap; use pact_models::headers::PARAMETERISED_HEADERS; use pact_models::matchingrules::MatchingRule; -use pact_models::path_exp::DocPath; +use pact_models::path_exp::{DocPath, PathToken}; use tracing::{instrument, debug, warn}; use crate::{CommonMismatch, MatchingContext, Mismatch}; use crate::field_rules::FieldMatchScope; @@ -157,8 +157,9 @@ pub(crate) fn match_header_lines( let path = DocPath::root().join(key.to_lowercase()); if context.matcher_is_defined(&path) { debug!("match_header_lines: Matcher is defined for path {}", path); - let values_result = compare_lists_with_matchingrules(&path, &context.select_best_matcher(&path), expected, actual, context.clone_with(context.matchers()).as_ref(), &mut |_, expected, actual, context| { - match_header_value(key, 0, expected, actual, context, false) + let values_result = compare_lists_with_matchingrules(&path, &context.select_best_matcher(&path), expected, actual, context.clone_with(context.matchers()).as_ref(), &mut |path, expected, actual, context| { + let index = match path.last() { Some(PathToken::Index(index)) => index, _ => 0 }; + match_header_value(key, index, expected, actual, context, false) }); mismatches.extend(values_result.err().unwrap_or_default()); } else { @@ -889,6 +890,18 @@ mod tests { expected: "like, regex, values, arrayContaining".to_string(), actual: "regex, like, values, arrayContaining".to_string(), mismatch: "Mismatch with header 'X-IMPROVED': Expected 'regex, like, values, arrayContaining' to be equal to 'like, regex, values, arrayContaining'".to_string(), + }, + Mismatch::HeaderMismatch { + key: "X-IMPROVED".to_string(), + expected: "like".to_string(), + actual: "regex".to_string(), + mismatch: "Mismatch with header 'X-IMPROVED': Expected 'regex' to be equal to 'like' for value at index 0".to_string(), + }, + Mismatch::HeaderMismatch { + key: "X-IMPROVED".to_string(), + expected: "regex".to_string(), + actual: "like".to_string(), + mismatch: "Mismatch with header 'X-IMPROVED': Expected 'like' to be equal to 'regex' for value at index 1".to_string(), } ])); diff --git a/rust/pact_matching/src/repeated_headers.rs b/rust/pact_matching/src/repeated_headers.rs index a60af24d6..2ae6dbc5e 100644 --- a/rust/pact_matching/src/repeated_headers.rs +++ b/rust/pact_matching/src/repeated_headers.rs @@ -217,7 +217,8 @@ pub(crate) fn match_repeated_header( if primary.is_empty() { return RepeatedHeaderResult::default(); } - if match_header_lines(key, expected, actual, context).is_empty() { + let per_line = match_header_lines(key, expected, actual, context); + if per_line.is_empty() { let warning = if bare.is_empty() { per_line_warning(key, &joined_actual) } else { @@ -229,7 +230,8 @@ pub(crate) fn match_repeated_header( }; return RepeatedHeaderResult { mismatches: vec![], warning: Some(warning) }; } - return RepeatedHeaderResult { mismatches: primary, warning: None }; + // The joined mismatch alone doesn't say which value failed, so report the per-line ones as well. + return RepeatedHeaderResult { mismatches: primary.into_iter().chain(per_line).collect(), warning: None }; } let joined_expected = join_field_lines(expected); @@ -307,6 +309,20 @@ mod tests { assert!(warning.contains("first-"), "{warning}"); } + #[test] + fn scalar_rule_mismatch_names_the_failing_value() { + // compatibility-suite V2 http_consumer "Supports matchers for repeated request headers (negative case)" + let mut category = MatchingRuleCategory::empty("header"); + category.add_rule(DocPath::new_unwrap("$.x-test"), MatchingRule::Regex(r"\d{1,4}".to_string()), RuleLogic::And); + let context = CoreMatchingContext { matchers: category, ..CoreMatchingContext::default() }; + let expected = vec!["1000".to_string()]; + let actual = vec!["1000".to_string(), "1234".to_string(), "9999ABC".to_string()]; + let result = match_repeated_header("X-Test", &expected, &actual, &context); + assert!(result.warning.is_none()); + assert!(result.mismatches.iter().any(|m| m.description.contains(r"Expected '9999ABC' to match '\d{1,4}'")), + "{:?}", result.mismatches); + } + #[test] fn scalar_rules_with_no_expected_lines_do_not_panic() { let mut category = MatchingRuleCategory::empty("header");