Skip to main content

larust_image/
route.rs

1//! The one route behind every `<Image ...>` tag - decodes, resizes, and
2//! encodes a local image on first request, then serves straight from a
3//! disk cache on every later one. Registered once per app via
4//! [`ImagePlugin`], the same `Plugin` shape `larust_support::wire::
5//! WirePlugin`/`larust_support::spa::SpaPlugin` already establish.
6//!
7//! **Also where the blur-placeholder cache gets populated.** `crate::tag`
8//! (`placeholder="blur"`) needs a tiny base64-encoded thumbnail inlined
9//! directly into the page's own HTML - but `tag` is a deliberately pure,
10//! synchronous function (no `.await`, no special binding, the one
11//! invariant this whole feature is built around), so it can't itself
12//! decode a source file and generate one; that's real, potentially-slow
13//! CPU work with no business running synchronously inside page rendering.
14//! Instead, every ordinary optimize request here *also* generates and
15//! caches a tiny blur thumbnail as a side effect of decoding the source
16//! anyway (see [`optimize::optimize`]'s own `generate_blur` parameter -
17//! essentially free once the source is already decoded in memory) - so
18//! `tag` only ever needs a cheap, synchronous cache-file *read*, never a
19//! decode. The practical effect: a brand-new image's very first page view
20//! renders with no blur (the cache is still empty) - the main `<img>`
21//! request that follows immediately after populates it, so every
22//! subsequent view (by anyone) gets the real blur. Graceful on a cold
23//! cache, not broken; self-healing after one real request.
24
25use 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
34/// `public/` - the one directory [`optimize_handler`] will ever read a
35/// source image from. Plain, CWD-relative, matching every other runtime
36/// path in this framework (`larust_support::vitex`'s own `public/hot`/
37/// `public/build/manifest.json`, `larust-storage`'s own `public()` disk) -
38/// not `larust_core::AppPaths`, which nothing else at this tier reaches
39/// for either.
40const PUBLIC_ROOT: &str = "public";
41
42/// `storage/framework/cache/images/` - Laravel's own `storage/framework/
43/// cache` naming, so a developer coming from Laravel recognizes what this
44/// directory is for at a glance, even though nothing in this framework had
45/// established that exact path before this crate.
46const 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    /// Omitted for a `fill`/`sizes`-driven request - see
61    /// [`ResizeTarget::Width`]'s own doc comment for why that needs
62    /// different resize behavior than a fixed `width`×`height` box.
63    #[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(&params.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(&params.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(&params.src, blur_bytes).await;
120    }
121
122    Ok(serve(result.main.bytes, result.main.format))
123}
124
125/// Resolves `src` (a path relative to `public/`, exactly as a template's
126/// own `<Image src="...">` wrote it) to a real file, rejecting anything
127/// that - via `..` or a symlink - would resolve *outside* `public/`.
128/// Canonicalizing both sides and checking a prefix relationship is the
129/// only reliable way to catch this: string-level `..` filtering alone
130/// misses symlink-based escapes, and a non-existent path can't be
131/// canonicalized at all (which this treats as simply "not found", the
132/// same response an attacker gets either way - never distinguishing "path
133/// traversal rejected" from "file doesn't exist").
134fn 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
141/// AVIF wins over WebP when the `Accept` header lists both - see
142/// [`FormatPreference`]'s own doc comment for why that priority order is
143/// the right default, not an arbitrary one.
144fn 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
172/// The blur thumbnail's own cache key - deliberately keyed on `src` alone,
173/// not width/height/quality/format: a source image has exactly one
174/// reasonable blur regardless of how many different boxes it's displayed
175/// in across a page (or a whole site), so every `<Image>` using the same
176/// `src` shares the same cached thumbnail. Like the main cache, this never
177/// invalidates on the *source file's* own content changing (replacing the
178/// file at an unchanged `src` path keeps serving the old cached bytes) -
179/// a known limitation already true of the main image cache, not a new one
180/// introduced here.
181fn 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        // Best-effort: a cache write failure (read-only filesystem, disk
224        // full) shouldn't fail the response - the caller already has a
225        // perfectly good result in memory, it just won't be cached for
226        // next time.
227        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
240/// A `data:image/jpeg;base64,...` URI for `src`'s cached blur thumbnail,
241/// if one has been generated yet (see this module's own doc comment for
242/// when that happens) - `None` on a cold cache, which [`crate::tag`]
243/// treats as "render without a blur background" rather than an error.
244/// Deliberately synchronous (`std::fs::read`, not `tokio::fs`) - this is
245/// called from [`crate::tag`], which has no async runtime context to
246/// `.await` inside (see that function's own doc comment for why it stays
247/// a plain, synchronous call). Safe to do synchronously specifically
248/// because it's a cheap existence-check-sized read of a file that, when
249/// present, is always tiny (see [`crate::optimize::optimize`]'s own
250/// `BLUR_WIDTH`) - nothing like the potentially-large, potentially-slow
251/// decode a cache *miss* would need.
252pub(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            // Next.js's own identical reasoning for its optimized-image
264            // endpoint: the URL already encodes every input (`src`,
265            // dimensions, quality, format) that could ever change the
266            // bytes behind it, so a cache-busting re-request never
267            // actually needs to happen - safe to cache "forever".
268            (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        // No real `public/` directory needs to exist for this one - a
282        // `..`-laden path should never even reach the point of trying to
283        // read a real file in the first place when the sandboxed root
284        // itself doesn't exist (as in a unit test's own CWD), but the
285        // actual traversal rejection is exercised for real in the crate's
286        // own end-to-end verification against a real app.
287        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        // WebP and AVIF must land in distinct cache entries too - not just
313        // each distinct from the plain-JPEG baseline above.
314        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        // A `fill`/srcset-style width-only request must not collide with
327        // a fixed-box request that happens to resolve to the same height.
328        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}