use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use sha2::{Digest, Sha256};
pub fn entity_tag(body: &[u8]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let digest = Sha256::digest(body);
let mut tag = String::with_capacity(34);
tag.push('"');
for byte in &digest[..16] {
tag.push(HEX[usize::from(byte >> 4)] as char);
tag.push(HEX[usize::from(byte & 0x0f)] as char);
}
tag.push('"');
tag
}
fn header_value(tag: &str) -> String {
crate::std_shim::format!("W/{tag}")
}
pub fn matches_if_none_match(headers: &HeaderMap, tag: &str) -> bool {
let Some(value) = headers
.get(header::IF_NONE_MATCH)
.and_then(|v| v.to_str().ok())
else {
return false;
};
if value.trim() == "*" {
return true;
}
value
.split(',')
.map(|candidate| candidate.trim().trim_start_matches("W/"))
.any(|candidate| candidate == tag)
}
#[derive(Debug)]
pub struct Cached {
body: Vec<u8>,
etag: Option<String>,
not_modified: bool,
}
impl Cached {
pub fn json<T: serde::Serialize>(
value: &T,
request_headers: &HeaderMap,
enabled: bool,
) -> Result<Self, serde_json::Error> {
let body = serde_json::to_vec(value)?;
if !enabled {
return Ok(Self {
body,
etag: None,
not_modified: false,
});
}
let etag = entity_tag(&body);
let not_modified = matches_if_none_match(request_headers, &etag);
Ok(Self {
body,
etag: Some(etag),
not_modified,
})
}
pub fn etag(&self) -> Option<&str> {
self.etag.as_deref()
}
}
const CACHE_CONTROL: &str = "private, no-cache";
impl IntoResponse for Cached {
fn into_response(self) -> Response {
let mut headers = HeaderMap::new();
if let Some(etag) = &self.etag
&& let Ok(v) = HeaderValue::from_str(&header_value(etag))
{
headers.insert(header::ETAG, v);
}
headers.insert(
header::CACHE_CONTROL,
HeaderValue::from_static(CACHE_CONTROL),
);
headers.insert(header::VARY, HeaderValue::from_static("authorization"));
if self.not_modified {
return (StatusCode::NOT_MODIFIED, headers).into_response();
}
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
);
(StatusCode::OK, headers, self.body).into_response()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn headers(if_none_match: &str) -> HeaderMap {
let mut h = HeaderMap::new();
h.insert(
header::IF_NONE_MATCH,
HeaderValue::from_str(if_none_match).unwrap(),
);
h
}
#[test]
fn identical_bodies_produce_identical_tags() {
assert_eq!(entity_tag(b"{\"a\":1}"), entity_tag(b"{\"a\":1}"));
assert_ne!(entity_tag(b"{\"a\":1}"), entity_tag(b"{\"a\":2}"));
}
#[test]
fn tags_are_quoted_and_short() {
let tag = entity_tag(b"body");
assert!(tag.starts_with('"') && tag.ends_with('"'));
assert_eq!(tag.len(), 34);
}
#[test]
fn if_none_match_handles_lists_wildcards_and_weak_tags() {
let tag = entity_tag(b"body");
assert!(matches_if_none_match(&headers(&tag), &tag));
assert!(matches_if_none_match(&headers("*"), &tag));
assert!(matches_if_none_match(
&headers(&format!("\"other\", {tag}")),
&tag
));
assert!(matches_if_none_match(&headers(&format!("W/{tag}")), &tag));
assert!(!matches_if_none_match(&headers("\"stale\""), &tag));
assert!(!matches_if_none_match(&HeaderMap::new(), &tag));
}
#[test]
fn a_matching_tag_yields_304_with_no_body() {
let value = serde_json::json!({"programName": "tou"});
let first = Cached::json(&value, &HeaderMap::new(), true).unwrap();
let tag = first.etag().expect("caching is on").to_string();
let second = Cached::json(&value, &headers(&tag), true).unwrap();
let response = second.into_response();
assert_eq!(response.status(), StatusCode::NOT_MODIFIED);
}
#[test]
fn the_header_is_weak_and_the_client_may_send_either_form() {
let value = serde_json::json!({"programName": "tou"});
let cached = Cached::json(&value, &HeaderMap::new(), true).unwrap();
let tag = cached.etag().expect("caching is on").to_string();
let response = cached.into_response();
let sent = response
.headers()
.get(header::ETAG)
.unwrap()
.to_str()
.unwrap();
assert_eq!(sent, format!("W/{tag}"));
for candidate in [tag.clone(), format!("W/{tag}")] {
let response = Cached::json(&value, &headers(&candidate), true)
.unwrap()
.into_response();
assert_eq!(response.status(), StatusCode::NOT_MODIFIED, "{candidate}");
}
}
#[test]
fn caching_off_means_no_validator_at_all() {
let value = serde_json::json!({"programName": "tou"});
let tag = entity_tag(&serde_json::to_vec(&value).unwrap());
let cached = Cached::json(&value, &headers(&tag), false).unwrap();
assert_eq!(cached.etag(), None);
let response = cached.into_response();
assert_eq!(response.status(), StatusCode::OK);
assert!(
response.headers().get(header::ETAG).is_none(),
"an ETag was sent by a VTN that ignores If-None-Match"
);
}
}