use crate::optimize::{optimize, EncodedFormat, FormatPreference, ResizeTarget};
use crate::MAX_DIMENSION;
use axum::extract::Query;
use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use base64::Engine;
use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};
const PUBLIC_ROOT: &str = "public";
const CACHE_ROOT: &str = "storage/framework/cache/images";
pub struct ImagePlugin;
impl larust_http::Plugin for ImagePlugin {
fn routes(&self) -> larust_http::Router {
larust_http::Router::new().get("/__larust_image/optimize", optimize_handler)
}
}
#[derive(serde::Deserialize)]
struct OptimizeQuery {
src: String,
w: u32,
#[serde(default)]
h: Option<u32>,
#[serde(default)]
q: Option<u8>,
}
async fn optimize_handler(
Query(params): Query<OptimizeQuery>,
headers: HeaderMap,
) -> Result<Response, (StatusCode, &'static str)> {
if params.w == 0 || params.w > MAX_DIMENSION {
return Err((StatusCode::BAD_REQUEST, "width out of range"));
}
if let Some(h) = params.h {
if h == 0 || h > MAX_DIMENSION {
return Err((StatusCode::BAD_REQUEST, "height out of range"));
}
}
let quality = params.q.unwrap_or(crate::DEFAULT_QUALITY).clamp(1, 100);
let target = match params.h {
Some(height) => ResizeTarget::Exact {
width: params.w,
height,
},
None => ResizeTarget::Width { width: params.w },
};
let source_path =
resolve_source_path(¶ms.src).ok_or((StatusCode::NOT_FOUND, "image not found"))?;
let preferred_format = preferred_format_from_accept(headers.get(header::ACCEPT));
let cache_key = cache_key(¶ms.src, params.w, params.h, quality, preferred_format);
if let Some(cached) = read_cached(&cache_key).await {
return Ok(serve(cached.0, cached.1));
}
let source_bytes = tokio::fs::read(&source_path)
.await
.map_err(|_| (StatusCode::NOT_FOUND, "image not found"))?;
let result = tokio::task::spawn_blocking(move || {
optimize(&source_bytes, target, quality, preferred_format, true)
})
.await
.map_err(|_| {
(
StatusCode::INTERNAL_SERVER_ERROR,
"image processing panicked",
)
})?
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "failed to process image"))?;
write_cache(&cache_key, result.main.format, &result.main.bytes).await;
if let Some(blur_bytes) = &result.blur {
write_blur_cache(¶ms.src, blur_bytes).await;
}
Ok(serve(result.main.bytes, result.main.format))
}
fn resolve_source_path(src: &str) -> Option<PathBuf> {
let public_root = Path::new(PUBLIC_ROOT).canonicalize().ok()?;
let candidate = public_root.join(src.trim_start_matches('/'));
let canonical = candidate.canonicalize().ok()?;
canonical.starts_with(&public_root).then_some(canonical)
}
fn preferred_format_from_accept(accept: Option<&header::HeaderValue>) -> FormatPreference {
let accept = accept.and_then(|v| v.to_str().ok()).unwrap_or_default();
if accept.contains("image/avif") {
FormatPreference::Avif
} else if accept.contains("image/webp") {
FormatPreference::Webp
} else {
FormatPreference::Jpeg
}
}
fn cache_key(
src: &str,
width: u32,
height: Option<u32>,
quality: u8,
preferred_format: FormatPreference,
) -> String {
let mut hasher = Sha256::new();
hasher.update(src.as_bytes());
hasher.update(width.to_le_bytes());
hasher.update([height.is_some() as u8]);
hasher.update(height.unwrap_or(0).to_le_bytes());
hasher.update([quality]);
hasher.update([preferred_format as u8]);
hex_digest(hasher)
}
fn blur_cache_key(src: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(src.as_bytes());
hex_digest(hasher)
}
fn hex_digest(hasher: Sha256) -> String {
let digest = hasher.finalize();
let mut hex = String::with_capacity(digest.len() * 2);
for byte in digest {
use std::fmt::Write as _;
let _ = write!(hex, "{byte:02x}");
}
hex
}
async fn read_cached(cache_key: &str) -> Option<(Vec<u8>, EncodedFormat)> {
for format in [
EncodedFormat::Avif,
EncodedFormat::Webp,
EncodedFormat::Jpeg,
] {
let path = cache_path(cache_key, format);
if let Ok(bytes) = tokio::fs::read(&path).await {
return Some((bytes, format));
}
}
None
}
async fn write_cache(cache_key: &str, format: EncodedFormat, bytes: &[u8]) {
let path = cache_path(cache_key, format);
ensure_parent_and_write(&path, bytes).await;
}
async fn write_blur_cache(src: &str, bytes: &[u8]) {
let path = blur_cache_path(src);
ensure_parent_and_write(&path, bytes).await;
}
async fn ensure_parent_and_write(path: &Path, bytes: &[u8]) {
if let Some(parent) = path.parent() {
let _ = tokio::fs::create_dir_all(parent).await;
}
let _ = tokio::fs::write(path, bytes).await;
}
fn cache_path(cache_key: &str, format: EncodedFormat) -> PathBuf {
Path::new(CACHE_ROOT).join(format!("{cache_key}.{}", format.extension()))
}
fn blur_cache_path(src: &str) -> PathBuf {
Path::new(CACHE_ROOT).join(format!("blur_{}.jpg", blur_cache_key(src)))
}
pub(crate) fn read_blur_data_uri(src: &str) -> Option<String> {
let bytes = std::fs::read(blur_cache_path(src)).ok()?;
let encoded = base64::engine::general_purpose::STANDARD.encode(bytes);
Some(format!("data:image/jpeg;base64,{encoded}"))
}
fn serve(bytes: Vec<u8>, format: EncodedFormat) -> Response {
(
StatusCode::OK,
[
(header::CONTENT_TYPE, format.content_type()),
(header::CACHE_CONTROL, "public, max-age=31536000, immutable"),
],
bytes,
)
.into_response()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn resolve_source_path_rejects_a_traversal_attempt() {
assert!(resolve_source_path("../../../../etc/passwd").is_none());
}
#[test]
fn cache_key_is_stable_and_sensitive_to_every_input() {
let a = cache_key("hero.jpg", 400, Some(300), 75, FormatPreference::Jpeg);
let b = cache_key("hero.jpg", 400, Some(300), 75, FormatPreference::Jpeg);
assert_eq!(a, b);
assert_ne!(
a,
cache_key("hero.jpg", 401, Some(300), 75, FormatPreference::Jpeg)
);
assert_ne!(
a,
cache_key("hero.jpg", 400, Some(301), 75, FormatPreference::Jpeg)
);
assert_ne!(
a,
cache_key("hero.jpg", 400, Some(300), 76, FormatPreference::Jpeg)
);
assert_ne!(
a,
cache_key("hero.jpg", 400, Some(300), 75, FormatPreference::Avif)
);
assert_ne!(
a,
cache_key("hero.jpg", 400, Some(300), 75, FormatPreference::Webp)
);
assert_ne!(
cache_key("hero.jpg", 400, Some(300), 75, FormatPreference::Avif),
cache_key("hero.jpg", 400, Some(300), 75, FormatPreference::Webp)
);
assert_ne!(
a,
cache_key("other.jpg", 400, Some(300), 75, FormatPreference::Jpeg)
);
assert_ne!(
a,
cache_key("hero.jpg", 400, None, 75, FormatPreference::Jpeg)
);
}
#[test]
fn preferred_format_from_accept_prioritizes_avif_over_webp() {
let accept = header::HeaderValue::from_static("image/webp,image/avif,*/*");
assert_eq!(
preferred_format_from_accept(Some(&accept)),
FormatPreference::Avif
);
}
#[test]
fn preferred_format_from_accept_falls_back_to_webp_then_jpeg() {
let webp_only = header::HeaderValue::from_static("image/webp,*/*");
assert_eq!(
preferred_format_from_accept(Some(&webp_only)),
FormatPreference::Webp
);
assert_eq!(preferred_format_from_accept(None), FormatPreference::Jpeg);
}
#[test]
fn blur_cache_key_depends_only_on_src() {
assert_eq!(blur_cache_key("hero.jpg"), blur_cache_key("hero.jpg"));
assert_ne!(blur_cache_key("hero.jpg"), blur_cache_key("other.jpg"));
}
#[test]
fn read_blur_data_uri_is_none_on_a_cold_cache() {
assert!(read_blur_data_uri("definitely-never-cached.jpg").is_none());
}
}