pub fn is_fresh(
headers: &hyper::HeaderMap,
etag: Option<&str>,
last_modified: Option<i64>,
) -> bool {
if let Some(candidates) = headers
.get(hyper::header::IF_NONE_MATCH)
.and_then(|v| v.to_str().ok())
{
let Some(etag) = etag else {
return false;
};
let etag = strip_weak(etag);
return candidates.split(',').any(|candidate| {
let candidate = candidate.trim();
if candidate == "*" {
return true;
}
let candidate = strip_weak(candidate);
candidate == etag || strip_encoding_suffix(candidate).is_some_and(|base| base == etag)
});
}
let (Some(since), Some(modified)) = (
headers
.get(hyper::header::IF_MODIFIED_SINCE)
.and_then(|v| v.to_str().ok())
.and_then(|v| httpdate::parse_http_date(v).ok()),
last_modified,
) else {
return false;
};
let since = since
.duration_since(std::time::SystemTime::UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as i64);
modified <= since
}
fn strip_weak(etag: &str) -> &str {
etag.strip_prefix("W/").unwrap_or(etag)
}
fn strip_encoding_suffix(tag: &str) -> Option<String> {
let inner = tag.strip_prefix('"')?.strip_suffix('"')?;
["gzip", "br"].iter().find_map(|token| {
inner
.strip_suffix(token)
.and_then(|s| s.strip_suffix('-'))
.map(|base| format!("\"{base}\""))
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_weak_prefixed_star_is_not_the_wildcard() {
let mut headers = hyper::HeaderMap::new();
headers.insert("if-none-match", "W/*".parse().expect("value"));
assert!(!is_fresh(&headers, Some("\"abc\""), None));
assert!(!is_fresh(&headers, Some("w/*"), None));
headers.insert(
"if-none-match",
"w/*x, W/w/*x, w/, W/*".parse().expect("value"),
);
assert!(!is_fresh(&headers, Some("w/*"), None));
for list in ["*", " * ", "\"aaa\", *, W/\"bbb\""] {
headers.insert("if-none-match", list.parse().expect("value"));
assert!(is_fresh(&headers, Some("\"abc\""), None), "{list:?}");
assert!(!is_fresh(&headers, None, None), "{list:?}");
}
}
#[test]
fn encoded_variant_tags_revalidate_against_the_identity_tag() {
let mut headers = hyper::HeaderMap::new();
headers.insert("if-none-match", "W/\"abc-gzip\"".parse().expect("value"));
assert!(is_fresh(&headers, Some("\"abc\""), None));
assert!(!is_fresh(&headers, Some("\"abd\""), None));
headers.insert("if-none-match", "\"x-gzip\"".parse().expect("value"));
assert!(is_fresh(&headers, Some("\"x-gzip\""), None));
assert!(!is_fresh(&headers, Some("\"x-zip\""), None));
assert_eq!(strip_encoding_suffix("\"a-br\"").as_deref(), Some("\"a\""));
assert_eq!(strip_encoding_suffix("\"a-zstd\""), None);
assert_eq!(
strip_encoding_suffix("abc-gzip"),
None,
"unquoted is not a tag"
);
}
}