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
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
106 changes: 101 additions & 5 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::{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, normalise_list};
#[cfg(feature = "xml")] use crate::xml::resolve_attr_namespaces;

/// Main interpreter for the matching plan AST
Expand Down Expand Up @@ -321,6 +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: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 @@ -2519,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 All @@ -2547,6 +2550,64 @@ impl ExecutionPlanInterpreter {
}
}

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;
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![]
}
}
}
}

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![]
}
}
}
}

fn execute_for_each(
&mut self,
value_resolver: &dyn ValueResolver,
Expand Down Expand Up @@ -2860,3 +2921,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(", ")))
}
}
60 changes: 53 additions & 7 deletions rust/pact_matching/src/engine/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ 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;
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, normalise_list, 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,12 +2033,14 @@ fn setup_header_plan<T: HttpPart>(

let item_path = DocPath::root().join(key);
let path = doc_path.join(key);
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),
&ExecutionPlanNode::resolve_value(&path), &matchers, true,
context.config.show_types_in_errors));
let match_node = build_matching_rule_node(&ExecutionPlanNode::value_node(item_value),
&actual_value, &matchers, true,
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 All @@ -2018,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 All @@ -2031,11 +2077,11 @@ fn setup_header_plan<T: HttpPart>(
} else {
item_check
.add(ExecutionPlanNode::value_node(item_value))
.add(ExecutionPlanNode::resolve_value(doc_path.join(key)))
.add(actual_value)
.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
Loading