Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions rust/pact_matching/src/engine/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -2523,9 +2523,8 @@ impl ExecutionPlanInterpreter {
Err(value) => return value
};

let normalize = |s: &str| -> String {
s.split(',').map(|v| v.trim()).collect::<Vec<_>>().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| {
Expand Down
4 changes: 2 additions & 2 deletions rust/pact_matching/src/engine/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -2064,7 +2064,7 @@ fn setup_header_plan<T: HttpPart>(
// 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::<Vec<_>>().join(","))
NodeValue::STRING(normalise_list(key, s))
} else {
item_value.clone()
};
Expand Down
2 changes: 1 addition & 1 deletion rust/pact_matching/src/engine/tests/header_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
Expand Down
32 changes: 21 additions & 11 deletions rust/pact_matching/src/headers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ 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;
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()
Expand Down Expand Up @@ -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::<Vec<_>>().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 <URI> 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 {
Expand Down Expand Up @@ -160,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 {
Expand Down Expand Up @@ -892,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(),
}
]));

Expand Down
54 changes: 42 additions & 12 deletions rust/pact_matching/src/repeated_headers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand All @@ -229,12 +230,13 @@ 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);
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 {
Expand Down Expand Up @@ -280,14 +282,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"));
}

Expand All @@ -306,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");
Expand Down Expand Up @@ -440,7 +457,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);
}
}

Expand Down Expand Up @@ -555,8 +572,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("singleton untouched", "Set-Cookie", &["one", "two"], &["one, two"], false, false)
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#"<https://a.example/x,y>; rel="a""#, r#"<https://b.example/>; rel="b""#],
&[r#"<https://a.example/x, y>; rel="a", <https://b.example/>; 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("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#"<https://a.example/?x=1,2>; rel="a""#], &[r#"<https://a.example/?x=1, 2>; 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)
]
}
}