From 0560f13ddaee257a9094c335fcb9206522a0439d Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Mon, 2 Nov 2026 13:53:23 +0000 Subject: [PATCH 1/3] fix(matching): don't report a body type mismatch for a sniffed actual content type When the actual request or response has no Content-Type header, its content type is only a guess from the body bytes (the mock server stores that guess on the body). Compare the body using the expected content type instead of reporting a BodyTypeMismatch, so a binary body sent without a header can match an expected application/octet-stream body. Refs pact-foundation/pact-go#263 Co-Authored-By: Claude Opus 5.5 --- rust/pact_matching/src/lib.rs | 5 ++++- rust/pact_matching/src/tests.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/rust/pact_matching/src/lib.rs b/rust/pact_matching/src/lib.rs index c711c9faf..c8af39fb4 100644 --- a/rust/pact_matching/src/lib.rs +++ b/rust/pact_matching/src/lib.rs @@ -1777,9 +1777,12 @@ pub async fn match_body( let actual_content_type = actual.content_type().unwrap_or_default(); debug!("expected content type = '{}', actual content type = '{}'", expected_content_type, actual_content_type); + // Without a Content-Type header the actual type was only sniffed from the body (the mock server + // stores that guess on the body), so it can't contradict the expected type (pact-go#263). + let actual_declares_type = actual.has_header("Content-Type"); let content_type_matcher = header_context.select_best_matcher(&DocPath::root().join("content-type")); debug!("content type header matcher = '{:?}'", content_type_matcher); - if expected_content_type.is_unknown() || actual_content_type.is_unknown() || + if expected_content_type.is_unknown() || actual_content_type.is_unknown() || !actual_declares_type || expected_content_type.is_equivalent_to(&actual_content_type) || expected_content_type.is_equivalent_to(&actual_content_type.base_type()) || (!content_type_matcher.is_empty() && diff --git a/rust/pact_matching/src/tests.rs b/rust/pact_matching/src/tests.rs index 967083bd8..f97481eba 100644 --- a/rust/pact_matching/src/tests.rs +++ b/rust/pact_matching/src/tests.rs @@ -502,6 +502,33 @@ async fn body_does_not_match_if_different_content_types() { })); } +#[tokio::test] +async fn body_uses_expected_content_type_if_actual_has_none() { + let octet_stream = ContentType::parse("application/octet-stream").unwrap(); + let expected = Request { + method: "POST".to_string(), + body: OptionalBody::Present(Bytes::from_static(b"\x00\x01\x02"), Some(octet_stream), None), + ..Request::default() + }; + let actual = Request { + method: "POST".to_string(), + body: OptionalBody::Present(Bytes::from_static(b"\x00\x01\x02"), Some(TEXT.clone()), None), + ..Request::default() + }; + let result = match_body(&expected, &actual, &CoreMatchingContext::default(), + &CoreMatchingContext::default()).await; + expect!(result.mismatches().iter()).to(be_empty()); + + let different = Request { + body: OptionalBody::Present(Bytes::from_static(b"\x00\x01\x09"), None, None), + ..actual.clone() + }; + let result = match_body(&expected, &different, &CoreMatchingContext::default(), + &CoreMatchingContext::default()).await; + expect!(result.mismatches().iter()).to_not(be_empty()); + expect!(matches!(result.mismatches()[0], Mismatch::BodyTypeMismatch { .. })).to(be_false()); +} + #[tokio::test] async fn body_matching_uses_any_matcher_for_content_type_header() { let expected = Request { From 68c96e6353efbd04d9ce47ed2c68d0c247727f79 Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Mon, 2 Nov 2026 13:53:23 +0000 Subject: [PATCH 2/3] feat(ffi): add pactffi_remove_header to remove a header and its rules Removes a header (case-insensitively) from the request or response of an interaction, along with its matching rules and generators. This lets a wrapper drop the Content-Type header that pactffi_with_body and pactffi_with_binary_body add by default, while the body keeps its content type. Before V4 the body has nowhere else to record its type, so removing Content-Type from a part with a non-text body is refused. Refs pact-foundation/pact-go#263 Co-Authored-By: Claude Opus 5.5 --- rust/pact_ffi/src/mock_server/handles.rs | 135 ++++++++++++++++++++++- 1 file changed, 134 insertions(+), 1 deletion(-) diff --git a/rust/pact_ffi/src/mock_server/handles.rs b/rust/pact_ffi/src/mock_server/handles.rs index 466725ecd..bba4bc1c4 100644 --- a/rust/pact_ffi/src/mock_server/handles.rs +++ b/rust/pact_ffi/src/mock_server/handles.rs @@ -124,7 +124,7 @@ use maplit::*; use pact_models::{Consumer, PactSpecification, Provider}; use pact_models::bodies::OptionalBody; use pact_models::content_types::{detect_content_type_from_string, ContentType, TEXT}; -use pact_models::generators::{generators_from_json, Generator, Generators}; +use pact_models::generators::{generators_from_json, Generator, GeneratorCategory, Generators}; use pact_models::headers::parse_header; use pact_models::http_parts::HttpPart; use pact_models::interaction::Interaction; @@ -1639,6 +1639,82 @@ ffi_fn! { } } +ffi_fn! { + /// Removes a header from the Interaction, along with any matching rules and generators + /// configured for it. The header name is matched case-insensitively. Returns false if the + /// interaction or Pact can't be modified (i.e. the mock server for it has already started), the + /// interaction is not an HTTP interaction, or the header is not set. + /// + /// This can be used to remove the `Content-Type` header that the body functions + /// (`pactffi_with_body`, `pactffi_with_binary_body`, etc.) add by default, when the request or + /// response must not have one. The content type of the body is kept with the body, so it is + /// still compared using that content type. Before V4, a Pact file can only record the content + /// type of a body with the `Content-Type` header, so removing it from a part with a body that is + /// not text is not allowed for those specification versions, and this function will return + /// false. + /// + /// * `part` - The part of the interaction to remove the header from (Request or Response). + /// * `name` - the header name. + /// + /// # Safety + /// The name parameter must be a valid pointer to a NULL terminated string. + fn pactffi_remove_header( + interaction: InteractionHandle, + part: InteractionPart, + name: *const c_char + ) -> bool { + if let Some(name) = convert_cstr("name", name) { + let spec_version = interaction.with_pact(&|_, inner| inner.specification_version) + .unwrap_or_default(); + interaction.with_interaction(&|_, mock_server_started, inner| { + if let Some(reqres) = inner.as_v4_http_mut() { + let http_part: &mut dyn HttpPart = match part { + InteractionPart::Request => &mut reqres.request, + InteractionPart::Response => &mut reqres.response + }; + remove_header(http_part, name, spec_version) && !mock_server_started + } else { + error!("Interaction is not an HTTP interaction, is {}", inner.type_of()); + false + } + }).unwrap_or(false) + } else { + warn!("Ignoring header with empty or null name"); + false + } + } { + false + } +} + +fn remove_header(part: &mut dyn HttpPart, name: &str, spec_version: PactSpecification) -> bool { + if spec_version < PactSpecification::V4 && name.eq_ignore_ascii_case("content-type") { + let body = part.body(); + if body.is_present() && !body.content_type().map(|ct| ct.is_text()).unwrap_or(false) { + warn!("Not removing the Content-Type header: a {} Pact file can not record the content type \ + of a body that is not text without it", spec_version); + return false; + } + } + + let removed = match part.headers_mut().keys().find(|k| k.eq_ignore_ascii_case(name)).cloned() { + Some(key) => part.headers_mut().remove(&key).is_some(), + None => false + }; + + let matches_name = |path: &DocPath| path.first_field() + .map(|field| field.eq_ignore_ascii_case(name)) + .unwrap_or(false); + if let Some(category) = part.matching_rules_mut().rules.get_mut(&Category::HEADER) { + category.rules.retain(|path, _| !matches_name(path)); + } + if let Some(generators) = part.generators_mut().categories.get_mut(&GeneratorCategory::HEADER) { + generators.retain(|path, _| !matches_name(path)); + } + + removed +} + /// Configures the response for the Interaction. Returns false if the interaction or Pact can't be /// modified (i.e. the mock server for it has already started) /// @@ -3903,6 +3979,63 @@ mod tests { expect!(interaction.request.matching_rules.rules.get(&Category::HEADER).cloned().unwrap_or_default().is_empty()).to(be_true()); } + #[test] + fn pactffi_remove_header_test() { + let pact_handle = PactHandle::new("TestHC1", "TestHP"); + let description = CString::new("remove_header").unwrap(); + let handle = pactffi_new_interaction(pact_handle, description.as_ptr()); + + let name = CString::new("x-id").unwrap(); + let value = CString::new("{\"pact:matcher:type\":\"regex\",\"regex\":\"\\\\d+\",\"value\":\"100\"}").unwrap(); + pactffi_with_header_v2(handle, InteractionPart::Request, name.as_ptr(), 0, value.as_ptr()); + let other = CString::new("x-other").unwrap(); + pactffi_with_header_v2(handle, InteractionPart::Request, other.as_ptr(), 0, value.as_ptr()); + + let upper_name = CString::new("X-ID").unwrap(); + let result = pactffi_remove_header(handle, InteractionPart::Request, upper_name.as_ptr()); + let result2 = pactffi_remove_header(handle, InteractionPart::Request, upper_name.as_ptr()); + + let interaction = handle.with_interaction(&|_, _, inner| { + inner.as_v4_http().unwrap() + }).unwrap(); + + pactffi_free_pact_handle(pact_handle); + + expect!(result).to(be_true()); + expect!(result2).to(be_false()); + expect!(interaction.request.headers.clone()).to(be_some().value(hashmap!{ + "x-other".to_string() => vec!["100".to_string()] + })); + let rules = interaction.request.matching_rules.rules.get(&Category::HEADER).cloned().unwrap_or_default(); + expect!(rules.rules.keys().map(|k| k.to_string()).collect::>()).to(be_equal_to(vec!["$['x-other']".to_string()])); + } + + #[rstest] + #[case(PactSpecification::V4, true)] + #[case(PactSpecification::V3, false)] + fn pactffi_remove_header_binary_body_content_type(#[case] spec: PactSpecification, #[case] expected_result: bool) { + let pact_handle = PactHandle::new("TestHC1", "TestHP"); + pactffi_with_specification(pact_handle, spec); + let description = CString::new("remove_header_binary").unwrap(); + let handle = pactffi_new_interaction(pact_handle, description.as_ptr()); + + let body = [0x00_u8, 0x01, 0xFF, 0xFE]; + pactffi_with_binary_body(handle, InteractionPart::Request, std::ptr::null(), body.as_ptr(), body.len()); + + let name = CString::new("content-type").unwrap(); + let result = pactffi_remove_header(handle, InteractionPart::Request, name.as_ptr()); + + let interaction = handle.with_interaction(&|_, _, inner| { + inner.as_v4_http().unwrap() + }).unwrap(); + + pactffi_free_pact_handle(pact_handle); + + expect!(result).to(be_equal_to(expected_result)); + expect!(interaction.request.has_header("Content-Type")).to(be_equal_to(!expected_result)); + expect!(interaction.request.body.content_type().unwrap().to_string()).to(be_equal_to("application/octet-stream")); + } + #[test] fn pactffi_set_header_different_case() { let pact_handle = PactHandle::new("TestHC1", "TestHP"); From c409a43a30fe453ec341a1c30bd28627773b1650 Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Mon, 2 Nov 2026 14:19:26 +0000 Subject: [PATCH 3/3] test(compatibility-suite): steps to remove a header from the expected and received requests Co-Authored-By: Claude Opus 5.5 --- .../tests/v4_steps/http_matching.rs | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/compatibility-suite/tests/v4_steps/http_matching.rs b/compatibility-suite/tests/v4_steps/http_matching.rs index feeed8569..542a3303b 100644 --- a/compatibility-suite/tests/v4_steps/http_matching.rs +++ b/compatibility-suite/tests/v4_steps/http_matching.rs @@ -5,6 +5,7 @@ use anyhow::anyhow; use cucumber::gherkin::Step; use cucumber::{given, then, when}; use maplit::hashmap; +use pact_models::bodies::OptionalBody; use pact_models::interaction::Interaction; use pact_models::matchingrules::matchers_from_json; use pact_models::pact::Pact; @@ -157,6 +158,27 @@ fn a_request_is_received_with_the_following(world: &mut V4World, step: &Step) { world.received_requests.push(request); } +#[given(expr = "the {string} header is removed from the expected request")] +fn the_header_is_removed_from_the_expected_request(world: &mut V4World, name: String) { + remove_header(&mut world.expected_request, &name); +} + +#[given(expr = "the {string} header is removed from the received request")] +fn the_header_is_removed_from_the_received_request(world: &mut V4World, name: String) { + let request = world.received_requests.last_mut().unwrap(); + remove_header(request, &name); + // A real request without a Content-Type header has a body with no known content type + if let OptionalBody::Present(body, _, _) = &request.body { + request.body = OptionalBody::Present(body.clone(), None, None); + } +} + +fn remove_header(request: &mut HttpRequest, name: &str) { + if let Some(headers) = request.headers.as_mut() { + headers.retain(|key, _| !key.eq_ignore_ascii_case(name)); + } +} + #[when("the request is compared to the expected one")] async fn the_request_is_compared_to_the_expected_one(world: &mut V4World) { world.request_results.push(