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, 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 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(&params.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(&params.src, blur_bytes).await;
123    }
124
125    Ok(serve(result.main.bytes, result.main.format))
126}
127
128/// Resolves `src` (a path relative to `public/`, exactly as a template's
129/// own `<Image src="...">` wrote it) to a real file, rejecting anything
130/// that - via `..` or a symlink - would resolve *outside* `public/`.
131/// Canonicalizing both sides and checking a prefix relationship is the
132/// only reliable way to catch this: string-level `..` filtering alone
133/// misses symlink-based escapes, and a non-existent path can't be
134/// canonicalized at all (which this treats as simply "not found", the
135/// same response an attacker gets either way - never distinguishing "path
136/// traversal rejected" from "file doesn't exist").
137fn 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
155/// The blur thumbnail's own cache key - deliberately keyed on `src` alone,
156/// not width/height/quality/format: a source image has exactly one
157/// reasonable blur regardless of how many different boxes it's displayed
158/// in across a page (or a whole site), so every `<Image>` using the same
159/// `src` shares the same cached thumbnail. Like the main cache, this never
160/// invalidates on the *source file's* own content changing (replacing the
161/// file at an unchanged `src` path keeps serving the old cached bytes) -
162/// a known limitation already true of the main image cache, not a new one
163/// introduced here.
164fn 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        // Best-effort: a cache write failure (read-only filesystem, disk
203        // full) shouldn't fail the response - the caller already has a
204        // perfectly good result in memory, it just won't be cached for
205        // next time.
206        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
219/// A `data:image/jpeg;base64,...` URI for `src`'s cached blur thumbnail,
220/// if one has been generated yet (see this module's own doc comment for
221/// when that happens) - `None` on a cold cache, which [`crate::tag`]
222/// treats as "render without a blur background" rather than an error.
223/// Deliberately synchronous (`std::fs::read`, not `tokio::fs`) - this is
224/// called from [`crate::tag`], which has no async runtime context to
225/// `.await` inside (see that function's own doc comment for why it stays
226/// a plain, synchronous call). Safe to do synchronously specifically
227/// because it's a cheap existence-check-sized read of a file that, when
228/// present, is always tiny (see [`crate::optimize::optimize`]'s own
229/// `BLUR_WIDTH`) - nothing like the potentially-large, potentially-slow
230/// decode a cache *miss* would need.
231pub(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            // Next.js's own identical reasoning for its optimized-image
243            // endpoint: the URL already encodes every input (`src`,
244            // dimensions, quality, format) that could ever change the
245            // bytes behind it, so a cache-busting re-request never
246            // actually needs to happen - safe to cache "forever".
247            (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        // No real `public/` directory needs to exist for this one - a
261        // `..`-laden path should never even reach the point of trying to
262        // read a real file in the first place when the sandboxed root
263        // itself doesn't exist (as in a unit test's own CWD), but the
264        // actual traversal rejection is exercised for real in the crate's
265        // own end-to-end verification against a real app.
266        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        // A `fill`/srcset-style width-only request must not collide with
281        // a fixed-box request that happens to resolve to the same height.
282        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}