Skip to content
Closed
24 changes: 23 additions & 1 deletion rust/pact_matching/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,29 @@ are compared in the order they appear in the query string.
For matching header values:

1. If there is a matcher defined for `header.<HEADER_KEY>`, default to that matcher
2. Otherwise strip all whitespace after commas and compare the resulting strings.
2. Otherwise compare the values according to the kind of header:
* Single-value headers (`Set-Cookie`, `Date`, `User-Agent`, …): each value is compared on its own.
* `Accept` and `Content-Type`: the media type must be equal and the parameters are compared
by name, ignoring the case of their values.
* Known multi-value headers: each value is compared on its own, in order.
* Custom headers: see below.

Plain comparison of two single values trims whitespace around each comma and then compares the
strings for equality, so `a,b` matches `a, b`.

Custom headers: repeated field lines are one comma-joined list (RFC 9110 section 5.3).

* **No matcher.** The field lines on each side are joined with commas, ignoring whitespace and
empty elements outside quoted strings, and the joined values are compared.
* **Scalar matchers** (`Equality`, `Regex`, `Type`, `Include` and so on) see the joined value.
* **List matchers** (`MinType`, `MaxType`, `MinMaxType`, `EachValue`, `ArrayContains`,
index-specific rules and `[*]` wildcard rules) see the list elements. The joined value is split
on commas outside quoted strings. `Link` also keeps commas inside `<...>` together, and `Via`
keeps commas inside nested `(...)` comments together.

When the joined comparison fails but comparing the field lines one by one succeeds, the header
passes with a deprecation warning. A future release will compare only the joined value, or the
list elements for list matchers.

#### Matching Request Headers

Expand Down
110 changes: 90 additions & 20 deletions rust/pact_matching/src/engine/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ use anyhow::anyhow;
use itertools::Itertools;
use maplit::hashset;
use serde_json::{json, Value};
use tracing::{debug, error, instrument, Level, trace};
use tracing::{debug, error, instrument, Level, trace, warn};

use itertools::Either;
use pact_models::matchingrules::MatchingRule;
use pact_models::matchingrules::{MatchingRule, MatchingRuleCategory};
use pact_models::path_exp::{DocPath, PathToken};
#[cfg(feature = "xml")] use pact_models::xml_utils::resolve_matching_node;

Expand All @@ -20,9 +20,11 @@ use crate::engine::context::PlanMatchingContext;
use crate::engine::value_resolvers::ValueResolver;
use crate::field_rules::scope_from_plan_path;
#[cfg(feature = "xml")] use crate::engine::xml::XmlValue;
use crate::headers::{parse_charset_parameters, split_header_field_lines, strip_whitespace};
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;
#[cfg(feature = "xml")] use crate::xml::resolve_attr_namespaces;

/// Main interpreter for the matching plan AST
Expand Down Expand Up @@ -321,7 +323,8 @@ impl ExecutionPlanInterpreter {
"error" => self.execute_error(action, value_resolver, node, &action_path),
"header:parse" => self.execute_header_parse(action, value_resolver, node, &action_path),
"header:normalize-commas" => self.execute_normalize_comma_whitespace(action, value_resolver, node, &action_path),
"header:split-values" => self.execute_split_header_values(value_resolver, node, &action_path),
"header:repeated" => self.execute_header_repeated(action, value_resolver, node, &action_path),
"header:match-repeated" => self.execute_header_match_repeated(action, value_resolver, node, &action_path),
"for-each" => self.execute_for_each(value_resolver, node, &action_path),
#[cfg(feature = "multipart")]
"multipart:parse" => self.execute_multipart_parse(action, value_resolver, node, &action_path),
Expand Down Expand Up @@ -2548,29 +2551,61 @@ impl ExecutionPlanInterpreter {
}
}

fn execute_split_header_values(
fn execute_header_repeated(
&mut self,
action: &str,
value_resolver: &dyn ValueResolver,
node: ExecutionPlanNode,
action_path: &Vec<String>
) -> ExecutionPlanNode {
let ExecutionPlanNode { node_type, children, .. } = node;
let (result_children, values) = match self.evaluate_children(value_resolver, &node_type, children, action_path, true) {
Ok(value) => value,
Err(value) => return value
};
let values = values.iter()
.flat_map(|value| match value.as_value().unwrap_or_default() {
NodeValue::STRING(value) => split_header_field_lines(&[value]),
NodeValue::SLIST(values) => split_header_field_lines(&values),
_ => vec![]
})
.collect();
match self.validate_one_arg(children, action, value_resolver, action_path) {
Ok(value) => {
let repeated = value.value()
.unwrap_or_default()
.as_slist()
.is_some_and(|values| values.len() > 1);
ExecutionPlanNode {
node_type,
result: Some(NodeResult::VALUE(NodeValue::BOOL(repeated))),
children: vec![value]
}
}
Err(err) => {
ExecutionPlanNode {
node_type,
result: Some(NodeResult::ERROR(err.to_string())),
children: vec![]
}
}
}
}

ExecutionPlanNode {
node_type,
result: Some(NodeResult::VALUE(NodeValue::SLIST(values))),
children: result_children
fn execute_header_match_repeated(
&mut self,
action: &str,
value_resolver: &dyn ValueResolver,
node: ExecutionPlanNode,
action_path: &Vec<String>
) -> ExecutionPlanNode {
let ExecutionPlanNode { node_type, children, .. } = node;
match self.validate_args(4, 0, children, action, value_resolver, action_path) {
Ok((args, _)) => {
let result = match_repeated_header_args(&args)
.unwrap_or_else(|err| NodeResult::ERROR(err.to_string()));
ExecutionPlanNode {
node_type,
result: Some(result),
children: args
}
}
Err(err) => {
ExecutionPlanNode {
node_type,
result: Some(NodeResult::ERROR(err.to_string())),
children: vec![]
}
}
}
}

Expand Down Expand Up @@ -2887,3 +2922,38 @@ fn json_check_type(expected_type: String, json_value: &Value) -> anyhow::Result<
_ => Err(anyhow!("'{}' is not a valid JSON type", expected_type))
}
}

fn header_values(value: NodeValue) -> Vec<String> {
match value {
NodeValue::STRING(value) => vec![value],
NodeValue::SLIST(values) => values,
_ => vec![]
}
}

fn match_repeated_header_args(args: &[ExecutionPlanNode]) -> anyhow::Result<NodeResult> {
let mut values = args.iter()
.map(|arg| arg.value().unwrap_or_default().value_or_error())
.collect::<anyhow::Result<Vec<_>>>()?
.into_iter();
let key = values.next().and_then(|value| value.as_string()).unwrap_or_default();
let expected = header_values(values.next().unwrap_or_default());
let actual = header_values(values.next().unwrap_or_default());
let mut rules = MatchingRuleCategory::empty("header");
rules.add_rules_from_json(&values.next().and_then(|value| value.as_json()).unwrap_or_default())?;

#[cfg(feature = "plugins")] #[cfg(not(target_family = "wasm"))]
let context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys, &rules, &std::collections::HashMap::new());
#[cfg(any(not(feature = "plugins"), target_family = "wasm"))]
let context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys, &rules);

let result = match_repeated_header(&key, &expected, &actual, &context);
if result.mismatches.is_empty() {
if let Some(warning) = &result.warning {
warn!("{}", warning);
}
Ok(NodeResult::VALUE(NodeValue::BOOL(true)))
} else {
Ok(NodeResult::ERROR(result.mismatches.iter().map(|mismatch| mismatch.description.as_str()).join(", ")))
}
}
66 changes: 51 additions & 15 deletions rust/pact_matching/src/engine/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ use bytes::Bytes;
use itertools::Itertools;
#[cfg(feature = "xml")] use kiss_xml::dom::Element;
use maplit::hashmap;
use serde_json::Value;
use serde_json::{json, Value};
use serde_json::Value::Object;
use tracing::debug;
use pact_models::bodies::OptionalBody;
use pact_models::content_types::TEXT;
use pact_models::headers::{MULTI_VALUE_HEADERS, PARAMETERISED_HEADERS, SINGLE_VALUE_HEADERS};
use pact_models::headers::{MULTI_VALUE_HEADERS, PARAMETERISED_HEADERS};
use pact_models::json_utils::json_to_string;
use pact_models::http_parts::HttpPart;
use pact_models::matchingrules::{MatchingRule, RuleList, RuleLogic};
Expand All @@ -35,6 +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};

mod bodies;
mod value_resolvers;
Expand Down Expand Up @@ -1961,6 +1962,49 @@ fn setup_query_plan(
Ok(plan_node)
}

/// Routes a custom header with more than one field line on either side through
/// `header:match-repeated`. Other headers keep `match_node`.
fn build_custom_header_node(
key: &str,
expected: &[String],
path: &DocPath,
match_node: ExecutionPlanNode,
context: &PlanMatchingContext
) -> ExecutionPlanNode {
if header_kind(key) != HeaderKind::Custom || expected.is_empty() {
return match_node;
}

let rules = context.matching_rules
.filter(|(rule_path, _)| rule_path.first_field().is_some_and(|field| field.eq_ignore_ascii_case(key)));
// Keyed by the full path, as `MatchingRuleCategory::to_v3_json` drops indexes from header paths.
let rules_json = Value::Object(rules.rules.iter()
.map(|(rule_path, rule_list)| (rule_path.to_lower_case().to_string(), json!({
"combine": if rule_list.rule_logic == RuleLogic::Or { "OR" } else { "AND" },
"matchers": rule_list.rules.iter().map(|rule| rule.to_json()).collect_vec()
})))
.sorted_by(|(a, _), (b, _)| a.cmp(b))
.collect());
let mut match_repeated = ExecutionPlanNode::action("header:match-repeated");
match_repeated
.add(ExecutionPlanNode::value_node(key))
.add(ExecutionPlanNode::value_node(NodeValue::SLIST(expected.to_vec())))
.add(ExecutionPlanNode::resolve_value(path.clone()))
.add(ExecutionPlanNode::value_node(NodeValue::JSON(rules_json)));

if expected.len() > 1 {
match_repeated
} else {
let mut repeated_check = ExecutionPlanNode::action("if");
repeated_check
.add(ExecutionPlanNode::action("header:repeated")
.add(ExecutionPlanNode::resolve_value(path.clone())))
.add(match_repeated)
.add(match_node);
repeated_check
}
}

fn setup_header_plan<T: HttpPart>(
expected: &T,
context: &PlanMatchingContext
Expand Down Expand Up @@ -1989,22 +2033,14 @@ fn setup_header_plan<T: HttpPart>(

let item_path = DocPath::root().join(key);
let path = doc_path.join(key);
let actual_value = if value.len() > 1
&& !SINGLE_VALUE_HEADERS.contains(&key.to_lowercase().as_str())
&& !PARAMETERISED_HEADERS.contains(&key.to_lowercase().as_str())
&& !MULTI_VALUE_HEADERS.contains(&key.to_lowercase().as_str()) {
let mut split_values = ExecutionPlanNode::action("header:split-values");
split_values.add(ExecutionPlanNode::resolve_value(path.clone()));
split_values
} else {
ExecutionPlanNode::resolve_value(path.clone())
};
let actual_value = ExecutionPlanNode::resolve_value(path.clone());
if context.matcher_is_defined(&item_path) {
let matchers = context.select_best_matcher(&item_path);
item_node.add(ExecutionPlanNode::annotation(format!("{} {}", key, matchers.generate_description(true))));
presence_check.add(build_matching_rule_node(&ExecutionPlanNode::value_node(item_value),
let match_node = build_matching_rule_node(&ExecutionPlanNode::value_node(item_value),
&actual_value, &matchers, true,
context.config.show_types_in_errors));
context.config.show_types_in_errors);
presence_check.add(build_custom_header_node(key, value, &path, match_node, context));
} else if PARAMETERISED_HEADERS.contains(&key.to_lowercase().as_str()) {
item_node.add(ExecutionPlanNode::annotation(format!("{}={}", key, item_value.to_string())));
if value.len() == 1 {
Expand Down Expand Up @@ -2045,7 +2081,7 @@ fn setup_header_plan<T: HttpPart>(
.add(ExecutionPlanNode::value_node(NodeValue::NULL))
.add(ExecutionPlanNode::value_node(context.config.show_types_in_errors));
}
presence_check.add(item_check);
presence_check.add(build_custom_header_node(key, value, &path, item_check, context));
}

presence_check.add(
Expand Down
Loading