1use crate::optimize::{optimize, EncodedFormat, 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 prefer_avif = headers
94 .get(header::ACCEPT)
95 .and_then(|v| v.to_str().ok())
96 .is_some_and(|accept| accept.contains("image/avif"));
97
98 let cache_key = cache_key(¶ms.src, params.w, params.h, quality, prefer_avif);
99
100 if let Some(cached) = read_cached(&cache_key).await {
101 return Ok(serve(cached.0, cached.1));
102 }
103
104 let source_bytes = tokio::fs::read(&source_path)
105 .await
106 .map_err(|_| (StatusCode::NOT_FOUND, "image not found"))?;
107
108 let result = tokio::task::spawn_blocking(move || {
109 optimize(&source_bytes, target, quality, prefer_avif, true)
110 })
111 .await
112 .map_err(|_| {
113 (
114 StatusCode::INTERNAL_SERVER_ERROR,
115 "image processing panicked",
116 )
117 })?
118 .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "failed to process image"))?;
119
120 write_cache(&cache_key, result.main.format, &result.main.bytes).await;
121 if let Some(blur_bytes) = &result.blur {
122 write_blur_cache(¶ms.src, blur_bytes).await;
123 }
124
125 Ok(serve(result.main.bytes, result.main.format))
126}
127
128fn resolve_source_path(src: &str) -> Option<PathBuf> {
138 let public_root = Path::new(PUBLIC_ROOT).canonicalize().ok()?;
139 let candidate = public_root.join(src.trim_start_matches('/'));
140 let canonical = candidate.canonicalize().ok()?;
141 canonical.starts_with(&public_root).then_some(canonical)
142}
143
144fn cache_key(src: &str, width: u32, height: Option<u32>, quality: u8, prefer_avif: bool) -> String {
145 let mut hasher = Sha256::new();
146 hasher.update(src.as_bytes());
147 hasher.update(width.to_le_bytes());
148 hasher.update([height.is_some() as u8]);
149 hasher.update(height.unwrap_or(0).to_le_bytes());
150 hasher.update([quality]);
151 hasher.update([prefer_avif as u8]);
152 hex_digest(hasher)
153}
154
155fn blur_cache_key(src: &str) -> String {
165 let mut hasher = Sha256::new();
166 hasher.update(src.as_bytes());
167 hex_digest(hasher)
168}
169
170fn hex_digest(hasher: Sha256) -> String {
171 let digest = hasher.finalize();
172 let mut hex = String::with_capacity(digest.len() * 2);
173 for byte in digest {
174 use std::fmt::Write as _;
175 let _ = write!(hex, "{byte:02x}");
176 }
177 hex
178}
179
180async fn read_cached(cache_key: &str) -> Option<(Vec<u8>, EncodedFormat)> {
181 for format in [EncodedFormat::Avif, EncodedFormat::Jpeg] {
182 let path = cache_path(cache_key, format);
183 if let Ok(bytes) = tokio::fs::read(&path).await {
184 return Some((bytes, format));
185 }
186 }
187 None
188}
189
190async fn write_cache(cache_key: &str, format: EncodedFormat, bytes: &[u8]) {
191 let path = cache_path(cache_key, format);
192 ensure_parent_and_write(&path, bytes).await;
193}
194
195async fn write_blur_cache(src: &str, bytes: &[u8]) {
196 let path = blur_cache_path(src);
197 ensure_parent_and_write(&path, bytes).await;
198}
199
200async fn ensure_parent_and_write(path: &Path, bytes: &[u8]) {
201 if let Some(parent) = path.parent() {
202 let _ = tokio::fs::create_dir_all(parent).await;
207 }
208 let _ = tokio::fs::write(path, bytes).await;
209}
210
211fn cache_path(cache_key: &str, format: EncodedFormat) -> PathBuf {
212 Path::new(CACHE_ROOT).join(format!("{cache_key}.{}", format.extension()))
213}
214
215fn blur_cache_path(src: &str) -> PathBuf {
216 Path::new(CACHE_ROOT).join(format!("blur_{}.jpg", blur_cache_key(src)))
217}
218
219pub(crate) fn read_blur_data_uri(src: &str) -> Option<String> {
232 let bytes = std::fs::read(blur_cache_path(src)).ok()?;
233 let encoded = base64::engine::general_purpose::STANDARD.encode(bytes);
234 Some(format!("data:image/jpeg;base64,{encoded}"))
235}
236
237fn serve(bytes: Vec<u8>, format: EncodedFormat) -> Response {
238 (
239 StatusCode::OK,
240 [
241 (header::CONTENT_TYPE, format.content_type()),
242 (header::CACHE_CONTROL, "public, max-age=31536000, immutable"),
248 ],
249 bytes,
250 )
251 .into_response()
252}
253
254#[cfg(test)]
255mod tests {
256 use super::*;
257
258 #[test]
259 fn resolve_source_path_rejects_a_traversal_attempt() {
260 assert!(resolve_source_path("../../../../etc/passwd").is_none());
267 }
268
269 #[test]
270 fn cache_key_is_stable_and_sensitive_to_every_input() {
271 let a = cache_key("hero.jpg", 400, Some(300), 75, false);
272 let b = cache_key("hero.jpg", 400, Some(300), 75, false);
273 assert_eq!(a, b);
274
275 assert_ne!(a, cache_key("hero.jpg", 401, Some(300), 75, false));
276 assert_ne!(a, cache_key("hero.jpg", 400, Some(301), 75, false));
277 assert_ne!(a, cache_key("hero.jpg", 400, Some(300), 76, false));
278 assert_ne!(a, cache_key("hero.jpg", 400, Some(300), 75, true));
279 assert_ne!(a, cache_key("other.jpg", 400, Some(300), 75, false));
280 assert_ne!(a, cache_key("hero.jpg", 400, None, 75, false));
283 }
284
285 #[test]
286 fn blur_cache_key_depends_only_on_src() {
287 assert_eq!(blur_cache_key("hero.jpg"), blur_cache_key("hero.jpg"));
288 assert_ne!(blur_cache_key("hero.jpg"), blur_cache_key("other.jpg"));
289 }
290
291 #[test]
292 fn read_blur_data_uri_is_none_on_a_cold_cache() {
293 assert!(read_blur_data_uri("definitely-never-cached.jpg").is_none());
294 }
295}