diff --git a/crates/e2e_test/src/dual_stack_differential/compare.rs b/crates/e2e_test/src/dual_stack_differential/compare.rs index 0ddbfb952f..8090f27127 100644 --- a/crates/e2e_test/src/dual_stack_differential/compare.rs +++ b/crates/e2e_test/src/dual_stack_differential/compare.rs @@ -20,6 +20,7 @@ //! corpus, not here. The comparator is pure so it can be tested without a server. use serde::Serialize; +use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; @@ -69,6 +70,9 @@ pub(crate) struct Observation { pub error_code: Option, /// Allowlisted headers only, lowercase names, normalized values. pub headers: BTreeMap, + /// Captured before SDK response interceptors can rewrite the response. + #[serde(skip)] + pub(super) wire_head: Option, /// Typed values decoded from the response body, never free text. pub fields: BTreeMap, /// Diagnostic only; never compared. @@ -87,10 +91,10 @@ impl Observation { ) -> Self { let headers = headers .into_iter() - .filter_map(|(name, value)| compared_header(name).map(|name| (name, value))) - .map(|(name, value)| { + .filter_map(|(name, value)| { + let name = compared_header(name)?; let value = normalized_header_value(&name, value); - (name, value) + Some((name, value)) }) .collect(); Self { @@ -99,6 +103,7 @@ impl Observation { status, error_code, headers, + wire_head: None, fields: BTreeMap::new(), message: None, } @@ -225,6 +230,65 @@ pub(crate) fn compared_cases(a: &[Observation], b: &[Observation]) -> usize { .count() } +/// Status and the digest of unique header names at the transport boundary. Header values are never retained. +#[derive(Clone, Debug, Serialize)] +pub(super) struct WireHead { + status: u16, + header_names_sha256: String, +} + +impl WireHead { + pub(super) fn new<'h>(status: u16, names: impl Iterator) -> Self { + let names: BTreeSet<_> = names.map(str::to_ascii_lowercase).collect(); + let mut digest = Sha256::new(); + for name in names { + digest.update(name.as_bytes()); + digest.update(b"\n"); + } + Self { + status, + header_names_sha256: hex_simd::encode_to_string(digest.finalize(), hex_simd::AsciiCase::Lower), + } + } +} + +/// Evidence for one transmitted response, including cases where the two sides agreed. +#[derive(Debug, Serialize)] +pub(super) struct ResponseReceipt { + op: &'static str, + case: &'static str, + #[serde(flatten)] + head: WireHead, +} + +pub(super) fn response_receipts(observations: &[Observation]) -> Vec { + observations + .iter() + .filter_map(|o| { + Some(ResponseReceipt { + op: o.op, + case: o.case, + head: o.wire_head.clone()?, + }) + }) + .collect() +} + +#[derive(Debug, Serialize)] +pub(super) struct PairedReceipts { + responses_a: Vec, + responses_b: Vec, +} + +impl PairedReceipts { + pub(super) fn new(a: &[Observation], b: &[Observation]) -> Self { + Self { + responses_a: response_receipts(a), + responses_b: response_receipts(b), + } + } +} + /// The JSON report written for every run. #[derive(Debug, Serialize)] pub(crate) struct Report { @@ -243,6 +307,8 @@ pub(crate) struct Report { pub compared_ops: usize, pub compared_cases: usize, pub differences: Vec, + #[serde(flatten)] + pub(super) responses: PairedReceipts, } impl Report { @@ -485,6 +551,20 @@ mod tests { #[test] fn the_report_lists_each_difference_as_op_field_a_b() { let directory = std::env::temp_dir().join(format!("dual-stack-report-{}", uuid::Uuid::new_v4())); + let mut a = [Observation::new( + "GetBucketLocation", + "normal", + 200, + None, + [("x-test-only", "private value"), ("Date", "clock a"), ("date", "duplicate")], + ) + .with_field("location_constraint", "us-east-1")]; + let mut b = [ + Observation::new("GetBucketLocation", "normal", 200, None, [("DATE", "clock b"), ("X-TEST-ONLY", "other")]) + .with_field("location_constraint", "eu-west-1"), + ]; + a[0].wire_head = Some(WireHead::new(200, ["x-test-only", "Date", "date"].into_iter())); + b[0].wire_head = Some(WireHead::new(201, ["Date"].into_iter())); let report = Report { schema: 2, run: "unit".into(), @@ -497,15 +577,26 @@ mod tests { region_b: Some("eu-west-1".into()), compared_ops: 1, compared_cases: 1, - differences: compare( - &[ok("GetBucketLocation").with_field("location_constraint", "us-east-1")], - &[ok("GetBucketLocation").with_field("location_constraint", "eu-west-1")], - ), + differences: compare(&a, &b), + responses: PairedReceipts::new(&a, &b), }; let path = report.write_to(&directory).expect("write the report"); let json: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).expect("read the report")).expect("parse"); let _ = std::fs::remove_dir_all(&directory); assert_eq!(path.file_name().and_then(|name| name.to_str()), Some("unit.json")); + let expected_receipt = serde_json::json!([{ + "op": "GetBucketLocation", "case": "normal", "status": 200, + "header_names_sha256": "fc98ca59b6a14566b52845df9838e7fb48e1e162149d2b6967085ff0a6a20da3", + }]); + assert_eq!(json["responses_a"], expected_receipt); + assert_eq!( + json["responses_b"], + serde_json::json!([{ + "op": "GetBucketLocation", "case": "normal", "status": 201, + "header_names_sha256": "426e0b848d77d7b3d778187d006056ee406221ca567ce2844ca403dc834ff8f1" + }]) + ); + assert!(response_receipts(&[ok("HeadBucket")]).is_empty()); assert_eq!(json["compared_ops"], 1); assert_eq!(json["reference_side"], "a"); assert_eq!(json["version_a"], "rustfs 1.0.4"); diff --git a/crates/e2e_test/src/dual_stack_differential/mod.rs b/crates/e2e_test/src/dual_stack_differential/mod.rs index fadb4f0fa9..f17eac8cef 100644 --- a/crates/e2e_test/src/dual_stack_differential/mod.rs +++ b/crates/e2e_test/src/dual_stack_differential/mod.rs @@ -33,7 +33,7 @@ pub(crate) mod reference; mod scenarios; use crate::common::{RustFSTestEnvironment, init_logging, rustfs_binary_path, workspace_root}; -use compare::{Difference, Observation, Report, compare, compared_cases, compared_ops, render}; +use compare::{Difference, Observation, PairedReceipts, Report, compare, compared_cases, compared_ops, render}; use reference::{SideA, binary_version}; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -167,6 +167,7 @@ async fn run_differential(label: &str, config: &PairConfig) -> Run { compared_ops: compared_ops(&a, &b).len(), compared_cases: compared_cases(&a, &b), differences: compare(&a, &b), + responses: PairedReceipts::new(&a, &b), }; let path = report.write_to(&report_directory()).expect("write the dual-stack report"); Run { report, path, a } diff --git a/crates/e2e_test/src/dual_stack_differential/scenarios/mod.rs b/crates/e2e_test/src/dual_stack_differential/scenarios/mod.rs index 02f9009555..350ada6109 100644 --- a/crates/e2e_test/src/dual_stack_differential/scenarios/mod.rs +++ b/crates/e2e_test/src/dual_stack_differential/scenarios/mod.rs @@ -22,7 +22,7 @@ mod extra; -use super::compare::Observation; +use super::compare::{Observation, WireHead}; use crate::common::{RustFSTestEnvironment, build_test_s3_config}; use aws_sdk_s3::Client; use aws_sdk_s3::config::interceptors::BeforeDeserializationInterceptorContextRef; @@ -67,7 +67,11 @@ const RETAIN_UNTIL_SECS: i64 = 4_070_908_800; const SELECT_DEADLINE: Duration = Duration::from_secs(30); type Fields = Vec<(&'static str, String)>; -type Captured = (u16, Vec<(String, String)>); +#[derive(Default, Debug)] +struct Captured { + wire: Option, + sdk: Option<(u16, Vec<(String, String)>)>, +} /// Every method of `impl S3 for FS` in `rustfs/src/storage/ecfs.rs`, by S3 operation name, sorted. /// Derived with @@ -152,11 +156,11 @@ pub(crate) const OPERATIONS: [&str; 73] = [ /// Records the status and headers of the one response each request receives (retries are off). #[derive(Clone, Debug, Default)] -struct ResponseCapture(Arc>>); +struct ResponseCapture(Arc>); impl ResponseCapture { - fn take(&self) -> Option { - self.0.lock().ok().and_then(|mut slot| slot.take()) + fn take(&self) -> Captured { + self.0.lock().map(|mut slot| std::mem::take(&mut *slot)).unwrap_or_default() } } @@ -165,6 +169,21 @@ impl Intercept for ResponseCapture { "dual-stack-response-capture" } + fn read_after_transmit( + &self, + context: &BeforeDeserializationInterceptorContextRef<'_>, + _runtime_components: &RuntimeComponents, + _cfg: &mut ConfigBag, + ) -> Result<(), BoxError> { + let response = context.response(); + let head = WireHead::new(response.status().as_u16(), response.headers().iter().map(|(name, _)| name)); + self.0 + .lock() + .map_err(|_| std::io::Error::other("response capture mutex was poisoned"))? + .wire = Some(head); + Ok(()) + } + fn read_before_deserialization( &self, context: &BeforeDeserializationInterceptorContextRef<'_>, @@ -177,11 +196,10 @@ impl Intercept for ResponseCapture { .iter() .map(|(name, value)| (name.to_owned(), value.to_owned())) .collect(); - *self - .0 + self.0 .lock() - .map_err(|_| std::io::Error::other("response capture mutex was poisoned"))? = - Some((response.status().as_u16(), headers)); + .map_err(|_| std::io::Error::other("response capture mutex was poisoned"))? + .sdk = Some((response.status().as_u16(), headers)); Ok(()) } } @@ -277,25 +295,27 @@ impl Recorder { { let _ = self.capture.take(); let result = request.await; - let (status, headers) = self.capture.take().unwrap_or_default(); + let captured = self.capture.take(); + let (status, headers) = captured.sdk.unwrap_or_default(); let headers = headers.iter().map(|(name, value)| (name.as_str(), value.as_str())); - match result { + let (mut observation, output) = match result { Ok(output) => { let observation = fields(&output) .into_iter() .fold(Observation::new(op, case, status, None, headers), |observation, (name, value)| { observation.with_field(name, value) }); - self.observations.push(observation); - Some(output) + (observation, Some(output)) } Err(error) => { let mut observation = Observation::new(op, case, status, Some(error_code(&error)), headers); observation.message = error.as_service_error().and_then(|e| e.message()).map(str::to_owned); - self.observations.push(observation); - None + (observation, None) } - } + }; + observation.wire_head = captured.wire; + self.observations.push(observation); + output } /// Adds a field decoded after the response headers arrived (a streamed body). @@ -1151,6 +1171,64 @@ mod tests { use super::OPERATIONS; use super::{Observation, md5_hex, normalize_sse_c_etags}; + #[tokio::test] + async fn head_object_receipt_uses_the_transmitted_headers_before_the_sdk_derives_expires_string() { + use super::{Client, Recorder, ResponseCapture, RetryConfig, build_test_s3_config, none}; + use crate::dual_stack_differential::compare::PairedReceipts; + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + + const DATE: &str = "Wed, 21 Oct 2037 07:28:00 GMT"; + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let capture = ResponseCapture::default(); + let client = Client::from_conf( + build_test_s3_config(&endpoint, "test", &uuid::Uuid::new_v4().to_string(), None, "wire-head") + .to_builder() + .retry_config(RetryConfig::disabled()) + .interceptor(capture.clone()) + .build(), + ); + let mut recorder = Recorder { + capture, + observations: Vec::new(), + }; + let server = async { + for (status, extra) in [ + ("200 OK", format!("Expires: {DATE}\r\nETag: \"data\"\r\n")), + ("404 Not Found", String::new()), + ] { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut lines = BufReader::new(&mut socket).lines(); + assert!(lines.next_line().await.unwrap().unwrap().starts_with("HEAD /bucket/key ")); + while !lines.next_line().await.unwrap().unwrap().is_empty() {} + let response = format!("HTTP/1.1 {status}\r\n{extra}Content-Length: 0\r\nConnection: close\r\n\r\n"); + socket.write_all(response.as_bytes()).await.unwrap(); + } + }; + let requests = async { + let head = || client.head_object().bucket("bucket").key("key").send(); + let output = recorder.step("HeadObject", "expires", head(), none).await.unwrap(); + assert_eq!(output.expires_string(), Some(DATE)); + assert!(recorder.step("HeadObject", "absent", head(), none).await.is_none()); + let absent = recorder + .step("HeadObject", "unsent", client.head_object().key("key").send(), none) + .await; + assert!(absent.is_none()); + }; + tokio::time::timeout(std::time::Duration::from_secs(10), async { tokio::join!(server, requests) }) + .await + .unwrap(); + let (a, b) = recorder.observations.split_at(1); + let receipts = serde_json::to_value(PairedReceipts::new(a, b)).unwrap(); + assert_eq!( + receipts, + serde_json::json!({ + "responses_a": [{"op":"HeadObject", "case":"expires", "status":200, "header_names_sha256":"bade6835ceb831c4bf589348000369e2501eec559843403cf4e596baae5367d7"}], + "responses_b": [{"op":"HeadObject", "case":"absent", "status":404, "header_names_sha256":"ef176135a5f329e2b96dace1cc94aaf3e2a172d89d99dd5c52ab12679b7383ba"}] + }) + ); + } + #[test] fn the_operation_list_is_sorted_without_duplicates() { assert!(