diff --git a/rust/pact_models/src/lib.rs b/rust/pact_models/src/lib.rs index e4efabe94..e5f894c9f 100644 --- a/rust/pact_models/src/lib.rs +++ b/rust/pact_models/src/lib.rs @@ -47,6 +47,7 @@ pub mod sync_pact; pub mod message_pact; mod iterator_utils; pub mod plugins; +pub mod spec_version_check; /// A "prelude" or a default list of import types to include. pub mod prelude { diff --git a/rust/pact_models/src/matchingrules/mod.rs b/rust/pact_models/src/matchingrules/mod.rs index 2c7b7b68d..0ce60a6c5 100644 --- a/rust/pact_models/src/matchingrules/mod.rs +++ b/rust/pact_models/src/matchingrules/mod.rs @@ -164,6 +164,17 @@ impl MatchingRule { } } + /// Converts this `MatchingRule` to the V2 rule that matches the same values, if there is one. + /// Only lossless rewrites are done: `include` becomes an escaped `regex`. Everything else + /// returns None. + pub fn to_v2_json(&self) -> Option { + match self { + MatchingRule::Include(s) => Some(json!({ "match": "regex", + "regex": format!("(?s).*{}.*", regex::escape(s)) })), + _ => None + } + } + /// Converts this `MatchingRule` to a `Value` struct pub fn to_json(&self) -> Value { match self { @@ -817,11 +828,17 @@ impl RuleList { fn to_v2_json(&self) -> Value { match self.rules.get(0) { - Some(rule) => rule.to_json(), + Some(rule) => rule.to_v2_json().unwrap_or_else(|| rule.to_json()), None => json!({}) } } + // V2 has no equality matcher, but equality is what V2 does when no rule applies. So the + // rule can be left out, as long as nothing cascades onto this path from a parent. + fn is_only_equality(&self) -> bool { + matches!(self.rules.as_slice(), [MatchingRule::Equality]) + } + /// If there is a type matcher defined for the rule list pub fn type_matcher_defined(&self) -> bool { self.rules.iter().any(|rule| match rule { @@ -1138,21 +1155,22 @@ impl MatchingRuleCategory { /// Returns a JSON Value representation in V2 format pub fn to_v2_json(&self) -> HashMap { let mut map = hashmap!{}; + let rules = self.v2_rules(); match &self.name { - Category::PATH => for (_, v) in self.rules.clone() { + Category::PATH => for (_, v) in rules.clone() { map.insert("$.path".to_string(), v.to_v2_json()); } - Category::BODY => for (k, v) in self.rules.clone() { + Category::BODY => for (k, v) in rules.clone() { map.insert(String::from(k).replace("$", "$.body"), v.to_v2_json()); } - Category::HEADER | Category::QUERY => for (k, v) in &self.rules { + Category::HEADER | Category::QUERY => for (k, v) in &rules { let mut path = DocPath::root(); path.push_field(self.name.v2_form()); path.push_path(k); map.insert(path.to_string(), v.to_v2_json()); } - _ => for (k, v) in &self.rules { + _ => for (k, v) in &rules { map.insert(format!("$.{}.{}", self.name.v2_form(), k), v.to_v2_json()); } }; @@ -1160,6 +1178,23 @@ impl MatchingRuleCategory { map } + // The rules to write to a V2 pact: equality-only rules are dropped where no other rule is + // defined on a parent path, as V2 falls back to equality there anyway. + fn v2_rules(&self) -> HashMap { + self.rules.iter() + .filter(|(path, rules)| !(rules.is_only_equality() && !self.has_parent_rule(path))) + .map(|(k, v)| (k.clone(), v.clone())) + .collect() + } + + fn has_parent_rule(&self, path: &DocPath) -> bool { + let path = path.to_string(); + self.rules.keys() + .map(|other| other.to_string()) + .any(|other| other != path && (path.starts_with(&format!("{}.", other)) + || path.starts_with(&format!("{}[", other)))) + } + /// If there is a type matcher defined for the category pub fn type_matcher_defined(&self) -> bool { self.rules.values().any(|rule_list| rule_list.type_matcher_defined()) diff --git a/rust/pact_models/src/pact.rs b/rust/pact_models/src/pact.rs index fea221489..2d7ddc000 100644 --- a/rust/pact_models/src/pact.rs +++ b/rust/pact_models/src/pact.rs @@ -12,6 +12,7 @@ use std::sync::{Arc, Mutex}; use anyhow::anyhow; #[cfg(not(target_family = "wasm"))] use anyhow::Context; +use itertools::Itertools; use lazy_static::lazy_static; use maplit::btreemap; use serde_json::{json, Value}; @@ -24,6 +25,7 @@ use crate::{Consumer, PactSpecification, Provider}; use crate::interaction::Interaction; use crate::message_pact::MessagePact; use crate::plugins::PluginData; +use crate::spec_version_check::{spec_violations, strict_spec_version, STRICT_SPEC_ENV_VAR}; use crate::sync_pact::RequestResponsePact; use crate::v4; use crate::v4::pact::V4Pact; @@ -240,9 +242,9 @@ pub fn write_pact( f.read_to_string(&mut existing)?; } - let pact_json = if existing.is_empty() { + let json = if existing.is_empty() { debug!("Writing new pact file to {:?}", path); - serde_json::to_string_pretty(&pact.to_json(pact_spec)?)? + pact.to_json(pact_spec)? } else { debug!("Merging pact with file {:?}", path); let existing_pact = parse_pact_file(&existing, path)?; @@ -253,8 +255,10 @@ pub fn write_pact( } let merged_pact = pact.merge(existing_pact.deref())?; - serde_json::to_string_pretty(&merged_pact.to_json(pact_spec)?)? + merged_pact.to_json(pact_spec)? }; + check_spec_version(&json, pact_spec, path)?; + let pact_json = serde_json::to_string_pretty(&json)?; f.set_len(0)?; f.seek(SeekFrom::Start(0))?; @@ -264,6 +268,26 @@ pub fn write_pact( } +// Rules and generators the target spec doesn't define are a warning for now, and an error +// with PACT_STRICT_SPEC_VERSION=true. The plan is to make the error the default in the next +// major version. +fn check_spec_version(json: &Value, pact_spec: PactSpecification, path: &Path) -> anyhow::Result<()> { + let violations = spec_violations(json, pact_spec); + if violations.is_empty() { + return Ok(()); + } + let details = violations.iter().map(|v| format!(" {}", v)).join("\n"); + if strict_spec_version() { + Err(anyhow!("Pact {:?} uses features the {} specification does not define:\n{}\n\ + Write it as a newer specification version, or remove them", path, pact_spec, details)) + } else { + warn!("Pact {:?} uses features the {} specification does not define, they will be written \ + anyway but other pact implementations may reject or ignore them (set {}=true to make this \ + an error):\n{}", path, pact_spec, STRICT_SPEC_ENV_VAR, details); + Ok(()) + } +} + /// Construct Metadata from JSON value pub fn parse_meta_data(pact_json: &Value) -> BTreeMap> { match pact_json.get("metadata") { diff --git a/rust/pact_models/src/request.rs b/rust/pact_models/src/request.rs index 4a1219882..9df5f5302 100644 --- a/rust/pact_models/src/request.rs +++ b/rust/pact_models/src/request.rs @@ -217,7 +217,7 @@ impl Request { &self.matching_rules.clone(), spec_version)); } - if self.generators.is_not_empty() { + if self.generators.is_not_empty() && spec_version >= &PactSpecification::V3 { map.insert("generators".to_string(), generators_to_json( &self.generators.clone(), spec_version)); } diff --git a/rust/pact_models/src/response.rs b/rust/pact_models/src/response.rs index 7fb6f3ff3..a0adaab62 100644 --- a/rust/pact_models/src/response.rs +++ b/rust/pact_models/src/response.rs @@ -94,7 +94,7 @@ impl Response { map.insert("matchingRules".to_string(), matchers_to_json( &self.matching_rules.clone(), spec_version)); } - if self.generators.is_not_empty() { + if self.generators.is_not_empty() && spec_version >= &PactSpecification::V3 { map.insert("generators".to_string(), generators_to_json( &self.generators.clone(), spec_version)); } diff --git a/rust/pact_models/src/spec_version_check.rs b/rust/pact_models/src/spec_version_check.rs new file mode 100644 index 000000000..52d259a4e --- /dev/null +++ b/rust/pact_models/src/spec_version_check.rs @@ -0,0 +1,227 @@ +//! Checks that a serialised pact only uses the matching rules and generators its +//! specification version defines. +//! +//! The model is version-agnostic, so it is possible to build an interaction with V4-only +//! matchers (`eachKey`, `arrayContains`, ...) and then write it out as a V3 pact, or V3 +//! matchers into a V2 pact. Consumers reading those files against the spec (or a schema) +//! will reject them, and older verifiers will silently ignore the rules. This check is run +//! on the JSON that is about to be written, so it sees exactly what lands on disk. + +use std::env; + +use serde_json::Value; + +use crate::PactSpecification; + +/// Environment variable that turns spec violations into errors instead of warnings. +pub const STRICT_SPEC_ENV_VAR: &str = "PACT_STRICT_SPEC_VERSION"; + +/// A matching rule or generator that is not defined by the pact specification being written +#[derive(Debug, Clone, PartialEq)] +pub struct SpecViolation { + /// JSON pointer to the offending rule or generator + pub path: String, + /// The `match` or `type` value + pub name: String, + /// If it is a matching rule (true) or a generator (false) + pub matcher: bool, + /// The specification version that would be required for it + pub required: PactSpecification +} + +impl std::fmt::Display for SpecViolation { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{} '{}' at {} requires a {} pact", if self.matcher { "matcher" } else { "generator" }, + self.name, self.path, self.required) + } +} + +/// If strict spec checking has been enabled via the `PACT_STRICT_SPEC_VERSION` environment variable +pub fn strict_spec_version() -> bool { + env::var(STRICT_SPEC_ENV_VAR) + .map(|v| matches!(v.to_lowercase().as_str(), "1" | "true" | "yes")) + .unwrap_or(false) +} + +/// The lowest specification version that defines the given `match` type. +/// Unknown types are treated as plugin matchers, which need V4. +pub fn matcher_spec_version(name: &str) -> PactSpecification { + match name { + "regex" | "type" => PactSpecification::V2, + "equality" | "include" | "integer" | "decimal" | "number" | "null" | "boolean" | "date" + | "time" | "datetime" | "timestamp" | "values" | "contentType" => PactSpecification::V3, + _ => PactSpecification::V4 + } +} + +/// The lowest specification version that defines the given generator type. +/// Unknown types are treated as plugin generators, which need V4. +pub fn generator_spec_version(name: &str) -> PactSpecification { + match name { + "RandomInt" | "RandomDecimal" | "RandomHexadecimal" | "RandomString" | "Regex" | "Uuid" + | "Date" | "Time" | "DateTime" | "RandomBoolean" => PactSpecification::V3, + _ => PactSpecification::V4 + } +} + +/// Returns all the matching rules and generators in the serialised pact that the given +/// specification version does not define. V4 (and unknown) pacts are never reported. +pub fn spec_violations(pact_json: &Value, spec: PactSpecification) -> Vec { + let mut violations = vec![]; + if matches!(spec, PactSpecification::V2 | PactSpecification::V3) { + walk(pact_json, "", spec, &mut violations); + } + violations +} + +fn walk(json: &Value, pointer: &str, spec: PactSpecification, violations: &mut Vec) { + match json { + Value::Object(map) => for (key, value) in map { + let path = format!("{}/{}", pointer, escape(key)); + match key.as_str() { + "matchingRules" => collect(value, &path, "match", true, spec, violations), + "generators" if spec == PactSpecification::V2 => if !value.is_null() { + violations.push(SpecViolation { + path, name: "generators".to_string(), matcher: false, required: PactSpecification::V3 + }) + }, + "generators" => collect(value, &path, "type", false, spec, violations), + _ => walk(value, &path, spec, violations) + } + }, + Value::Array(items) => for (i, item) in items.iter().enumerate() { + walk(item, &format!("{}/{}", pointer, i), spec, violations); + }, + _ => {} + } +} + +// Finds the rule/generator objects (those with a `match`/`type` string) below a +// matchingRules or generators block. Does not descend into a found rule: anything nested +// in it (eachKey rules, arrayContains variants) is only reachable through a V4 matcher, +// which is already reported. +fn collect( + json: &Value, + pointer: &str, + field: &str, + matcher: bool, + spec: PactSpecification, + violations: &mut Vec +) { + match json { + Value::Object(map) => if let Some(Value::String(name)) = map.get(field) { + let required = if matcher { matcher_spec_version(name) } else { generator_spec_version(name) }; + if required > spec { + violations.push(SpecViolation { path: pointer.to_string(), name: name.clone(), matcher, required }); + } + } else { + for (key, value) in map { + collect(value, &format!("{}/{}", pointer, escape(key)), field, matcher, spec, violations); + } + }, + Value::Array(items) => for (i, item) in items.iter().enumerate() { + collect(item, &format!("{}/{}", pointer, i), field, matcher, spec, violations); + }, + _ => {} + } +} + +fn escape(key: &str) -> String { + key.replace('~', "~0").replace('/', "~1") +} + +#[cfg(test)] +mod tests { + use expectest::prelude::*; + use itertools::Itertools; + use serde_json::json; + + use super::*; + + #[test] + fn v3_pact_with_v4_matchers_and_generators() { + let pact = json!({ + "interactions": [{ + "response": { + "matchingRules": { + "body": { + "$": { "combine": "AND", "matchers": [{ "match": "eachKey", "rules": [{ "match": "regex", "regex": "\\w+" }] }] }, + "$.id": { "combine": "AND", "matchers": [{ "match": "integer" }] } + }, + "status": { "combine": "AND", "matchers": [{ "match": "statusCode", "status": "success" }] } + }, + "generators": { + "body": { "$.url": { "type": "MockServerURL", "example": "http://x", "regex": ".*" }, "$.id": { "type": "RandomInt" } } + } + } + }] + }); + let violations = spec_violations(&pact, PactSpecification::V3); + let names: Vec<_> = violations.iter().map(|v| v.name.as_str()).sorted().collect(); + expect!(names).to(be_equal_to(vec!["MockServerURL", "eachKey", "statusCode"])); + let each_key = violations.iter().find(|v| v.name == "eachKey").unwrap(); + expect!(each_key.to_string()).to(be_equal_to( + "matcher 'eachKey' at /interactions/0/response/matchingRules/body/$/matchers/0 requires a V4 pact")); + } + + #[test] + fn v2_pact_with_v3_matchers_and_generators() { + let pact = json!({ + "interactions": [{ + "response": { + "matchingRules": { "$.body.id": { "match": "integer" }, "$.body.name": { "match": "type" } }, + "generators": { "body": { "$.id": { "type": "RandomInt" } } } + } + }] + }); + let violations = spec_violations(&pact, PactSpecification::V2); + let names: Vec<_> = violations.iter().map(|v| v.name.as_str()).sorted().collect(); + expect!(names).to(be_equal_to(vec!["generators", "integer"])); + } + + #[test] + fn v4_pacts_are_not_checked() { + let pact = json!({ "interactions": [{ "response": { "matchingRules": { "body": { + "$": { "combine": "AND", "matchers": [{ "match": "some-plugin-matcher" }] } + } } } }] }); + expect!(spec_violations(&pact, PactSpecification::V4).iter()).to(be_empty()); + } + + #[test] + fn v2_matching_rules_are_downgraded_where_nothing_is_lost() { + use crate::matchingrules; + use crate::matchingrules::{matchers_to_json, MatchingRule}; + + let rules = matchingrules! { + "body" => { + "$.name" => [ MatchingRule::Equality ], + "$.desc" => [ MatchingRule::Include("a.b".to_string()) ], + "$.items" => [ MatchingRule::MinType(1) ], + "$.items[*].id" => [ MatchingRule::Equality ] + } + }; + let json = matchers_to_json(&rules, &PactSpecification::V2); + expect!(json.clone()).to(be_equal_to(json!({ + "$.body.desc": { "match": "regex", "regex": "(?s).*a\\.b.*" }, + "$.body.items": { "match": "type", "min": 1 }, + // under a type matcher, so dropping it would change what is matched: kept, and reported + "$.body.items[*].id": { "match": "equality" } + }))); + let violations = spec_violations(&json!({ "matchingRules": json }), PactSpecification::V2); + expect!(violations.iter().map(|v| v.name.as_str()).collect::>()).to(be_equal_to(vec!["equality"])); + } + + #[test] + fn v2_requests_and_responses_do_not_write_generators() { + use crate::generators; + use crate::generators::Generator; + use crate::request::Request; + + let request = Request { + generators: generators! { "BODY" => { "$.id" => Generator::RandomInt(1, 10) } }, + .. Request::default() + }; + expect!(request.to_json(&PactSpecification::V2).get("generators").cloned()).to(be_none()); + expect!(request.to_json(&PactSpecification::V3).get("generators").cloned()).to(be_some()); + } +}