diff --git a/README.md b/README.md index eecd2e1..38c88b6 100644 --- a/README.md +++ b/README.md @@ -349,8 +349,13 @@ controls needed to avoid unsafe reuse: require the original `Authorization` value to match even when the server did not include `Authorization` in `Vary` - stale stored responses with `ETag` or `Last-Modified` validators are - revalidated with conditional GET requests, and `304 Not Modified` responses - refresh stored metadata before returning the cached body as `200 OK` + revalidated with conditional GET requests. A `304 Not Modified` refreshes + eligible matching responses. When the cache added the condition, it returns + the validated body as `200 OK` or retries the original GET once if the `304` + cannot validate a stored response. Caller-supplied conditions are forwarded + and the origin's `304` is returned to the caller. +- responses from a followed redirect are excluded from the original URI's + cache entries - stale stored responses are served only when the request explicitly permits them with `max-stale` and the cached response does not require validation - non-error `2xx` / `3xx` unsafe-method responses invalidate stored responses diff --git a/crates/openwire-cache/src/lib.rs b/crates/openwire-cache/src/lib.rs index cf2ec9a..f30175f 100644 --- a/crates/openwire-cache/src/lib.rs +++ b/crates/openwire-cache/src/lib.rs @@ -13,7 +13,8 @@ use http::{ HeaderMap, HeaderName, HeaderValue, Method, Request, Response, StatusCode, Uri, Version, }; use openwire::{ - BoxFuture, Exchange, Interceptor, Next, RequestBody, ResponseBody, ResponseTiming, WireError, + BoxFuture, Exchange, Interceptor, Next, RedirectedResponse, RequestBody, ResponseBody, + ResponseTiming, WireError, WireErrorKind, }; use tokio::sync::RwLock; use url::Url; @@ -63,23 +64,26 @@ where .is_cacheable .then(|| cache_key(exchange.request().uri())); let request_headers = exchange.request().headers().clone(); + let caller_conditional = request_headers.contains_key(IF_NONE_MATCH) + || request_headers.contains_key(IF_MODIFIED_SINCE); + let mut candidates = Vec::new(); let mut validation_entry = None; if let Some(cache_key) = cache_key.as_ref() { - for entry in store.get_candidates(cache_key).await.into_iter().rev() { - if entry.matches_request(&request_policy, &request_headers) { - if request_policy.lookup && entry.is_servable_for(&request_policy) { - let response = entry.into_response(); - ctx.listener().cache_hit(&ctx, &response); - return Ok(response); - } + candidates = store.get_candidates(cache_key).await; + candidates.retain(|entry| entry.matches_request(&request_policy, &request_headers)); + candidates.sort_by_key(CachedResponse::recency); + if let Some(entry) = candidates.last().filter(|_| !caller_conditional) { + if request_policy.lookup && entry.is_servable_for(&request_policy) { + let response = entry.clone().into_response(); + ctx.listener().cache_hit(&ctx, &response); + return Ok(response); + } - if !request_policy.only_if_cached - && entry.can_revalidate(exchange.request().headers()) - { - validation_entry = Some(entry); - } - break; + if !request_policy.only_if_cached + && CacheValidators::from_headers(&entry.headers).has_any() + { + validation_entry = Some(entry); } } @@ -90,16 +94,25 @@ where } } - if let Some(entry) = validation_entry.as_ref() { + let retry = if let Some(entry) = validation_entry { + let original = recovery_exchange(&exchange).ok_or_else(|| { + WireError::new( + WireErrorKind::Internal, + "cache validation requires a replayable request", + ) + })?; let cached = entry.clone().into_response(); ctx.listener().cache_conditional_hit(&ctx, &cached); entry.apply_revalidation_headers(exchange.request_mut().headers_mut()); - } else if cache_key.is_some() { - ctx.listener().cache_miss(&ctx); - } + Some((next.clone(), original)) + } else { + if cache_key.is_some() { + ctx.listener().cache_miss(&ctx); + } + None + }; - let response = next.run(exchange).await?; - let timing = response.extensions().get::().copied(); + let mut response = next.run(exchange).await?; if let Some(invalidation_target) = invalidation_target.as_ref() { if response_status_invalidates_cache(response.status()) { for key in invalidation_keys(invalidation_target, response.headers()) { @@ -112,49 +125,88 @@ where return Ok(response); }; - if let Some(entry) = validation_entry.as_ref() { - if response.status() == StatusCode::NOT_MODIFIED { - let (parts, body) = response.into_parts(); - let _ = body.bytes().await?; - let Some(timing) = timing else { - // The conditional request was ours, so still reconstruct - // its response. Without exchange timing, do not publish - // a refreshed entry with an underestimated age. - store.remove_candidate(&cache_key, entry).await; - let mut validation_headers = parts.headers; - ensure_response_date(&mut validation_headers, SystemTime::now()); - let response = build_response( - entry.status, - entry.version, - merge_304_headers(&entry.headers, &validation_headers), - entry.body.clone(), - ); - ctx.listener().cache_hit(&ctx, &response); - return Ok(response); - }; - let (freshened, store_response) = - entry.freshen_from_not_modified(&parts.headers, &request_headers, timing); - if store_response { - store.put_candidate(cache_key, freshened.clone()).await; + if response.status() == StatusCode::NOT_MODIFIED + && (retry.is_some() || caller_conditional) + { + if retry.is_some() { + std::mem::take(response.body_mut()).bytes().await?; + } + let timing = response.extensions().get::().copied(); + let eligible = if response.extensions().get::().is_some() { + &[] + } else { + candidates.as_slice() + }; + let mut reconstructed = None; + for entry in validated_candidates(eligible, response.headers()) { + let (freshened, storable) = if let Some(timing) = timing { + entry.freshen_from_not_modified( + response.headers(), + &request_headers, + timing, + ) } else { - store.remove_candidate(&cache_key, entry).await; + // Without timing, reconstruct the response without publishing a new Age. + let mut headers = response.headers().clone(); + ensure_response_date(&mut headers, SystemTime::now()); + let mut freshened = entry.clone(); + freshened.headers = merge_304_headers(&entry.headers, &headers); + (freshened, false) + }; + if request_policy.store_response { + store + .replace_validated_candidate( + &cache_key, + entry, + storable.then(|| freshened.clone()), + ) + .await; } - let response = freshened.into_response(); + reconstructed.get_or_insert(freshened); + } + + let Some((next, original)) = retry else { + return Ok(response); + }; + if let Some(freshened) = reconstructed { + let response = if timing.is_some() { + freshened.into_response() + } else { + build_response( + freshened.status, + freshened.version, + freshened.headers, + freshened.body, + ) + }; ctx.listener().cache_hit(&ctx, &response); return Ok(response); } + + // Drop the response extensions before re-entering the chain so any + // admission permit from the conditional exchange is released. + drop(response); + response = next.run_when_ready(original).await?; + if response.status() == StatusCode::NOT_MODIFIED { + return Err(WireError::new( + WireErrorKind::Protocol, + "304 response to a cache recovery request without a validation condition", + )); + } } - if !request_policy.store_response { + if !request_policy.store_response + || response.extensions().get::().is_some() + { return Ok(response); } - let Some(timing) = timing else { + let Some(timing) = response.extensions().get::().copied() else { if response.status() == StatusCode::OK { remove_unusable_candidate( store.as_ref(), &cache_key, - validation_entry.as_ref(), + validation_entry, &request_policy, &request_headers, ) @@ -170,7 +222,7 @@ where remove_unusable_candidate( store.as_ref(), &cache_key, - validation_entry.as_ref(), + validation_entry, &request_policy, &request_headers, ) @@ -197,7 +249,7 @@ where remove_unusable_candidate( store.as_ref(), &cache_key, - validation_entry.as_ref(), + validation_entry, &request_policy, &request_headers, ) @@ -210,7 +262,7 @@ where remove_unusable_candidate( store.as_ref(), &cache_key, - validation_entry.as_ref(), + validation_entry, &request_policy, &request_headers, ) @@ -247,6 +299,21 @@ where } } +fn recovery_exchange(exchange: &Exchange) -> Option { + let request = exchange.request(); + let mut cloned = Request::new(request.body().try_clone()?); + *cloned.method_mut() = request.method().clone(); + *cloned.uri_mut() = request.uri().clone(); + *cloned.version_mut() = request.version(); + *cloned.headers_mut() = request.headers().clone(); + *cloned.extensions_mut() = request.extensions().clone(); + Some(Exchange::new( + cloned, + exchange.context().clone(), + exchange.attempt().saturating_add(1), + )) +} + #[derive(Clone, Debug, Default)] struct RequestCachePolicy { is_cacheable: bool, @@ -297,6 +364,77 @@ impl CacheValidators { } } +#[derive(PartialEq, Eq)] +struct EntityTag<'a> { + weak: bool, + opaque: &'a [u8], +} + +fn entity_tag(value: &HeaderValue) -> Option> { + let value = value.as_bytes(); + let (weak, value) = match value.strip_prefix(b"W/") { + Some(value) => (true, value), + None => (false, value), + }; + let opaque = value.strip_prefix(b"\"")?.strip_suffix(b"\"")?; + // RFC 9110 §8.8.3 permits obs-text and compares opaque tags as octets. + opaque + .iter() + .all(|byte| matches!(byte, b'!' | b'#'..=b'~' | 0x80..=0xff)) + .then_some(EntityTag { weak, opaque }) +} + +fn etag_header(headers: &HeaderMap) -> Option> { + let mut values = headers.get_all(ETAG).into_iter(); + let tag = entity_tag(values.next()?)?; + values.next().is_none().then_some(tag) +} + +fn validated_candidates<'a>( + candidates: &'a [CachedResponse], + headers: &HeaderMap, +) -> Vec<&'a CachedResponse> { + let tag = etag_header(headers); + if headers.contains_key(ETAG) && tag.is_none() { + return Vec::new(); + } + if let Some(tag) = tag.as_ref().filter(|tag| !tag.weak) { + // A strong validator takes precedence over weak validators, even on a miss. + return candidates + .iter() + .rev() + .filter(|entry| etag_header(&entry.headers).as_ref() == Some(tag)) + .collect(); + } + + // No trusted origin-clock provenance is available to establish strength for Last-Modified. + let last_modified = parse_http_date_header(headers, LAST_MODIFIED); + if tag.is_some() || last_modified.is_some() { + return candidates + .iter() + .rev() + .find(|entry| { + tag.as_ref().is_some_and(|tag| { + etag_header(&entry.headers).is_some_and(|stored| tag.opaque == stored.opaque) + }) || last_modified.is_some_and(|date| { + parse_http_date_header(&entry.headers, LAST_MODIFIED) == Some(date) + }) + }) + .into_iter() + .collect(); + } + + match candidates { + [entry] + if !headers.contains_key(LAST_MODIFIED) + && !CacheValidators::from_headers(&entry.headers).has_any() => + { + vec![entry] + } + _ => Vec::new(), + } +} + impl CacheDirectives { fn from_headers(headers: &HeaderMap) -> Self { let mut out = Self::default(); @@ -508,6 +646,35 @@ pub trait CacheStore: Send + Sync + 'static { let _ = value; self.remove(key).await; } + + /// Updates or removes a candidate identified by a validation response if the + /// stored candidate still matches the snapshot taken before validation. + /// Stores shared between concurrent calls should override this method to + /// make the check and write atomic. + async fn replace_validated_candidate( + &self, + key: &str, + previous: &CachedResponse, + replacement: Option, + ) { + if !self + .get_candidates(key) + .await + .iter() + .any(|entry| entry.same_snapshot_as(previous)) + { + return; + } + match replacement { + Some(replacement) => { + if !previous.same_variant_as(&replacement) { + self.remove_candidate(key, previous).await; + } + self.put_candidate(key.to_owned(), replacement).await; + } + None => self.remove_candidate(key, previous).await, + } + } } #[derive(Clone)] @@ -627,6 +794,36 @@ impl CacheStore for MemoryCacheStore { entries.remove(key); } } + + async fn replace_validated_candidate( + &self, + key: &str, + previous: &CachedResponse, + replacement: Option, + ) { + let mut entries = self.entries.write().await; + let Some(candidates) = entries.get_mut(key) else { + return; + }; + let Some(index) = candidates + .iter() + .position(|entry| entry.same_snapshot_as(previous)) + else { + return; + }; + candidates.remove(index); + if let Some(replacement) = replacement { + if !candidates + .iter() + .any(|entry| entry.same_variant_as(&replacement)) + { + candidates.insert(index, replacement); + } + } + if candidates.is_empty() { + entries.remove(key); + } + } } #[derive(Clone)] @@ -775,10 +972,26 @@ impl CachedResponse { self.vary == other.vary } - fn can_revalidate(&self, request_headers: &HeaderMap) -> bool { - !request_headers.contains_key(IF_NONE_MATCH) - && !request_headers.contains_key(IF_MODIFIED_SINCE) - && CacheValidators::from_headers(&self.headers).has_any() + /// Checks whether two entries have the same stored representation and cache + /// metadata. Cache stores can use this before replacing a validated entry. + pub fn same_snapshot_as(&self, other: &Self) -> bool { + self.received_at == other.received_at + && self.same_variant_as(other) + && self.status == other.status + && self.version == other.version + && self.headers == other.headers + && self.body == other.body + && self.initial_age == other.initial_age + && self.freshness_lifetime == other.freshness_lifetime + && self.must_validate == other.must_validate + && self.must_revalidate == other.must_revalidate + } + + fn recency(&self) -> (Option, Instant) { + ( + parse_http_date_header(&self.headers, DATE), + self.received_at, + ) } fn apply_revalidation_headers(&self, request_headers: &mut HeaderMap) { @@ -1126,13 +1339,14 @@ mod tests { use std::time::{Duration, Instant, SystemTime}; use bytes::Bytes; - use http::header::{AGE, CONTENT_LOCATION, DATE, LOCATION}; - use http::{HeaderMap, StatusCode, Uri, Version}; + use http::header::{AGE, CONTENT_LOCATION, DATE, ETAG, LAST_MODIFIED, LOCATION}; + use http::{HeaderMap, HeaderValue, StatusCode, Uri, Version}; use openwire::ResponseTiming; use super::{ - invalidation_keys, parse_delta_seconds, response_age, response_current_age, CachedResponse, - CachedResponseOptions, RequestCachePolicy, MAX_DELTA_SECONDS, + invalidation_keys, parse_delta_seconds, response_age, response_current_age, + validated_candidates, CacheStore, CachedResponse, CachedResponseOptions, MemoryCacheStore, + RequestCachePolicy, MAX_DELTA_SECONDS, }; #[test] @@ -1187,6 +1401,68 @@ mod tests { ) } + #[test] + fn validation_selects_all_strong_matches_or_the_most_recent_weak_match() { + let instant = Instant::now(); + let timing = ResponseTiming::new(instant, instant, SystemTime::UNIX_EPOCH); + let mut candidates = [b"\"\x80\"".as_slice(), b"\"\x80\"", b"W/\"\x80\""].map(|tag| { + let mut headers = HeaderMap::new(); + headers.insert(ETAG, HeaderValue::from_bytes(tag).unwrap()); + timed_entry(headers, timing, Duration::ZERO) + }); + let mut validation = HeaderMap::new(); + validation.insert(ETAG, HeaderValue::from_bytes(b"\"\x80\"").unwrap()); + let matched = validated_candidates(&candidates, &validation); + assert_eq!(matched.len(), 2); + assert!(std::ptr::eq(matched[0], &candidates[1])); + assert!(std::ptr::eq(matched[1], &candidates[0])); + + validation.insert(ETAG, HeaderValue::from_bytes(b"W/\"\x80\"").unwrap()); + let matched = validated_candidates(&candidates, &validation); + assert_eq!(matched.len(), 1); + assert!(std::ptr::eq(matched[0], &candidates[2])); + + validation.clear(); + assert!(validated_candidates(&candidates[..1], &validation).is_empty()); + candidates[0].headers.remove(ETAG); + assert_eq!(validated_candidates(&candidates[..1], &validation).len(), 1); + assert!(validated_candidates(&candidates, &validation).is_empty()); + + let modified = HeaderValue::from_static("Wed, 01 Jan 2020 00:00:00 GMT"); + candidates[0] + .headers + .insert(LAST_MODIFIED, modified.clone()); + validation.insert(LAST_MODIFIED, modified); + assert_eq!(validated_candidates(&candidates, &validation).len(), 1); + validation.insert(ETAG, HeaderValue::from_static("\"unknown\"")); + assert!(validated_candidates(&candidates, &validation).is_empty()); + validation.append(ETAG, HeaderValue::from_static("W/\"duplicate\"")); + assert!(validated_candidates(&candidates, &validation).is_empty()); + } + + #[tokio::test] + async fn validated_snapshot_cannot_overwrite_a_replaced_variant() { + let instant = Instant::now(); + let timing = ResponseTiming::new(instant, instant, SystemTime::UNIX_EPOCH); + let entry = |tag: &'static str| { + let mut headers = HeaderMap::new(); + headers.insert(ETAG, HeaderValue::from_static(tag)); + timed_entry(headers, timing, Duration::ZERO) + }; + let store = MemoryCacheStore::new(); + let key = "http://example.test/resource"; + let snapshot = entry("\"v1\""); + store.put(key.to_owned(), snapshot.clone()).await; + store.put(key.to_owned(), entry("\"v2\"")).await; + store + .replace_validated_candidate(key, &snapshot, Some(snapshot.clone())) + .await; + store + .replace_validated_candidate(key, &snapshot, None) + .await; + assert_eq!(store.get(key).await.unwrap().headers[ETAG], "\"v2\""); + } + #[test] fn response_age_vectors_choose_corrected_or_apparent_age() { // RFC 9111 §4.2.3. Request=100, response=105, now=112. diff --git a/crates/openwire-cache/tests/integration.rs b/crates/openwire-cache/tests/integration.rs index 9cd54ba..6adaf20 100644 --- a/crates/openwire-cache/tests/integration.rs +++ b/crates/openwire-cache/tests/integration.rs @@ -10,7 +10,7 @@ use http::{Method, Request, Response, StatusCode}; use hyper::body::Incoming; use openwire::{ BoxFuture, Client, Exchange, Interceptor, Next, RequestBody, ResponseBody, ResponseTiming, - WireError, + WireError, WireErrorKind, }; use openwire_cache::CacheInterceptor; use openwire_test::{spawn_http1, text_response, RecordingEventListenerFactory}; @@ -1918,6 +1918,322 @@ async fn stale_etag_response_revalidates_with_if_none_match() { assert_eq!(hits.load(Ordering::SeqCst), 2); } +#[tokio::test] +async fn strong_etag_304_only_refreshes_a_strong_match() { + for (stored_tag, validation_tag, expected_body, expected_tag, expected_hits) in [ + ("\"old\"", "\"old\"", "original", "\"old\"", 2), + ("\"old\"", "\"new\"", "replacement", "\"new\"", 3), + ("W/\"new\"", "\"new\"", "replacement", "\"new\"", 3), + ] { + let hits = Arc::new(AtomicUsize::new(0)); + let server = spawn_http1({ + let hits = hits.clone(); + move |request: Request| { + let hit = hits.fetch_add(1, Ordering::SeqCst); + async move { + assert_eq!(request.headers()[ACCEPT_LANGUAGE], "en"); + let last_modified = "Wed, 01 Jan 2020 00:00:00 GMT"; + let (mut response, cache_control, etag) = match hit { + 0 => ( + text_response(StatusCode::OK, "original"), + "max-age=0", + stored_tag, + ), + 1 => { + assert_eq!(request.headers()[IF_NONE_MATCH], stored_tag); + assert_eq!(request.headers()[IF_MODIFIED_SINCE], last_modified); + ( + text_response(StatusCode::NOT_MODIFIED, ""), + "max-age=600", + validation_tag, + ) + } + 2 => { + assert!(!request.headers().contains_key(IF_NONE_MATCH)); + assert!(!request.headers().contains_key(IF_MODIFIED_SINCE)); + ( + text_response(StatusCode::OK, "replacement"), + "max-age=60", + expected_tag, + ) + } + _ => panic!("an unexpected extra request reached the origin"), + }; + let headers = response.headers_mut(); + headers.insert(CACHE_CONTROL, cache_control.parse().unwrap()); + headers.insert(ETAG, etag.parse().unwrap()); + headers.insert(LAST_MODIFIED, last_modified.parse().unwrap()); + headers.insert(VARY, "Accept-Language".parse().unwrap()); + response + } + } + }) + .await; + let client = Client::builder() + .max_requests_total(1) + .application_interceptor(CacheInterceptor::memory()) + .build() + .unwrap(); + let uri = server.http_url("/strong-validator"); + for (body, tag, cache_control) in [ + ("original", stored_tag, "max-age=0"), + ( + expected_body, + expected_tag, + if expected_hits == 2 { + "max-age=600" + } else { + "max-age=60" + }, + ), + ( + expected_body, + expected_tag, + if expected_hits == 2 { + "max-age=600" + } else { + "max-age=60" + }, + ), + ] { + let response = tokio::time::timeout( + Duration::from_secs(5), + client.execute(request_with_header(&uri, ACCEPT_LANGUAGE, "en")), + ) + .await + .expect("cache recovery released the validation exchange") + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()[ETAG], tag); + assert_eq!(response.headers()[CACHE_CONTROL], cache_control); + assert_eq!(response.into_body().text().await.unwrap(), body); + } + assert_eq!(hits.load(Ordering::SeqCst), expected_hits); + } +} + +#[tokio::test] +async fn untimed_mismatched_304_and_unsolicited_recovery_304_do_not_modify_cache() { + let hits = Arc::new(AtomicUsize::new(0)); + let server = spawn_http1({ + let hits = hits.clone(); + move |request: Request| { + let hit = hits.fetch_add(1, Ordering::SeqCst); + async move { + let (mut response, etag, max_age) = match hit { + 0 => ( + text_response(StatusCode::OK, "original"), + "\"v1\"", + "max-age=0", + ), + 1 => { + assert_eq!(request.headers()[IF_NONE_MATCH], "\"v1\""); + ( + text_response(StatusCode::NOT_MODIFIED, ""), + "\"v2\"", + "max-age=600", + ) + } + 2 => { + assert!(!request.headers().contains_key(IF_NONE_MATCH)); + ( + text_response(StatusCode::NOT_MODIFIED, ""), + "\"v2\"", + "max-age=600", + ) + } + _ => panic!("recovery repeated"), + }; + response + .headers_mut() + .insert(CACHE_CONTROL, max_age.parse().unwrap()); + response.headers_mut().insert(ETAG, etag.parse().unwrap()); + response + } + } + }) + .await; + let client = Client::builder() + .application_interceptor(CacheInterceptor::memory()) + .network_interceptor(RemoveValidationTiming) + .build() + .unwrap(); + let uri = server.http_url("/invalid-304"); + client + .execute(empty_request(&uri)) + .await + .unwrap() + .into_body() + .bytes() + .await + .unwrap(); + let error = client.execute(empty_request(&uri)).await.unwrap_err(); + assert_eq!(error.kind(), WireErrorKind::Protocol); + let still_cached = client + .execute(request_with_header( + &uri, + CACHE_CONTROL, + "only-if-cached, max-stale", + )) + .await + .unwrap(); + assert_eq!(still_cached.headers()[ETAG], "\"v1\""); + assert_eq!(still_cached.headers()[CACHE_CONTROL], "max-age=0"); + assert_eq!(still_cached.into_body().text().await.unwrap(), "original"); + assert_eq!(hits.load(Ordering::SeqCst), 3); +} + +#[tokio::test] +async fn caller_validation_preserves_the_304_and_refreshes_only_a_matching_entry() { + for (caller_tag, expected_cache_control) in + [("\"v1\"", "max-age=600"), ("\"v2\"", "max-age=60")] + { + let server = spawn_http1(move |request: Request| async move { + let language = request.headers()[ACCEPT_LANGUAGE].to_str().unwrap(); + let (mut response, tag, max_age) = + if let Some(value) = request.headers().get(IF_NONE_MATCH) { + assert_eq!(language, "en"); + assert_eq!(value, caller_tag); + ( + text_response(StatusCode::NOT_MODIFIED, ""), + caller_tag, + "max-age=600", + ) + } else { + ( + text_response(StatusCode::OK, language.to_owned()), + if language == "en" { + "\"v1\"" + } else { + caller_tag + }, + "max-age=60", + ) + }; + response.headers_mut().insert(ETAG, tag.parse().unwrap()); + response + .headers_mut() + .insert(VARY, "Accept-Language".parse().unwrap()); + response + .headers_mut() + .insert(CACHE_CONTROL, max_age.parse().unwrap()); + response + }) + .await; + let client = Client::builder() + .application_interceptor(CacheInterceptor::memory()) + .build() + .unwrap(); + let uri = server.http_url("/caller-validation"); + for language in ["en", "fr"] { + let seed = client + .execute(request_with_header(&uri, ACCEPT_LANGUAGE, language)) + .await + .unwrap(); + assert_eq!(seed.into_body().text().await.unwrap(), language); + } + let response = client + .execute(request_with_headers( + &uri, + ACCEPT_LANGUAGE, + "en", + IF_NONE_MATCH, + caller_tag, + )) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::NOT_MODIFIED); + assert_eq!(response.headers()[ETAG], caller_tag); + assert!(response.into_body().bytes().await.unwrap().is_empty()); + for (language, tag, cache_control) in [ + ("en", "\"v1\"", expected_cache_control), + ("fr", caller_tag, "max-age=60"), + ] { + let cached = client + .execute(request_with_headers( + &uri, + ACCEPT_LANGUAGE, + language, + CACHE_CONTROL, + "only-if-cached", + )) + .await + .unwrap(); + assert_eq!(cached.headers()[ETAG], tag); + assert_eq!(cached.headers()[CACHE_CONTROL], cache_control); + assert_eq!(cached.into_body().text().await.unwrap(), language); + } + } +} + +#[tokio::test] +async fn redirect_target_304_cannot_validate_the_original_uri() { + let original_hits = Arc::new(AtomicUsize::new(0)); + let target_hits = Arc::new(AtomicUsize::new(0)); + let server = spawn_http1({ + let original_hits = original_hits.clone(); + let target_hits = target_hits.clone(); + move |request: Request| { + let (counter, original) = match request.uri().path() { + "/original" => (&original_hits, true), + "/target" => (&target_hits, false), + _ => panic!("unexpected URI"), + }; + let hit = counter.fetch_add(1, Ordering::SeqCst); + async move { + let mut response = match (original, hit) { + (true, 0) => text_response(StatusCode::OK, "original body"), + (true, 1 | 2) => { + let mut response = text_response(StatusCode::TEMPORARY_REDIRECT, ""); + response + .headers_mut() + .insert(LOCATION, "/target".parse().unwrap()); + return response; + } + (false, 0) => { + assert_eq!(request.headers()[IF_NONE_MATCH], "\"v1\""); + text_response(StatusCode::NOT_MODIFIED, "") + } + (false, 1) => { + assert!(!request.headers().contains_key(IF_NONE_MATCH)); + text_response(StatusCode::OK, "different target body") + } + _ => panic!("unexpected request"), + }; + let cache_control = if original { "max-age=0" } else { "max-age=600" }; + response + .headers_mut() + .insert(CACHE_CONTROL, cache_control.parse().unwrap()); + response + .headers_mut() + .insert(ETAG, "\"v1\"".parse().unwrap()); + response + } + } + }) + .await; + let client = Client::builder() + .application_interceptor(CacheInterceptor::memory()) + .build() + .unwrap(); + let uri = server.http_url("/original"); + let initial = client.execute(empty_request(&uri)).await.unwrap(); + assert_eq!(initial.into_body().text().await.unwrap(), "original body"); + let resolved = client.execute(empty_request(&uri)).await.unwrap(); + assert_eq!(resolved.status(), StatusCode::OK); + assert_eq!( + resolved.into_body().text().await.unwrap(), + "different target body" + ); + let cache_only = client + .execute(request_with_header(&uri, CACHE_CONTROL, "only-if-cached")) + .await + .unwrap(); + assert_eq!(cache_only.status(), StatusCode::GATEWAY_TIMEOUT); + assert_eq!(original_hits.load(Ordering::SeqCst), 3); + assert_eq!(target_hits.load(Ordering::SeqCst), 2); +} + #[tokio::test] async fn stale_last_modified_response_revalidates_with_if_modified_since() { let hits = Arc::new(AtomicUsize::new(0)); diff --git a/crates/openwire-core/src/interceptor.rs b/crates/openwire-core/src/interceptor.rs index 5e43ebd..4795933 100644 --- a/crates/openwire-core/src/interceptor.rs +++ b/crates/openwire-core/src/interceptor.rs @@ -3,7 +3,7 @@ use std::task::{Context, Poll}; use http::{Request, Response}; use tower::layer::Layer; use tower::util::BoxCloneSyncService; -use tower::Service; +use tower::{Service, ServiceExt}; use crate::{BoxFuture, CallContext, RequestBody, ResponseBody, WireError}; @@ -68,6 +68,15 @@ impl Next { inner.call(exchange).await }) } + + /// Waits for the downstream service to be ready before running the exchange. + /// Use this for an additional exchange on a clone of `Next`. + pub fn run_when_ready(self, exchange: Exchange) -> BoxFuture> { + Box::pin(async move { + let mut inner = self.inner; + inner.ready().await?.call(exchange).await + }) + } } pub trait Interceptor: Send + Sync + 'static { diff --git a/crates/openwire-tokio/src/lib.rs b/crates/openwire-tokio/src/lib.rs index b1650eb..2942ed0 100644 --- a/crates/openwire-tokio/src/lib.rs +++ b/crates/openwire-tokio/src/lib.rs @@ -445,31 +445,73 @@ pub struct TcpSocketConfig { pub send_buffer_size: Option, } +impl TcpSocketConfig { + const DEFAULT: Self = Self { + nodelay: true, + linger: None, + recv_buffer_size: None, + send_buffer_size: None, + }; +} + impl Default for TcpSocketConfig { fn default() -> Self { - Self { - nodelay: true, - linger: None, - recv_buffer_size: None, - send_buffer_size: None, - } + Self::DEFAULT } } +/// A Tokio TCP connector using the default socket options. #[derive(Clone, Debug, Default)] -pub struct TokioTcpConnector { - config: TcpSocketConfig, -} +pub struct TokioTcpConnector; impl TokioTcpConnector { pub fn new() -> Self { - Self::default() + Self + } + + pub fn from_config(config: TcpSocketConfig) -> ConfiguredTokioTcpConnector { + ConfiguredTokioTcpConnector { config } + } + + pub fn nodelay(self, enabled: bool) -> ConfiguredTokioTcpConnector { + ConfiguredTokioTcpConnector::default().nodelay(enabled) + } + + pub fn linger(self, linger: Option) -> ConfiguredTokioTcpConnector { + ConfiguredTokioTcpConnector::default().linger(linger) + } + + pub fn recv_buffer_size(self, size: u32) -> ConfiguredTokioTcpConnector { + ConfiguredTokioTcpConnector::default().recv_buffer_size(size) + } + + pub fn send_buffer_size(self, size: u32) -> ConfiguredTokioTcpConnector { + ConfiguredTokioTcpConnector::default().send_buffer_size(size) } - pub fn from_config(config: TcpSocketConfig) -> Self { - Self { config } + pub fn config(&self) -> &TcpSocketConfig { + &TcpSocketConfig::DEFAULT } +} +impl TcpConnector for TokioTcpConnector { + fn connect( + &self, + ctx: CallContext, + addr: SocketAddr, + timeout: Option, + ) -> BoxFuture> { + ConfiguredTokioTcpConnector::default().connect(ctx, addr, timeout) + } +} + +/// A Tokio TCP connector with explicit socket options. +#[derive(Clone, Debug, Default)] +pub struct ConfiguredTokioTcpConnector { + config: TcpSocketConfig, +} + +impl ConfiguredTokioTcpConnector { pub fn nodelay(mut self, enabled: bool) -> Self { self.config.nodelay = enabled; self @@ -495,7 +537,7 @@ impl TokioTcpConnector { } } -impl TcpConnector for TokioTcpConnector { +impl TcpConnector for ConfiguredTokioTcpConnector { fn connect( &self, ctx: CallContext, diff --git a/crates/openwire-tokio/tests/tcp_connector.rs b/crates/openwire-tokio/tests/tcp_connector.rs new file mode 100644 index 0000000..fb97871 --- /dev/null +++ b/crates/openwire-tokio/tests/tcp_connector.rs @@ -0,0 +1,13 @@ +use openwire_core::TcpConnector; +use openwire_tokio::{ConfiguredTokioTcpConnector, TokioTcpConnector}; + +#[test] +fn released_unit_connector_can_be_constructed_and_destructured() { + const CONNECTOR: TokioTcpConnector = TokioTcpConnector; + let _connector: &dyn TcpConnector = &CONNECTOR; + let TokioTcpConnector = CONNECTOR; + assert!(CONNECTOR.config().nodelay); + + let configured: ConfiguredTokioTcpConnector = TokioTcpConnector.nodelay(false); + assert!(!configured.config().nodelay); +} diff --git a/crates/openwire/benches/perf_baseline.rs b/crates/openwire/benches/perf_baseline.rs index 55c0815..573cd33 100644 --- a/crates/openwire/benches/perf_baseline.rs +++ b/crates/openwire/benches/perf_baseline.rs @@ -177,7 +177,7 @@ impl TcpConnector for ScriptedRaceTcpConnector { .expect("missing tcp script"); Box::pin(async move { tokio::time::sleep(script.delay).await; - TokioTcpConnector::default() + TokioTcpConnector .connect(ctx, script.actual_addr, timeout) .await }) diff --git a/crates/openwire/src/lib.rs b/crates/openwire/src/lib.rs index 3d45270..af59b00 100644 --- a/crates/openwire/src/lib.rs +++ b/crates/openwire/src/lib.rs @@ -42,3 +42,9 @@ pub use openwire_rustls::{RustlsTlsConnector, RustlsTlsConnectorBuilder}; pub use policy::{DefaultRedirectPolicy, DefaultRetryPolicy}; pub use proxy::{NoProxy, Proxy, ProxyChoice, ProxyRules, ProxySelection, ProxySelector}; pub use url::Url; + +/// Response extension indicating that the client followed at least one redirect. +/// Cache and other application interceptors can use it to distinguish the +/// response to the original request from a response to a redirect target. +#[derive(Clone, Copy, Debug)] +pub struct RedirectedResponse; diff --git a/crates/openwire/src/policy/follow_up.rs b/crates/openwire/src/policy/follow_up.rs index 6738c96..7e05955 100644 --- a/crates/openwire/src/policy/follow_up.rs +++ b/crates/openwire/src/policy/follow_up.rs @@ -26,6 +26,7 @@ pub(crate) type SharedCookieJar = Arc; use crate::proxy::SelectedProxy; use crate::trace::PolicyTraceContext; use crate::transport::{CoalescedConnectionRetryable, NoCoalescedConnections}; +use crate::RedirectedResponse; #[derive(Clone)] pub(crate) struct PolicyConfig { @@ -112,7 +113,10 @@ impl Service for FollowUpPolicyService { }; match result { - Ok(response) => { + Ok(mut response) => { + if redirects != 0 { + response.extensions_mut().insert(RedirectedResponse); + } let selected_proxy = response.extensions().get::().cloned(); store_response_cookies( &response, diff --git a/crates/openwire/tests/support/harness.rs b/crates/openwire/tests/support/harness.rs index 9897b86..4881c70 100644 --- a/crates/openwire/tests/support/harness.rs +++ b/crates/openwire/tests/support/harness.rs @@ -826,9 +826,7 @@ impl TcpConnector for FailingTcpConnector { return Err(error); } - TokioTcpConnector::default() - .connect(ctx, addr, timeout) - .await + TokioTcpConnector.connect(ctx, addr, timeout).await }) } } @@ -854,9 +852,7 @@ impl TcpConnector for AttemptCountingTcpConnector { let attempts = self.attempts.clone(); Box::pin(async move { attempts.fetch_add(1, Ordering::Relaxed); - TokioTcpConnector::default() - .connect(ctx, addr, timeout) - .await + TokioTcpConnector.connect(ctx, addr, timeout).await }) } } @@ -882,9 +878,7 @@ impl TcpConnector for RecordingTimeoutTcpConnector { let timeouts = self.timeouts.clone(); Box::pin(async move { timeouts.lock().expect("connector timeouts").push(timeout); - TokioTcpConnector::default() - .connect(ctx, addr, timeout) - .await + TokioTcpConnector.connect(ctx, addr, timeout).await }) } } @@ -930,7 +924,7 @@ impl TcpConnector for ScriptedRaceTcpConnector { Box::pin(async move { attempts.fetch_add(1, Ordering::Relaxed); tokio::time::sleep(script.delay).await; - TokioTcpConnector::default() + TokioTcpConnector .connect(ctx, script.actual_addr, timeout) .await }) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 2a9af48..bf51b2d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -482,8 +482,11 @@ cargo test -p openwire --test live_network -- --ignored --test-threads=1 - HTTP/2 `TransportConfig` knobs (window sizes, frame/header limits, keep-alive timeout, reset-stream cap) and HTTP/1 `writev` / `title_case_headers` are applied in `bind_http1` / `bind_http2`. TCP linger and buffer sizes are - optional on `TokioTcpConnector` and are set on `TcpSocket` before connect. - Defaults keep nodelay on and leave buffers/linger to the OS. + set on `TcpSocket` before connect by `ConfiguredTokioTcpConnector`. + `TokioTcpConnector` is a public unit struct for default options. Its + configuration methods return `ConfiguredTokioTcpConnector`. Both implement + `TcpConnector` and share the same socket path. Defaults keep nodelay on and + leave buffers and linger to the OS. - Dual-stack route plans share a single `Arc
` across candidate routes instead of cloning the full address key per IP. - Follow-up `RequestSnapshot` stores headers and extensions behind `Arc` so diff --git a/docs/cache-age.md b/docs/cache-age.md index 8bf21ae..07966cb 100644 --- a/docs/cache-age.md +++ b/docs/cache-age.md @@ -39,8 +39,8 @@ feasible. 4. Validation uses the 304 exchange's timing and Age/Date. A recipient with a clock adds a missing Date at receipt before merging headers; old Age is removed. Missing timing is not guessed: synthetic responses without metadata - are returned but not stored, and internal 304s still reconstruct the caller's - response without publishing an unverified refreshed entry. + are returned without storage. A matching internal 304 with no timing still + reconstructs the caller's response without publishing a refreshed entry. Public metadata API in `crates/openwire-core/src/transport.rs`: @@ -75,7 +75,7 @@ corrections. | [RFC 9111 §4.2.3](https://www.rfc-editor.org/rfc/rfc9111.html#section-4.2.3): Age correction accounts for request initiation and response delay | MUST interpret corrected Age relative to request initiation; conservative max is a permitted choice | transport timing + cache arithmetic | request1000/response1002/Date900/Age200/now1005 yields205; Date-dominant and future-Date cases | verified by focused tests listed below | | RFC 9111 §4.2.3: residence begins at receipt | §4 MUST on unvalidated cache hits; §4.2.3 algorithm | cache entry | entry age uses header receipt rather than construction time; subsecond delay/residence retained | verified by focused tests listed below | | RFC 9111 §4 and §4.2: hits emit current Age and freshness is strict | MUST replace Age on unvalidated hits; freshness definition | cache hit/freshness decision | exact Age serialization and stale at equality; local peer request counts | verified by focused tests listed below | -| RFC 9111 §4.3.3–4 and §4.2.3: an identified response gets validation age metadata | 304 age/Date reconstruction only; validator eligibility remains blocked | 304 merge/cache | validation uses new exchange delay/Age, absent Age is zero; old representation body preserved | verified by focused tests listed below | +| RFC 9111 §4.3.3–4 and §4.2.3: an identified response gets validation age metadata | 304 age/Date reconstruction for an eligible validator match | 304 merge/cache | validation uses new exchange delay/Age, absent Age is zero; old representation body preserved | verified by focused tests listed below | | RFC 9111 §§1.2.2 and 5.1: valid overflow never becomes zero; invalid Age is ignored; first list member selected by default | MUST saturation/invalid handling; SHOULD first-member choice | Age parser | legal oversized digits saturate; signed/fractional/invalid first member ignored | verified by focused tests listed below | | [RFC 9110 §6.6.1](https://www.rfc-editor.org/rfc/rfc9110.html#section-6.6.1): recipient with clock records a missing Date when caching | MUST when a clocked recipient caches a response with absent Date | cache normalization | missing ordinary/304 Date becomes receipt wall time, future Date clamps apparent age to zero | verified by focused tests listed below | @@ -83,6 +83,26 @@ Use the conservative RFC formula: maximum of apparent age and incoming Age plus response delay, then add monotonic residence. This is an explicit permitted choice even when corrected Age alone could be used. +### Validator selection before a 304 update + +The private GET cache uses the existing cache key, request-header selection +(`Vary`), and authorization eligibility before comparing validators. The +current RFC 9111 text applies. The RFC Editor rejected erratum 9185, which +would have expanded the candidate set beyond matching `Vary` values. No +verified erratum changes the comparison or selection rules below. +[RFC 9111 §§4.3.2–4.3.4](https://www.rfc-editor.org/rfc/rfc9111.html#section-4.3.4) · +[RFC 9110 §§8.8.2–8.8.3](https://www.rfc-editor.org/rfc/rfc9110.html#section-8.8.3.2) · +[Erratum 9185 decision](https://lists.w3.org/Archives/Public/ietf-http-wg/2026OctDec/0193.html) · +[Erratum 9164 decision](https://lists.w3.org/Archives/Public/ietf-http-wg/2026OctDec/0191.html) + +| Requirement and conditions | Implementation | Verified evidence | +| --- | --- | --- | +| A strong `ETag` selects every eligible response with the identical strong tag. With zero matches the cache MUST leave stored responses alone, even when `Last-Modified` agrees. | `validated_candidates` compares opaque tag bytes and strength before the merge. | `strong_etag_304_only_refreshes_a_strong_match` covers identical tags, different strong tags, and weak-to-strong with identical opaque bytes. The match makes two origin requests and refreshes metadata. The other cases make three and return the replacement body. | +| A weak validator selects the most recent corresponding eligible response. With no validators, selection requires exactly one eligible stored response that also has none. | `validated_candidates` uses weak tag comparison and parsed HTTP dates. The cache treats `Last-Modified` as weak because it lacks origin clock provenance. | `validation_selects_all_strong_matches_or_the_most_recent_weak_match` covers strong and weak selection, opaque obs-text, date matching, missing validators and duplicate tags. | +| Eligibility from `Vary` applies before tag matching. Caller-supplied validation stays with the origin. | `CacheInterceptor::intercept` forwards the original conditional headers and carries the origin `304` back to its caller. This delegates the §4.3.2 SHOULD for local precondition evaluation to the origin to preserve its full evaluation semantics. The cache skips the optional validator union. | `caller_validation_preserves_the_304_and_refreshes_only_a_matching_entry` verifies a fresh entry, matching and mismatching tags, and another language variant with the same tag. | +| [RFC 9111 §4](https://www.rfc-editor.org/rfc/rfc9111.html#section-4) requires the cached and requested URI to match. `ETag` identifies representations within a resource. | The follow-up coordinator attaches `RedirectedResponse` after following a redirect. The cache excludes that response from selection and storage for the initial URI. | `redirect_target_304_cannot_validate_the_original_uri` uses identical strong tags for two URIs and verifies that recovery returns the target body without refreshing the original entry. | +| An internal `304` with zero eligible matches cannot validate the stored response. Use the full response from an original-request replay if available. | `Next::run_when_ready` performs one recovery exchange after releasing the first response. A second `304` yields a protocol error. `MemoryCacheStore::replace_validated_candidate` guards the snapshot under its write lock. | `untimed_mismatched_304_and_unsolicited_recovery_304_do_not_modify_cache`, `strong_etag_304_only_refreshes_a_strong_match`, and `validated_snapshot_cannot_overwrite_a_replaced_variant` cover failed recovery, a single admission slot, and concurrent replacement. | + ## Phased Implementation ## Phase 1: Demonstrate the Failure (Completed) @@ -177,11 +197,8 @@ other operating systems remains separate evidence. assuming zero delay. This affects synthetic interceptor responses; attach ResponseTiming to opt into automatic storage. - No new production dependency or global clock/test framework. -- This repair proves the age/Date cases listed above, not all cache conformance. - In particular, 304 validator eligibility is outside this repair: the existing - freshening path does not reject a mismatched strong ETag. That pre-existing - §4.3.4 gap blocks a full validation-conformance claim and affected releases - until separately fixed; passing age tests do not waive it. +- The verification covers the age/Date cases and private GET validation + scenarios listed above. ## File Change Summary