1use crate::optimize::{optimize, EncodedFormat, FormatPreference, ResizeTarget};
26use crate::MAX_DIMENSION;
27use axum::extract::Query;
28use axum::http::{header, HeaderMap, StatusCode};
29use axum::response::{IntoResponse, Response};
30use base64::Engine;
31use sha2::{Digest, Sha256};
32use std::path::{Path, PathBuf};
33
34const PUBLIC_ROOT: &str = "public";
41
42const CACHE_ROOT: &str = "storage/framework/cache/images";
47
48pub struct ImagePlugin;
49
50impl larust_http::Plugin for ImagePlugin {
51 fn routes(&self) -> larust_http::Router {
52 larust_http::Router::new().get("/__larust_image/optimize", optimize_handler)
53 }
54}
55
56#[derive(serde::Deserialize)]
57struct OptimizeQuery {
58 src: String,
59 w: u32,
60 #[serde(default)]
64 h: Option<u32>,
65 #[serde(default)]
66 q: Option<u8>,
67}
68
69async fn optimize_handler(
70 Query(params): Query<OptimizeQuery>,
71 headers: HeaderMap,
72) -> Result<Response, (StatusCode, &'static str)> {
73 if params.w == 0 || params.w > MAX_DIMENSION {
74 return Err((StatusCode::BAD_REQUEST, "width out of range"));
75 }
76 if let Some(h) = params.h {
77 if h == 0 || h > MAX_DIMENSION {
78 return Err((StatusCode::BAD_REQUEST, "height out of range"));
79 }
80 }
81 let quality = params.q.unwrap_or(crate::DEFAULT_QUALITY).clamp(1, 100);
82 let target = match params.h {
83 Some(height) => ResizeTarget::Exact {
84 width: params.w,
85 height,
86 },
87 None => ResizeTarget::Width { width: params.w },
88 };
89
90 let source_path =
91 resolve_source_path(¶ms.src).ok_or((StatusCode::NOT_FOUND, "image not found"))?;
92
93 let preferred_format = preferred_format_from_accept(headers.get(header::ACCEPT));
94
95 let cache_key = cache_key(¶ms.src, params.w, params.h, quality, preferred_format);
96
97 if let Some(cached) = read_cached(&cache_key).await {
98 return Ok(serve(cached.0, cached.1));
99 }
100
101 let source_bytes = tokio::fs::read(&source_path)
102 .await
103 .map_err(|_| (StatusCode::NOT_FOUND, "image not found"))?;
104
105 let result = tokio::task::spawn_blocking(move || {
106 optimize(&source_bytes, target, quality, preferred_format, true)
107 })
108 .await
109 .map_err(|_| {
110 (
111 StatusCode::INTERNAL_SERVER_ERROR,
112 "image processing panicked",
113 )
114 })?
115 .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "failed to process image"))?;
116
117 write_cache(&cache_key, result.main.format, &result.main.bytes).await;
118 if let Some(blur_bytes) = &result.blur {
119 write_blur_cache(¶ms.src, blur_bytes).await;
120 }
121
122 Ok(serve(result.main.bytes, result.main.format))
123}
124
125fn resolve_source_path(src: &str) -> Option<PathBuf> {
135 let public_root = Path::new(PUBLIC_ROOT).canonicalize().ok()?;
136 let candidate = public_root.join(src.trim_start_matches('/'));
137 let canonical = candidate.canonicalize().ok()?;
138 canonical.starts_with(&public_root).then_some(canonical)
139}
140
141fn preferred_format_from_accept(accept: Option<&header::HeaderValue>) -> FormatPreference {
145 let accept = accept.and_then(|v| v.to_str().ok()).unwrap_or_default();
146 if accept.contains("image/avif") {
147 FormatPreference::Avif
148 } else if accept.contains("image/webp") {
149 FormatPreference::Webp
150 } else {
151 FormatPreference::Jpeg
152 }
153}
154
155fn cache_key(
156 src: &str,
157 width: u32,
158 height: Option<u32>,
159 quality: u8,
160 preferred_format: FormatPreference,
161) -> String {
162 let mut hasher = Sha256::new();
163 hasher.update(src.as_bytes());
164 hasher.update(width.to_le_bytes());
165 hasher.update([height.is_some() as u8]);
166 hasher.update(height.unwrap_or(0).to_le_bytes());
167 hasher.update([quality]);
168 hasher.update([preferred_format as u8]);
169 hex_digest(hasher)
170}
171
172fn blur_cache_key(src: &str) -> String {
182 let mut hasher = Sha256::new();
183 hasher.update(src.as_bytes());
184 hex_digest(hasher)
185}
186
187fn hex_digest(hasher: Sha256) -> String {
188 let digest = hasher.finalize();
189 let mut hex = String::with_capacity(digest.len() * 2);
190 for byte in digest {
191 use std::fmt::Write as _;
192 let _ = write!(hex, "{byte:02x}");
193 }
194 hex
195}
196
197async fn read_cached(cache_key: &str) -> Option<(Vec<u8>, EncodedFormat)> {
198 for format in [
199 EncodedFormat::Avif,
200 EncodedFormat::Webp,
201 EncodedFormat::Jpeg,
202 ] {
203 let path = cache_path(cache_key, format);
204 if let Ok(bytes) = tokio::fs::read(&path).await {
205 return Some((bytes, format));
206 }
207 }
208 None
209}
210
211async fn write_cache(cache_key: &str, format: EncodedFormat, bytes: &[u8]) {
212 let path = cache_path(cache_key, format);
213 ensure_parent_and_write(&path, bytes).await;
214}
215
216async fn write_blur_cache(src: &str, bytes: &[u8]) {
217 let path = blur_cache_path(src);
218 ensure_parent_and_write(&path, bytes).await;
219}
220
221async fn ensure_parent_and_write(path: &Path, bytes: &[u8]) {
222 if let Some(parent) = path.parent() {
223 let _ = tokio::fs::create_dir_all(parent).await;
228 }
229 let _ = tokio::fs::write(path, bytes).await;
230}
231
232fn cache_path(cache_key: &str, format: EncodedFormat) -> PathBuf {
233 Path::new(CACHE_ROOT).join(format!("{cache_key}.{}", format.extension()))
234}
235
236fn blur_cache_path(src: &str) -> PathBuf {
237 Path::new(CACHE_ROOT).join(format!("blur_{}.jpg", blur_cache_key(src)))
238}
239
240pub(crate) fn read_blur_data_uri(src: &str) -> Option<String> {
253 let bytes = std::fs::read(blur_cache_path(src)).ok()?;
254 let encoded = base64::engine::general_purpose::STANDARD.encode(bytes);
255 Some(format!("data:image/jpeg;base64,{encoded}"))
256}
257
258fn serve(bytes: Vec<u8>, format: EncodedFormat) -> Response {
259 (
260 StatusCode::OK,
261 [
262 (header::CONTENT_TYPE, format.content_type()),
263 (header::CACHE_CONTROL, "public, max-age=31536000, immutable"),
269 ],
270 bytes,
271 )
272 .into_response()
273}
274
275#[cfg(test)]
276mod tests {
277 use super::*;
278
279 #[test]
280 fn resolve_source_path_rejects_a_traversal_attempt() {
281 assert!(resolve_source_path("../../../../etc/passwd").is_none());
288 }
289
290 #[test]
291 fn cache_key_is_stable_and_sensitive_to_every_input() {
292 let a = cache_key("hero.jpg", 400, Some(300), 75, FormatPreference::Jpeg);
293 let b = cache_key("hero.jpg", 400, Some(300), 75, FormatPreference::Jpeg);
294 assert_eq!(a, b);
295
296 assert_ne!(
297 a,
298 cache_key("hero.jpg", 401, Some(300), 75, FormatPreference::Jpeg)
299 );
300 assert_ne!(
301 a,
302 cache_key("hero.jpg", 400, Some(301), 75, FormatPreference::Jpeg)
303 );
304 assert_ne!(
305 a,
306 cache_key("hero.jpg", 400, Some(300), 76, FormatPreference::Jpeg)
307 );
308 assert_ne!(
309 a,
310 cache_key("hero.jpg", 400, Some(300), 75, FormatPreference::Avif)
311 );
312 assert_ne!(
315 a,
316 cache_key("hero.jpg", 400, Some(300), 75, FormatPreference::Webp)
317 );
318 assert_ne!(
319 cache_key("hero.jpg", 400, Some(300), 75, FormatPreference::Avif),
320 cache_key("hero.jpg", 400, Some(300), 75, FormatPreference::Webp)
321 );
322 assert_ne!(
323 a,
324 cache_key("other.jpg", 400, Some(300), 75, FormatPreference::Jpeg)
325 );
326 assert_ne!(
329 a,
330 cache_key("hero.jpg", 400, None, 75, FormatPreference::Jpeg)
331 );
332 }
333
334 #[test]
335 fn preferred_format_from_accept_prioritizes_avif_over_webp() {
336 let accept = header::HeaderValue::from_static("image/webp,image/avif,*/*");
337 assert_eq!(
338 preferred_format_from_accept(Some(&accept)),
339 FormatPreference::Avif
340 );
341 }
342
343 #[test]
344 fn preferred_format_from_accept_falls_back_to_webp_then_jpeg() {
345 let webp_only = header::HeaderValue::from_static("image/webp,*/*");
346 assert_eq!(
347 preferred_format_from_accept(Some(&webp_only)),
348 FormatPreference::Webp
349 );
350 assert_eq!(preferred_format_from_accept(None), FormatPreference::Jpeg);
351 }
352
353 #[test]
354 fn blur_cache_key_depends_only_on_src() {
355 assert_eq!(blur_cache_key("hero.jpg"), blur_cache_key("hero.jpg"));
356 assert_ne!(blur_cache_key("hero.jpg"), blur_cache_key("other.jpg"));
357 }
358
359 #[test]
360 fn read_blur_data_uri_is_none_on_a_cold_cache() {
361 assert!(read_blur_data_uri("definitely-never-cached.jpg").is_none());
362 }
363}